On Fri, May 19, 2017 at 03:33:12PM +0100, Dr. David Alan Gilbert wrote: > * Daniel P. Berrange (berra...@redhat.com) wrote: > > > shutdown() is safe, in that it stops any other threads accessing the fd > > > but doesn't allow it's reallocation until the close; We perform the > > > close only when we've joined all other threads that were using the fd. > > > Any of the threads that do new calls on the fd get an error and quickly > > > fall down their error paths. > > > > Ahh that's certainly an interesting scenario. That would certainly be > > a problem with the migration code when this was originally written. > > It had two QEMUFile structs each with an 'int fd' field, so when you > > close 'fd' on one QEMUFile struct, it wouldn't update the other QEMUFile > > used by another thread. > > > > Since we switched over to use QIOChannel though, I think the thread > > scenario you describe should be avoided entirely. When you have multiple > > QEMUFile objects, they each have a reference counted pointer to the same > > underlying QIOChannel object instance. So when QEMUFile triggers a call > > to qio_channel_close() in one thread, that'll set fd=-1 in the QIOChannel. > > Since the other threads have a reference to the same QIOChannel object, > > they'll now see this fd == -1 straightaway. > > > > So, IIUC, this should make the need for shutdown() redundant (at least > > for the thread race conditions you describe). > > That's not thread safe unless you're doing some very careful locking. > Consider: > T1 T2 > oldfd=fd tmp=fd > fd=-1 > close(oldfd) > unrelated open() > read(tmp,... > > In practice every use of fd will be a copy into a tmp and then the > syscall; the unrelated open() could happen in another thread. > (OK, the gap between the tmp and the read is tiny, although if we're > doing multiple operations chances are the compiler will optimise > it to the top of a loop). > > There's no way to make that code safe.
Urgh, yes, I see what you mean. Currently the QIOChannelCommand implementation, uses a pair of anonymous pipes for stdin/out to the child process. I wonder if we could switch that to use socketpair() instead, thus letting us shutdown() on it too. Though I guess it would be sufficient for qio_channel_shutdown() to merely kill the child PID, while leaving the FDs open, as then you'd get EOF and/or EPIPE on the read/writes. Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|