Subject: Re: [bpf PATCH] bpf: sockmap, remove bucket->lock from sock_{hash|map}_free

From: Jakub Sitnicki <[email-masked]>
Date: Wed, 03 Jun 2020 22:39:12 +0200

On Wed, Jun 03, 2020 at 08:35 PM CEST, John Fastabend wrote:
> Jakub Sitnicki wrote:

[...]

>> I'm not sure that the check for map->refcnt when sock is unlinking
>> itself from the map will do it. I worry we will then have issues when
>> sockhash is unlinking itself from socks (so the other way around) in
>> sock_hash_free(). We could no longer assume that the sock & psock
>> exists.
>>
>> What comes to mind is to reintroduce the spin-lock protected critical
>> section in sock_hash_free(), but delay the processing of sockets to be
>> unlinked from sockhash. We could grab a ref to sk_psock while holding a
>> spin-lock and unlink it while no longer in atomic critical section.
>
> It seems so. In sock_hash_free we logically need,
>
>  for (i = 0; i < htab->buckets_num; i++) {
>   hlist_for_each_entryy_safe(...) {
>   	hlist_del_rcu() <- detached from bucket and no longer reachable

Just to confirm - synchronize_rcu() doesn't prevent
sock_hash_delete_from_link() from getting as far as hlist_del_rcu(),
that is here [0], while on another cpu sock_hash_free() is also
performing hlist_del_rcu().

That is, reintroducing the spin-lock is needed, right? Otherwise we have
two concurrent updaters that are not synchronized.

>         synchronize_rcu()
>         // now element can not be reached from unhash()
> 	... sock_map_unref(elem->sk, elem) ...
>   }
>  }
>
> We don't actually want to stick a synchronize_rcu() in that loop
> so I agree we need to collect the elements do a sync then remove them.

[...]

>>
>> John, WDYT?
>
> Want to give it a try? Or I can draft something.

I can give it a try, as I clearly need to wrap my head better around
this code path. But I can only see how to do it with a spin-lock back in
place in sock_hash_free(). If you have an idea in mind how to do it
locklessly, please go ahead.

[...]

[0] https://elixir.bootlin.com/linux/latest/source/net/core/sock_map.c#L738