Allowing more than 64k bound connections.
Linux sockets have nice reuse-addr option, which allows to bind multiple sockets to the same port if they use different local addresses and are not listeining sockets. This works only if selecting port by hands and if setting zero port in
bind(), it will fail after local port range is exhausted.
There are crazy people who want to have many tens of thousands of bound connections, but having several interface aliases to be able to bing to the different addresses and being able to have many connections, and calling
bind() with zero port ends up only with 32-64k connections (depending on the local port range syscall).
Attached patch allows to remove this limit. Currently inet port selection algorithm runs over the whole bind hash table and checks if appropriate hash bucket does not use randomly selected port. When it found given cell, system binds socket to the selected port. If sockets are not freed, this will be finished after local port range is exhausted, not even trying to check if bound sockets have reuse socket option and thus could share the bucket.
My patch implements just that: when there are no buckets, which do not have our random port, we will use that one, which contains sockets with reuse option and has the smallest number of sockets in it. Its hot path overhead (i.e. when there are empty buckets) corresponds to additional three additional condition checks for the buckets which are not empty, and in case of all positive, storing two values into the local variables. When local port range is empty, we will quickly select given port based on that stored values. It could be possible to add some heuerisstics into the bucket selection, i.e. when overall number of ports is more than 2/3 of the hash table, we could just randomly select the bucket and work with it.
This only affects port selection path invoked via
bind() call with port fiels being equal to zero.