ipvs: per-net tables and optimizations
Subsystems (6)
Julian Anastasov
maintainerv6 cover ipvs: per-net tables and optimizations
Hello,
This patchset targets more netns isolation when IPVS
is used in large setups and also includes some optimizations.
First patch adds useful wrappers to rculist_bl, thehlist_bl methods IPVS will use in the following patches. The other patches are IPVS-specific.
The following patches will:
* Convert the global __ip_vs_mutex to per-net service_mutex and switch the service tables to be per-net, cowork by Jiejian Wu and Dust Li
* Convert some code that walks the service lists to use RCU instead of the service_mutex
* We used two tables for services (non-fwmark and fwmark), merge them into single svc_table
* The list for unavailable destinations (dest_trash) holds dsts and thus dev references causing extra work for the ip_vs_dst_event() dev notifier handler. Change this by dropping the reference when dest is removed and saved into dest_trash. The dest_trash will need more changes to make it light for lookups. TODO.
* On new connection we can do multiple lookups for services by tryng different fallback options. Add more counters for service types, so that we can avoid unneeded lookups for services.
* Add infrastructure for resizable hash tables based on hlist_bl which we will use for services and connections: hlists with per-bucket bit lock in the heads. The resizing delays RCU lookups on a bucket level with seqcounts which are protected with spin locks. The entries keep the table ID and the hash value which allows to filter the entries without touching many cache lines and to unlink the entries without lookup by keys.
* Change the 256-bucket service hash table to be resizable in the range of 4..20 bits depending on the added services and use jhash hashing to reduce the collisions.
* Change the global connection table to be per-net and resizable in the range of 256..ip_vs_conn_tab_size. As the connections are hashed by using remote addresses and ports, use siphash instead of jhash for better security.
* As the connection table is not with fixed size, show its current size to user space
* As the connection table is not global anymore, the no_cport and dropentry counters can be per-net
* Make the connection hashing more secure for setups with multiple services. Hashing only by remote address and port (client info) is not enough. To reduce the possible hash collisions add the used virtual address/port (local info) into the hash and as a side effect the MASQ connections will be double hashed into the hash table to match the traffic from real servers:
OLD:
- all methods: c_list node: proto, caddr:cport
NEW:
- all methods: hn0 node (dir 0): proto, caddr:cport -> vaddr:vport
- MASQ method: hn1 node (dir 1): proto, daddr:dport -> caddr:cport
* Add /proc/net/ip_vs_status to show current state of IPVS, per-net
cat /proc/net/ip_vs_status
Conns: 9401
Conn buckets: 524288 (19 bits, lfactor -5)
Conn buckets empty: 505633 (96%)
Conn buckets len-1: 18322 (98%)
Conn buckets len-2: 329 (1%)
Conn buckets len-3: 3 (0%)
Conn buckets len-4: 1 (0%)
Services: 12
Service buckets: 128 (7 bits, lfactor -3)
Service buckets empty: 116 (90%)
Service buckets len-1: 12 (100%)
Stats thread slots: 1 (max 16)
Stats chain max len: 16
Stats thread ests: 38400
It shows the table size, the load factor (2^n), how many are the empty buckets, with percents from the all buckets, the number of buckets with length 1..7 where len-7 catches all len>=7 (zero values are not shown). The len-N percents ignore the empty buckets, so they are relative among all len-N buckets. It shows that smaller lfactor is needed to achieve len-1 buckets to be ~98%. Only real tests can show if relying on len-1 buckets is a better option because the hash table becomes too large with multiple connections. And as every table uses random key, the services may not avoid collision in all cases.
* add conn_lfactor and svc_lfactor sysctl vars, so that one can tune the connection/service hash table sizing
Links to downloadable patchset versions:
v6 (19 Oct 2025):
https://ja.ssi.bg/tmp/rht_v6.tgz
v5 (16 Sep 2024):
https://ja.ssi.bg/tmp/rht_v5.tgz
v4 (28 May 2024):
https://ja.ssi.bg/tmp/rht_v4.tgz
v3 (31 Mar 2024):
https://ja.ssi.bg/tmp/rht_v3.tgz
v2 (12 Dec 2023):
https://ja.ssi.bg/tmp/rht_v2.tgz
v1 (15 Aug 2023):
https://ja.ssi.bg/tmp/rht_v1.tgz
Changes in v6:
Patch 5:
* resync
Patch 8:
* resync: use READ_ONCE for ipvs->enable
* resync: use %zu for size_t
Patch 9:
* resync: use the new skip_elems value
* resync: use READ_ONCE for ipvs->enable
Patch 12:
* resync: use the new skip_elems value
Changes in v5:
Patch 6:
* resync with changes in main tree (6.11)
Patch 8:
* resync with changes in main tree (6.11)
Patch 9:
* resync with changes in main tree (6.11)
Patch 14:
* resync with changes in main tree (6.11)
Changes in v4:
Patch 14:
* the load factor parameters will be read-only for unprivileged namespaces while we do not account the allocated memory
Patch 5:
* resync with changes in main tree
Changes in v3:
Patch 7:
* change the sign of the load factor parameter, so that 2^lfactor = load/size
Patch 8:
* change the sign of the load factor parameter
* fix 'goto unlock_sem' in svc_resize_work_handler() after the last mutex_trylock() call, should be goto unlock_m
* now cond_resched_rcu() needs to include linux/rcupdate_wait.h Patch 9:
* consider that the sign of the load factor parameter is changed Patch 12:
* consider that the sign of the load factor parameter is changed Patch 14:
* change the sign of the load factor parameters in docs
Changes in v2:
Patch 1:
* add comments to hlist_bl_for_each_entry_continue_rcu and fix sparse warnings
Patch 9:
* Simon Kirby reports that backup server crashes if conn_tab is not created. Create it just to sync conns before any services are added.
Patch 11:
* kernel test robot reported for dropentry_counters problem when compiling with !CONFIG_SYSCTL, so it is time to wrap todrop_entry, ip_vs_conn_ops_mode and ip_vs_random_dropentry under CONFIG_SYSCTL
Patch 13:
* remove extra old_gen assignment at start of ip_vs_status_show()
Jiejian Wu (1):
ipvs: make ip_vs_svc_table and ip_vs_svc_fwm_table per netns
Julian Anastasov (13):
rculist_bl: add hlist_bl_for_each_entry_continue_rcu
ipvs: some service readers can use RCU
ipvs: use single svc table
ipvs: do not keep dest_dst after dest is removed
ipvs: use more counters to avoid service lookups
ipvs: add resizable hash tables
ipvs: use resizable hash table for services
ipvs: switch to per-net connection table
ipvs: show the current conn_tab size to users
ipvs: no_cport and dropentry counters can be per-net
ipvs: use more keys for connection hashing
ipvs: add ip_vs_status info
ipvs: add conn_lfactor and svc_lfactor sysctl vars
Documentation/networking/ipvs-sysctl.rst | 33 + include/linux/rculist_bl.h | 49 +- include/net/ip_vs.h | 395 ++++++- net/netfilter/ipvs/ip_vs_conn.c | 1052 +++++++++++++----- net/netfilter/ipvs/ip_vs_core.c | 177 +++- net/netfilter/ipvs/ip_vs_ctl.c | 1232 ++++++++++++++++------ net/netfilter/ipvs/ip_vs_est.c | 18 +- net/netfilter/ipvs/ip_vs_pe_sip.c | 4 +- net/netfilter/ipvs/ip_vs_sync.c | 23 + net/netfilter/ipvs/ip_vs_xmit.c | 39 +- 10 files changed, 2340 insertions(+), 682 deletions(-)
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 1/14 rculist_bl: add hlist_bl_for_each_entry_continue_rcu
Change the old hlist_bl_first_rcu to hlist_bl_first_rcu_dereference to indicate that it is a RCU dereference.
Add hlist_bl_next_rcu and hlist_bl_first_rcu to use RCU pointers and use them to fix sparse warnings.
Add hlist_bl_for_each_entry_continue_rcu.
--- include/linux/rculist_bl.h | 49 +++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-)
include/linux/rculist_bl.h +40 -9
@@ -8,21 +8,31 @@#include <linux/list_bl.h> #include <linux/rcupdate.h> +/* return the first ptr or next element in an RCU protected list */ +#define hlist_bl_first_rcu (head) \ + (*((struct hlist_bl_node __rcu **)(&(head)->first))) +#define hlist_bl_next_rcu (node) \ + (*((struct hlist_bl_node __rcu **)(&(node)->next))) +static inline void hlist_bl_set_first_rcu (struct hlist_bl_head *h,struct hlist_bl_node *n) {LIST_BL_BUG_ON ((unsigned long )n &LIST_BL_LOCKMASK );LIST_BL_BUG_ON (((unsigned long )h->first &LIST_BL_LOCKMASK ) !=LIST_BL_LOCKMASK ); -rcu_assign_pointer (h->first, +rcu_assign_pointer (hlist_bl_first_rcu (h), (struct hlist_bl_node *)((unsigned long )n |LIST_BL_LOCKMASK )); } -static inline struct hlist_bl_node *hlist_bl_first_rcu (struct hlist_bl_head *h) -{ -return (struct hlist_bl_node *) - ((unsigned long )rcu_dereference_check (h->first,hlist_bl_is_locked (h)) & ~LIST_BL_LOCKMASK ); -} +#define hlist_bl_first_rcu_dereference (head) \ +({ \ + struct hlist_bl_head *__head = (head); \ + \ + (struct hlist_bl_node *) \ + ((unsigned long)rcu_dereference_check(hlist_bl_first_rcu(__head), \ + hlist_bl_is_locked(__head)) & \ + ~LIST_BL_LOCKMASK); \ +})/** * hlist_bl_del_rcu - deletes entry from hash list without re-initialization
@@ -73,7 +83,7 @@ static inline void hlist_bl_add_head_rcu(struct hlist_bl_node *n, {struct hlist_bl_node *first; -/* don't need hlist_bl_first_rcu because we're under lock */ +/* don't need hlist_bl_first_rcu* because we're under lock */ first =hlist_bl_first (h); n->next = first;
@@ -93,9 +103,30 @@ static inline void hlist_bl_add_head_rcu(struct hlist_bl_node *n,* */ #define hlist_bl_for_each_entry_rcu (tpos, pos, head, member) \ - for (pos = hlist_bl_first_rcu(head); \ + for (pos = hlist_bl_first_rcu_dereference(head); \ pos && \ ({ tpos = hlist_bl_entry(pos, typeof(*tpos), member); 1; }); \ - pos = rcu_dereference_raw(pos->next)) + pos = rcu_dereference_raw(hlist_bl_next_rcu(pos))) + +/** +* hlist_bl_for_each_entry_continue_rcu - continue iteration over list of given +* type +* @tpos: the type * to use as a loop cursor. +* @pos: the &struct hlist_bl_node to use as a loop cursor. +* @member: the name of the hlist_bl_node within the struct. +* +* Continue to iterate over list of given type, continuing after +* the current position which must have been in the list when the RCU read +* lock was taken. +* This would typically require either that you obtained the node from a +* previous walk of the list in the same RCU read-side critical section, or +* that you held some sort of non-RCU reference (such as a reference count) +* to keep the node alive *and* in the list. +*/ +#define hlist_bl_for_each_entry_continue_rcu (tpos, pos, member) \ + for (pos = rcu_dereference_raw(hlist_bl_next_rcu(&(tpos)->member)); \ + pos && \ + ({ tpos = hlist_bl_entry(pos, typeof(*tpos), member); 1; }); \ + pos = rcu_dereference_raw(hlist_bl_next_rcu(pos)))#endif
Signature · 1 line
2.51.0
Florian Westphal
maintainerRe: [PATCHv6 net-next 01/14] rculist_bl: add hlist_bl_for_each_entry_continue_rcu
Quoted 6 lines · Julian Anastasov
Change the old
hlist_bl_first_rcutohlist_bl_first_rcu_dereferenceto indicate that it is a RCU dereference.Add
hlist_bl_next_rcuandhlist_bl_first_rcuto use RCU pointers and use them to fix sparse warnings.
Quoted 6 lines
Add
hlist_bl_for_each_entry_continue_rcu.Signed-off-by Julian Anastasov <[email protected]>--- include/linux/rculist_bl.h | 49 +++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-)
Are the RCU maintainers OK with this?
An explicit Ack or RvB would be good to have.
Julian Anastasov
maintainerRe: [PATCHv6 net-next 01/14] rculist_bl: add hlist_bl_for_each_entry_continue_rcu
Hello,
Quoted 9 lines · Florian Westphal
Quoted 8 lines · Julian Anastasov
Change the old
hlist_bl_first_rcutohlist_bl_first_rcu_dereferenceto indicate that it is a RCU dereference.Add
hlist_bl_next_rcuandhlist_bl_first_rcuto use RCU pointers and use them to fix sparse warnings.Add
hlist_bl_for_each_entry_continue_rcu.
Quoted 7 lines
Quoted 4 lines
Signed-off-by Julian Anastasov <[email protected]>--- include/linux/rculist_bl.h | 49 +++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-)Are the RCU maintainers OK with this?
An explicit Ack or RvB would be good to have.
Paul McKenney requested on 15 Aug 2023 some changes
for 1st version:
https://archive.linuxvirtualserver.org/html/lvs-devel/2023-08/msg00044.html
And they are now present in v2+:
https://archive.linuxvirtualserver.org/html/lvs-devel/2023-08/msg00057.html
So, the RCU change is expected to be ack-ed after
the other patches are accepted. I'm also expecting review and ack from Simon, so that we can finally include the patchset to -next...
Regards
--
Julian Anastasov <[email protected]>
Julian Anastasov
maintainerPATCH v6 2/14 ipvs: make ip_vs_svc_table and ip_vs_svc_fwm_table per netns
In reply to Julian AnastasovFrom: Jiejian Wu <[email protected]>
Current ipvs uses one global mutex "__ip_vs_mutex" to keep the global "ip_vs_svc_table" and "ip_vs_svc_fwm_table" safe. But when there are tens of thousands of services from different netns in the table, it takes a long time to look up the table, for example, using "ipvsadm -ln" from different netns simultaneously.
We make "ip_vs_svc_table" and "ip_vs_svc_fwm_table" per netns, and we add "service_mutex" per netns to keep these two tables safe instead of the global "__ip_vs_mutex" in current version. To this end, looking up services from different netns simultaneously will not get stuck, shortening the time consumption in large-scale deployment. It can be reproduced using the simple scripts below.
init.sh: #!/bin/bash
for((i=1;i<=4;i++));do
ip netns add ns$i
ip netns exec ns$i ip link set dev lo up
ip netns exec ns$i sh add-services.sh
done
add-services.sh: #!/bin/bash
for((i=0;i<30000;i++)); do
ipvsadm -A -t 10.10.10.10:$((80+$i)) -s rr
done
runtest.sh: #!/bin/bash for((i=1;i<4;i++));do
ip netns exec ns$i ipvsadm -ln > /dev/null &
done
ip netns exec ns4 ipvsadm -ln > /dev/null
Run "sh init.sh" to initiate the network environment. Then run "time ./runtest.sh" to evaluate the time consumption. Our testbed is a 4-core Intel Xeon ECS. The result of the original version is around 8 seconds, while the result of the modified version is only 0.8 seconds.
--- include/net/ip_vs.h | 13 +++ net/netfilter/ipvs/ip_vs_ctl.c | 167 ++++++++++++++------------------- net/netfilter/ipvs/ip_vs_est.c | 18 ++-- 3 files changed, 94 insertions(+), 104 deletions(-)
include/net/ip_vs.h +13 -0
@@ -33,6 +33,12 @@#define IP_VS_HDR_INVERSE 1#define IP_VS_HDR_ICMP 2 +/* +* Hash table: for virtual service lookups +*/ +#define IP_VS_SVC_TAB_BITS 8 +#define IP_VS_SVC_TAB_SIZE BIT(IP_VS_SVC_TAB_BITS) +#define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1)/* Generic access of ipvs struct */ static inline struct netns_ipvs *net_ipvs (struct net * net)
@@ -1041,6 +1047,13 @@ struct netns_ipvs {*/ unsigned int mixed_address_family_dests;unsigned int hooks_afmask;/* &1=AF_INET, &2=AF_INET6 */ + +/* the service mutex that protect svc_table and svc_fwm_table */ +struct mutex service_mutex; +/* the service table hashed by <protocol, addr, port> */ +struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ]; +/* the service table hashed by fwmark */ +struct hlist_head svc_fwm_table[IP_VS_SVC_TAB_SIZE ]; };#define DEFAULT_SYNC_THRESHOLD 3
net/netfilter/ipvs/ip_vs_ctl.c +72 -95
423 lines not on this page · raw message
net/netfilter/ipvs/ip_vs_est.c +9 -9
@@ -603,7 +603,7 @@ static void ip_vs_est_drain_temp_list(struct netns_ipvs *ipvs)while (1 ) {int max =16 ; -mutex_lock (&__ip_vs_mutex); +mutex_lock (&ipvs->service_mutex);while (max-- >0 ) { est = hlist_entry_safe(ipvs->est_temp_list.first,
@@ -623,12 +623,12 @@ static void ip_vs_est_drain_temp_list(struct netns_ipvs *ipvs) } goto unlock; } -mutex_unlock (&__ip_vs_mutex); +mutex_unlock (&ipvs->service_mutex);cond_resched (); } unlock: -mutex_unlock (&__ip_vs_mutex); +mutex_unlock (&ipvs->service_mutex); }/* Calculate limits for all kthreads */
@@ -648,9 +648,9 @@ static int ip_vs_est_calc_limits(struct netns_ipvs *ipvs, int *chain_max)u64 val;INIT_HLIST_HEAD (&chain); -mutex_lock (&__ip_vs_mutex); +mutex_lock (&ipvs->service_mutex); kd = ipvs->est_kt_arr[0 ]; -mutex_unlock (&__ip_vs_mutex); +mutex_unlock (&ipvs->service_mutex); s = kd ? kd->calc_stats :NULL ;if (!s) goto out;
@@ -749,7 +749,7 @@ static void ip_vs_est_calc_phase(struct netns_ipvs *ipvs)if (!ip_vs_est_calc_limits (ipvs, &chain_max))return ; -mutex_lock (&__ip_vs_mutex); +mutex_lock (&ipvs->service_mutex);/* Stop all other tasks, so that we can immediately move the * estimators to est_temp_list without RCU grace period
@@ -816,9 +816,9 @@ static void ip_vs_est_calc_phase(struct netns_ipvs *ipvs)/* Give chance estimators to be added (to est_temp_list) * and deleted (releasing kthread contexts) */ -mutex_unlock (&__ip_vs_mutex); +mutex_unlock (&ipvs->service_mutex);cond_resched (); -mutex_lock (&__ip_vs_mutex); +mutex_lock (&ipvs->service_mutex);/* Current kt released ? */ if (id >= ipvs->est_kt_count)
@@ -894,7 +894,7 @@ static void ip_vs_est_calc_phase(struct netns_ipvs *ipvs)mutex_unlock (&ipvs->est_mutex); unlock: -mutex_unlock (&__ip_vs_mutex); +mutex_unlock (&ipvs->service_mutex); }void ip_vs_zero_estimator (struct ip_vs_stats *stats)
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 3/14 ipvs: some service readers can use RCU
In reply to Julian AnastasovSome places walk the services under mutex but they can just use RCU:
* ip_vs_dst_event() uses ip_vs_forget_dev() which uses its own lock to modify dest
* ip_vs_genl_dump_services(): ip_vs_genl_fill_service() just fills skb
* ip_vs_genl_parse_service(): move RCU lock to callers ip_vs_genl_set_cmd(), ip_vs_genl_dump_dests() and ip_vs_genl_get_cmd()
* ip_vs_genl_dump_dests(): just fill skb
--- net/netfilter/ipvs/ip_vs_ctl.c | 47 +++++++++++++++++----------------- 1 file changed, 23 insertions(+), 24 deletions(-)
net/netfilter/ipvs/ip_vs_ctl.c +23 -24
@@ -1759,23 +1759,21 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,if (event !=NETDEV_DOWN || !ipvs)return NOTIFY_DONE ;IP_VS_DBG (3 ,"%s() dev=%s\n" , __func__, dev->name); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_table[idx], s_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[idx], s_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[idx], f_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[idx], f_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } } +rcu_read_unlock (); +mutex_lock (&ipvs->service_mutex);spin_lock_bh (&ipvs->dest_trash_lock);list_for_each_entry (dest, &ipvs->dest_trash, t_list) {ip_vs_forget_dev (dest, dev);
@@ -3318,9 +3316,9 @@ static int ip_vs_genl_fill_service(struct sk_buff *skb, goto nla_put_failure; } - sched =rcu_dereference_protected (svc->scheduler,1 ); + sched =rcu_dereference (svc->scheduler); sched_name = sched ? sched->name :"none" ; - pe =rcu_dereference_protected (svc->pe,1 ); + pe =rcu_dereference (svc->pe); if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) || (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) || nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
@@ -3374,9 +3372,9 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_table[i], s_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[i], s_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {
@@ -3387,7 +3385,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, }for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[i], f_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[i], f_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {
@@ -3398,7 +3396,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, } nla_put_failure: -mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock (); cb->args[0 ] = idx;return skb->len;
@@ -3454,13 +3452,11 @@ static int ip_vs_genl_parse_service(struct netns_ipvs *ipvs, usvc->fwmark =0 ; } -rcu_read_lock ();if (usvc->fwmark) svc =__ip_vs_svc_fwm_find (ipvs, usvc->af, usvc->fwmark);else svc =__ip_vs_service_find (ipvs, usvc->af, usvc->protocol, &usvc->addr, usvc->port); -rcu_read_unlock (); *ret_svc = svc;/* If a full entry was requested, check for the additional fields */
@@ -3587,7 +3583,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();/* Try to find the service for which to dump destinations */ if (nlmsg_parse_deprecated (cb->nlh,GENL_HDRLEN , attrs,IPVS_CMD_ATTR_MAX , ip_vs_cmd_policy, cb->extack))
@@ -3599,7 +3595,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, goto out_err;/* Dump the destinations */ -list_for_each_entry (dest, &svc->destinations, n_list) { +list_for_each_entry_rcu (dest, &svc->destinations, n_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_dest (skb, dest, cb) <0 ) {
@@ -3612,7 +3608,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, cb->args[0 ] = idx; out_err: -mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();return skb->len; }
@@ -3915,9 +3911,12 @@ static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)if (cmd ==IPVS_CMD_NEW_SERVICE || cmd ==IPVS_CMD_SET_SERVICE ) need_full_svc = true; +/* We use function that requires RCU lock */ +rcu_read_lock (); ret =ip_vs_genl_parse_service (ipvs, &usvc, info->attrs[IPVS_CMD_ATTR_SERVICE ], need_full_svc, &svc); +rcu_read_unlock ();if (ret) goto out;
@@ -4037,7 +4036,7 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)if (!msg)return -ENOMEM ; -mutex_lock (&ipvs->service_mutex); +rcu_read_lock (); reply =genlmsg_put_reply (msg, info, &ip_vs_genl_family,0 , reply_cmd);if (reply ==NULL )
@@ -4105,7 +4104,7 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) out_err:nlmsg_free (msg); out: -mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();return ret; }
Signature · 1 line
2.51.0
Re: [PATCHv6 net-next 03/14] ipvs: some service readers can use RCU
Quoted 10 lines · Julian Anastasov
Some places walk the services under mutex but they can just use RCU:
*
ip_vs_dst_event()usesip_vs_forget_dev()which uses its own lock to modify dest
*ip_vs_genl_dump_services():ip_vs_genl_fill_service()just fills skb
*ip_vs_genl_parse_service(): move RCU lock to callersip_vs_genl_set_cmd(),ip_vs_genl_dump_dests()andip_vs_genl_get_cmd()
*ip_vs_genl_dump_dests(): just fill skbSigned-off-by Julian Anastasov <[email protected]>
Best regards,
Dust
Quoted 158 lines
---
net/netfilter/ipvs/ip_vs_ctl.c| 47 +++++++++++++++++-----------------1 file changed, 23 insertions(+), 24 deletions(-)net/netfilter/ipvs/ip_vs_ctl.c +14
-16@@ -1759,23 +1759,21 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,if (event !=NETDEV_DOWN || !ipvs)return NOTIFY_DONE ;IP_VS_DBG (3 ,"%s() dev=%s\n" , __func__, dev->name); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_table[idx], s_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[idx], s_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[idx], f_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[idx], f_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } } +rcu_read_unlock (); +mutex_lock (&ipvs->service_mutex);spin_lock_bh (&ipvs->dest_trash_lock);list_for_each_entry (dest, &ipvs->dest_trash, t_list) {ip_vs_forget_dev (dest, dev);@@ -3318,9 +3316,9 @@ static int ip_vs_genl_fill_service(struct sk_buff *skb, goto nla_put_failure; } - sched =rcu_dereference_protected (svc->scheduler,1 ); + sched =rcu_dereference (svc->scheduler); sched_name = sched ? sched->name :"none" ; - pe =rcu_dereference_protected (svc->pe,1 ); + pe =rcu_dereference (svc->pe); if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) || (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) || nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||@@ -3374,9 +3372,9 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_table[i], s_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[i], s_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {@@ -3387,7 +3385,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, }for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[i], f_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[i], f_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {@@ -3398,7 +3396,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, }
nla_put_failure:net/netfilter/ipvs/ip_vs_ctl.c +1
-1-mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();cb->args[0] = idx; return skb->len;net/netfilter/ipvs/ip_vs_ctl.c +2
-4@@ -3454,13 +3452,11 @@ static int ip_vs_genl_parse_service(struct netns_ipvs *ipvs, usvc->fwmark =0 ; } -rcu_read_lock ();if (usvc->fwmark) svc =__ip_vs_svc_fwm_find (ipvs, usvc->af, usvc->fwmark);else svc =__ip_vs_service_find (ipvs, usvc->af, usvc->protocol, &usvc->addr, usvc->port); -rcu_read_unlock (); *ret_svc = svc;/* If a full entry was requested, check for the additional fields */ @@ -3587,7 +3583,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();/* Try to find the service for which to dump destinations */ if (nlmsg_parse_deprecated (cb->nlh,GENL_HDRLEN , attrs,IPVS_CMD_ATTR_MAX , ip_vs_cmd_policy, cb->extack))@@ -3599,7 +3595,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, goto out_err;/* Dump the destinations */ -list_for_each_entry (dest, &svc->destinations, n_list) { +list_for_each_entry_rcu (dest, &svc->destinations, n_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_dest (skb, dest, cb) <0 ) {@@ -3612,7 +3608,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, cb->args[0 ] = idx;
out_err:net/netfilter/ipvs/ip_vs_ctl.c +1
-1-mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();return skb->len; }net/netfilter/ipvs/ip_vs_ctl.c +4
-1@@ -3915,9 +3911,12 @@ static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)if (cmd ==IPVS_CMD_NEW_SERVICE || cmd ==IPVS_CMD_SET_SERVICE ) need_full_svc = true; +/* We use function that requires RCU lock */ +rcu_read_lock (); ret =ip_vs_genl_parse_service (ipvs, &usvc, info->attrs[IPVS_CMD_ATTR_SERVICE ], need_full_svc, &svc); +rcu_read_unlock ();if (ret) goto out;@@ -4037,7 +4036,7 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)if (!msg)return -ENOMEM ; -mutex_lock (&ipvs->service_mutex); +rcu_read_lock (); reply =genlmsg_put_reply (msg, info, &ip_vs_genl_family,0 , reply_cmd);if (reply ==NULL )@@ -4105,7 +4104,7 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
out_err:nlmsg_free(msg);out:
net/netfilter/ipvs/ip_vs_ctl.c +1
-1-mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();return ret; }Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 03/14] ipvs: some service readers can use RCU
In reply to Julian AnastasovHi Julian,
Comments below.
Quoted 19 lines · Julian Anastasov
Some places walk the services under mutex but they can just use RCU:
*
ip_vs_dst_event()usesip_vs_forget_dev()which uses its own lock to modify dest
*ip_vs_genl_dump_services():ip_vs_genl_fill_service()just fills skb
*ip_vs_genl_parse_service(): move RCU lock to callersip_vs_genl_set_cmd(),ip_vs_genl_dump_dests()andip_vs_genl_get_cmd()
*ip_vs_genl_dump_dests(): just fill skbSigned-off-by Julian Anastasov <[email protected]>--- net/netfilter/ipvs/ip_vs_ctl.c | 47 +++++++++++++++++----------------- 1 file changed, 23 insertions(+), 24 deletions(-)net/netfilter/ipvs/ip_vs_ctl.c +0
-0
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_dst_event(struct notifier_block *this, unsigned long event, · line 1762
Quoted 5 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-1@@ -1759,23 +1759,21 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,if (event !=NETDEV_DOWN || !ipvs)return NOTIFY_DONE ;IP_VS_DBG (3 ,"%s() dev=%s\n" , __func__, dev->name); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();
Control plane can still add destinations to svc->destinations that can be skipped by the rcu walk. I think it should be possible to trigger leaks with a sufficiently large list, given concurrent updates can happen. ip_vs_forget_dev() has its own lock, but this is a per-dest lock which is taken during the list walk.
Quoted 40 lines
net/netfilter/ipvs/ip_vs_ctl.c +10
-12for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_table[idx], s_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[idx], s_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[idx], f_list) { -list_for_each_entry (dest, &svc->destinations, - n_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[idx], f_list) +list_for_each_entry_rcu (dest, &svc->destinations, + n_list)ip_vs_forget_dev (dest, dev); - } - } } +rcu_read_unlock (); +mutex_lock (&ipvs->service_mutex);spin_lock_bh (&ipvs->dest_trash_lock);list_for_each_entry (dest, &ipvs->dest_trash, t_list) {ip_vs_forget_dev (dest, dev);@@ -3318,9 +3316,9 @@ static int ip_vs_genl_fill_service(struct sk_buff *skb, goto nla_put_failure; } - sched =rcu_dereference_protected (svc->scheduler,1 ); + sched =rcu_dereference (svc->scheduler); sched_name = sched ? sched->name :"none" ; - pe =rcu_dereference_protected (svc->pe,1 ); + pe =rcu_dereference (svc->pe); if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) || (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) || nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_genl_dump_services(struct sk_buff *skb, · line 3375
Quoted 5 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-1@@ -3374,9 +3372,9 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();
Here I can see this is safe, because this is netlink path.
Quoted 66 lines
net/netfilter/ipvs/ip_vs_ctl.c +6
-8for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_table[i], s_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[i], s_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {@@ -3387,7 +3385,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, }for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[i], f_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[i], f_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) {@@ -3398,7 +3396,7 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, } nla_put_failure: -mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock (); cb->args[0 ] = idx;return skb->len;@@ -3454,13 +3452,11 @@ static int ip_vs_genl_parse_service(struct netns_ipvs *ipvs, usvc->fwmark =0 ; } -rcu_read_lock ();if (usvc->fwmark) svc =__ip_vs_svc_fwm_find (ipvs, usvc->af, usvc->fwmark);else svc =__ip_vs_service_find (ipvs, usvc->af, usvc->protocol, &usvc->addr, usvc->port); -rcu_read_unlock (); *ret_svc = svc;/* If a full entry was requested, check for the additional fields */ @@ -3587,7 +3583,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb,struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();/* Try to find the service for which to dump destinations */ if (nlmsg_parse_deprecated (cb->nlh,GENL_HDRLEN , attrs,IPVS_CMD_ATTR_MAX , ip_vs_cmd_policy, cb->extack))@@ -3599,7 +3595,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, goto out_err;/* Dump the destinations */ -list_for_each_entry (dest, &svc->destinations, n_list) { +list_for_each_entry_rcu (dest, &svc->destinations, n_list) {if (++idx <= start)continue ;if (ip_vs_genl_dump_dest (skb, dest, cb) <0 ) {@@ -3612,7 +3608,7 @@ static int ip_vs_genl_dump_dests(struct sk_buff *skb, cb->args[0 ] = idx; out_err: -mutex_unlock (&ipvs->service_mutex); +rcu_read_unlock ();return skb->len; }
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info) · line 3915
Quoted 5 lines
net/netfilter/ipvs/ip_vs_ctl.c +2
-0@@ -3915,9 +3911,12 @@ static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)if (cmd ==IPVS_CMD_NEW_SERVICE || cmd ==IPVS_CMD_SET_SERVICE ) need_full_svc = true; +/* We use function that requires RCU lock */ +rcu_read_lock ();
This is ip_vs_genl_set_cmd path and the new per-netns mutex is held.
I think __ip_vs_service_find() can now just access this mutex to check if it is held, using fourth parameter:
list_for_each_entry_rcu(..., lockdep_is_held(&ipvs->service_mutex))
Then this rcu_read_lock() after mutex_lock(&ipvs->service_mutex) can be removed. I suspect you added it to quiet a rcu debugging splat.
Quoted 7 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-0ret =ip_vs_genl_parse_service (ipvs, &usvc, info->attrs[IPVS_CMD_ATTR_SERVICE ], need_full_svc, &svc); +rcu_read_unlock ();if (ret) goto out;
Julian Anastasov
maintainerRe: [PATCHv6 net-next 03/14] ipvs: some service readers can use RCU
Hello,
Quoted 15 lines · Pablo Neira Ayuso
Quoted 14 lines · Julian Anastasov
Some places walk the services under mutex but they can just use RCU:
*
ip_vs_dst_event()usesip_vs_forget_dev()which uses its own lock to modify dest
*ip_vs_genl_dump_services():ip_vs_genl_fill_service()just fills skb
*ip_vs_genl_parse_service(): move RCU lock to callersip_vs_genl_set_cmd(),ip_vs_genl_dump_dests()andip_vs_genl_get_cmd()
*ip_vs_genl_dump_dests(): just fill skbSigned-off-by Julian Anastasov <[email protected]>--- net/netfilter/ipvs/ip_vs_ctl.c | 47 +++++++++++++++++----------------- 1 file changed, 23 insertions(+), 24 deletions(-)
Quoted 11 lines
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_dst_event(struct notifier_block *this, unsigned long event, · line 1762
Quoted 10 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-1@@ -1759,23 +1759,21 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,if (event !=NETDEV_DOWN || !ipvs)return NOTIFY_DONE ;IP_VS_DBG (3 ,"%s() dev=%s\n" , __func__, dev->name); -mutex_lock (&ipvs->service_mutex); +rcu_read_lock ();
First, thanks for the review!
Quoted 5 lines
Control plane can still add destinations to
svc->destinationsthat can be skipped by the rcu walk. I think it should be possible to trigger leaks with a sufficiently large list, given concurrent updates can happen.ip_vs_forget_dev()has its own lock, but this is a per-dest lock which is taken during the list walk.
Even if dest is added, its dest_dst will be allocated on
next packet. And this is not the real problem.
The race is different: the first flow
clears __LINK_STATE_START, IFF_UP and then notifies for NETDEV_DOWN ip_vs_dst_event() and then FIB. During ip_vs_dst_event() device is down but the routes are not dead yet. The second flow can call do_output_route4() and create again dest->dest_dst because the routes still work, see fib_lookup_good_nhc(). Even adding new dest can trigger this. It can happen even immediately after a mutex unlock in ip_vs_dst_event(). And the problem is that during the notification phase there is a gap where we can attach new routes while the device is marked down but it is not yet propagated to FIB.
As we hold implicit reference to dev via
dst, if due to race we miss to drop a route, the dev will be replaced with blackhole_netdev on NETDEV_UNREGISTER. So, the leak is until UNREGISTER or until next packet that will catch the dead route in __ip_vs_dst_check(). And if dest is deleted we always drop this route in __ip_vs_dst_cache_reset(), the leak is gone.
One way to make this rt caching more robust
is to add a netif_running() check together with the IP_VS_DEST_F_AVAILABLE check that is under dst_lock after the do_output_route4() call. By this way we synchronize with both dest deletion and device closing. I'll probably extend the patch with such change in the next days, including the same for IPv6:
net/netfilter/ipvs/ip_vs_xmit.c +8 -1
@@ -295,6 +295,12 @@ static inline bool decrement_ttl(struct netns_ipvs *ipvs,return true; } +/* rt has device that is down */ +static bool rt_dev_is_down (const struct net_device *dev) +{ +return dev && !netif_running (dev); +} +/* Get route to destination or remote server */ static int __ip_vs_get_out_rt(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb,
@@ -335,7 +341,8 @@ __ip_vs_get_out_rt(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb,* for very short period and it must be checked under * dst_lock. */ -if (dest->flags &IP_VS_DEST_F_AVAILABLE ) +if (dest->flags &IP_VS_DEST_F_AVAILABLE && + !rt_dev_is_down (rt->dst.dev))__ip_vs_dst_set (dest, dest_dst, &rt->dst,0 );else noref =0 ;
Quoted 9 lines
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info) · line 3915
Quoted 6 lines
net/netfilter/ipvs/ip_vs_ctl.c +2
-0@@ -3915,9 +3911,12 @@ static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)if (cmd ==IPVS_CMD_NEW_SERVICE || cmd ==IPVS_CMD_SET_SERVICE ) need_full_svc = true; +/* We use function that requires RCU lock */ +rcu_read_lock ();This is
ip_vs_genl_set_cmdpath and the new per-netns mutex is held.
Quoted 7 lines
I think
__ip_vs_service_find()can now just access this mutex to check if it is held, using fourth parameter:list_for_each_entry_rcu(..., lockdep_is_held(&ipvs->service_mutex))Then this
rcu_read_lock()aftermutex_lock(&ipvs->service_mutex)can be removed. I suspect you added it to quiet a rcu debugging splat.
Yep, that is why the above comment. I'll check this...
Regards
--
Julian Anastasov <[email protected]>
Julian Anastasov
maintainerPATCH v6 4/14 ipvs: use single svc table
In reply to Julian Anastasovfwmark based services and non-fwmark based services can be hashed in same service table. This reduces the burden of working with two tables.
--- include/net/ip_vs.h | 8 +- net/netfilter/ipvs/ip_vs_ctl.c | 146 +++++---------------------------- 2 files changed, 22 insertions(+), 132 deletions(-)
include/net/ip_vs.h +2 -6
@@ -679,8 +679,7 @@ struct ip_vs_dest_user_kern {* forwarding entries. */ struct ip_vs_service { -struct hlist_node s_list;/* for normal service table */ -struct hlist_node f_list;/* for fwmark-based service table */ +struct hlist_node s_list;/* node in service table */ atomic_t refcnt;/* reference counter */ u16 af;/* address family */
@@ -1050,10 +1049,7 @@ struct netns_ipvs {/* the service mutex that protect svc_table and svc_fwm_table */ struct mutex service_mutex; -/* the service table hashed by <protocol, addr, port> */ -struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ]; -/* the service table hashed by fwmark */ -struct hlist_head svc_fwm_table[IP_VS_SVC_TAB_SIZE ]; +struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ];/* Services */ };#define DEFAULT_SYNC_THRESHOLD 3
net/netfilter/ipvs/ip_vs_ctl.c +20 -126
282 lines not on this page · raw message
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 04/14] ipvs: use single svc table
Quoted 9 lines · Julian Anastasov
fwmark based services and non-fwmark based services can be hashed in same service table. This reduces the burden of working with two tables.
Signed-off-by Julian Anastasov <[email protected]>--- include/net/ip_vs.h | 8 +- net/netfilter/ipvs/ip_vs_ctl.c | 146 +++++---------------------------- 2 files changed, 22 insertions(+), 132 deletions(-)
This diffstat is nice. By reading the patch description, I am missing if this depends on the previous patches (1-3)? Or just a preparatory patch that can be applied right away?
Thanks.
Quoted 334 lines
include/net/ip_vs.h +2
-6@@ -679,8 +679,7 @@ struct ip_vs_dest_user_kern {* forwarding entries. */ struct ip_vs_service { -struct hlist_node s_list;/* for normal service table */ -struct hlist_node f_list;/* for fwmark-based service table */ +struct hlist_node s_list;/* node in service table */ atomic_t refcnt;/* reference counter */ u16 af;/* address family */ @@ -1050,10 +1049,7 @@ struct netns_ipvs {/* the service mutex that protect svc_table and svc_fwm_table */ struct mutex service_mutex; -/* the service table hashed by <protocol, addr, port> */ -struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ]; -/* the service table hashed by fwmark */ -struct hlist_head svc_fwm_table[IP_VS_SVC_TAB_SIZE ]; +struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ];/* Services */ };#define DEFAULT_SYNC_THRESHOLD 3net/netfilter/ipvs/ip_vs_ctl.c +20
-126@@ -329,7 +329,7 @@ static inline unsigned int ip_vs_svc_fwm_hashkey(struct netns_ipvs *ipvs, __u32/* * Hashes a service in the svc_table by <netns,proto,addr,port> -* or in the svc_fwm_table by fwmark. +* or by fwmark. * Should be called with locked tables. */ static int ip_vs_svc_hash (struct ip_vs_service *svc)@@ -344,18 +344,17 @@ static int ip_vs_svc_hash(struct ip_vs_service *svc)if (svc->fwmark ==0 ) {/* -* Hash it by <netns,protocol,addr,port> in svc_table +* Hash it by <netns,protocol,addr,port> */ hash =ip_vs_svc_hashkey (svc->ipvs, svc->af, svc->protocol, &svc->addr, svc->port); -hlist_add_head_rcu (&svc->s_list, &svc->ipvs->svc_table[hash]); }else {/* -* Hash it by fwmark in svc_fwm_table +* Hash it by fwmark */ hash =ip_vs_svc_fwm_hashkey (svc->ipvs, svc->fwmark); -hlist_add_head_rcu (&svc->f_list, &svc->ipvs->svc_fwm_table[hash]); } +hlist_add_head_rcu (&svc->s_list, &svc->ipvs->svc_table[hash]); svc->flags |=IP_VS_SVC_F_HASHED ;/* increase its refcnt because it is referenced by the svc table */ @@ -365,7 +364,7 @@ static int ip_vs_svc_hash(struct ip_vs_service *svc)/* -* Unhashes a service from svc_table / svc_fwm_table. +* Unhashes a service from svc_table. * Should be called with locked tables. */ static int ip_vs_svc_unhash (struct ip_vs_service *svc)@@ -376,13 +375,8 @@ static int ip_vs_svc_unhash(struct ip_vs_service *svc)return 0 ; } -if (svc->fwmark ==0 ) { -/* Remove it from the svc_table table */ -hlist_del_rcu (&svc->s_list); - }else { -/* Remove it from the svc_fwm_table table */ -hlist_del_rcu (&svc->f_list); - } +/* Remove it from svc_table */ +hlist_del_rcu (&svc->s_list); svc->flags &= ~IP_VS_SVC_F_HASHED ;atomic_dec (&svc->refcnt);@@ -405,7 +399,8 @@ __ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u16 protocol,hlist_for_each_entry_rcu (svc, &ipvs->svc_table[hash], s_list) {if (svc->af == af &&ip_vs_addr_equal (af, &svc->addr, vaddr) && - svc->port == vport && svc->protocol == protocol) { + svc->port == vport && svc->protocol == protocol && + !svc->fwmark) {/* HIT */ return svc; }@@ -427,7 +422,7 @@ __ip_vs_svc_fwm_find(struct netns_ipvs *ipvs, int af, __u32 fwmark)/* Check for fwmark addressed entries */ hash =ip_vs_svc_fwm_hashkey (ipvs, fwmark); -hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[hash], f_list) { +hlist_for_each_entry_rcu (svc, &ipvs->svc_table[hash], s_list) {if (svc->fwmark == fwmark && svc->af == af) {/* HIT */ return svc;@@ -1683,26 +1678,11 @@ static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup)struct ip_vs_service *svc;struct hlist_node *n; -/* -* Flush the service table hashed by <netns,protocol,addr,port> -*/ for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) {hlist_for_each_entry_safe (svc, n, &ipvs->svc_table[idx], - s_list) { + s_list)ip_vs_unlink_service (svc, cleanup); - } } - -/* -* Flush the service table hashed by fwmark -*/ -for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry_safe (svc, n, &ipvs->svc_fwm_table[idx], - f_list) { -ip_vs_unlink_service (svc, cleanup); - } - } -return 0 ; }@@ -1765,11 +1745,6 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,list_for_each_entry_rcu (dest, &svc->destinations, n_list)ip_vs_forget_dev (dest, dev); - -hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[idx], f_list) -list_for_each_entry_rcu (dest, &svc->destinations, - n_list) -ip_vs_forget_dev (dest, dev); }rcu_read_unlock ();@@ -1803,15 +1778,8 @@ static int ip_vs_zero_all(struct netns_ipvs *ipvs)struct ip_vs_service *svc;for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_table[idx], s_list) { +hlist_for_each_entry (svc, &ipvs->svc_table[idx], s_list)ip_vs_zero_service (svc); - } - } - -for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[idx], f_list) { -ip_vs_zero_service (svc); - } }ip_vs_zero_stats (&ipvs->tot_stats->s);@@ -2247,7 +2215,6 @@ static struct ctl_table vs_vars[] = {struct ip_vs_iter {struct seq_net_private p;/* Do not move this, netns depends upon it*/ -struct hlist_head *table;int bucket; };@@ -2270,7 +2237,6 @@ static inline const char *ip_vs_fwd_name(unsigned int flags) } -/* Get the Nth entry in the two lists */ static struct ip_vs_service *ip_vs_info_array (struct seq_file *seq,loff_t pos) {struct net *net =seq_file_net (seq);@@ -2279,29 +2245,14 @@ static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)int idx;struct ip_vs_service *svc; -/* look in hash by protocol */ for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) {hlist_for_each_entry_rcu (svc, &ipvs->svc_table[idx], s_list) {if (pos-- ==0 ) { - iter->table = ipvs->svc_table; - iter->bucket = idx; -return svc; - } - } - } - -/* keep looking in fwmark */ -for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[idx], - f_list) { -if (pos-- ==0 ) { - iter->table = ipvs->svc_fwm_table; iter->bucket = idx;return svc; } } } -return NULL ; }@@ -2328,38 +2279,17 @@ static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos) svc = v; iter = seq->private; -if (iter->table == ipvs->svc_table) { -/* next service in table hashed by protocol */ - e =rcu_dereference (hlist_next_rcu (&svc->s_list)); -if (e) - return hlist_entry(e, struct ip_vs_service, s_list); - -while (++iter->bucket <IP_VS_SVC_TAB_SIZE ) { -hlist_for_each_entry_rcu (svc, - &ipvs->svc_table[iter->bucket], - s_list) { -return svc; - } - } - - iter->table = ipvs->svc_fwm_table; - iter->bucket =-1 ; - goto scan_fwmark; - } - -/* next service in hashed by fwmark */ - e =rcu_dereference (hlist_next_rcu (&svc->f_list)); + e =rcu_dereference (hlist_next_rcu (&svc->s_list));if (e) - return hlist_entry(e, struct ip_vs_service, f_list); + return hlist_entry(e, struct ip_vs_service, s_list); - scan_fwmark:while (++iter->bucket <IP_VS_SVC_TAB_SIZE ) {hlist_for_each_entry_rcu (svc, - &ipvs->svc_fwm_table[iter->bucket], - f_list) + &ipvs->svc_table[iter->bucket], + s_list) {return svc; + } } -return NULL ; }@@ -2381,17 +2311,12 @@ static int ip_vs_info_seq_show(struct seq_file *seq, void *v)seq_puts (seq," -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n" ); }else { -struct net *net =seq_file_net (seq); -struct netns_ipvs *ipvs =net_ipvs (net);const struct ip_vs_service *svc = v; -const struct ip_vs_iter *iter = seq->private;const struct ip_vs_dest *dest;struct ip_vs_scheduler *sched =rcu_dereference (svc->scheduler);char *sched_name = sched ? sched->name :"none" ; -if (svc->ipvs != ipvs) -return 0 ; -if (iter->table == ipvs->svc_table) { +if (!svc->fwmark) {#ifdef CONFIG_IP_VS_IPV6 if (svc->af ==AF_INET6 ) seq_printf(seq, "%s [%pI6]:%04X %s ",@@ -2866,24 +2791,6 @@ __ip_vs_get_service_entries(struct netns_ipvs *ipvs, } } -for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { -hlist_for_each_entry (svc, &ipvs->svc_fwm_table[idx], f_list) { -/* Only expose IPv4 entries to old interface */ -if (svc->af !=AF_INET ) -continue ; - -if (count >= get->num_services) - goto out; -memset (&entry,0 ,sizeof (entry)); -ip_vs_copy_service (&entry, svc); -if (copy_to_user (&uptr->entrytable[count], - &entry,sizeof (entry))) { - ret = -EFAULT ; - goto out; - } - count++; - } - } out:return ret; }@@ -3384,17 +3291,6 @@ static int ip_vs_genl_dump_services(struct sk_buff *skb, } } -for (i =0 ; i <IP_VS_SVC_TAB_SIZE ; i++) { -hlist_for_each_entry_rcu (svc, &ipvs->svc_fwm_table[i], f_list) { -if (++idx <= start) -continue ; -if (ip_vs_genl_dump_service (skb, svc, cb) <0 ) { - idx--; - goto nla_put_failure; - } - } - } - nla_put_failure:rcu_read_unlock (); cb->args[0 ] = idx;@@ -4404,12 +4300,10 @@ int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs)int ret = -ENOMEM ;int idx; -/* Initialize service_mutex, svc_table, svc_fwm_table per netns */ +/* Initialize service_mutex, svc_table per netns */ __mutex_init (&ipvs->service_mutex,"ipvs->service_mutex" , &__ipvs_service_key); -for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++) { +for (idx =0 ; idx <IP_VS_SVC_TAB_SIZE ; idx++)INIT_HLIST_HEAD (&ipvs->svc_table[idx]); -INIT_HLIST_HEAD (&ipvs->svc_fwm_table[idx]); - }/* Initialize rs_table */ for (idx =0 ; idx <IP_VS_RTAB_SIZE ; idx++)Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 5/14 ipvs: do not keep dest_dst after dest is removed
In reply to Julian AnastasovBefore now dest->dest_dst is not released when server is moved into dest_trash list after removal. As result, we can keep dst/dev references for long time without actively using them.
It is better to avoid walking the dest_trash list when ip_vs_dst_event() receives dev events. So, make sure we do not hold dev references in dest_trash list. As packets can be flying while server is being removed, check the IP_VS_DEST_F_AVAILABLE flag in slow path to ensure we do not save new dev references to removed servers.
--- net/netfilter/ipvs/ip_vs_ctl.c | 20 +++++++---------- net/netfilter/ipvs/ip_vs_xmit.c | 39 ++++++++++++++++++++++++--------- 2 files changed, 37 insertions(+), 22 deletions(-)
net/netfilter/ipvs/ip_vs_ctl.c +8 -12
@@ -810,7 +810,6 @@ static void ip_vs_dest_free(struct ip_vs_dest *dest) {struct ip_vs_service *svc =rcu_dereference_protected (dest->svc,1 ); -__ip_vs_dst_cache_reset (dest);__ip_vs_svc_put (svc);call_rcu (&dest->rcu_head, ip_vs_dest_rcu_free); }
@@ -1013,10 +1012,6 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, dest->af = udest->af; -spin_lock_bh (&dest->dst_lock); -__ip_vs_dst_cache_reset (dest); -spin_unlock_bh (&dest->dst_lock); -if (add) {list_add_rcu (&dest->n_list, &svc->destinations); svc->num_dests++;
@@ -1024,6 +1019,10 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,if (sched && sched->add_dest) sched->add_dest (svc, dest); }else { +spin_lock_bh (&dest->dst_lock); +__ip_vs_dst_cache_reset (dest); +spin_unlock_bh (&dest->dst_lock); + sched =rcu_dereference_protected (svc->scheduler,1 );if (sched && sched->upd_dest) sched->upd_dest (svc, dest);
@@ -1258,6 +1257,10 @@ static void __ip_vs_unlink_dest(struct ip_vs_service *svc, { dest->flags &= ~IP_VS_DEST_F_AVAILABLE ; +spin_lock_bh (&dest->dst_lock); +__ip_vs_dst_cache_reset (dest); +spin_unlock_bh (&dest->dst_lock); +/* * Remove it from the d-linked destination list. */
@@ -1748,13 +1751,6 @@ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event, }rcu_read_unlock (); -mutex_lock (&ipvs->service_mutex); -spin_lock_bh (&ipvs->dest_trash_lock); -list_for_each_entry (dest, &ipvs->dest_trash, t_list) { -ip_vs_forget_dev (dest, dev); - } -spin_unlock_bh (&ipvs->dest_trash_lock); -mutex_unlock (&ipvs->service_mutex);return NOTIFY_DONE ; }
net/netfilter/ipvs/ip_vs_xmit.c +29 -10
@@ -310,9 +310,11 @@ __ip_vs_get_out_rt(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb,if (dest) { dest_dst =__ip_vs_dst_check (dest); -if (likely (dest_dst)) +if (likely (dest_dst)) { rt =dst_rtable (dest_dst->dst_cache); -else { +if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.ip; + }else { dest_dst =ip_vs_dest_dst_alloc ();spin_lock_bh (&dest->dst_lock);if (!dest_dst) {
@@ -328,14 +330,24 @@ __ip_vs_get_out_rt(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb,ip_vs_dest_dst_free (dest_dst); goto err_unreach; } -__ip_vs_dst_set (dest, dest_dst, &rt->dst,0 ); +/* It is forbidden to attach dest->dest_dst if +* server is deleted. We can see the flag going down, +* for very short period and it must be checked under +* dst_lock. +*/ +if (dest->flags &IP_VS_DEST_F_AVAILABLE ) +__ip_vs_dst_set (dest, dest_dst, &rt->dst,0 ); +else + noref =0 ;spin_unlock_bh (&dest->dst_lock);IP_VS_DBG (10 ,"new dst %pI4, src %pI4, refcnt=%d\n" , &dest->addr.ip, &dest_dst->dst_saddr.ip,rcuref_read (&rt->dst.__rcuref)); +if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.ip; +if (!noref) +ip_vs_dest_dst_free (dest_dst); } -if (ret_saddr) - *ret_saddr = dest_dst->dst_saddr.ip; }else { noref =0 ;
@@ -469,9 +481,11 @@ __ip_vs_get_out_rt_v6(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb,if (dest) { dest_dst =__ip_vs_dst_check (dest); -if (likely (dest_dst)) +if (likely (dest_dst)) { rt =dst_rt6_info (dest_dst->dst_cache); -else { +if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.in6; + }else {u32 cookie; dest_dst =ip_vs_dest_dst_alloc ();
@@ -492,14 +506,19 @@ __ip_vs_get_out_rt_v6(struct netns_ipvs *ipvs, int skb_af, struct sk_buff *skb, } rt =dst_rt6_info (dst); cookie =rt6_get_cookie (rt); -__ip_vs_dst_set (dest, dest_dst, &rt->dst, cookie); +if (dest->flags &IP_VS_DEST_F_AVAILABLE ) +__ip_vs_dst_set (dest, dest_dst, &rt->dst, cookie); +else + noref =0 ;spin_unlock_bh (&dest->dst_lock);IP_VS_DBG (10 ,"new dst %pI6, src %pI6, refcnt=%d\n" , &dest->addr.in6, &dest_dst->dst_saddr.in6,rcuref_read (&rt->dst.__rcuref)); +if (ret_saddr) + *ret_saddr = dest_dst->dst_saddr.in6; +if (!noref) +ip_vs_dest_dst_free (dest_dst); } -if (ret_saddr) - *ret_saddr = dest_dst->dst_saddr.in6; }else { noref =0 ; dst = __ip_vs_route_output_v6(net, daddr, ret_saddr, do_xfrm,
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 6/14 ipvs: use more counters to avoid service lookups
In reply to Julian AnastasovWhen new connection is created we can lookup for services multiple times to support fallback options. We already have some counters to skip specific lookups because it costs CPU cycles for hash calculation, etc.
Add more counters for fwmark/non-fwmark services (fwm_services and nonfwm_services) and make all counters per address family.
--- include/net/ip_vs.h | 24 ++++++--- net/netfilter/ipvs/ip_vs_core.c | 2 +- net/netfilter/ipvs/ip_vs_ctl.c | 86 +++++++++++++++++++-------------- 3 files changed, 69 insertions(+), 43 deletions(-)
include/net/ip_vs.h +18 -6
@@ -271,6 +271,18 @@ static inline const char *ip_vs_dbg_addr(int af, char *buf, size_t buf_len, pr_err(msg, ##__VA_ARGS__); \ }while (0 ) +/* For arrays per family */ +enum { +IP_VS_AF_INET , +IP_VS_AF_INET6 , + IP_VS_AF_MAX +}; + +static inline int ip_vs_af_index (int af) +{ +return af ==AF_INET6 ?IP_VS_AF_INET6 :IP_VS_AF_INET ; +} +/* The port number of FTP service (in network order). */ #define FTPPORT cpu_to_be16(21)#define FTPDATA cpu_to_be16(20)
@@ -940,17 +952,17 @@ struct netns_ipvs {/* ip_vs_ctl */ struct ip_vs_stats_rcu *tot_stats;/* Statistics & est. */ -int num_services;/* no of virtual services */ -int num_services6;/* IPv6 virtual services */ -/* Trash for destinations */ struct list_head dest_trash;spinlock_t dest_trash_lock;struct timer_list dest_trash_timer;/* expiration timer */ /* Service counters */ -atomic_t ftpsvc_counter; -atomic_t nullsvc_counter; -atomic_t conn_out_counter; +atomic_t num_services[IP_VS_AF_MAX ];/* Services */ +atomic_t fwm_services[IP_VS_AF_MAX ];/* Services */ +atomic_t nonfwm_services[IP_VS_AF_MAX ];/* Services */ +atomic_t ftpsvc_counter[IP_VS_AF_MAX ];/* FTPPORT */ +atomic_t nullsvc_counter[IP_VS_AF_MAX ];/* Zero port */ +atomic_t conn_out_counter[IP_VS_AF_MAX ];/* out conn */ #ifdef CONFIG_SYSCTL /* delayed work for expiring no dest connections */
net/netfilter/ipvs/ip_vs_core.c +1 -1
@@ -1401,7 +1401,7 @@ ip_vs_out_hook(void *priv, struct sk_buff *skb, const struct nf_hook_state *statreturn handle_response (af, skb, pd, cp, &iph, hooknum);/* Check for real-server-started requests */ -if (atomic_read (&ipvs->conn_out_counter)) { +if (atomic_read (&ipvs->conn_out_counter[ip_vs_af_index (af)])) {/* Currently only for UDP: * connection oriented protocols typically use * ephemeral ports for outgoing connections, so
net/netfilter/ipvs/ip_vs_ctl.c +50 -36
183 lines not on this page · raw message
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 7/14 ipvs: add resizable hash tables
In reply to Julian AnastasovAdd infrastructure for resizable hash tables based on hlist_bl which we will use in followup patches.
The tables allow RCU lookups during resizing, bucket modifications are protected with per-bucket bit lock and additional custom locking, the tables are resized when load reaches thresholds determined based on load factor parameter.
--- include/net/ip_vs.h | 197 ++++++++++++++++++++++++++++++++ net/netfilter/ipvs/ip_vs_conn.c | 5 - net/netfilter/ipvs/ip_vs_core.c | 175 ++++++++++++++++++++++++++++ 3 files changed, 372 insertions(+), 5 deletions(-)
include/net/ip_vs.h +197 -0
@@ -11,6 +11,7 @@#include <asm/types.h> /* for __uXX types */ #include <linux/list.h> /* for struct list_head */ +#include <linux/rculist_bl.h> /* for struct hlist_bl_head */ #include <linux/spinlock.h> /* for struct rwlock_t */ #include <linux/atomic.h> /* for struct atomic_t */ #include <linux/refcount.h> /* for struct refcount_t */
@@ -30,6 +31,7 @@#endif #include <net/net_namespace.h> /* Netw namespace */ #include <linux/sched/isolation.h> +#include <linux/siphash.h> #define IP_VS_HDR_INVERSE 1#define IP_VS_HDR_ICMP 2
@@ -271,6 +273,10 @@ static inline const char *ip_vs_dbg_addr(int af, char *buf, size_t buf_len, pr_err(msg, ##__VA_ARGS__); \ }while (0 ) +struct ip_vs_aligned_lock { +spinlock_t l;/* Protect buckets */ +}____cacheline_aligned_in_smp ; +/* For arrays per family */ enum {IP_VS_AF_INET ,
@@ -484,6 +490,197 @@ struct ip_vs_est_kt_data {int est_row;/* estimated row */ }; +/* IPVS resizable hash tables */ +struct ip_vs_rht { +struct hlist_bl_head *buckets; +struct ip_vs_rht __rcu *new_tbl;/* New/Same table */ +seqcount_t *seqc;/* Protects moves */ +struct ip_vs_aligned_lock *lock;/* Protect seqc */ +int mask;/* Buckets mask */ +int size;/* Buckets */ +int seqc_mask;/* seqc mask */ +int lock_mask;/* lock mask */ +u32 table_id; +int u_thresh;/* upper threshold */ +int l_thresh;/* lower threshold */ +int lfactor;/* Load Factor (shift)*/ +int bits;/* size = 1 << bits */ +siphash_key_t hash_key; +struct rcu_head rcu_head; +}; + +/** +* ip_vs_rht_for_each_table() - Walk the hash tables +* @table: struct ip_vs_rht __rcu *table +* @t: current table, used as cursor, struct ip_vs_rht *var +* @p: previous table, temp struct ip_vs_rht *var +* +* Walk tables assuming others can not change the installed tables +*/ +#define ip_vs_rht_for_each_table (table, t, p) \ + for (p = NULL, t = rcu_dereference_protected(table, 1); \ + t != p; \ + p = t, t = rcu_dereference_protected(t->new_tbl, 1)) + +/** +* ip_vs_rht_for_each_table_rcu() - Walk the hash tables under RCU reader lock +* @table: struct ip_vs_rht __rcu *table +* @t: current table, used as cursor, struct ip_vs_rht *var +* @p: previous table, temp struct ip_vs_rht *var +* +* We usually search in one table and also in second table on resizing +*/ +#define ip_vs_rht_for_each_table_rcu (table, t, p) \ + for (p = NULL, t = rcu_dereference(table); \ + t != p; \ + p = t, t = rcu_dereference(t->new_tbl)) + +/** +* ip_vs_rht_for_each_bucket() - Walk all table buckets +* @t: current table, used as cursor, struct ip_vs_rht *var +* @bucket: bucket index, used as cursor, u32 var +* @head: bucket address, used as cursor, struct hlist_bl_head *var +*/ +#define ip_vs_rht_for_each_bucket (t, bucket, head) \ + for (bucket = 0, head = (t)->buckets; \ + bucket < t->size; bucket++, head++) + +/** +* ip_vs_rht_for_bucket_retry() - Retry bucket if entries are moved +* @t: current table, used as cursor, struct ip_vs_rht *var +* @bucket: index of current bucket or hash key +* @sc: temp seqcount_t *var +* @retry: temp int var +*/ +#define ip_vs_rht_for_bucket_retry (t, bucket, sc, seq, retry) \ + for (retry = 1, sc = &(t)->seqc[(bucket) & (t)->seqc_mask]; \ + retry && ({ seq = read_seqcount_begin(sc); 1; }); \ + retry = read_seqcount_retry(sc, seq)) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS_RCU () \ + struct ip_vs_rht *_t, *_p; \ + unsigned int _seq; \ + seqcount_t *_sc; \ + u32 _bucket; \ + int _retry +/** +* ip_vs_rht_walk_buckets_rcu() - Walk all buckets under RCU read lock +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete/move entries +* Not suitable if duplicates are not desired +* Possible cases for reader that uses cond_resched_rcu() in the loop: +* - new table can not be installed, no need to repeat +* - new table can be installed => check and repeat if new table is +* installed, needed for !PREEMPT_RCU +*/ +#define ip_vs_rht_walk_buckets_rcu (table, head) \ + ip_vs_rht_for_each_table_rcu(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) \ + ip_vs_rht_for_bucket_retry(_t, _bucket, _sc, \ + _seq, _retry) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKET_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_bucket_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKET_RCU () \ + unsigned int _seq; \ + seqcount_t *_sc; \ + int _retry +/** +* ip_vs_rht_walk_bucket_rcu() - Walk bucket under RCU read lock +* @t: current table, struct ip_vs_rht *var +* @bucket: index of current bucket or hash key +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete/move entries +* Not suitable if duplicates are not desired +* Possible cases for reader that uses cond_resched_rcu() in the loop: +* - new table can not be installed, no need to repeat +* - new table can be installed => check and repeat if new table is +* installed, needed for !PREEMPT_RCU +*/ +#define ip_vs_rht_walk_bucket_rcu (t, bucket, head) \ + if (({ head = (t)->buckets + ((bucket) & (t)->mask); 0; })) \ + {} \ + else \ + ip_vs_rht_for_bucket_retry(t, (bucket), _sc, _seq, _retry) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS_SAFE_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets_safe_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS_SAFE_RCU () \ + struct ip_vs_rht *_t, *_p; \ + u32 _bucket +/** +* ip_vs_rht_walk_buckets_safe_rcu() - Walk all buckets under RCU read lock +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete entries but moving is disabled +* Using cond_resched_rcu() should be safe if tables do not change +*/ +#define ip_vs_rht_walk_buckets_safe_rcu (table, head) \ + ip_vs_rht_for_each_table_rcu(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS () \ + struct ip_vs_rht *_t, *_p; \ + u32 _bucket + +/** +* ip_vs_rht_walk_buckets() - Walk all buckets +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Use if others can not add/delete/move entries +*/ +#define ip_vs_rht_walk_buckets (table, head) \ + ip_vs_rht_for_each_table(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) + +/* Entries can be in one of two tables, so we flip bit when new table is +* created and store it as highest bit in hash keys +*/ +#define IP_VS_RHT_TABLE_ID_MASK BIT(31) + +/* Check if hash key is from this table */ +static inline bool ip_vs_rht_same_table (struct ip_vs_rht *t,u32 hash_key) +{ +return !((t->table_id ^ hash_key) &IP_VS_RHT_TABLE_ID_MASK ); +} + +/* Build per-table hash key from hash value */ +static inline u32 ip_vs_rht_build_hash_key (struct ip_vs_rht *t,u32 hash) +{ +return t->table_id | (hash & ~IP_VS_RHT_TABLE_ID_MASK ); +} + +void ip_vs_rht_free (struct ip_vs_rht *t); +void ip_vs_rht_rcu_free (struct rcu_head *head); +struct ip_vs_rht *ip_vs_rht_alloc (int buckets,int scounts,int locks); +int ip_vs_rht_desired_size (struct netns_ipvs *ipvs,struct ip_vs_rht *t,int n, +int lfactor,int min_bits,int max_bits); +void ip_vs_rht_set_thresholds (struct ip_vs_rht *t,int size,int lfactor, +int min_bits,int max_bits); +u32 ip_vs_rht_hash_linfo (struct ip_vs_rht *t,int af, +const union nf_inet_addr *addr,u32 v1,u32 v2); +struct dst_entry ;struct iphdr ;struct ip_vs_conn ;
net/netfilter/ipvs/ip_vs_conn.c +0 -5
@@ -80,11 +80,6 @@ static unsigned int ip_vs_conn_rnd __read_mostly;#define IP_VS_ADDRSTRLEN (8+1)#endif -struct ip_vs_aligned_lock -{ -spinlock_t l; -} __attribute__((__aligned__ (SMP_CACHE_BYTES ))); -/* lock array for conn table */ static struct ip_vs_aligned_lock __ip_vs_conntbl_lock_array[CT_LOCKARRAY_SIZE] __cacheline_aligned;
net/netfilter/ipvs/ip_vs_core.c +175 -0
181 lines not on this page · raw message
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 07/14] ipvs: add resizable hash tables
Quoted 7 lines · Julian Anastasov
Add infrastructure for resizable hash tables based on
hlist_blwhich we will use in followup patches.The tables allow RCU lookups during resizing, bucket modifications are protected with per-bucket bit lock and additional custom locking, the tables are resized when load reaches thresholds determined based on load factor parameter.
I understand the generic rhashtable implementation cannot be used in this case, but I am missing the reason why (comparison?).
Quoted 443 lines
Signed-off-by Julian Anastasov <[email protected]>--- include/net/ip_vs.h | 197 ++++++++++++++++++++++++++++++++ net/netfilter/ipvs/ip_vs_conn.c | 5 - net/netfilter/ipvs/ip_vs_core.c | 175 ++++++++++++++++++++++++++++ 3 files changed, 372 insertions(+), 5 deletions(-)include/net/ip_vs.h +197
-0@@ -11,6 +11,7 @@#include <asm/types.h> /* for __uXX types */ #include <linux/list.h> /* for struct list_head */ +#include <linux/rculist_bl.h> /* for struct hlist_bl_head */ #include <linux/spinlock.h> /* for struct rwlock_t */ #include <linux/atomic.h> /* for struct atomic_t */ #include <linux/refcount.h> /* for struct refcount_t */ @@ -30,6 +31,7 @@#endif #include <net/net_namespace.h> /* Netw namespace */ #include <linux/sched/isolation.h> +#include <linux/siphash.h> #define IP_VS_HDR_INVERSE 1#define IP_VS_HDR_ICMP 2@@ -271,6 +273,10 @@ static inline const char *ip_vs_dbg_addr(int af, char *buf, size_t buf_len, pr_err(msg, ##__VA_ARGS__); \ }while (0 ) +struct ip_vs_aligned_lock { +spinlock_t l;/* Protect buckets */ +}____cacheline_aligned_in_smp ; +/* For arrays per family */ enum {IP_VS_AF_INET ,@@ -484,6 +490,197 @@ struct ip_vs_est_kt_data {int est_row;/* estimated row */ }; +/* IPVS resizable hash tables */ +struct ip_vs_rht { +struct hlist_bl_head *buckets; +struct ip_vs_rht __rcu *new_tbl;/* New/Same table */ +seqcount_t *seqc;/* Protects moves */ +struct ip_vs_aligned_lock *lock;/* Protect seqc */ +int mask;/* Buckets mask */ +int size;/* Buckets */ +int seqc_mask;/* seqc mask */ +int lock_mask;/* lock mask */ +u32 table_id; +int u_thresh;/* upper threshold */ +int l_thresh;/* lower threshold */ +int lfactor;/* Load Factor (shift)*/ +int bits;/* size = 1 << bits */ +siphash_key_t hash_key; +struct rcu_head rcu_head; +}; + +/** +* ip_vs_rht_for_each_table() - Walk the hash tables +* @table: struct ip_vs_rht __rcu *table +* @t: current table, used as cursor, struct ip_vs_rht *var +* @p: previous table, temp struct ip_vs_rht *var +* +* Walk tables assuming others can not change the installed tables +*/ +#define ip_vs_rht_for_each_table (table, t, p) \ + for (p = NULL, t = rcu_dereference_protected(table, 1); \ + t != p; \ + p = t, t = rcu_dereference_protected(t->new_tbl, 1)) + +/** +* ip_vs_rht_for_each_table_rcu() - Walk the hash tables under RCU reader lock +* @table: struct ip_vs_rht __rcu *table +* @t: current table, used as cursor, struct ip_vs_rht *var +* @p: previous table, temp struct ip_vs_rht *var +* +* We usually search in one table and also in second table on resizing +*/ +#define ip_vs_rht_for_each_table_rcu (table, t, p) \ + for (p = NULL, t = rcu_dereference(table); \ + t != p; \ + p = t, t = rcu_dereference(t->new_tbl)) + +/** +* ip_vs_rht_for_each_bucket() - Walk all table buckets +* @t: current table, used as cursor, struct ip_vs_rht *var +* @bucket: bucket index, used as cursor, u32 var +* @head: bucket address, used as cursor, struct hlist_bl_head *var +*/ +#define ip_vs_rht_for_each_bucket (t, bucket, head) \ + for (bucket = 0, head = (t)->buckets; \ + bucket < t->size; bucket++, head++) + +/** +* ip_vs_rht_for_bucket_retry() - Retry bucket if entries are moved +* @t: current table, used as cursor, struct ip_vs_rht *var +* @bucket: index of current bucket or hash key +* @sc: temp seqcount_t *var +* @retry: temp int var +*/ +#define ip_vs_rht_for_bucket_retry (t, bucket, sc, seq, retry) \ + for (retry = 1, sc = &(t)->seqc[(bucket) & (t)->seqc_mask]; \ + retry && ({ seq = read_seqcount_begin(sc); 1; }); \ + retry = read_seqcount_retry(sc, seq)) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS_RCU () \ + struct ip_vs_rht *_t, *_p; \ + unsigned int _seq; \ + seqcount_t *_sc; \ + u32 _bucket; \ + int _retry +/** +* ip_vs_rht_walk_buckets_rcu() - Walk all buckets under RCU read lock +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete/move entries +* Not suitable if duplicates are not desired +* Possible cases for reader that uses cond_resched_rcu() in the loop: +* - new table can not be installed, no need to repeat +* - new table can be installed => check and repeat if new table is +* installed, needed for !PREEMPT_RCU +*/ +#define ip_vs_rht_walk_buckets_rcu (table, head) \ + ip_vs_rht_for_each_table_rcu(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) \ + ip_vs_rht_for_bucket_retry(_t, _bucket, _sc, \ + _seq, _retry) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKET_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_bucket_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKET_RCU () \ + unsigned int _seq; \ + seqcount_t *_sc; \ + int _retry +/** +* ip_vs_rht_walk_bucket_rcu() - Walk bucket under RCU read lock +* @t: current table, struct ip_vs_rht *var +* @bucket: index of current bucket or hash key +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete/move entries +* Not suitable if duplicates are not desired +* Possible cases for reader that uses cond_resched_rcu() in the loop: +* - new table can not be installed, no need to repeat +* - new table can be installed => check and repeat if new table is +* installed, needed for !PREEMPT_RCU +*/ +#define ip_vs_rht_walk_bucket_rcu (t, bucket, head) \ + if (({ head = (t)->buckets + ((bucket) & (t)->mask); 0; })) \ + {} \ + else \ + ip_vs_rht_for_bucket_retry(t, (bucket), _sc, _seq, _retry) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS_SAFE_RCU() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets_safe_rcu +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS_SAFE_RCU () \ + struct ip_vs_rht *_t, *_p; \ + u32 _bucket +/** +* ip_vs_rht_walk_buckets_safe_rcu() - Walk all buckets under RCU read lock +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Can be used while others add/delete entries but moving is disabled +* Using cond_resched_rcu() should be safe if tables do not change +*/ +#define ip_vs_rht_walk_buckets_safe_rcu (table, head) \ + ip_vs_rht_for_each_table_rcu(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) + +/** +* DECLARE_IP_VS_RHT_WALK_BUCKETS() - Declare variables +* +* Variables for ip_vs_rht_walk_buckets +*/ +#define DECLARE_IP_VS_RHT_WALK_BUCKETS () \ + struct ip_vs_rht *_t, *_p; \ + u32 _bucket + +/** +* ip_vs_rht_walk_buckets() - Walk all buckets +* @table: struct ip_vs_rht __rcu *table +* @head: bucket address, used as cursor, struct hlist_bl_head *var +* +* Use if others can not add/delete/move entries +*/ +#define ip_vs_rht_walk_buckets (table, head) \ + ip_vs_rht_for_each_table(table, _t, _p) \ + ip_vs_rht_for_each_bucket(_t, _bucket, head) + +/* Entries can be in one of two tables, so we flip bit when new table is +* created and store it as highest bit in hash keys +*/ +#define IP_VS_RHT_TABLE_ID_MASK BIT(31) + +/* Check if hash key is from this table */ +static inline bool ip_vs_rht_same_table (struct ip_vs_rht *t,u32 hash_key) +{ +return !((t->table_id ^ hash_key) &IP_VS_RHT_TABLE_ID_MASK ); +} + +/* Build per-table hash key from hash value */ +static inline u32 ip_vs_rht_build_hash_key (struct ip_vs_rht *t,u32 hash) +{ +return t->table_id | (hash & ~IP_VS_RHT_TABLE_ID_MASK ); +} + +void ip_vs_rht_free (struct ip_vs_rht *t); +void ip_vs_rht_rcu_free (struct rcu_head *head); +struct ip_vs_rht *ip_vs_rht_alloc (int buckets,int scounts,int locks); +int ip_vs_rht_desired_size (struct netns_ipvs *ipvs,struct ip_vs_rht *t,int n, +int lfactor,int min_bits,int max_bits); +void ip_vs_rht_set_thresholds (struct ip_vs_rht *t,int size,int lfactor, +int min_bits,int max_bits); +u32 ip_vs_rht_hash_linfo (struct ip_vs_rht *t,int af, +const union nf_inet_addr *addr,u32 v1,u32 v2); +struct dst_entry ;struct iphdr ;struct ip_vs_conn ;net/netfilter/ipvs/ip_vs_conn.c +0
-5@@ -80,11 +80,6 @@ static unsigned int ip_vs_conn_rnd __read_mostly;#define IP_VS_ADDRSTRLEN (8+1)#endif -struct ip_vs_aligned_lock -{ -spinlock_t l; -} __attribute__((__aligned__ (SMP_CACHE_BYTES ))); -/* lock array for conn table */ static struct ip_vs_aligned_lock __ip_vs_conntbl_lock_array[CT_LOCKARRAY_SIZE] __cacheline_aligned;net/netfilter/ipvs/ip_vs_core.c +175
-0@@ -118,6 +118,181 @@ void ip_vs_init_hash_table(struct list_head *table, int rows)INIT_LIST_HEAD (&table[rows]); } +/* IPVS Resizable Hash Tables: +* - list_bl buckets with bit lock +* +* Goals: +* - RCU lookup for entry can run in parallel with add/del/move operations +* - resizing can trigger on load change or depending on key refresh period +* - add/del/move operations should be allowed for any context +* +* Resizing: +* - new table is attached to the current table and all entries are moved +* with new hash key. Finally, the new table is installed as current one and +* the old table is released after RCU grace period. +* - RCU read-side critical sections will walk two tables while resizing is +* in progress +* - new entries are added to the new table +* - entries will be deleted from the old or from the new table, the table_id +* can be saved into entry as part of the hash key to know where the entry is +* hashed +* - move operations may delay readers or to cause retry for the modified +* bucket. As result, searched entry will be found but walkers that operate +* on multiple entries may see same entry twice if bucket walking is retried. +* - for fast path the number of entries (load) can be compared to u_thresh +* and l_thresh to decide when to trigger table growing/shrinking. They +* are calculated based on load factor (shift count), negative value allows +* load to be below 100% to reduce collisions by maintaining larger table +* while positive value tolerates collisions by using smaller table and load +* above 100%: u_thresh(load) = size * (2 ^ lfactor) +* +* Locking: +* - lock: protect seqc if other context except resizer can move entries +* - seqc: seqcount_t, delay/retry readers while entries are moved to +* new table on resizing +* - bit lock: serialize bucket modifications +* - writers may use other locking mechanisms to serialize operations for +* resizing, moving and installing new tables +*/ + +void ip_vs_rht_free (struct ip_vs_rht *t) +{ +kvfree (t->buckets); +kvfree (t->seqc); +kvfree (t->lock); +kfree (t); +} + +void ip_vs_rht_rcu_free (struct rcu_head *head) +{ +struct ip_vs_rht *t; + + t = container_of(head, struct ip_vs_rht, rcu_head); +ip_vs_rht_free (t); +} + +struct ip_vs_rht *ip_vs_rht_alloc (int buckets,int scounts,int locks) +{ +struct ip_vs_rht *t =kzalloc (sizeof (*t),GFP_KERNEL ); +int i; + +if (!t) +return NULL ; +if (scounts) { +int ml =roundup_pow_of_two (nr_cpu_ids); + + scounts =min (scounts, buckets); + scounts =min (scounts, ml); + t->seqc =kvmalloc_array (scounts,sizeof (*t->seqc),GFP_KERNEL ); +if (!t->seqc) + goto err; +for (i =0 ; i < scounts; i++) +seqcount_init (&t->seqc[i]); + +if (locks) { + locks =min (locks, scounts); + t->lock =kvmalloc_array (locks,sizeof (*t->lock), +GFP_KERNEL ); +if (!t->lock) + goto err; +for (i =0 ; i < locks; i++) +spin_lock_init (&t->lock[i].l); + } + } + + t->buckets =kvmalloc_array (buckets,sizeof (*t->buckets),GFP_KERNEL ); +if (!t->buckets) + goto err; +for (i =0 ; i < buckets; i++) +INIT_HLIST_BL_HEAD (&t->buckets[i]); + t->mask = buckets -1 ; + t->size = buckets; + t->seqc_mask = scounts -1 ; + t->lock_mask = locks -1 ; + t->u_thresh = buckets; + t->l_thresh = buckets >>4 ; + t->bits =order_base_2 (buckets); +/* new_tbl points to self if no new table is filled */ +RCU_INIT_POINTER (t->new_tbl, t); +get_random_bytes (&t->hash_key,sizeof (t->hash_key)); +return t; + +err: +ip_vs_rht_free (t); +return NULL ; +} + +/* Get the desired table size for n entries based on current table size and +* by using the formula size = n / (2^lfactor) +* lfactor: shift value for the load factor: +* - >0: u_thresh=size << lfactor, for load factor above 100% +* - <0: u_thresh=size >> -lfactor, for load factor below 100% +* - 0: for load factor of 100% +*/ +int ip_vs_rht_desired_size (struct netns_ipvs *ipvs,struct ip_vs_rht *t,int n, +int lfactor,int min_bits,int max_bits) +{ +if (!t) +return 1 << min_bits; + n =roundup_pow_of_two (n); +if (lfactor <0 ) { +int factor =min (-lfactor, max_bits); + + n =min (n,1 << (max_bits - factor)); + n <<= factor; + }else { + n =min (n >> lfactor,1 << max_bits); + } +if (lfactor != t->lfactor) +return clamp (n,1 << min_bits,1 << max_bits); +if (n > t->size) +return n; +if (n > t->size >>4 ) +return t->size; +/* Shrink but keep it n * 2 to prevent frequent resizing */ +return clamp (n <<1 ,1 << min_bits,1 << max_bits); +} + +/* Set thresholds based on table size and load factor: +* u_thresh = size * (2^lfactor) +* l_thresh = u_thresh / 16 +* u_thresh/l_thresh can be used to check if load triggers a table grow/shrink +*/ +void ip_vs_rht_set_thresholds (struct ip_vs_rht *t,int size,int lfactor, +int min_bits,int max_bits) +{ +if (size >=1 << max_bits) + t->u_thresh =INT_MAX ;/* stop growing */ +else if (lfactor <=0 ) + t->u_thresh = size >>min (-lfactor, max_bits); +else + t->u_thresh =min (size,1 << (30 - lfactor)) << lfactor; + +/* l_thresh: shrink when load is 16 times lower, can be 0 */ +if (size >=1 << max_bits) + t->l_thresh = (1 << max_bits) >>4 ; +else if (size >1 << min_bits) + t->l_thresh = t->u_thresh >>4 ; +else + t->l_thresh =0 ;/* stop shrinking */ +} + +/* Return hash value for local info (fast, insecure) */ +u32 ip_vs_rht_hash_linfo (struct ip_vs_rht *t,int af, +const union nf_inet_addr *addr,u32 v1,u32 v2) +{ +u32 v3; + +#ifdef CONFIG_IP_VS_IPV6 +if (af ==AF_INET6 ) + v3 =ipv6_addr_hash (&addr->in6); + else +#endif + v3 = addr->all[0 ]; + +return jhash_3words (v1, v2, v3, (u32 )t->hash_key.key[0 ]); +} +static inline void ip_vs_in_stats (struct ip_vs_conn *cp,struct sk_buff *skb) {Signature · 1 line
2.51.0
Julian Anastasov
maintainerRe: [PATCHv6 net-next 07/14] ipvs: add resizable hash tables
Hello,
Quoted 11 lines · Pablo Neira Ayuso
Quoted 7 lines · Julian Anastasov
Add infrastructure for resizable hash tables based on
hlist_blwhich we will use in followup patches.The tables allow RCU lookups during resizing, bucket modifications are protected with per-bucket bit lock and additional custom locking, the tables are resized when load reaches thresholds determined based on load factor parameter.
I understand the generic rhashtable implementation cannot be used in this case, but I am missing the reason why (comparison?).
The main differences are:
- our hash keys are not on contiguous memory, need to fit properly in cachelines
- we avoid IRQ locks: local_irq_save/local_irq_restore
- we will use double hashing for NAT
- we allow entries with duplicate keys, for performance reasons
- we do not lookup the entry that is to be removed, we know its table and bucket id and unlink it with hlist_bl_del_rcu
- we prefer to customize the grow/shrink process
Regards
--
Julian Anastasov <[email protected]>
Julian Anastasov
maintainerPATCH v6 8/14 ipvs: use resizable hash table for services
In reply to Julian AnastasovMake the hash table for services resizable in the bit range of 4-20. Table is attached only while services are present. Resizing is done by delayed work based on load (the number of hashed services). Table grows when load increases 2+ times (above 12.5% with lfactor=-3) and shrinks 8+ times when load decreases 16+ times (below 0.78%).
Switch to jhash hashing to reduce the collisions for multiple services.
Add a hash_key field into the service to store the table ID in the highest bit and the entry's hash value in the lowest bits. The lowest part of the hash value is used as bucket ID, the remaining part is used to filter the entries in the bucket before matching the keys and as result, helps the lookup operation to access only one cache line. By knowing the table ID and bucket ID for entry, we can unlink it without calculating the hash value and doing lookup by keys. We need only to validate the saved hash_key under lock.
--- include/net/ip_vs.h | 49 ++- net/netfilter/ipvs/ip_vs_ctl.c | 673 +++++++++++++++++++++++++++------ 2 files changed, 593 insertions(+), 129 deletions(-)
include/net/ip_vs.h +34 -15
@@ -35,12 +35,10 @@#define IP_VS_HDR_INVERSE 1#define IP_VS_HDR_ICMP 2 -/* -* Hash table: for virtual service lookups -*/ -#define IP_VS_SVC_TAB_BITS 8 -#define IP_VS_SVC_TAB_SIZE BIT(IP_VS_SVC_TAB_BITS) -#define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1) + +/* svc_table limits */ +#define IP_VS_SVC_TAB_MIN_BITS 4 +#define IP_VS_SVC_TAB_MAX_BITS 20/* Generic access of ipvs struct */ static inline struct netns_ipvs *net_ipvs (struct net * net)
@@ -51,8 +49,6 @@ static inline struct netns_ipvs *net_ipvs(struct net* net)/* Connections' size value needed by ip_vs_ctl.c */ extern int ip_vs_conn_tab_size; -extern struct mutex __ip_vs_mutex; -struct ip_vs_iphdr {int hdr_flags;/* ipvs flags */ __u32 off;/* Where IP or IPv4 header starts */
@@ -289,6 +285,12 @@ static inline int ip_vs_af_index(int af)return af ==AF_INET6 ?IP_VS_AF_INET6 :IP_VS_AF_INET ; } +/* work_flags */ +enum { +IP_VS_WORK_SVC_RESIZE ,/* Schedule svc_resize_work */ +IP_VS_WORK_SVC_NORESIZE ,/* Stopping svc_resize_work */ +}; +/* The port number of FTP service (in network order). */ #define FTPPORT cpu_to_be16(21)#define FTPDATA cpu_to_be16(20)
@@ -888,14 +890,15 @@ struct ip_vs_dest_user_kern {* forwarding entries. */ struct ip_vs_service { -struct hlist_node s_list;/* node in service table */ -atomic_t refcnt;/* reference counter */ - +struct hlist_bl_node s_list;/* node in service table */ +u32 hash_key;/* Key for the hash table */ u16 af;/* address family */ __u16 protocol;/* which protocol (TCP/UDP) */ +union nf_inet_addr addr;/* IP address for virtual service */ -__be16 port;/* port number for the service */ __u32 fwmark;/* firewall mark of the service */ +atomic_t refcnt;/* reference counter */ +__be16 port;/* port number for the service */ unsigned int flags;/* service status flags */ unsigned int timeout;/* persistent timeout in ticks */ __be32 netmask;/* grouping granularity, mask/plen */
@@ -1153,6 +1156,10 @@ struct netns_ipvs {struct list_head dest_trash;spinlock_t dest_trash_lock;struct timer_list dest_trash_timer;/* expiration timer */ +struct mutex service_mutex;/* service reconfig */ +struct rw_semaphore svc_resize_sem;/* svc_table resizing */ +struct delayed_work svc_resize_work;/* resize svc_table */ +atomic_t svc_table_changes;/* ++ on new table */ /* Service counters */ atomic_t num_services[IP_VS_AF_MAX ];/* Services */ atomic_t fwm_services[IP_VS_AF_MAX ];/* Services */
@@ -1216,6 +1223,7 @@ struct netns_ipvs {int sysctl_est_nice;/* kthread nice */ int est_stopped;/* stop tasks */ #endif +int sysctl_svc_lfactor;/* ip_vs_lblc */ int sysctl_lblc_expiration;
@@ -1225,6 +1233,7 @@ struct netns_ipvs {int sysctl_lblcr_expiration;struct ctl_table_header *lblcr_ctl_header;struct ctl_table *lblcr_ctl_table; +unsigned long work_flags;/* IP_VS_WORK_* flags */ /* ip_vs_est */ struct delayed_work est_reload_work;/* Reload kthread tasks */ struct mutex est_mutex;/* protect kthread tasks */
@@ -1256,9 +1265,7 @@ struct netns_ipvs {unsigned int mixed_address_family_dests;unsigned int hooks_afmask;/* &1=AF_INET, &2=AF_INET6 */ -/* the service mutex that protect svc_table and svc_fwm_table */ -struct mutex service_mutex; -struct hlist_head svc_table[IP_VS_SVC_TAB_SIZE ];/* Services */ +struct ip_vs_rht __rcu *svc_table;/* Services */ };#define DEFAULT_SYNC_THRESHOLD 3
@@ -1508,6 +1515,18 @@ static inline int sysctl_est_nice(struct netns_ipvs *ipvs)#endif +/* Get load factor to map num_services/u_thresh to t->size +* Smaller value decreases u_thresh to reduce collisions but increases +* the table size +* Returns factor where: +* - <0: u_thresh = size >> -factor, eg. lfactor -2 = 25% load +* - >=0: u_thresh = size << factor, eg. lfactor 1 = 200% load +*/ +static inline int sysctl_svc_lfactor (struct netns_ipvs *ipvs) +{ +return READ_ONCE (ipvs->sysctl_svc_lfactor); +} +/* IPVS core functions * (from ip_vs_core.c) */
net/netfilter/ipvs/ip_vs_ctl.c +559 -114
918 lines not on this page · raw message
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 9/14 ipvs: switch to per-net connection table
In reply to Julian AnastasovUse per-net resizable hash table for connections. The global table is slow to walk when using many namespaces.
The table can be resized in the range of [256 - ip_vs_conn_tab_size]. Table is attached only while services are present. Resizing is done by delayed work based on load (the number of connections).
Add a hash_key field into the connection to store the table ID in the highest bit and the entry's hash value in the lowest bits. The lowest part of the hash value is used as bucket ID, the remaining part is used to filter the entries in the bucket before matching the keys and as result, helps the lookup operation to access only one cache line. By knowing the table ID and bucket ID for entry, we can unlink it without calculating the hash value and doing lookup by keys. We need only to validate the saved hash_key under lock.
For better security switch from jhash to siphash for the default connection hashing but the persistence engines may use their own function. Keeping the hash table loaded with entries below the size (12%) allows to avoid collision for 96+% of the conns.
ip_vs_conn_fill_cport() now will rehash the connection with proper locking because unhash+hash is not safe for RCU readers.
To invalidate the templates setting just dport to 0xffff is enough, no need to rehash them. As result, ip_vs_conn_unhash() is now unused and removed.
--- include/net/ip_vs.h | 34 +- net/netfilter/ipvs/ip_vs_conn.c | 848 +++++++++++++++++++++--------- net/netfilter/ipvs/ip_vs_ctl.c | 18 + net/netfilter/ipvs/ip_vs_pe_sip.c | 4 +- net/netfilter/ipvs/ip_vs_sync.c | 23 + 5 files changed, 667 insertions(+), 260 deletions(-)
include/net/ip_vs.h +29 -5
@@ -36,6 +36,14 @@#define IP_VS_HDR_INVERSE 1#define IP_VS_HDR_ICMP 2 +/* conn_tab limits (as per Kconfig) */ +#define IP_VS_CONN_TAB_MIN_BITS 8 +#if BITS_PER_LONG >32 +#define IP_VS_CONN_TAB_MAX_BITS 27 +#else +#define IP_VS_CONN_TAB_MAX_BITS 20 +#endif +/* svc_table limits */ #define IP_VS_SVC_TAB_MIN_BITS 4#define IP_VS_SVC_TAB_MAX_BITS 20
@@ -289,6 +297,7 @@ static inline int ip_vs_af_index(int af)enum {IP_VS_WORK_SVC_RESIZE ,/* Schedule svc_resize_work */ IP_VS_WORK_SVC_NORESIZE ,/* Stopping svc_resize_work */ +IP_VS_WORK_CONN_RESIZE ,/* Schedule conn_resize_work */ };/* The port number of FTP service (in network order). */
@@ -778,18 +787,19 @@ struct ip_vs_conn_param {/* IP_VS structure allocated for each dynamically scheduled connection */ struct ip_vs_conn { -struct hlist_node c_list;/* hashed list heads */ +struct hlist_bl_node c_list;/* node in conn_tab */ +__u32 hash_key;/* Key for the hash table */ /* Protocol, addresses and port numbers */ __be16 cport;__be16 dport;__be16 vport;u16 af;/* address family */ +__u16 protocol;/* Which protocol (TCP/UDP) */ +__u16 daf;/* Address family of the dest */ union nf_inet_addr caddr;/* client address */ union nf_inet_addr vaddr;/* virtual address */ union nf_inet_addr daddr;/* destination address */ volatile __u32 flags;/* status flags */ -__u16 protocol;/* Which protocol (TCP/UDP) */ -__u16 daf;/* Address family of the dest */ struct netns_ipvs *ipvs;/* counter and timer */
@@ -1008,8 +1018,8 @@ struct ip_vs_pe {int (*fill_param)(struct ip_vs_conn_param *p,struct sk_buff *skb);bool (*ct_match)(const struct ip_vs_conn_param *p,struct ip_vs_conn *ct); -u32 (*hashkey_raw)(const struct ip_vs_conn_param *p,u32 initval, -bool inverse); +u32 (*hashkey_raw)(const struct ip_vs_conn_param *p, +struct ip_vs_rht *t,bool inverse);int (*show_pe_data)(const struct ip_vs_conn *cp,char *buf);/* create connections for real-server outgoing packets */ struct ip_vs_conn* (*conn_out)(struct ip_vs_service *svc,
@@ -1148,6 +1158,7 @@ struct netns_ipvs {#endif /* ip_vs_conn */ atomic_t conn_count;/* connection counter */ +struct delayed_work conn_resize_work;/* resize conn_tab */ /* ip_vs_ctl */ struct ip_vs_stats_rcu *tot_stats;/* Statistics & est. */
@@ -1223,6 +1234,7 @@ struct netns_ipvs {int sysctl_est_nice;/* kthread nice */ int est_stopped;/* stop tasks */ #endif +int sysctl_conn_lfactor;int sysctl_svc_lfactor;/* ip_vs_lblc */
@@ -1266,6 +1278,8 @@ struct netns_ipvs {unsigned int hooks_afmask;/* &1=AF_INET, &2=AF_INET6 */ struct ip_vs_rht __rcu *svc_table;/* Services */ +struct ip_vs_rht __rcu *conn_tab;/* Connections */ +atomic_t conn_tab_changes;/* ++ on new table */ };#define DEFAULT_SYNC_THRESHOLD 3
@@ -1515,6 +1529,12 @@ static inline int sysctl_est_nice(struct netns_ipvs *ipvs)#endif +/* Get load factor to map conn_count/u_thresh to t->size */ +static inline int sysctl_conn_lfactor (struct netns_ipvs *ipvs) +{ +return READ_ONCE (ipvs->sysctl_conn_lfactor); +} +/* Get load factor to map num_services/u_thresh to t->size * Smaller value decreases u_thresh to reduce collisions but increases * the table size
@@ -1600,6 +1620,10 @@ static inline void __ip_vs_conn_put(struct ip_vs_conn *cp) }void ip_vs_conn_put (struct ip_vs_conn *cp);void ip_vs_conn_fill_cport (struct ip_vs_conn *cp,__be16 cport); +int ip_vs_conn_desired_size (struct netns_ipvs *ipvs,struct ip_vs_rht *t, +int lfactor); +struct ip_vs_rht *ip_vs_conn_tab_alloc (struct netns_ipvs *ipvs,int buckets, +int lfactor); struct ip_vs_conn *ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, const union nf_inet_addr *daddr,
net/netfilter/ipvs/ip_vs_conn.c +595 -253
1,210 lines not on this page · raw message
net/netfilter/ipvs/ip_vs_ctl.c +18 -0
@@ -1644,6 +1644,7 @@ ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u, struct ip_vs_service **svc_p) {struct ip_vs_scheduler *sched =NULL ; +struct ip_vs_rht *tc_new =NULL ;struct ip_vs_rht *t, *t_new =NULL ;int af_id =ip_vs_af_index (u->af);struct ip_vs_service *svc =NULL ;
@@ -1703,6 +1704,17 @@ ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u, } } +if (!rcu_dereference_protected (ipvs->conn_tab,1 )) { +int lfactor =sysctl_conn_lfactor (ipvs); +int new_size =ip_vs_conn_desired_size (ipvs,NULL , lfactor); + + tc_new =ip_vs_conn_tab_alloc (ipvs, new_size, lfactor); +if (!tc_new) { + ret = -ENOMEM ; + goto out_err; + } + } +if (!atomic_read (&ipvs->num_services[af_id])) { ret =ip_vs_register_hooks (ipvs, u->af);if (ret <0 )
@@ -1753,6 +1765,10 @@ ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u,rcu_assign_pointer (ipvs->svc_table, t_new); t_new =NULL ; } +if (tc_new) { +rcu_assign_pointer (ipvs->conn_tab, tc_new); + tc_new =NULL ; + }/* Update the virtual service counters */ if (svc->port ==FTPPORT )
@@ -1795,6 +1811,8 @@ ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u, out_err: +if (tc_new) +ip_vs_rht_free (tc_new);if (t_new)ip_vs_rht_free (t_new);if (ret_hooks >=0 )
net/netfilter/ipvs/ip_vs_pe_sip.c +2 -2
@@ -133,9 +133,9 @@ static bool ip_vs_sip_ct_match(const struct ip_vs_conn_param *p, }static u32 ip_vs_sip_hashkey_raw (const struct ip_vs_conn_param *p, -u32 initval,bool inverse) +struct ip_vs_rht *t,bool inverse) { -return jhash (p->pe_data, p->pe_data_len, initval); +return jhash (p->pe_data, p->pe_data_len, (u32 )t->hash_key.key[0 ]); }static int ip_vs_sip_show_pe_data (const struct ip_vs_conn *cp,char *buf)
net/netfilter/ipvs/ip_vs_sync.c +23 -0
@@ -1756,6 +1756,28 @@ int start_sync_thread(struct netns_ipvs *ipvs, struct ipvs_sync_daemon_cfg *c,if (!ip_vs_use_count_inc ())return -ENOPROTOOPT ; +/* Backup server can be started without services just to sync conns, +* make sure conn_tab is created even if ipvs->enable is 0. +*/ +if (state ==IP_VS_STATE_BACKUP ) { +mutex_lock (&ipvs->service_mutex); +if (!rcu_dereference_protected (ipvs->conn_tab,1 )) { +int lfactor =sysctl_conn_lfactor (ipvs); +int new_size =ip_vs_conn_desired_size (ipvs,NULL , + lfactor); +struct ip_vs_rht *tc_new; + + tc_new =ip_vs_conn_tab_alloc (ipvs, new_size, lfactor); +if (!tc_new) { +mutex_unlock (&ipvs->service_mutex); + result = -ENOMEM ; + goto out_module; + } +rcu_assign_pointer (ipvs->conn_tab, tc_new); + } +mutex_unlock (&ipvs->service_mutex); + } +/* Do not hold one mutex and then to block on another */ for (;;) {rtnl_lock ();
@@ -1924,6 +1946,7 @@ int start_sync_thread(struct netns_ipvs *ipvs, struct ipvs_sync_daemon_cfg *c,mutex_unlock (&ipvs->sync_mutex);rtnl_unlock (); +out_module:/* decrease the module use count */ ip_vs_use_count_dec ();return result;
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 10/14 ipvs: show the current conn_tab size to users
In reply to Julian AnastasovAs conn_tab is per-net, better to show the current hash table size to users instead of the ip_vs_conn_tab_size (max).
--- net/netfilter/ipvs/ip_vs_ctl.c | 36 +++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-)
net/netfilter/ipvs/ip_vs_ctl.c +31 -5
@@ -2743,10 +2743,16 @@ static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)static int ip_vs_info_seq_show (struct seq_file *seq,void *v) { +struct net *net =seq_file_net (seq); +struct netns_ipvs *ipvs =net_ipvs (net); +if (v ==SEQ_START_TOKEN ) { +struct ip_vs_rht *tc =rcu_dereference (ipvs->conn_tab); +int csize = tc ? tc->size :0 ; +seq_printf (seq,"IP Virtual Server version %d.%d.%d (size=%d)\n" , -NVERSION (IP_VS_VERSION_CODE ), ip_vs_conn_tab_size); +NVERSION (IP_VS_VERSION_CODE ), csize);seq_puts (seq,"Prot LocalAddress:Port Scheduler Flags\n" ); seq_puts(seq,
@@ -3424,10 +3430,17 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)switch (cmd) {case IP_VS_SO_GET_VERSION : { +struct ip_vs_rht *t; +int csize =0 ;char buf[64 ]; +rcu_read_lock (); + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size; +rcu_read_unlock ();sprintf (buf,"IP Virtual Server version %d.%d.%d (size=%d)" , -NVERSION (IP_VS_VERSION_CODE ), ip_vs_conn_tab_size); +NVERSION (IP_VS_VERSION_CODE ), csize);if (copy_to_user (user, buf,strlen (buf)+1 ) !=0 ) { ret = -EFAULT ; goto out;
@@ -3439,8 +3452,16 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)case IP_VS_SO_GET_INFO : {struct ip_vs_getinfo info; +struct ip_vs_rht *t; +int csize =0 ; + +rcu_read_lock (); + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size; +rcu_read_unlock (); info.version =IP_VS_VERSION_CODE ; - info.size = ip_vs_conn_tab_size; + info.size = csize; info.num_services =atomic_read (&ipvs->num_services[IP_VS_AF_INET ]);if (copy_to_user (user, &info,sizeof (info)) !=0 )
@@ -4379,6 +4400,8 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)int ret, cmd, reply_cmd;struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); +struct ip_vs_rht *t; +int csize; cmd = info->genlhdr->cmd;
@@ -4446,10 +4469,13 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) }case IPVS_CMD_GET_INFO : + csize =0 ; + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size;if (nla_put_u32 (msg,IPVS_INFO_ATTR_VERSION ,IP_VS_VERSION_CODE ) || -nla_put_u32 (msg,IPVS_INFO_ATTR_CONN_TAB_SIZE , - ip_vs_conn_tab_size)) +nla_put_u32 (msg,IPVS_INFO_ATTR_CONN_TAB_SIZE , csize)) goto nla_put_failure;break ; }
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 10/14] ipvs: show the current conn_tab size to users
Quoted 33 lines · Julian Anastasov
As
conn_tabis per-net, better to show the current hash table size to users instead of theip_vs_conn_tab_size(max).Signed-off-by Julian Anastasov <[email protected]>--- net/netfilter/ipvs/ip_vs_ctl.c | 36 +++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-)net/netfilter/ipvs/ip_vs_ctl.c +7
-1@@ -2743,10 +2743,16 @@ static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)static int ip_vs_info_seq_show (struct seq_file *seq,void *v) { +struct net *net =seq_file_net (seq); +struct netns_ipvs *ipvs =net_ipvs (net); +if (v ==SEQ_START_TOKEN ) { +struct ip_vs_rht *tc =rcu_dereference (ipvs->conn_tab); +int csize = tc ? tc->size :0 ; +seq_printf (seq,"IP Virtual Server version %d.%d.%d (size=%d)\n" , -NVERSION (IP_VS_VERSION_CODE ), ip_vs_conn_tab_size); +NVERSION (IP_VS_VERSION_CODE ), csize);seq_puts (seq,"Prot LocalAddress:Port Scheduler Flags\n" ); seq_puts(seq,@@ -3424,10 +3430,17 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)switch (cmd) {case IP_VS_SO_GET_VERSION :
net/netfilter/ipvs/ip_vs_ctl.c do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) · line 3441
Quoted 10 lines
net/netfilter/ipvs/ip_vs_ctl.c +7
-0{ +struct ip_vs_rht *t; +int csize =0 ;char buf[64 ]; +rcu_read_lock (); + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size; +rcu_read_unlock ();
here too, maybe add helper function?
Quoted 8 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-1sprintf (buf,"IP Virtual Server version %d.%d.%d (size=%d)" , -NVERSION (IP_VS_VERSION_CODE ), ip_vs_conn_tab_size); +NVERSION (IP_VS_VERSION_CODE ), csize);if (copy_to_user (user, buf,strlen (buf)+1 ) !=0 ) { ret = -EFAULT ; goto out;@@ -3439,8 +3452,16 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)case IP_VS_SO_GET_INFO :
net/netfilter/ipvs/ip_vs_ctl.c do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) · line 3462
Quoted 10 lines
net/netfilter/ipvs/ip_vs_ctl.c +8
-0{struct ip_vs_getinfo info; +struct ip_vs_rht *t; +int csize =0 ; + +rcu_read_lock (); + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size; +rcu_read_unlock ();
... that can be used here?
Quoted 16 lines
net/netfilter/ipvs/ip_vs_ctl.c +3
-1info.version =IP_VS_VERSION_CODE ; - info.size = ip_vs_conn_tab_size; + info.size = csize; info.num_services =atomic_read (&ipvs->num_services[IP_VS_AF_INET ]);if (copy_to_user (user, &info,sizeof (info)) !=0 )@@ -4379,6 +4400,8 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)int ret, cmd, reply_cmd;struct net *net =sock_net (skb->sk);struct netns_ipvs *ipvs =net_ipvs (net); +struct ip_vs_rht *t; +int csize; cmd = info->genlhdr->cmd;
net/netfilter/ipvs/ip_vs_ctl.c static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) · line 4475
Quoted 7 lines
net/netfilter/ipvs/ip_vs_ctl.c +4
-0@@ -4446,10 +4469,13 @@ static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) }case IPVS_CMD_GET_INFO : + csize =0 ; + t =rcu_dereference (ipvs->conn_tab); +if (t) + csize = t->size;
... I found another candidate to use the helper here :)
If you add the helper function first, then I think this patch will be super-small when switching to per-netns, because only the helper function to get the size will need to be adjusted.
Quoted 13 lines
net/netfilter/ipvs/ip_vs_ctl.c +1
-2if (nla_put_u32 (msg,IPVS_INFO_ATTR_VERSION ,IP_VS_VERSION_CODE ) || -nla_put_u32 (msg,IPVS_INFO_ATTR_CONN_TAB_SIZE , - ip_vs_conn_tab_size)) +nla_put_u32 (msg,IPVS_INFO_ATTR_CONN_TAB_SIZE , csize)) goto nla_put_failure;break ; }Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 11/14 ipvs: no_cport and dropentry counters can be per-net
In reply to Julian AnastasovWith using per-net conn_tab these counters do not need to be global anymore.
--- include/net/ip_vs.h | 2 ++ net/netfilter/ipvs/ip_vs_conn.c | 62 ++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 25 deletions(-)
include/net/ip_vs.h +2 -0
@@ -1158,6 +1158,7 @@ struct netns_ipvs {#endif /* ip_vs_conn */ atomic_t conn_count;/* connection counter */ +atomic_t no_cport_conns[IP_VS_AF_MAX ];struct delayed_work conn_resize_work;/* resize conn_tab */ /* ip_vs_ctl */
@@ -1188,6 +1189,7 @@ struct netns_ipvs {int drop_counter;int old_secure_tcp;atomic_t dropentry; +s8 dropentry_counters[8 ];/* locks in ctl.c */ spinlock_t dropentry_lock;/* drop entry handling */ spinlock_t droppacket_lock;/* drop packet handling */
net/netfilter/ipvs/ip_vs_conn.c +37 -25
132 lines not on this page · raw message
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 11/14] ipvs: no_cport and dropentry counters can be per-net
Quoted 132 lines · Julian Anastasov
With using per-net
conn_tabthese counters do not need to be global anymore.Signed-off-by Julian Anastasov <[email protected]>--- include/net/ip_vs.h | 2 ++ net/netfilter/ipvs/ip_vs_conn.c | 62 ++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 25 deletions(-)include/net/ip_vs.h +2
-0@@ -1158,6 +1158,7 @@ struct netns_ipvs {#endif /* ip_vs_conn */ atomic_t conn_count;/* connection counter */ +atomic_t no_cport_conns[IP_VS_AF_MAX ];struct delayed_work conn_resize_work;/* resize conn_tab */ /* ip_vs_ctl */ @@ -1188,6 +1189,7 @@ struct netns_ipvs {int drop_counter;int old_secure_tcp;atomic_t dropentry; +s8 dropentry_counters[8 ];/* locks in ctl.c */ spinlock_t dropentry_lock;/* drop entry handling */ spinlock_t droppacket_lock;/* drop packet handling */ net/netfilter/ipvs/ip_vs_conn.c +24
-18@@ -54,9 +54,6 @@ int ip_vs_conn_tab_size __read_mostly;/* SLAB cache for IPVS connections */ static struct kmem_cache *ip_vs_conn_cachep__read_mostly ; -/* counter for no client port connections */ -static atomic_t ip_vs_conn_no_cport_cnt =ATOMIC_INIT (0 ); -/* We need an addrstrlen that works with or without v6 */ #ifdef CONFIG_IP_VS_IPV6 #define IP_VS_ADDRSTRLEN INET6_ADDRSTRLEN@@ -319,10 +316,16 @@ struct ip_vs_conn *ip_vs_conn_in_get(const struct ip_vs_conn_param *p)struct ip_vs_conn *cp; cp =__ip_vs_conn_in_get (p); -if (!cp &&atomic_read (&ip_vs_conn_no_cport_cnt)) { -struct ip_vs_conn_param cport_zero_p = *p; - cport_zero_p.cport =0 ; - cp =__ip_vs_conn_in_get (&cport_zero_p); +if (!cp) { +struct netns_ipvs *ipvs = p->ipvs; +int af_id =ip_vs_af_index (p->af); + +if (atomic_read (&ipvs->no_cport_conns[af_id])) { +struct ip_vs_conn_param cport_zero_p = *p; + + cport_zero_p.cport =0 ; + cp =__ip_vs_conn_in_get (&cport_zero_p); + } } IP_VS_DBG_BUF(9, "lookup/in %s %s:%d->%s:%d %s\n",@@ -535,6 +538,7 @@ void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport) {struct hlist_bl_head *head, *head2, *head_new;struct netns_ipvs *ipvs = cp->ipvs; +int af_id =ip_vs_af_index (cp->af);u32 hash_r =0 , hash_key_r =0 ;struct ip_vs_rht *t, *tp, *t2;u32 hash_key, hash_key_new;@@ -613,7 +617,7 @@ void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport)hlist_bl_del_rcu (&cp->c_list);hlist_bl_add_head_rcu (&cp->c_list, head_new); } -atomic_dec (&ip_vs_conn_no_cport_cnt); +atomic_dec (&ipvs->no_cport_conns[af_id]); cp->flags &= ~IP_VS_CONN_F_NO_CPORT ; cp->cport = cport; }@@ -1169,8 +1173,11 @@ static void ip_vs_conn_expire(struct timer_list *t)if (unlikely (cp->app !=NULL ))ip_vs_unbind_app (cp);ip_vs_unbind_dest (cp); -if (cp->flags &IP_VS_CONN_F_NO_CPORT ) -atomic_dec (&ip_vs_conn_no_cport_cnt); +if (unlikely (cp->flags &IP_VS_CONN_F_NO_CPORT )) { +int af_id =ip_vs_af_index (cp->af); + +atomic_dec (&ipvs->no_cport_conns[af_id]); + }if (cp->flags &IP_VS_CONN_F_ONE_PACKET )ip_vs_conn_rcu_free (&cp->rcu_head);else @@ -1277,8 +1284,11 @@ ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, cp->out_seq.delta =0 ;atomic_inc (&ipvs->conn_count); -if (flags &IP_VS_CONN_F_NO_CPORT ) -atomic_inc (&ip_vs_conn_no_cport_cnt); +if (unlikely (flags &IP_VS_CONN_F_NO_CPORT )) { +int af_id =ip_vs_af_index (cp->af); + +atomic_inc (&ipvs->no_cport_conns[af_id]); + }/* Bind the connection with a destination server */ cp->dest =NULL ;@@ -1556,6 +1566,7 @@ static const struct seq_operations ip_vs_conn_sync_seq_ops = { };#endif +#ifdef CONFIG_SYSCTL /* Randomly drop connection entries before running out of memory * Can be used for DATA and CTL conns. For TPL conns there are exceptions: @@ -1565,12 +1576,7 @@ static const struct seq_operations ip_vs_conn_sync_seq_ops = {*/ static inline int todrop_entry (struct ip_vs_conn *cp) { -/* -* The drop rate array needs tuning for real environments. -* Called from timer bh only => no locking -*/ -static const signed char todrop_rate[9 ] = {0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 }; -static signed char todrop_counter[9 ] = {0 }; +struct netns_ipvs *ipvs = cp->ipvs;int i;/* if the conn entry hasn't lasted for 60 seconds, don't drop it.
net/netfilter/ipvs/ip_vs_conn.c static inline int todrop_entry(struct ip_vs_conn *cp) · line 1590
Quoted 9 lines
net/netfilter/ipvs/ip_vs_conn.c +2
-3@@ -1579,15 +1585,17 @@ static inline int todrop_entry(struct ip_vs_conn *cp)if (time_before (cp->timeout + jiffies, cp->timer.expires +60 *HZ ))return 0 ; -/* Don't drop the entry if its number of incoming packets is not -located in [0, 8] */ +/* Drop only conns with number of incoming packets in [1..8] range */ i =atomic_read (&cp->in_pkts); -if (i >8 || i <0 )return 0 ; +if (i >8 || i <1 )
Why did this change? How is this related to the per-netns update?
Quoted 40 lines
net/netfilter/ipvs/ip_vs_conn.c +11
-4+return 0 ; -if (!todrop_rate[i])return 0 ; -if (--todrop_counter[i] >0 )return 0 ; + i--; +if (--ipvs->dropentry_counters[i] >0 ) +return 0 ; - todrop_counter[i] = todrop_rate[i]; +/* Prefer to drop conns with less number of incoming packets */ + ipvs->dropentry_counters[i] = i +1 ;return 1 ; }@@ -1681,7 +1689,7 @@ void ip_vs_random_dropentry(struct netns_ipvs *ipvs) out: rcu_read_unlock(); } - +#endif /* Flush all the connection entries in the conn_tab */ static void ip_vs_conn_flush (struct netns_ipvs *ipvs)@@ -1806,7 +1814,11 @@ void ip_vs_expire_nodest_conn_flush(struct netns_ipvs *ipvs)*/ int __net_init ip_vs_conn_net_init (struct netns_ipvs *ipvs) { +int idx; +atomic_set (&ipvs->conn_count,0 ); +for (idx =0 ; idx <IP_VS_AF_MAX ; idx++) +atomic_set (&ipvs->no_cport_conns[idx],0 );INIT_DELAYED_WORK (&ipvs->conn_resize_work, conn_resize_work_handler);RCU_INIT_POINTER (ipvs->conn_tab,NULL );atomic_set (&ipvs->conn_tab_changes,0 );Signature · 1 line
2.51.0
Julian Anastasov
maintainerRe: [PATCHv6 net-next 11/14] ipvs: no_cport and dropentry counters can be per-net
Hello,
Quoted 22 lines · Pablo Neira Ayuso
Quoted 20 lines · Julian Anastasov
With using per-net
conn_tabthese counters do not need to be global anymore.Signed-off-by Julian Anastasov <[email protected]>--- include/net/ip_vs.h | 2 ++ net/netfilter/ipvs/ip_vs_conn.c | 62 ++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 25 deletions(-)include/net/ip_vs.h +1
-0+s8 dropentry_counters[8 ];net/netfilter/ipvs/ip_vs_conn.c +0
-0
Quoted 8 lines
net/netfilter/ipvs/ip_vs_conn.c static const struct seq_operations ip_vs_conn_sync_seq_ops = { · line 1573
Quoted 8 lines
static inline int
todrop_entry(struct ip_vs_conn *cp){net/netfilter/ipvs/ip_vs_conn.c +0
-6-/* -* The drop rate array needs tuning for real environments. -* Called from timer bh only => no locking -*/ -static const signed char todrop_rate[9 ] = {0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 }; -static signed char todrop_counter[9 ] = {0 };
We go from 9 to 8, see below.
Quoted 8 lines
Quoted 8 lines
net/netfilter/ipvs/ip_vs_conn.c +1
-0+struct netns_ipvs *ipvs = cp->ipvs;int i;/* if the conn entry hasn't lasted for 60 seconds, don't drop it. @@ -1579,15 +1585,17 @@ static inline int todrop_entry(struct ip_vs_conn *cp)if (time_before (cp->timeout + jiffies, cp->timer.expires +60 *HZ ))return 0 ;
Quoted 8 lines
net/netfilter/ipvs/ip_vs_conn.c static inline int todrop_entry(struct ip_vs_conn *cp) · line 1590
Quoted 6 lines
net/netfilter/ipvs/ip_vs_conn.c +2
-3-/* Don't drop the entry if its number of incoming packets is not -located in [0, 8] */ +/* Drop only conns with number of incoming packets in [1..8] range */ i =atomic_read (&cp->in_pkts); -if (i >8 || i <0 )return 0 ; +if (i >8 || i <1 )Why did this change? How is this related to the per-netns update?
Using global state in todrop_counter[] is not good,
so we move it to the ipvs struct. We do not want floods in one netns to lead to drops in another netns.
The funny part is that todrop_rate[0] is 0,
so 'if (!todrop_rate[i]) return 0;' will do nothing for i = 0. And I simply converted it to array [8] and translate the packet count 1..8 to index 0..7. So, there is no change in functionality.
Quoted 8 lines
Quoted 8 lines
net/netfilter/ipvs/ip_vs_conn.c +4
-2+return 0 ; -if (!todrop_rate[i])return 0 ; -if (--todrop_counter[i] >0 )return 0 ; + i--; +if (--ipvs->dropentry_counters[i] >0 ) +return 0 ;
Quoted 5 lines
net/netfilter/ipvs/ip_vs_conn.c static inline int todrop_entry(struct ip_vs_conn *cp) · line 1600
Quoted 5 lines
net/netfilter/ipvs/ip_vs_conn.c +2
-1- todrop_counter[i] = todrop_rate[i]; +/* Prefer to drop conns with less number of incoming packets */ + ipvs->dropentry_counters[i] = i +1 ;return 1 ; }
Regards
--
Julian Anastasov <[email protected]>
Julian Anastasov
maintainerPATCH v6 12/14 ipvs: use more keys for connection hashing
In reply to Julian AnastasovSimon Kirby reported long time ago that IPVS connection hashing based only on the client address/port (caddr, cport) as hash keys is not suitable for setups that accept traffic on multiple virtual IPs and ports. It can happen for multiple VIP:VPORT services, for single or many fwmark service(s) that match multiple virtual IPs and ports or even for passive FTP with peristence in DR/TUN mode where we expect traffic on multiple ports for the virtual IP.
Fix it by adding virtual addresses and ports to the hash function. This causes the traffic from NAT real servers to clients to use second hashing for the in->out direction.
As result:
- the IN direction from client will use hash node hn0 where the source/dest addresses and ports used by client will be used as hash keys
- the OUT direction from NAT real servers will use hash node hn1 for the traffic from real server to client
- the persistence templates are hashed only with parameters based on the IN direction, so they now will also use the virtual address, port and fwmark from the service.
OLD:
- all methods: c_list node: proto, caddr:cport
- persistence templates: c_list node: proto, caddr_net:0
- persistence engine templates: c_list node: per-PE, PE-SIP uses jhash
NEW:
- all methods: hn0 node (dir 0): proto, caddr:cport -> vaddr:vport
- MASQ method: hn1 node (dir 1): proto, daddr:dport -> caddr:cport
- persistence templates: hn0 node (dir 0):
proto, caddr_net:0 -> vaddr:vport_or_0
proto, caddr_net:0 -> fwmark:0
- persistence engine templates: hn0 node (dir 0): as before
Also reorder the ip_vs_conn fields, so that hash nodes are on same read-mostly cache line while write-mostly fields are on separate cache line.
--- include/net/ip_vs.h | 104 +++++++----- net/netfilter/ipvs/ip_vs_conn.c | 271 ++++++++++++++++++++++++-------- 2 files changed, 275 insertions(+), 100 deletions(-)
include/net/ip_vs.h +69 -35
@@ -785,51 +785,48 @@ struct ip_vs_conn_param {__u8 pe_data_len; }; +/* Hash node in conn_tab */ +struct ip_vs_conn_hnode { +struct hlist_bl_node node;/* node in conn_tab */ +u32 hash_key;/* Key for the hash table */ +u8 dir;/* 0=out->in, 1=in->out */ +} __packed; +/* IP_VS structure allocated for each dynamically scheduled connection */ struct ip_vs_conn { -struct hlist_bl_node c_list;/* node in conn_tab */ -__u32 hash_key;/* Key for the hash table */ -/* Protocol, addresses and port numbers */ +/* Cacheline for hash table nodes - rarely modified */ + +struct ip_vs_conn_hnode hn0;/* Original direction */ +u8 af;/* address family */ __be16 cport; +struct ip_vs_conn_hnode hn1;/* Reply direction */ +u8 daf;/* Address family of the dest */ __be16 dport; -__be16 vport; -u16 af;/* address family */ -__u16 protocol;/* Which protocol (TCP/UDP) */ -__u16 daf;/* Address family of the dest */ -union nf_inet_addr caddr;/* client address */ -union nf_inet_addr vaddr;/* virtual address */ -union nf_inet_addr daddr;/* destination address */ +struct ip_vs_dest *dest;/* real server */ +atomic_t n_control;/* Number of controlled ones */ volatile __u32 flags;/* status flags */ -struct netns_ipvs *ipvs; - -/* counter and timer */ -refcount_t refcnt;/* reference count */ -struct timer_list timer;/* Expiration timer */ -volatile unsigned long timeout;/* timeout */ +/* 44/64 */ -/* Flags and state transition */ -spinlock_t lock;/* lock for state transition */ +struct ip_vs_conn *control;/* Master control connection */ +const struct ip_vs_pe *pe; +char *pe_data; +__u8 pe_data_len;volatile __u16 state;/* state info */ volatile __u16 old_state;/* old state, to be used for * state transition triggered * synchronization */ -__u32 fwmark;/* Fire wall mark from skb */ -unsigned long sync_endtime;/* jiffies + sent_retries */ +/* 2-byte hole */ +/* 64/96 */ -/* Control members */ -struct ip_vs_conn *control;/* Master control connection */ -atomic_t n_control;/* Number of controlled ones */ -struct ip_vs_dest *dest;/* real server */ -atomic_t in_pkts;/* incoming packet counter */ +union nf_inet_addr caddr;/* client address */ +union nf_inet_addr vaddr;/* virtual address */ +/* 96/128 */ -/* Packet transmitter for different forwarding methods. If it -* mangles the packet, it must return NF_DROP or better NF_STOLEN, -* otherwise this must be changed to a sk_buff **. -* NF_ACCEPT can be returned when destination is local. -*/ -int (*packet_xmit)(struct sk_buff *skb,struct ip_vs_conn *cp, -struct ip_vs_protocol *pp,struct ip_vs_iphdr *iph); +union nf_inet_addr daddr;/* destination address */ +__u32 fwmark;/* Fire wall mark from skb */ +__be16 vport; +__u16 protocol;/* Which protocol (TCP/UDP) */ /* Note: we can group the following members into a structure, * in order to save more space, and the following members are
@@ -837,14 +834,31 @@ struct ip_vs_conn {*/ struct ip_vs_app *app;/* bound ip_vs_app object */ void *app_data;/* Application private data */ +/* 128/168 */ struct_group (sync_conn_opt, struct ip_vs_seq in_seq; /* incoming seq. struct */struct ip_vs_seq out_seq;/* outgoing seq. struct */ ); +/* 152/192 */ -const struct ip_vs_pe *pe; -char *pe_data; -__u8 pe_data_len; +struct timer_list timer;/* Expiration timer */ +volatile unsigned long timeout;/* timeout */ +spinlock_t lock;/* lock for state transition */ +refcount_t refcnt;/* reference count */ +atomic_t in_pkts;/* incoming packet counter */ +/* 64-bit: 4-byte gap */ + +/* 188/256 */ +unsigned long sync_endtime;/* jiffies + sent_retries */ +struct netns_ipvs *ipvs; + +/* Packet transmitter for different forwarding methods. If it +* mangles the packet, it must return NF_DROP or better NF_STOLEN, +* otherwise this must be changed to a sk_buff **. +* NF_ACCEPT can be returned when destination is local. +*/ +int (*packet_xmit)(struct sk_buff *skb,struct ip_vs_conn *cp, +struct ip_vs_protocol *pp,struct ip_vs_iphdr *iph);struct rcu_head rcu_head; };
@@ -1627,6 +1641,19 @@ int ip_vs_conn_desired_size(struct netns_ipvs *ipvs, struct ip_vs_rht *t,struct ip_vs_rht *ip_vs_conn_tab_alloc (struct netns_ipvs *ipvs,int buckets,int lfactor); +static inline struct ip_vs_conn * +ip_vs_hn0_to_conn (struct ip_vs_conn_hnode *hn) +{ + return container_of(hn, struct ip_vs_conn, hn0); +} + +static inline struct ip_vs_conn * +ip_vs_hn_to_conn (struct ip_vs_conn_hnode *hn) +{ + return hn->dir ? container_of(hn, struct ip_vs_conn, hn1) : + container_of(hn, struct ip_vs_conn, hn0); +} + struct ip_vs_conn *ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af, const union nf_inet_addr *daddr, __be16 dport, unsigned int flags,
@@ -1979,6 +2006,13 @@ static inline char ip_vs_fwd_tag(struct ip_vs_conn *cp)return fwd; } +/* Check if connection uses double hashing */ +static inline bool ip_vs_conn_use_hash2 (struct ip_vs_conn *cp) +{ +return IP_VS_FWD_METHOD (cp) ==IP_VS_CONN_F_MASQ && + !(cp->flags &IP_VS_CONN_F_TEMPLATE ); +} +void ip_vs_nat_icmp (struct sk_buff *skb,struct ip_vs_protocol *pp,struct ip_vs_conn *cp,int dir);
net/netfilter/ipvs/ip_vs_conn.c +206 -65
592 lines not on this page · raw message
Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 13/14 ipvs: add ip_vs_status info
In reply to Julian AnastasovAdd /proc/net/ip_vs_status to show current state of IPVS.
--- net/netfilter/ipvs/ip_vs_ctl.c | 145 +++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+)
net/netfilter/ipvs/ip_vs_ctl.c +145 -0
@@ -2915,6 +2915,144 @@ static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)return 0 ; } + +static int ip_vs_status_show (struct seq_file *seq,void *v) +{ +struct net *net =seq_file_single_net (seq); +struct netns_ipvs *ipvs =net_ipvs (net); +unsigned int resched_score =0 ; +struct ip_vs_conn_hnode *hn; +struct hlist_bl_head *head; +struct ip_vs_service *svc; +struct ip_vs_rht *t, *pt; +struct hlist_bl_node *e; +int old_gen, new_gen; +u32 counts[8 ]; +u32 bucket; +int count; +u32 sum1; +u32 sum; +int i; + +rcu_read_lock (); + + t =rcu_dereference (ipvs->conn_tab); + +seq_printf (seq,"Conns:\t%d\n" ,atomic_read (&ipvs->conn_count)); +seq_printf (seq,"Conn buckets:\t%d (%d bits, lfactor %d)\n" , + t ? t->size :0 , t ? t->bits :0 , t ? t->lfactor :0 ); + +if (!atomic_read (&ipvs->conn_count)) + goto after_conns; + old_gen =atomic_read (&ipvs->conn_tab_changes); + +repeat_conn: +smp_rmb ();/* ipvs->conn_tab and conn_tab_changes */ +memset (counts,0 ,sizeof (counts)); +ip_vs_rht_for_each_table_rcu (ipvs->conn_tab, t, pt) { +for (bucket =0 ; bucket < t->size; bucket++) { +DECLARE_IP_VS_RHT_WALK_BUCKET_RCU (); + + count =0 ; + resched_score++; + ip_vs_rht_walk_bucket_rcu(t, bucket, head) { + count =0 ; +hlist_bl_for_each_entry_rcu (hn, e, head, node) + count++; + } + resched_score += count; +if (resched_score >=100 ) { + resched_score =0 ; +cond_resched_rcu (); + new_gen =atomic_read (&ipvs->conn_tab_changes); +/* New table installed ? */ +if (old_gen != new_gen) { + old_gen = new_gen; + goto repeat_conn; + } + } + counts[min (count, (int )ARRAY_SIZE (counts) -1 )]++; + } + } +for (sum =0 , i =0 ; i <ARRAY_SIZE (counts); i++) + sum += counts[i]; + sum1 = sum - counts[0 ]; +seq_printf (seq,"Conn buckets empty:\t%u (%lu%%)\n" , + counts[0 ], (unsigned long )counts[0 ] *100 /max (sum,1U )); +for (i =1 ; i <ARRAY_SIZE (counts); i++) { +if (!counts[i]) +continue ; +seq_printf (seq,"Conn buckets len-%d:\t%u (%lu%%)\n" , + i, counts[i], + (unsigned long )counts[i] *100 /max (sum1,1U )); + } + +after_conns: + t =rcu_dereference (ipvs->svc_table); + + count =ip_vs_get_num_services (ipvs); +seq_printf (seq,"Services:\t%d\n" , count); +seq_printf (seq,"Service buckets:\t%d (%d bits, lfactor %d)\n" , + t ? t->size :0 , t ? t->bits :0 , t ? t->lfactor :0 ); + +if (!count) + goto after_svc; + old_gen =atomic_read (&ipvs->svc_table_changes); + +repeat_svc: +smp_rmb ();/* ipvs->svc_table and svc_table_changes */ +memset (counts,0 ,sizeof (counts)); +ip_vs_rht_for_each_table_rcu (ipvs->svc_table, t, pt) { +for (bucket =0 ; bucket < t->size; bucket++) { +DECLARE_IP_VS_RHT_WALK_BUCKET_RCU (); + + count =0 ; + resched_score++; + ip_vs_rht_walk_bucket_rcu(t, bucket, head) { + count =0 ; +hlist_bl_for_each_entry_rcu (svc, e, head, + s_list) + count++; + } + resched_score += count; +if (resched_score >=100 ) { + resched_score =0 ; +cond_resched_rcu (); + new_gen =atomic_read (&ipvs->svc_table_changes); +/* New table installed ? */ +if (old_gen != new_gen) { + old_gen = new_gen; + goto repeat_svc; + } + } + counts[min (count, (int )ARRAY_SIZE (counts) -1 )]++; + } + } +for (sum =0 , i =0 ; i <ARRAY_SIZE (counts); i++) + sum += counts[i]; + sum1 = sum - counts[0 ]; +seq_printf (seq,"Service buckets empty:\t%u (%lu%%)\n" , + counts[0 ], (unsigned long )counts[0 ] *100 /max (sum,1U )); +for (i =1 ; i <ARRAY_SIZE (counts); i++) { +if (!counts[i]) +continue ; +seq_printf (seq,"Service buckets len-%d:\t%u (%lu%%)\n" , + i, counts[i], + (unsigned long )counts[i] *100 /max (sum1,1U )); + } + +after_svc: +seq_printf (seq,"Stats thread slots:\t%d (max %lu)\n" , + ipvs->est_kt_count, ipvs->est_max_threads); +seq_printf (seq,"Stats chain max len:\t%d\n" , ipvs->est_chain_max); +seq_printf (seq,"Stats thread ests:\t%d\n" , + ipvs->est_chain_max *IPVS_EST_CHAIN_FACTOR * +IPVS_EST_NTICKS ); + +rcu_read_unlock (); +return 0 ; +} +#endif /*
@@ -4835,6 +4973,9 @@ int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs) ipvs->net->proc_net, ip_vs_stats_percpu_show, NULL)) goto err_percpu; +if (!proc_create_net_single ("ip_vs_status" ,0 , ipvs->net->proc_net, + ip_vs_status_show,NULL )) + goto err_status;#endif ret =ip_vs_control_net_init_sysctl (ipvs);
@@ -4845,6 +4986,9 @@ int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs) err:#ifdef CONFIG_PROC_FS +remove_proc_entry ("ip_vs_status" , ipvs->net->proc_net); + +err_status:remove_proc_entry ("ip_vs_stats_percpu" , ipvs->net->proc_net); err_percpu:
@@ -4870,6 +5014,7 @@ void __net_exit ip_vs_control_net_cleanup(struct netns_ipvs *ipvs)ip_vs_control_net_cleanup_sysctl (ipvs);cancel_delayed_work_sync (&ipvs->est_reload_work);#ifdef CONFIG_PROC_FS +remove_proc_entry ("ip_vs_status" , ipvs->net->proc_net);remove_proc_entry ("ip_vs_stats_percpu" , ipvs->net->proc_net);remove_proc_entry ("ip_vs_stats" , ipvs->net->proc_net);remove_proc_entry ("ip_vs" , ipvs->net->proc_net);
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerRe: [PATCHv6 net-next 13/14] ipvs: add ip_vs_status info
Quoted 1 line · Julian Anastasov
Add
/proc/net/ip_vs_statusto show current state of IPVS.
The motivation for this new /proc interface is to provide the output for the users to help them decide when to shrink or grow the hashtable, which is possible with the new sysctl knobs coming in 14/14 in this series.
Quoted 187 lines
Signed-off-by Julian Anastasov <[email protected]>--- net/netfilter/ipvs/ip_vs_ctl.c | 145 +++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+)net/netfilter/ipvs/ip_vs_ctl.c +145
-0@@ -2915,6 +2915,144 @@ static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)return 0 ; } + +static int ip_vs_status_show (struct seq_file *seq,void *v) +{ +struct net *net =seq_file_single_net (seq); +struct netns_ipvs *ipvs =net_ipvs (net); +unsigned int resched_score =0 ; +struct ip_vs_conn_hnode *hn; +struct hlist_bl_head *head; +struct ip_vs_service *svc; +struct ip_vs_rht *t, *pt; +struct hlist_bl_node *e; +int old_gen, new_gen; +u32 counts[8 ]; +u32 bucket; +int count; +u32 sum1; +u32 sum; +int i; + +rcu_read_lock (); + + t =rcu_dereference (ipvs->conn_tab); + +seq_printf (seq,"Conns:\t%d\n" ,atomic_read (&ipvs->conn_count)); +seq_printf (seq,"Conn buckets:\t%d (%d bits, lfactor %d)\n" , + t ? t->size :0 , t ? t->bits :0 , t ? t->lfactor :0 ); + +if (!atomic_read (&ipvs->conn_count)) + goto after_conns; + old_gen =atomic_read (&ipvs->conn_tab_changes); + +repeat_conn: +smp_rmb ();/* ipvs->conn_tab and conn_tab_changes */ +memset (counts,0 ,sizeof (counts)); +ip_vs_rht_for_each_table_rcu (ipvs->conn_tab, t, pt) { +for (bucket =0 ; bucket < t->size; bucket++) { +DECLARE_IP_VS_RHT_WALK_BUCKET_RCU (); + + count =0 ; + resched_score++; + ip_vs_rht_walk_bucket_rcu(t, bucket, head) { + count =0 ; +hlist_bl_for_each_entry_rcu (hn, e, head, node) + count++; + } + resched_score += count; +if (resched_score >=100 ) { + resched_score =0 ; +cond_resched_rcu (); + new_gen =atomic_read (&ipvs->conn_tab_changes); +/* New table installed ? */ +if (old_gen != new_gen) { + old_gen = new_gen; + goto repeat_conn; + } + } + counts[min (count, (int )ARRAY_SIZE (counts) -1 )]++; + } + } +for (sum =0 , i =0 ; i <ARRAY_SIZE (counts); i++) + sum += counts[i]; + sum1 = sum - counts[0 ]; +seq_printf (seq,"Conn buckets empty:\t%u (%lu%%)\n" , + counts[0 ], (unsigned long )counts[0 ] *100 /max (sum,1U )); +for (i =1 ; i <ARRAY_SIZE (counts); i++) { +if (!counts[i]) +continue ; +seq_printf (seq,"Conn buckets len-%d:\t%u (%lu%%)\n" , + i, counts[i], + (unsigned long )counts[i] *100 /max (sum1,1U )); + } + +after_conns: + t =rcu_dereference (ipvs->svc_table); + + count =ip_vs_get_num_services (ipvs); +seq_printf (seq,"Services:\t%d\n" , count); +seq_printf (seq,"Service buckets:\t%d (%d bits, lfactor %d)\n" , + t ? t->size :0 , t ? t->bits :0 , t ? t->lfactor :0 ); + +if (!count) + goto after_svc; + old_gen =atomic_read (&ipvs->svc_table_changes); + +repeat_svc: +smp_rmb ();/* ipvs->svc_table and svc_table_changes */ +memset (counts,0 ,sizeof (counts)); +ip_vs_rht_for_each_table_rcu (ipvs->svc_table, t, pt) { +for (bucket =0 ; bucket < t->size; bucket++) { +DECLARE_IP_VS_RHT_WALK_BUCKET_RCU (); + + count =0 ; + resched_score++; + ip_vs_rht_walk_bucket_rcu(t, bucket, head) { + count =0 ; +hlist_bl_for_each_entry_rcu (svc, e, head, + s_list) + count++; + } + resched_score += count; +if (resched_score >=100 ) { + resched_score =0 ; +cond_resched_rcu (); + new_gen =atomic_read (&ipvs->svc_table_changes); +/* New table installed ? */ +if (old_gen != new_gen) { + old_gen = new_gen; + goto repeat_svc; + } + } + counts[min (count, (int )ARRAY_SIZE (counts) -1 )]++; + } + } +for (sum =0 , i =0 ; i <ARRAY_SIZE (counts); i++) + sum += counts[i]; + sum1 = sum - counts[0 ]; +seq_printf (seq,"Service buckets empty:\t%u (%lu%%)\n" , + counts[0 ], (unsigned long )counts[0 ] *100 /max (sum,1U )); +for (i =1 ; i <ARRAY_SIZE (counts); i++) { +if (!counts[i]) +continue ; +seq_printf (seq,"Service buckets len-%d:\t%u (%lu%%)\n" , + i, counts[i], + (unsigned long )counts[i] *100 /max (sum1,1U )); + } + +after_svc: +seq_printf (seq,"Stats thread slots:\t%d (max %lu)\n" , + ipvs->est_kt_count, ipvs->est_max_threads); +seq_printf (seq,"Stats chain max len:\t%d\n" , ipvs->est_chain_max); +seq_printf (seq,"Stats thread ests:\t%d\n" , + ipvs->est_chain_max *IPVS_EST_CHAIN_FACTOR * +IPVS_EST_NTICKS ); + +rcu_read_unlock (); +return 0 ; +} +#endif /* @@ -4835,6 +4973,9 @@ int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs) ipvs->net->proc_net, ip_vs_stats_percpu_show, NULL)) goto err_percpu; +if (!proc_create_net_single ("ip_vs_status" ,0 , ipvs->net->proc_net, + ip_vs_status_show,NULL )) + goto err_status;#endif ret =ip_vs_control_net_init_sysctl (ipvs);@@ -4845,6 +4986,9 @@ int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs) err:#ifdef CONFIG_PROC_FS +remove_proc_entry ("ip_vs_status" , ipvs->net->proc_net); + +err_status:remove_proc_entry ("ip_vs_stats_percpu" , ipvs->net->proc_net); err_percpu:@@ -4870,6 +5014,7 @@ void __net_exit ip_vs_control_net_cleanup(struct netns_ipvs *ipvs)ip_vs_control_net_cleanup_sysctl (ipvs);cancel_delayed_work_sync (&ipvs->est_reload_work);#ifdef CONFIG_PROC_FS +remove_proc_entry ("ip_vs_status" , ipvs->net->proc_net);remove_proc_entry ("ip_vs_stats_percpu" , ipvs->net->proc_net);remove_proc_entry ("ip_vs_stats" , ipvs->net->proc_net);remove_proc_entry ("ip_vs" , ipvs->net->proc_net);Signature · 1 line
2.51.0
Julian Anastasov
maintainerPATCH v6 14/14 ipvs: add conn_lfactor and svc_lfactor sysctl vars
In reply to Julian AnastasovAllow the default load factor for the connection and service tables to be configured.
--- Documentation/networking/ipvs-sysctl.rst | 33 ++++++++++ net/netfilter/ipvs/ip_vs_ctl.c | 76 ++++++++++++++++++++++++ 2 files changed, 109 insertions(+)
Documentation/networking/ipvs-sysctl.rst +33 -0
@@ -29,6 +29,30 @@ backup_only - BOOLEAN If set, disable the director function while the server is in backup mode to avoid packet loops for DR/TUN methods. +conn_lfactor - INTEGER + -4 - default + Valid range: -8 (larger table) .. 8 (smaller table) + + Controls the sizing of the connection hash table based on the + load factor (number of connections per table buckets): + 2^conn_lfactor = nodes / buckets + As result, the table grows if load increases and shrinks when + load decreases in the range of 2^8 - 2^conn_tab_bits (module + parameter). + The value is a shift count where negative values select + buckets = (connection hash nodes << -value) while positive + values select buckets = (connection hash nodes >> value). The + negative values reduce the collisions and reduce the time for + lookups but increase the table size. Positive values will + tolerate load above 100% when using smaller table is + preferred with the cost of more collisions. If using NAT + connections consider decreasing the value with one because + they add two nodes in the hash table. + + Example: + -4: grow if load goes above 6% (buckets = nodes * 16) + 2: grow if load goes above 400% (buckets = nodes / 4) + conn_reuse_mode - INTEGER 1 - default
@@ -219,6 +243,15 @@ secure_tcp - INTEGER The value definition is the same as that of drop_entry and drop_packet. +svc_lfactor - INTEGER + -3 - default + Valid range: -8 (larger table) .. 8 (smaller table) + + Controls the sizing of the service hash table based on the + load factor (number of services per table buckets). The table + will grow and shrink in the range of 2^4 - 2^20. + See conn_lfactor for explanation. + sync_threshold - vector of 2 INTEGERs: sync_threshold, sync_period default 3 50
net/netfilter/ipvs/ip_vs_ctl.c +76 -0
94 lines not on this page · raw message
Signature · 1 line
2.51.0
Pablo Neira Ayuso
maintainerHi Julian,
This is v6 and you have work hard on this, and I am coming late to review... but may I suggest to split this series?
From my understanding, here I can see initial preparation patches, including improvements, that could be applied initially before the per-netns support.
Then, follow up with initial basic per-netns conversion.
Finally, pursue more advanced datastructures / optimizations.
If this is too extreme/deal breaker, let me know.
Thanks a lot for your work on IPVS.
Quoted 211 lines · Julian Anastasov
Hello,
This patchset targets more netns isolation when IPVS
is used in large setups and also includes some optimizations.First patch adds useful wrappers to
rculist_bl, thehlist_blmethods IPVS will use in the following patches. The other patches are IPVS-specific.The following patches will:
* Convert the global
__ip_vs_mutexto per-netservice_mutexand switch the service tables to be per-net, cowork by Jiejian Wu and Dust Li* Convert some code that walks the service lists to use RCU instead of the
service_mutex* We used two tables for services (non-fwmark and fwmark), merge them into single
svc_table* The list for unavailable destinations (
dest_trash) holds dsts and thus dev references causing extra work for theip_vs_dst_event()dev notifier handler. Change this by dropping the reference when dest is removed and saved intodest_trash. Thedest_trashwill need more changes to make it light for lookups. TODO.* On new connection we can do multiple lookups for services by tryng different fallback options. Add more counters for service types, so that we can avoid unneeded lookups for services.
* Add infrastructure for resizable hash tables based on
hlist_blwhich we will use for services and connections: hlists with per-bucket bit lock in the heads. The resizing delays RCU lookups on a bucket level with seqcounts which are protected with spin locks. The entries keep the table ID and the hash value which allows to filter the entries without touching many cache lines and to unlink the entries without lookup by keys.* Change the 256-bucket service hash table to be resizable in the range of 4..20 bits depending on the added services and use jhash hashing to reduce the collisions.
* Change the global connection table to be per-net and resizable in the range of 256..ip_vs_conn_tab_size. As the connections are hashed by using remote addresses and ports, use siphash instead of jhash for better security.
* As the connection table is not with fixed size, show its current size to user space
* As the connection table is not global anymore, the
no_cportand dropentry counters can be per-net* Make the connection hashing more secure for setups with multiple services. Hashing only by remote address and port (client info) is not enough. To reduce the possible hash collisions add the used virtual address/port (local info) into the hash and as a side effect the MASQ connections will be double hashed into the hash table to match the traffic from real servers:
OLD:
- all methods:c_listnode: proto, caddr:cport
NEW:
- all methods: hn0 node (dir 0): proto, caddr:cport -> vaddr:vport
- MASQ method: hn1 node (dir 1): proto, daddr:dport -> caddr:cport* Add
/proc/net/ip_vs_statusto show current state of IPVS, per-netcat
/proc/net/ip_vs_status
Conns: 9401
Conn buckets: 524288 (19 bits, lfactor -5)
Conn buckets empty: 505633 (96%)
Conn buckets len-1: 18322 (98%)
Conn buckets len-2: 329 (1%)
Conn buckets len-3: 3 (0%)
Conn buckets len-4: 1 (0%)
Services: 12
Service buckets: 128 (7 bits, lfactor -3)
Service buckets empty: 116 (90%)
Service buckets len-1: 12 (100%)
Stats thread slots: 1 (max 16)
Stats chain max len: 16
Stats thread ests: 38400It shows the table size, the load factor (2^n), how many are the empty buckets, with percents from the all buckets, the number of buckets with length 1..7 where len-7 catches all len>=7 (zero values are not shown). The len-N percents ignore the empty buckets, so they are relative among all len-N buckets. It shows that smaller lfactor is needed to achieve len-1 buckets to be ~98%. Only real tests can show if relying on len-1 buckets is a better option because the hash table becomes too large with multiple connections. And as every table uses random key, the services may not avoid collision in all cases.
* add
conn_lfactorandsvc_lfactorsysctl vars, so that one can tune the connection/service hash table sizingLinks to downloadable patchset versions:
v6 (19 Oct 2025):
https://ja.ssi.bg/tmp/rht_v6.tgzv5 (16 Sep 2024):
https://ja.ssi.bg/tmp/rht_v5.tgzv4 (28 May 2024):
https://ja.ssi.bg/tmp/rht_v4.tgzv3 (31 Mar 2024):
https://ja.ssi.bg/tmp/rht_v3.tgzv2 (12 Dec 2023):
https://ja.ssi.bg/tmp/rht_v2.tgzv1 (15 Aug 2023):
https://ja.ssi.bg/tmp/rht_v1.tgzChanges in v6:
Patch 5:
* resync
Patch 8:
* resync: useREAD_ONCEforipvs->enable
* resync: use %zu forsize_t
Patch 9:
* resync: use the newskip_elemsvalue
* resync: useREAD_ONCEforipvs->enable
Patch 12:
* resync: use the newskip_elemsvalueChanges in v5:
Patch 6:
* resync with changes in main tree (6.11)
Patch 8:
* resync with changes in main tree (6.11)
Patch 9:
* resync with changes in main tree (6.11)
Patch 14:
* resync with changes in main tree (6.11)Changes in v4:
Patch 14:
* the load factor parameters will be read-only for unprivileged namespaces while we do not account the allocated memory
Patch 5:
* resync with changes in main treeChanges in v3:
Patch 7:
* change the sign of the load factor parameter, so that 2^lfactor = load/size
Patch 8:
* change the sign of the load factor parameter
* fix 'gotounlock_sem' insvc_resize_work_handler()after the lastmutex_trylock()call, should be gotounlock_m
* nowcond_resched_rcu()needs to includelinux/rcupdate_wait.hPatch 9:
* consider that the sign of the load factor parameter is changed Patch 12:
* consider that the sign of the load factor parameter is changed Patch 14:
* change the sign of the load factor parameters in docsChanges in v2:
Patch 1:
* add comments tohlist_bl_for_each_entry_continue_rcuand fix sparse warnings
Patch 9:
* Simon Kirby reports that backup server crashes ifconn_tabis not created. Create it just to sync conns before any services are added.
Patch 11:
* kernel test robot reported fordropentry_countersproblem when compiling with !CONFIG_SYSCTL, so it is time to wraptodrop_entry,ip_vs_conn_ops_modeandip_vs_random_dropentryunderCONFIG_SYSCTL
Patch 13:
* remove extraold_genassignment at start ofip_vs_status_show()Jiejian Wu (1):
ipvs: makeip_vs_svc_tableandip_vs_svc_fwm_tableper netnsJulian Anastasov (13):
rculist_bl: addhlist_bl_for_each_entry_continue_rcu
ipvs: some service readers can use RCU
ipvs: use single svc table
ipvs: do not keepdest_dstafter dest is removed
ipvs: use more counters to avoid service lookups
ipvs: add resizable hash tables
ipvs: use resizable hash table for services
ipvs: switch to per-net connection table
ipvs: show the currentconn_tabsize to users
ipvs:no_cportand dropentry counters can be per-net
ipvs: use more keys for connection hashing
ipvs: addip_vs_statusinfo
ipvs: addconn_lfactorandsvc_lfactorsysctl varsDocumentation/networking/ipvs-sysctl.rst | 33 + include/linux/rculist_bl.h | 49 +- include/net/ip_vs.h | 395 ++++++- net/netfilter/ipvs/ip_vs_conn.c | 1052 +++++++++++++----- net/netfilter/ipvs/ip_vs_core.c | 177 +++- net/netfilter/ipvs/ip_vs_ctl.c | 1232 ++++++++++++++++------ net/netfilter/ipvs/ip_vs_est.c | 18 +- net/netfilter/ipvs/ip_vs_pe_sip.c | 4 +- net/netfilter/ipvs/ip_vs_sync.c | 23 + net/netfilter/ipvs/ip_vs_xmit.c | 39 +- 10 files changed, 2340 insertions(+), 682 deletions(-)Signature · 1 line
2.51.0
Julian Anastasov
maintainerHello,
Quoted 6 lines · Pablo Neira Ayuso
Hi Julian,
This is v6 and you have work hard on this, and I am coming late to review... but may I suggest to split this series?
Quoted 1 line
From my understanding, here I can see initial preparation patches,
Quoted 8 lines
including improvements, that could be applied initially before the per-netns support.
Then, follow up with initial basic per-netns conversion.
Finally, pursue more advanced datastructures / optimizations.
If this is too extreme/deal breaker, let me know.
It should be possible to split it to 2-3 parts.
And may be I'll change the ip_vs_dst_event() code to be faster and race free...
Regards
--
Julian Anastasov <[email protected]>