iiod: Make DevEntry reference counted
iiod: Make DevEntry reference counted

Currently the ThreadEntry is managed and owned by the RW thread and we
need to make sure that it is not accidentally freed while being accessed in
the client threads. This is done using the devlist_lock. Since this lock is
shared between all threads there is contention between clients which try to
access different devices. Furthermore almost all critical sections are
protected by both the devlist_lock as well as the ThreadEntry thdlist_lock,
making one of them redundant.

To address the issue make the DevEntry structs reference counted. Each of
the client threads, which have the device open, as well as the RW thread
each own one reference. This makes sure that the data structure is not
freed while still in use and allows to remove the devlist_lock around most
critical sections. The devlist_lock is still used to protect against
concurrent RW thread creation and destruction.

One tricky part is to avoid race conditions between the RW thread shutting
itself down and a new client connecting and wanting to create a new thread.
Such a situation could lead to the new thread trying to call
iio_buffer_create() while the previous one hasn't called
iio_buffer_destroy() yet, causing the former to fail.  The thdlist_lock is
used in combination with the newly introduced 'closed' flag to make sure
that if a client connects while a thread is shutting down the new client
waits until iio_buffer_destroy() has finished for the current thread and
only then a new thread is created.

This patch is also necessary for fixing the pthread condition handling
which will be done in a follow up patch.

Signed-off-by: Lars-Peter Clausen <3318dc5ce3e4fb7c28a0b841b6801c884e1d0896@metafoo.de>

analogdevicesinc/libiio,analogdevicesinc/libiio,analogdevicesinc/libiio,analogdevicesinc/libiio