Re: [Libguestfs] [PATCH libnbd] examples: Fix theoretical cookie race in example.

Eric Blake
Tue, 30 Jul 2019 15:01:43 -0000

On 7/30/19 5:54 AM, Richard W.M. Jones wrote:
> On Tue, Jul 30, 2019 at 11:51:40AM +0100, Richard W.M. Jones wrote:
>> Previously discussed here:
>> https://www.redhat.com/archives/libguestfs/2019-July/msg00213.html
>>
>> It turns out that deferring callbacks is a PITA.  (It would be a bit
>> easier if C has closures.)  However by rewriting the example we can
>> avoid the need to use the cookie at all and make it run a bit more
>> efficiently, so let's do that instead.
>
> I was going to say also:
>
> The callbacks pass the command cookie back to the caller, and are thus
> all potentially racy.  There seem to be two possibilities here: (1)
> Drop the cookie parameter entirely.  (2) Document the possible race so
> that users don't use the cookie inappropritely.
>
> I think I favour option (1).

We already have option (2) to some extent; libnbd.pod states:

The completion callback will be invoked with C<cookie> set
to the same value returned by the original API such as
C<nbd_aio_pread_callback> (in rare cases, it is possible that the
completion callback may fire before the original API has returned).

But I also favor option (1); my recent changes to nbdkit to use
auto-retire also managed to get rid of the need to rely on the cookie
argument.  The cookie is still important for clients not using
auto-retire, but by getting rid of the cookie parameter to the
completion callback, we are forcing the client to do their own mapping
of their void* parameter to determine which command is being completed -
but that turns out to be the most efficient anyways (both nbdkit and
your glib example got that that point without too much difficulty).

It's another API/ABI break, but I don't see it as being detrimental
(none of our existing completion callbacks are too difficult to keep
working if they lose the cookie parameter).

--
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization:  qemu.org | libvirt.org