xfrm: Serialize offload stats updates with x->lock

xfrm_dev_state_update_stats() calls into the driver, which adds to
x->curlft and x->stats what the device counted since the last call.
Callers use different locks, so two of them can refresh the same
state at once and count the same packets twice, and a dump can copy
the counters while another caller updates them.

Serialize all device stats refreshes with x->lock and assert it in
xfrm_dev_state_update_stats(). Build the SA message of a netlink
dump, get or notification under the same lock.

The SA dump and xfrm_state_update_stats() walk the states under
xfrm_state_lock, where x->lock cannot be taken: the lock order is
x->lock, then xfrm_state_lock. Add xfrm_state_walk_batch(), which
takes references on at most 32 states per xfrm_state_lock hold, and
handle each state under x->lock after the list lock is dropped.
States rejected by the dump filter count against the 32, so a filter
that matches few states cannot keep the list lock held over the whole
list. xfrm_state_walk() cannot give this bound: it calls back only
for states that pass the filter. Walk markers and states being
deleted do not count, so a call always covers 32 states or reaches
the end of the list.

Keep the refresh right before each state is copied, so every part of
a multi-part dump still has current counters. When a state does not
fit into the skb, put the walk marker back in front of it and drop
the references, so no state stays referenced between two dump calls.
If the state was unlinked meanwhile, skip it and go on.

copy_to_user_state() cannot take x->lock itself: build_expire() calls
it with the lock held. Move the refresh out of it and let each caller
refresh under x->lock. PF_KEY never refreshed and does not change.

Fixes: c9fa320b00cf ("xfrm: copy_to_user_state fetch offloaded SA packets/bytes statistics")
Fixes: f9f221c98fd8 ("xfrm: get global statistics from the offloaded device")
Signed-off-by: Jianbo Liu <jianbol@nvidia.com>
Reviewed-by: Carolina Jubran <cjubran@nvidia.com>
Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com>
3 files changed