libxl child process handling Ian Campbell <[email protected]>, Stefano Stabellini <[email protected]>
cover libxl child process handling Ian Campbell <[email protected]>, Stefano Stabellini <[email protected]>
Once again, I have not executed the code in this series! I have however updated it, added several yak-shaving patches, and a new patch to make libxl_run_bootloader an ao function.
These three are intended to be bugfixes to sort out the deadlock problem that Roger Pau Monne reported.
01/20 libxl: ao: allow immediate completion
02/20 libxl: fix hang due to libxl__initiate_device_remove 03/20 libxl: Fix eventloop_iteration over-locking
Roger, can you confirm whether they work for you ?
These are other bugfixes:
04/20 libxl: Fix leak of ctx->lock
06/20 tools: Correct PTHREAD options in config/StdGNU.mk 07/20 libxl: Use PTHREAD_CFLAGS, LDFLAGS, LIBS 08/20 tools: Use PTHREAD_CFLAGS, _LDFLAGS, _LIBS 19/20 libxl: Clean up setdefault in do_domain_create
These are clarifications and improvements related to memory allocation:
09/20 libxl: Crash (more sensibly) on malloc failure
10/20 libxl: Make libxl__zalloc et al tolerate a NULL gc
These are preparatory work:
05/20 libxl: abolish libxl_ctx_postfork
11/20 libxl: Introduce some convenience macros
14/20 libxl: include <ctype.h> and introduce CTYPE helper macro 15/20 libxl: include <_libxl_paths.h> in libxl_internal.h 17/20 libxl: Provide libxl_string_list_length
These are new event-related infrastructure:
12/20 libxl: Protect fds with CLOEXEC even with forking threads 13/20 libxl: libxl_event.c:beforepoll_internal, REQUIRE_FDS 16/20 libxl: event API: new facilities for waiting for subprocesses 18/20 libxl: Introduce libxl__sendmsg_fds and libxl__recvmsg_fds
And here, finally, is a user!
20/20 libxl: ao: Convert libxl_run_bootloader
In the pipeline, I have a half-done reorganisation of libxl_create.c's do_domain_create to make it asynchronous. When that's completed I'll be able to test this stack.
Ian.
PATCH 1/20 libxl: ao: allow immediate completion
Make it possible to complete an ao during its initating function.
Previously this was not generally possible because initiators did not have an egc. But there is no reason why an ao initiator should not have an egc, so make the standard macros provide one.
Change the internal documentation comments accordingly. (This change, which means that an initiator function may call a completion callback directly, is already consistent with the documented external API.)
We also invent of a new state flag "constructing" which indicates whether we are between ao__create and ao__inprogress. This is a slightly optimisation which allows ao_complete to not bother poking the wakeup pipe, since the logic in ao__inprogress will not run the event loop if the ao is complete on entry.
Also fix the wording in the libxl_internal.h comment forbidding use of ao_how-taking functions from within libxl. (There are sadly currently some such functions.)
--- tools/libxl/libxl_event.c | 7 ++++++- tools/libxl/libxl_internal.h | 14 ++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-)
tools/libxl/libxl_event.c +6 -1
@@ -1225,7 +1225,9 @@ void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc)if (ao->poller) {assert (ao->in_initiator); -libxl__poller_wakeup (egc, ao->poller); +if (!ao->constructing) +/* don't bother with this if we're not in the event loop */ +libxl__poller_wakeup (egc, ao->poller); }else if (ao->how.callback) {LIBXL_TAILQ_INSERT_TAIL (&egc->aos_for_callback, ao, entry_for_callback); }else {
@@ -1251,6 +1253,7 @@ libxl__ao *libxl__ao_create(libxl_ctx *ctx, uint32_t domid,if (!ao) goto out; ao->magic =LIBXL__AO_MAGIC ; + ao->constructing =1 ; ao->in_initiator =1 ; ao->poller =0 ; ao->domid = domid;
@@ -1275,7 +1278,9 @@ int libxl__ao_inprogress(libxl__ao *ao)int rc;assert (ao->magic ==LIBXL__AO_MAGIC ); +assert (ao->constructing);assert (ao->in_initiator); + ao->constructing =0 ;if (ao->poller) {/* Caller wants it done synchronously. */
tools/libxl/libxl_internal.h +10 -4
@@ -347,7 +347,7 @@ struct libxl__egc {struct libxl__ao {uint32_t magic; -unsigned in_initiator:1 , complete:1 , notified:1 ; +unsigned constructing:1 , in_initiator:1 , complete:1 , notified:1 ;int rc;libxl__gc gc;libxl_asyncop_how how;
@@ -1209,7 +1209,11 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* operation ("ao") machinery. The function should take a parameter * const libxl_asyncop_how *ao_how and must start with a call to * AO_INITIATOR_ENTRY. These functions MAY NOT be called from -* outside libxl, because they can cause reentrancy callbacks. +* inside libxl, because they can cause reentrancy callbacks. +* +* For the same reason functions taking an ao_how may make themselves +* an egc with EGC_INIT (and they will generally want to, to be able +* to immediately complete an ao during its setup). * * Lifecycle of an ao: *
@@ -1240,8 +1244,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* directly or indirectly, should call libxl__ao_complete (with the * ctx locked, as it will generally already be in any event callback * function). This must happen exactly once for each ao (and not if -* the ao has been destroyed, obviously), and it may not happen -* until libxl__ao_inprogress has been called on the ao. +* the ao has been destroyed, obviously). * * - Note that during callback functions, two gcs are available: * - The one in egc, whose lifetime is only this callback
@@ -1255,12 +1258,14 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);libxl__ctx_lock (ctx); \libxl__ao *ao =libxl__ao_create (ctx, domid, ao_how); \if (!ao) {libxl__ctx_unlock (ctx);return ERROR_NOMEM ; } \ +libxl__egc egc[1 ];LIBXL_INIT_EGC (egc[0 ],ctx); \AO_GC ; #define AO_INPROGRESS ({ \ libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc); \ int ao__rc = libxl__ao_inprogress(ao); \ libxl__ctx_unlock(ao__ctx); /* gc is now invalid */ \ +EGC_FREE ; \ (ao__rc); \ })
@@ -1269,6 +1274,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);assert (rc); \libxl__ao_abort (ao); \libxl__ctx_unlock (ao__ctx);/* gc is now invalid */ \ +EGC_FREE ; \ (rc); \ })
Signature · 1 line
1.7.2.5
Re: [PATCH 01/20] libxl: ao: allow immediate completion
Quoted 16 lines · Ian Jackson
Make it possible to complete an ao during its initating function.
Previously this was not generally possible because initiators did not have an egc. But there is no reason why an ao initiator should not have an egc, so make the standard macros provide one.
Change the internal documentation comments accordingly. (This change, which means that an initiator function may call a completion callback directly, is already consistent with the documented external API.)
We also invent of a new state flag "constructing" which indicates whether we are between
ao__createandao__inprogress. This is a slightly optimisation which allowsao_completeto not bother poking the wakeup pipe, since the logic inao__inprogresswill not run the event loop if the ao is complete on entry.
Quoted 6 lines
Also fix the wording in the
libxl_internal.hcomment forbidding use of ao_how-taking functions from within libxl. (There are sadly currently some such functions.)Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>
Quoted 97 lines
--- tools/libxl/libxl_event.c | 7 ++++++- tools/libxl/libxl_internal.h | 14 ++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-)tools/libxl/libxl_event.c +6
-1@@ -1225,7 +1225,9 @@ void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc)if (ao->poller) {assert (ao->in_initiator); -libxl__poller_wakeup (egc, ao->poller); +if (!ao->constructing) +/* don't bother with this if we're not in the event loop */ +libxl__poller_wakeup (egc, ao->poller); }else if (ao->how.callback) {LIBXL_TAILQ_INSERT_TAIL (&egc->aos_for_callback, ao, entry_for_callback); }else {@@ -1251,6 +1253,7 @@ libxl__ao *libxl__ao_create(libxl_ctx *ctx, uint32_t domid,if (!ao) goto out; ao->magic =LIBXL__AO_MAGIC ; + ao->constructing =1 ; ao->in_initiator =1 ; ao->poller =0 ; ao->domid = domid;@@ -1275,7 +1278,9 @@ int libxl__ao_inprogress(libxl__ao *ao)int rc;assert (ao->magic ==LIBXL__AO_MAGIC ); +assert (ao->constructing);assert (ao->in_initiator); + ao->constructing =0 ;if (ao->poller) {/* Caller wants it done synchronously. */ tools/libxl/libxl_internal.h +10
-4@@ -347,7 +347,7 @@ struct libxl__egc {struct libxl__ao {uint32_t magic; -unsigned in_initiator:1 , complete:1 , notified:1 ; +unsigned constructing:1 , in_initiator:1 , complete:1 , notified:1 ;int rc;libxl__gc gc;libxl_asyncop_how how;@@ -1209,7 +1209,11 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* operation ("ao") machinery. The function should take a parameter * const libxl_asyncop_how *ao_how and must start with a call to * AO_INITIATOR_ENTRY. These functions MAY NOT be called from -* outside libxl, because they can cause reentrancy callbacks. +* inside libxl, because they can cause reentrancy callbacks. +* +* For the same reason functions taking an ao_how may make themselves +* an egc with EGC_INIT (and they will generally want to, to be able +* to immediately complete an ao during its setup). * * Lifecycle of an ao: * @@ -1240,8 +1244,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* directly or indirectly, should call libxl__ao_complete (with the * ctx locked, as it will generally already be in any event callback * function). This must happen exactly once for each ao (and not if -* the ao has been destroyed, obviously), and it may not happen -* until libxl__ao_inprogress has been called on the ao. +* the ao has been destroyed, obviously). * * - Note that during callback functions, two gcs are available: * - The one in egc, whose lifetime is only this callback @@ -1255,12 +1258,14 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);libxl__ctx_lock (ctx); \libxl__ao *ao =libxl__ao_create (ctx, domid, ao_how); \if (!ao) {libxl__ctx_unlock (ctx);return ERROR_NOMEM ; } \ +libxl__egc egc[1 ];LIBXL_INIT_EGC (egc[0 ],ctx); \AO_GC ; #define AO_INPROGRESS ({ \ libxl_ctx *ao__ctx = libxl__gc_owner(&ao->gc); \ int ao__rc = libxl__ao_inprogress(ao); \ libxl__ctx_unlock(ao__ctx); /* gc is now invalid */ \ +EGC_FREE ; \ (ao__rc); \ })@@ -1269,6 +1274,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);assert (rc); \libxl__ao_abort (ao); \libxl__ctx_unlock (ao__ctx);/* gc is now invalid */ \ +EGC_FREE ; \ (rc); \ })
PATCH 2/20 libxl: fix hang due to libxl__initiate_device_remove
In reply to Ian Jacksonlibxl__initiate_device_remove might discover that the operation was complete, immediately (typically, if the device is already removed).
Previously, in this situation, it would return 0 to the caller but never call libxl__ao_complete. Fix this. This necessitates passing the egc in from the functions which are the ao initiators.
--- tools/libxl/libxl.c | 8 ++++---- tools/libxl/libxl_device.c | 18 ++++++++++++------ tools/libxl/libxl_internal.h | 3 ++- 3 files changed, 18 insertions(+), 11 deletions(-)
tools/libxl/libxl.c +4 -4
@@ -1406,7 +1406,7 @@ int libxl_device_disk_remove(libxl_ctx *ctx, uint32_t domid, rc =libxl__device_from_disk (gc, domid, disk, &device);if (rc !=0 ) goto out; - rc =libxl__initiate_device_remove (ao, &device); + rc =libxl__initiate_device_remove (egc, ao, &device);if (rc) goto out;return AO_INPROGRESS ;
@@ -1873,7 +1873,7 @@ int libxl_device_nic_remove(libxl_ctx *ctx, uint32_t domid, rc =libxl__device_from_nic (gc, domid, nic, &device);if (rc !=0 ) goto out; - rc =libxl__initiate_device_remove (ao, &device); + rc =libxl__initiate_device_remove (egc, ao, &device);if (rc) goto out;return AO_INPROGRESS ;
@@ -2220,7 +2220,7 @@ int libxl_device_vkb_remove(libxl_ctx *ctx, uint32_t domid, rc =libxl__device_from_vkb (gc, domid, vkb, &device);if (rc !=0 ) goto out; - rc =libxl__initiate_device_remove (ao, &device); + rc =libxl__initiate_device_remove (egc, ao, &device);if (rc) goto out;return AO_INPROGRESS ;
@@ -2353,7 +2353,7 @@ int libxl_device_vfb_remove(libxl_ctx *ctx, uint32_t domid, rc =libxl__device_from_vfb (gc, domid, vfb, &device);if (rc !=0 ) goto out; - rc =libxl__initiate_device_remove (ao, &device); + rc =libxl__initiate_device_remove (egc, ao, &device);if (rc) goto out;return AO_INPROGRESS ;
tools/libxl/libxl_device.c +12 -6
@@ -376,7 +376,8 @@ static void device_remove_callback(libxl__egc *egc, libxl__ev_devstate *ds,device_remove_cleanup (gc, aorm); } -int libxl__initiate_device_remove (libxl__ao *ao,libxl__device *dev) +int libxl__initiate_device_remove (libxl__egc *egc,libxl__ao *ao, +libxl__device *dev) {AO_GC ;libxl_ctx *ctx =libxl__gc_owner (gc);
@@ -388,11 +389,11 @@ int libxl__initiate_device_remove(libxl__ao *ao, libxl__device *dev)libxl__ao_device_remove *aorm =0 ;if (!state) - goto out; + goto out_ok;if (atoi (state) !=4 ) {libxl__device_destroy_tapdisk (gc, be_path);xs_rm (ctx->xsh,XBT_NULL , be_path); - goto out; + goto out_ok; } retry_transaction:
@@ -404,7 +405,7 @@ retry_transaction: goto retry_transaction; else { rc =ERROR_FAIL ; - goto out; + goto out_fail; } }
@@ -417,13 +418,18 @@ retry_transaction: rc =libxl__ev_devstate_wait (gc, &aorm->ds, device_remove_callback, state_path, XenbusStateClosed,LIBXL_DESTROY_TIMEOUT *1000 ); -if (rc) goto out; +if (rc) goto out_fail;return 0 ; - out: + out_fail: +assert (rc);device_remove_cleanup (gc, aorm);return rc; + + out_ok: +libxl__ao_complete (egc, ao,0 ); +return 0 ; }int libxl__device_destroy (libxl__gc *gc,libxl__device *dev)
tools/libxl/libxl_internal.h +2 -1
@@ -692,7 +692,8 @@ _hidden int libxl__wait_for_backend(libxl__gc *gc, char *be_path, char *state);* this is done, the ao will be completed. An error * return from libxl__initiate_device_remove means that the ao * will _not_ be completed and the caller must do so. */ -_hidden int libxl__initiate_device_remove(libxl__ao*, libxl__device *dev); +_hidden int libxl__initiate_device_remove(libxl__egc*, libxl__ao*, +libxl__device *dev);/* * libxl__ev_devstate - waits a given time for a device to
Signature · 1 line
1.7.2.5
Re: [PATCH 02/20] libxl: fix hang due to libxl__initiate_device_remove
Quoted 9 lines · Ian Jackson
libxl__initiate_device_removemight discover that the operation was complete, immediately (typically, if the device is already removed).Previously, in this situation, it would return 0 to the caller but never call
libxl__ao_complete. Fix this. This necessitates passing the egc in from the functions which are the ao initiators.Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>
PATCH 3/20 libxl: Fix eventloop_iteration over-locking
In reply to Ian Jacksoneventloop_iteration's head comment says that it must be called with the ctx locked exactly once, and this is indeed true, and it's done correctly at both the call sites.
However, it takes out the lock an additional time itself. This is wrong because it prevents the unlocks around poll from being effective. This would mean that a multithreaded event-loop using program might suffer from undesired blocking, as one thread trying to enter libxl might end up stalled by another thread waiting for a slow event. So remove those two lock calls.
Also add a couple of comments documenting the locking behaviour of libxl__ao_inprogress and libxl__egc_cleanup.
--- tools/libxl/libxl_event.c | 4 ---- tools/libxl/libxl_internal.h | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-)
tools/libxl/libxl_event.c +0 -4
@@ -1058,8 +1058,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {int rc;struct timeval now; -CTX_LOCK ; - rc =libxl__gettimeofday (gc, &now);if (rc) goto out;
@@ -1102,8 +1100,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {afterpoll_internal (egc, poller, poller->fd_polls_allocd, poller->fd_polls, now); -CTX_UNLOCK ; - rc =0 ; out:return rc;
tools/libxl/libxl_internal.h +2 -2
@@ -1191,7 +1191,7 @@ libxl__device_model_version_running(libxl__gc *gc, uint32_t domid); _hidden void libxl__egc_cleanup(libxl__egc *egc);/* Frees memory allocated within this egc's gc, and and report all * occurred events via callback, if applicable. May reenter the -* application; see restrictions above. */ +* application; see restrictions above. The ctx must be UNLOCKED. */ /* convenience macros: */
@@ -1287,7 +1287,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* libxl__ao_inprogress MUST be called with the ctx locked exactly once. */ _hidden libxl__ao *libxl__ao_create(libxl_ctx*, uint32_t domid,const libxl_asyncop_how *); -_hidden int libxl__ao_inprogress(libxl__ao *ao); +_hidden int libxl__ao_inprogress(libxl__ao *ao); /* temporarily unlocks */ _hidden void libxl__ao_abort(libxl__ao *ao); _hidden void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc);
Signature · 1 line
1.7.2.5
Re: [PATCH 03/20] libxl: Fix eventloop_iteration over-locking
Quoted 11 lines · Ian Jackson
eventloop_iteration's head comment says that it must be called with the ctx locked exactly once, and this is indeed true, and it's done correctly at both the call sites.
However, it takes out the lock an additional time itself. This is wrong because it prevents the unlocks around poll from being effective. This would mean that a multithreaded event-loop using program might suffer from undesired blocking, as one thread trying to enter libxl might end up stalled by another thread waiting for a slow event. So remove those two lock calls.
Quoted 4 lines
Also add a couple of comments documenting the locking behaviour of
libxl__ao_inprogressandlibxl__egc_cleanup.Signed-off-by Ian Jackson <[email protected]>
A comment in eventloop_iteration along the lines "no need to lock, we must be called with lock held once" might be nice to prevent future re-occurences of the same error.
Quoted 49 lines
--- tools/libxl/libxl_event.c | 4 ---- tools/libxl/libxl_internal.h | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-)tools/libxl/libxl_event.c +0
-4@@ -1058,8 +1058,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {int rc;struct timeval now; -CTX_LOCK ; - rc =libxl__gettimeofday (gc, &now);if (rc) goto out;@@ -1102,8 +1100,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {afterpoll_internal (egc, poller, poller->fd_polls_allocd, poller->fd_polls, now); -CTX_UNLOCK ; - rc =0 ; out:return rc;tools/libxl/libxl_internal.h +2
-2@@ -1191,7 +1191,7 @@ libxl__device_model_version_running(libxl__gc *gc, uint32_t domid); _hidden void libxl__egc_cleanup(libxl__egc *egc);/* Frees memory allocated within this egc's gc, and and report all * occurred events via callback, if applicable. May reenter the -* application; see restrictions above. */ +* application; see restrictions above. The ctx must be UNLOCKED. */ /* convenience macros: */ @@ -1287,7 +1287,7 @@ _hidden void libxl__egc_cleanup(libxl__egc *egc);* libxl__ao_inprogress MUST be called with the ctx locked exactly once. */ _hidden libxl__ao *libxl__ao_create(libxl_ctx*, uint32_t domid,const libxl_asyncop_how *); -_hidden int libxl__ao_inprogress(libxl__ao *ao); +_hidden int libxl__ao_inprogress(libxl__ao *ao); /* temporarily unlocks */ _hidden void libxl__ao_abort(libxl__ao *ao); _hidden void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc);
Re: [PATCH 03/20] libxl: Fix eventloop_iteration over-locking
Ian Campbell writes ("Re: [Xen-devel] [PATCH 03/20] libxl: Fix eventloop_iteration over-locking"):
Quoted 3 lines
A comment in
eventloop_iterationalong the lines "no need to lock, we must be called with lock held once" might be nice to prevent future re-occurences of the same error.
You don't see it in this patch, but there's something along these lines already. Let me add some more context:
Quoted 1 line
Review static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {
Quoted 1 line
(quoted diff) +0
-0@@ -1058,8 +1058,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {
static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {
/* The CTX must be locked EXACTLY ONCE so that this function
* can unlock it when it polls.
*/
EGC_GC;Quoted 5 lines
tools/libxl/libxl_event.c static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) { · line 1062
Quoted 5 lines
tools/libxl/libxl_event.c +0
-2int rc;struct timeval now; -CTX_LOCK ; -
Ian.
Re: [PATCH 03/20] libxl: Fix eventloop_iteration over-locking
Quoted 5 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 03/20] libxl: Fix
eventloop_iterationover-locking"):Quoted 3 lines
A comment in
eventloop_iterationalong the lines "no need to lock, we must be called with lock held once" might be nice to prevent future re-occurences of the same error.
Quoted 8 lines
You don't see it in this patch, but there's something along these lines already. Let me add some more context:
Quoted 1 line
Review static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {
Quoted 1 line
(quoted diff) +0
-0@@ -1058,8 +1058,6 @@ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) {static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) { /* The CTX must be locked EXACTLY ONCE so that this function * can unlock it when it polls. */
Brilliant, thanks!
Quoted 8 lines
EGC_GC;Quoted 5 lines
tools/libxl/libxl_event.c static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) { · line 1062
Quoted 5 lines
tools/libxl/libxl_event.c +0
-2int rc;struct timeval now; -CTX_LOCK ; -Ian.
PATCH 4/20 libxl: Fix leak of ctx->lock
In reply to Ian JacksonA mutex created with pthread_mutex_init, like ctx->lock, may need to be destroyed with pthread_mutex_destroy.
Also, previously, if libxl__init_recursive_mutex failed, the nascent ctx would be leaked. Add some comments which will hopefully make these kind of mistakes less likely in future.
--- tools/libxl/libxl.c | 17 +++++++++++++---- 1 files changed, 13 insertions(+), 4 deletions(-)
tools/libxl/libxl.c +13 -4
@@ -39,10 +39,7 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,memset (ctx,0 ,sizeof (libxl_ctx)); ctx->lg = lg; -if (libxl__init_recursive_mutex (ctx, &ctx->lock) <0 ) { -LIBXL__LOG (ctx,LIBXL__LOG_ERROR ,"Failed to initialize mutex" ); -return ERROR_FAIL ; - } +/* First initialise pointers (cannot fail) */ LIBXL_TAILQ_INIT (&ctx->occurred);
@@ -61,6 +58,16 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,LIBXL_TAILQ_INIT (&ctx->death_list);libxl__ev_xswatch_init (&ctx->death_watch); +/* The mutex is special because we can't idempotently destroy it */ + +if (libxl__init_recursive_mutex (ctx, &ctx->lock) <0 ) { +LIBXL__LOG (ctx,LIBXL__LOG_ERROR ,"Failed to initialize mutex" ); +free (ctx); + ctx =0 ; + } + +/* Now ctx is safe for ctx_free; failures simply set rc and "goto out" */ + rc =libxl__poller_init (ctx, &ctx->poller_app);if (rc) goto out;
@@ -150,6 +157,8 @@ int libxl_ctx_free(libxl_ctx *ctx)discard_events (&ctx->occurred); +pthread_mutex_destroy (&ctx->lock); +GC_FREE ;free (ctx);return 0 ;
Signature · 1 line
1.7.2.5
PATCH 5/20 libxl: abolish libxl_ctx_postfork
In reply to Ian Jacksonlibxl's task has become too complicated (particularly in the presence of both forking and multithreading) to support reuse of the same libxl_ctx after fork.
So abolish libxl_ctx_fork. xl instead simply initialises a new libxl_ctx.
--- tools/libxl/libxl.h | 1 - tools/libxl/libxl_utils.c | 7 ------- tools/libxl/xl.c | 8 ++++++++ tools/libxl/xl.h | 1 + tools/libxl/xl_cmdimpl.c | 8 ++------ 5 files changed, 11 insertions(+), 14 deletions(-)
tools/libxl/libxl.h +0 -1
@@ -378,7 +378,6 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,unsigned flags/* none currently defined */ , xentoollog_logger *lg);int libxl_ctx_free (libxl_ctx *ctx/* 0 is OK */ ); -int libxl_ctx_postfork (libxl_ctx *ctx);/* domain related functions */ typedef int (*libxl_console_ready )(libxl_ctx *ctx,uint32_t domid,void *priv);
tools/libxl/libxl_utils.c +0 -7
@@ -365,13 +365,6 @@ READ_WRITE_EXACTLY(read, 1, /* */) READ_WRITE_EXACTLY(write, 0, const) -int libxl_ctx_postfork (libxl_ctx *ctx) { -if (ctx->xsh)xs_daemon_destroy_postfork (ctx->xsh); - ctx->xsh =xs_daemon_open (); -if (!ctx->xsh)return ERROR_FAIL ; -return 0 ; -} -pid_t libxl_fork (libxl_ctx *ctx) {pid_t pid;
tools/libxl/xl.c +8 -0
@@ -95,6 +95,14 @@ static void parse_global_config(const char *configfile,xlu_cfg_destroy (config); } +void postfork (void ) +{ +if (libxl_ctx_alloc (&ctx,LIBXL_VERSION ,0 , (xentoollog_logger *)logger)) { +fprintf (stderr,"cannot reinit xl context after fork\n" ); +exit (-1 ); + } +} +int main (int argc,char **argv) {int opt =0 ;
tools/libxl/xl.h +1 -0
@@ -104,6 +104,7 @@ struct cmd_spec *cmdtable_lookup(const char *s);extern libxl_ctx *ctx;extern xentoollog_logger_stdiostream *logger; +void postfork (void );/* global options */ extern int autoballoon;
tools/libxl/xl_cmdimpl.c +2 -6
@@ -1408,7 +1408,7 @@ static int autoconnect_console(libxl_ctx *ctx, uint32_t domid, void *priv) }else if (*pid >0 )return 0 ; -libxl_ctx_postfork (ctx); +postfork ();sleep (1 );libxl_primary_console_exec (ctx, domid);
@@ -1695,11 +1695,7 @@ start: goto out; } - rc =libxl_ctx_postfork (ctx); -if (rc) { -LOG ("failed to reinitialise context after fork" ); -exit (-1 ); - } +postfork ();if (asprintf (&name,"xl-%s" , d_config.c_info.name) <0 ) {LOG ("Failed to allocate memory in asprintf" );
Signature · 1 line
1.7.2.5
PATCH 6/20 tools: Correct PTHREAD options in config/StdGNU.mk
In reply to Ian JacksonIt is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
Fix the configure test to test -pthread, and plumb the resulting flag through to PTHREAD_{CFLAGS,LDFLAGS} in Tools.mk; also substitute PTHREAD_LIBS (although this will currently always be empty). Remove PTHREAD_LIBS setting from StdGNU.mk.
Fix the one user (libxc) to use PTHREAD_{CFLAGS,LDFLAGS} too.
There are still some other users in tree which pass -pthread or -lpthread by adding it as a literal to their own compiler options. These will be fixed in a later patch.
--- config/StdGNU.mk | 1 - config/Tools.mk.in | 4 ++ tools/configure | 95 +++++++++++++++++++++++++++++++++++--------------- tools/configure.ac | 5 ++- tools/libxc/Makefile | 4 ++- tools/m4/pthread.m4 | 41 +++++++++++++++++++++ tools/m4/savevar.m4 | 6 +++ 7 files changed, 124 insertions(+), 32 deletions(-) create mode 100644 tools/m4/pthread.m4 create mode 100644 tools/m4/savevar.m4
config/StdGNU.mk +0 -1
@@ -67,7 +67,6 @@ XEN_CONFIG_DIR = $(CONFIG_DIR)/xen XEN_SCRIPT_DIR = $(XEN_CONFIG_DIR)/scripts SOCKET_LIBS = -PTHREAD_LIBS = -lpthread UTIL_LIBS = -lutil DLOPEN_LIBS = -ldl
config/Tools.mk.in +4 -0
@@ -23,6 +23,10 @@ PREPEND_LIB := @PREPEND_LIB@ APPEND_INCLUDES := @APPEND_INCLUDES@ APPEND_LIB := @APPEND_LIB@ +PTHREAD_CFLAGS := @PTHREAD_CFLAGS@ +PTHREAD_LDFLAGS := @PTHREAD_LDFLAGS@ +PTHREAD_LIBS := @PTHREAD_LIBS@ + # Download GIT repositories via HTTP or GIT's own protocol? # GIT's protocol is faster and more robust, when it works at all (firewalls # may block it). We make it the default, but if your GIT repository downloads
tools/configure +67 -28
132 lines not on this page · raw message
tools/configure.ac +3 -2
@@ -23,6 +23,7 @@ AC_USE_SYSTEM_EXTENSIONS AC_CANONICAL_HOST # M4 Macro includes +m4_include([m4/savevar.m4]) m4_include([m4/enable_feature.m4]) m4_include([m4/disable_feature.m4]) m4_include([m4/path_or_fail.m4])
@@ -34,6 +35,7 @@ m4_include([m4/set_cflags_ldflags.m4]) m4_include([m4/uuid.m4]) m4_include([m4/pkg.m4]) m4_include([m4/curses.m4]) +m4_include([m4/pthread.m4]) # Enable/disable options AX_ARG_ENABLE_AND_EXPORT([githttp], [Download GIT repositories via HTTP])
@@ -123,8 +125,7 @@ AC_CHECK_LIB([ext2fs], [ext2fs_open2], [libext2fs="y"], [libext2fs="n"]) AC_SUBST(libext2fs) AC_CHECK_LIB([gcrypt], [gcry_md_hash_buffer], [libgcrypt="y"], [libgcrypt="n"]) AC_SUBST(libgcrypt) -AC_CHECK_LIB([pthread], [pthread_create], [] , - [AC_MSG_ERROR([Could not find libpthread])]) +AX_CHECK_PTHREAD AC_CHECK_LIB([rt], [clock_gettime]) AC_CHECK_LIB([yajl], [yajl_alloc], [], [AC_MSG_ERROR([Could not find yajl])])
tools/libxc/Makefile +3 -1
@@ -73,6 +73,8 @@ CFLAGS += -I. $(CFLAGS_xeninclude) # Needed for posix_fadvise64() in xc_linux.c CFLAGS-$(CONFIG_Linux) += -D_GNU_SOURCE +CFLAGS += $(PTHREAD_CFLAGS) + # Define this to make it possible to run valgrind on code linked with these # libraries. #CFLAGS += -DVALGRIND -O0 -ggdb3
@@ -157,7 +159,7 @@ libxenctrl.so.$(MAJOR): libxenctrl.so.$(MAJOR).$(MINOR) ln -sf $< $@ libxenctrl.so.$(MAJOR).$(MINOR): $(CTRL_PIC_OBJS) - $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS) + $(CC) $(LDFLAGS) $(PTHREAD_LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS) # libxenguest
tools/m4/pthread.m4 new file +41 -0
41 lines not on this page · raw message
tools/m4/savevar.m4 new file +6 -0
@@ -0,0 +1,6 @@ +AC_DEFUN([AX_SAVEVAR_SAVE],[ + saved_$1="$$1" +]) +AC_DEFUN([AX_SAVEVAR_RESTORE],[ + $1="$saved_$1" +])
Signature · 1 line
1.7.2.5
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
2012/3/16 Ian Jackson <[email protected]>:
Quoted 9 lines
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
Fix the configure test to test -pthread, and plumb the resulting flag through to PTHREAD_{CFLAGS,LDFLAGS} in Tools.mk; also substitute
PTHREAD_LIBS(although this will currently always be empty). RemovePTHREAD_LIBSsetting from StdGNU.mk.
Quoted 8 lines
Fix the one user (libxc) to use PTHREAD_{CFLAGS,LDFLAGS} too.
There are still some other users in tree which pass -pthread or -lpthread by adding it as a literal to their own compiler options. These will be fixed in a later patch.
Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>
Quoted 12 lines
---
config/StdGNU.mk | 1 -
config/Tools.mk.in | 4 ++
tools/configure | 95 +++++++++++++++++++++++++++++++++++---------------tools/configure.ac| 5 ++-
tools/libxc/Makefile | 4 ++-
tools/m4/pthread.m4 | 41 +++++++++++++++++++++tools/m4/savevar.m4| 6 +++7 files changed, 124 insertions(+), 32 deletions(-)create mode 100644
tools/m4/pthread.m4
create mode 100644tools/m4/savevar.m4
[...]
Quoted 28 lines
tools/m4/pthread.m4 new file +22
-0@@ -0,0 +1,41 @@ +# We define, separately, PTHREAD_CFLAGS, _LDFLAGS and _LIBS +# even though currently we don't set them very separately. +# This means that the makefiles will not need to change in +# the future if we make the test more sophisticated. + +AC_DEFUN([AX_PTHREAD_CV2VARS],[ + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" +]) + +# We invoke AX_PTHREAD_VARS with the name of another macro +# which is then expanded once for each variable. +AC_DEFUN([AX_PTHREAD_VARS],[$1(CFLAGS) $1(LDFLAGS) $1(LIBS)]) + +AC_DEFUN([AX_PTHREAD_VAR_APPLY],[ + $1="$$1 $PTHREAD_$1" +]) +AC_DEFUN([AX_PTHREAD_VAR_SUBST],[AC_SUBST(PTHREAD_$1)]) + +AC_DEFUN([AX_CHECK_PTHREAD],[ + AC_CACHE_CHECK([for pthread flag], [ax_cv_pthread_flags], [
tools/m4/pthread.m4 line 32
Quoted 10 lines
tools/m4/pthread.m4 new file +10
-0+ ax_cv_pthread_flags=-pthread + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_SAVEVAR_SAVE]) + AX_PTHREAD_VARS([AX_PTHREAD_VAR_APPLY]) + AC_LINK_IFELSE([ +#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0); +}
You can also use something like this here, which is more autoconf style:
AC_LANG_PROGRAM([#include <pthread.h>],[
pthread_atfork(0,0,0);
pthread_create(0,0,0,0);])But as is looks correct to me, I'm not a big fan of autoconf macros.
Quoted 15 lines
tools/m4/pthread.m4 new file +9
-0+],[],[ax_cv_pthread_flags=failed]) + AX_PTHREAD_VARS([AX_SAVEVAR_RESTORE]) + ]) + if test "x$ax_cv_pthread_flags" = xfailed; then + AC_MSG_ERROR([-pthread does not work]) + fi + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_PTHREAD_VAR_SUBST]) +])tools/m4/savevar.m4 new file +0
-0
tools/m4/savevar.m4 line 6
Quoted 6 lines
tools/m4/savevar.m4 new file +6
-0@@ -0,0 +1,6 @@ +AC_DEFUN([AX_SAVEVAR_SAVE],[ + saved_$1="$$1" +]) +AC_DEFUN([AX_SAVEVAR_RESTORE],[ + $1="$saved_$1" +])
This little macros will prove useful on other places, such as python_devel.m4, that actually uses ac_previous_* to temporary store variables.
Quoted 3 lines
--
1.7.2.5
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
Roger Pau Monné writes ("Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk"):
Quoted 4 lines
2012/3/16 Ian Jackson <[email protected]>:
Quoted 3 lines
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
...
Quoted 1 line
Acked-by Roger Pau Monne <[email protected]>
Thanks.
Quoted 9 lines
tools/m4/pthread.m4 line 32
Quoted 6 lines
+ AC_LINK_IFELSE([
tools/m4/pthread.m4 new file +5
-0+#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0); +}You can also use something like this here, which is more autoconf style:
Quoted 5 lines
AC_LANG_PROGRAM([#include <pthread.h>],[
pthread_atfork(0,0,0); pthread_create(0,0,0,0);])But as is looks correct to me, I'm not a big fan of autoconf macros.
Thanks for the comment. I think I agree with your sentiment so I'll leave this as it is.
Quoted 11 lines
tools/m4/savevar.m4 line 6
Quoted 7 lines
+],[],[ax_cv_pthread_flags=failed])
tools/m4/savevar.m4 new file +6
-0+AC_DEFUN([AX_SAVEVAR_SAVE],[ + saved_$1="$$1" +]) +AC_DEFUN([AX_SAVEVAR_RESTORE],[ + $1="$saved_$1" +])This little macros will prove useful on other places, such as python_devel.m4, that actually uses ac_previous_* to temporary store variables.
Right, that was the idea.
Ian.
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
In reply to Ian JacksonQuoted 3 lines · Ian Jackson
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
I guess this is a gcc-ism rather than a Linux-ism and so applies to the BSDs too (at least so long as they use gcc and not clang)?
Quoted 303 lines
Fix the configure test to test -pthread, and plumb the resulting flag through to PTHREAD_{CFLAGS,LDFLAGS} in Tools.mk; also substitute
PTHREAD_LIBS(although this will currently always be empty). RemovePTHREAD_LIBSsetting from StdGNU.mk.Fix the one user (libxc) to use PTHREAD_{CFLAGS,LDFLAGS} too.
There are still some other users in tree which pass -pthread or -lpthread by adding it as a literal to their own compiler options. These will be fixed in a later patch.
Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>--- config/StdGNU.mk | 1 - config/Tools.mk.in | 4 ++ tools/configure | 95 +++++++++++++++++++++++++++++++++++--------------- tools/configure.ac | 5 ++- tools/libxc/Makefile | 4 ++- tools/m4/pthread.m4 | 41 +++++++++++++++++++++ tools/m4/savevar.m4 | 6 +++ 7 files changed, 124 insertions(+), 32 deletions(-) create mode 100644 tools/m4/pthread.m4 create mode 100644 tools/m4/savevar.m4config/StdGNU.mk +0
-1@@ -67,7 +67,6 @@ XEN_CONFIG_DIR = $(CONFIG_DIR)/xen XEN_SCRIPT_DIR = $(XEN_CONFIG_DIR)/scripts SOCKET_LIBS = -PTHREAD_LIBS = -lpthread UTIL_LIBS = -lutil DLOPEN_LIBS = -ldlconfig/Tools.mk.in +4
-0@@ -23,6 +23,10 @@ PREPEND_LIB := @PREPEND_LIB@ APPEND_INCLUDES := @APPEND_INCLUDES@ APPEND_LIB := @APPEND_LIB@ +PTHREAD_CFLAGS := @PTHREAD_CFLAGS@ +PTHREAD_LDFLAGS := @PTHREAD_LDFLAGS@ +PTHREAD_LIBS := @PTHREAD_LIBS@ + # Download GIT repositories via HTTP or GIT's own protocol? # GIT's protocol is faster and more robust, when it works at all (firewalls # may block it). We make it the default, but if your GIT repository downloadstools/configure +67
-28@@ -602,6 +602,9 @@ POW_LIB LIBOBJS ALLOCA libiconv +PTHREAD_LIBS +PTHREAD_LDFLAGS +PTHREAD_CFLAGS libgcrypt libext2fs system_aio@@ -3844,6 +3847,9 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + # pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- # serial 1 (pkg-config-0.24) #@@ -3908,6 +3914,16 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + + + + + + + + # Enable/disable options # Check whether --enable-githttp was given. if test "${enable_githttp+set}" = set; then :@@ -7010,47 +7026,70 @@ else fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 -$as_echo_n "checking for pthread_create in -lpthread... " >&6; } -if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread flag" >&5 +$as_echo_n "checking for pthread flag... " >&6; } +if test "${ax_cv_pthread_flags+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthread $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext + + ax_cv_pthread_flags=-pthread + + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" + + + saved_CFLAGS="$CFLAGS" + + saved_LDFLAGS="$LDFLAGS" + + saved_LIBS="$LIBS" + + + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + LDFLAGS="$LDFLAGS $PTHREAD_LDFLAGS" + + LIBS="$LIBS $PTHREAD_LIBS" + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; +#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0); } + _ACEOF if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_pthread_pthread_create=yes + else - ac_cv_lib_pthread_pthread_create=no + ax_cv_pthread_flags=failed fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5 -$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; } -if test "x$ac_cv_lib_pthread_pthread_create" = x""yes; then : -else - as_fn_error $? "Could not find libpthread" "$LINENO" 5 + CFLAGS="$saved_CFLAGS" + + LDFLAGS="$saved_LDFLAGS" + + LIBS="$saved_LIBS" + + fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_pthread_flags" >&5 +$as_echo "$ax_cv_pthread_flags" >&6; } + if test "x$ax_cv_pthread_flags" = xfailed; then + as_fn_error $? "-pthread does not work" "$LINENO" 5 + fi + + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in -lrt" >&5 $as_echo_n "checking for clock_gettime in -lrt... " >&6; }tools/configure.ac +3
-2@@ -23,6 +23,7 @@ AC_USE_SYSTEM_EXTENSIONS AC_CANONICAL_HOST # M4 Macro includes +m4_include([m4/savevar.m4]) m4_include([m4/enable_feature.m4]) m4_include([m4/disable_feature.m4]) m4_include([m4/path_or_fail.m4])@@ -34,6 +35,7 @@ m4_include([m4/set_cflags_ldflags.m4]) m4_include([m4/uuid.m4]) m4_include([m4/pkg.m4]) m4_include([m4/curses.m4]) +m4_include([m4/pthread.m4]) # Enable/disable options AX_ARG_ENABLE_AND_EXPORT([githttp], [Download GIT repositories via HTTP])@@ -123,8 +125,7 @@ AC_CHECK_LIB([ext2fs], [ext2fs_open2], [libext2fs="y"], [libext2fs="n"]) AC_SUBST(libext2fs) AC_CHECK_LIB([gcrypt], [gcry_md_hash_buffer], [libgcrypt="y"], [libgcrypt="n"]) AC_SUBST(libgcrypt) -AC_CHECK_LIB([pthread], [pthread_create], [] , - [AC_MSG_ERROR([Could not find libpthread])]) +AX_CHECK_PTHREAD AC_CHECK_LIB([rt], [clock_gettime]) AC_CHECK_LIB([yajl], [yajl_alloc], [], [AC_MSG_ERROR([Could not find yajl])])tools/libxc/Makefile +3
-1@@ -73,6 +73,8 @@ CFLAGS += -I. $(CFLAGS_xeninclude) # Needed for posix_fadvise64() in xc_linux.c CFLAGS-$(CONFIG_Linux) += -D_GNU_SOURCE +CFLAGS += $(PTHREAD_CFLAGS) + # Define this to make it possible to run valgrind on code linked with these # libraries. #CFLAGS += -DVALGRIND -O0 -ggdb3@@ -157,7 +159,7 @@ libxenctrl.so.$(MAJOR): libxenctrl.so.$(MAJOR).$(MINOR) ln -sf $< $@ libxenctrl.so.$(MAJOR).$(MINOR): $(CTRL_PIC_OBJS) - $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS) + $(CC) $(LDFLAGS) $(PTHREAD_LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS) # libxenguesttools/m4/pthread.m4 new file +41
-0@@ -0,0 +1,41 @@ +# We define, separately, PTHREAD_CFLAGS, _LDFLAGS and _LIBS +# even though currently we don't set them very separately. +# This means that the makefiles will not need to change in +# the future if we make the test more sophisticated. + +AC_DEFUN([AX_PTHREAD_CV2VARS],[ + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" +]) + +# We invoke AX_PTHREAD_VARS with the name of another macro +# which is then expanded once for each variable. +AC_DEFUN([AX_PTHREAD_VARS],[$1(CFLAGS) $1(LDFLAGS) $1(LIBS)]) + +AC_DEFUN([AX_PTHREAD_VAR_APPLY],[ + $1="$$1 $PTHREAD_$1" +]) +AC_DEFUN([AX_PTHREAD_VAR_SUBST],[AC_SUBST(PTHREAD_$1)]) + +AC_DEFUN([AX_CHECK_PTHREAD],[ + AC_CACHE_CHECK([for pthread flag], [ax_cv_pthread_flags], [ + ax_cv_pthread_flags=-pthread + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_SAVEVAR_SAVE]) + AX_PTHREAD_VARS([AX_PTHREAD_VAR_APPLY]) + AC_LINK_IFELSE([ +#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0); +} +],[],[ax_cv_pthread_flags=failed]) + AX_PTHREAD_VARS([AX_SAVEVAR_RESTORE]) + ]) + if test "x$ax_cv_pthread_flags" = xfailed; then + AC_MSG_ERROR([-pthread does not work]) + fi + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_PTHREAD_VAR_SUBST]) +])tools/m4/savevar.m4 new file +6
-0@@ -0,0 +1,6 @@ +AC_DEFUN([AX_SAVEVAR_SAVE],[ + saved_$1="$$1" +]) +AC_DEFUN([AX_SAVEVAR_RESTORE],[ + $1="$saved_$1" +])
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
Ian Campbell writes ("Re: [Xen-devel] [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk"):
Quoted 7 lines · Ian Jackson
Quoted 3 lines
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
I guess this is a gcc-ism rather than a Linux-ism and so applies to the BSDs too (at least so long as they use gcc and not clang)?
I think so, yes. Some proprietary unices even have a different compiler (cc_r) but none of them currently have any dom0 support afaik.
Ian.
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
Quoted 8 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 06/20] tools: Correct PTHREAD options in
config/StdGNU.mk"):Quoted 7 lines · Ian Jackson
Quoted 3 lines
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
I guess this is a gcc-ism rather than a Linux-ism and so applies to the BSDs too (at least so long as they use gcc and not clang)?
Clang also accepts -pthread.
Tim.
A message that is not in the archive (sent off-list or not yet received): CAPLaKK4+TRroEox2ScUS=NZ7G7NZ4D2wpmvDZEjST5AGByRwUg@mail.gmail.com
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
Sorry, I've mean to send this to the list, but my phone doesn't like that, so I'm sending the mail again (you will receive this one two times Ian Campbell).
Quoted 8 lines · Ian Campbell
Quoted 3 lines · Ian Jackson
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
I guess this is a gcc-ism rather than a Linux-ism and so applies to the BSDs too (at least so long as they use gcc and not clang)?
From what I've read (not tested) BSD is fine with -pthread, but Solaris seems to only accept -lpthread (again from the information I've found online).
Quoted 296 lines
Quoted 296 lines
Fix the configure test to test -pthread, and plumb the resulting flag through to PTHREAD_{CFLAGS,LDFLAGS} in Tools.mk; also substitute
PTHREAD_LIBS(although this will currently always be empty). RemovePTHREAD_LIBSsetting from StdGNU.mk.Fix the one user (libxc) to use PTHREAD_{CFLAGS,LDFLAGS} too.
There are still some other users in tree which pass -pthread or -lpthread by adding it as a literal to their own compiler options. These will be fixed in a later patch.
Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>---
config/StdGNU.mk | 1 -
config/Tools.mk.in | 4 ++
tools/configure | 95 +++++++++++++++++++++++++++++++++++---------------tools/configure.ac| 5 ++-
tools/libxc/Makefile | 4 ++-
tools/m4/pthread.m4 | 41 +++++++++++++++++++++tools/m4/savevar.m4| 6 +++7 files changed, 124 insertions(+), 32 deletions(-)create mode 100644
tools/m4/pthread.m4
create mode 100644tools/m4/savevar.m4config/StdGNU.mk +0
-0@@ -67,7 +67,6 @@ XEN_CONFIG_DIR = $(CONFIG_DIR)/xenXEN_SCRIPT_DIR = $(XEN_CONFIG_DIR)/scripts
SOCKET_LIBS =
-PTHREAD_LIBS = -lpthread
UTIL_LIBS = -lutil
DLOPEN_LIBS = -ldlconfig/Tools.mk.in +0
-0@@ -23,6 +23,10 @@ PREPEND_LIB := @PREPEND_LIB@APPEND_INCLUDES := @APPEND_INCLUDES@
APPEND_LIB := @APPEND_LIB@config/Tools.mk.in +4
-0+PTHREAD_CFLAGS := @PTHREAD_CFLAGS@ +PTHREAD_LDFLAGS := @PTHREAD_LDFLAGS@ +PTHREAD_LIBS := @PTHREAD_LIBS@ +# Download GIT repositories via HTTP or GIT's own protocol?
# GIT's protocol is faster and more robust, when it works at all (firewalls# may block it). We make it the default, but if your GIT repository downloadstools/configure +0
-0@@ -602,6 +602,9 @@ POW_LIBLIBOBJS
ALLOCA
libiconvtools/configure +3
-0+PTHREAD_LIBS +PTHREAD_LDFLAGS +PTHREAD_CFLAGSlibgcrypt
libext2fs
system_aiotools/configure +13
-0@@ -3844,6 +3847,9 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + # pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- # serial 1 (pkg-config-0.24) #@@ -3908,6 +3914,16 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + + + + + + + + # Enable/disable options # Check whether --enable-githttp was given.if test "${enable_githttp+set}" = set; then :
tools/configure +0
-0@@ -7010,47 +7026,70 @@ elsefi
tools/configure +4
-3-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 -$as_echo_n "checking for pthread_create in -lpthread... " >&6; } -if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread flag" >&5 +$as_echo_n "checking for pthread flag... " >&6; } +if test "${ax_cv_pthread_flags+set}" = set; then :$as_echo_n "(cached) " >&6
else
- ac_check_lib_save_LIBS=$LIBStools/configure +22
-2-LIBS="-lpthread $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext + + ax_cv_pthread_flags=-pthread + + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" + + + saved_CFLAGS="$CFLAGS" + + saved_LDFLAGS="$LDFLAGS" + + saved_LIBS="$LIBS" + + + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + LDFLAGS="$LDFLAGS $PTHREAD_LDFLAGS" + + LIBS="$LIBS $PTHREAD_LIBS" + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext/* end
confdefs.h. */tools/configure +4
-13-/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; +#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0);}
+
_ACEOF
ifac_fn_c_try_link"$LINENO"; then :
- ac_cv_lib_pthread_pthread_create=yes
+
else
- ac_cv_lib_pthread_pthread_create=no
+ ax_cv_pthread_flags=failed
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext conftest.$ac_exttools/configure +7
-7-LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5 -$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; } -if test "x$ac_cv_lib_pthread_pthread_create" = x""yes; then : -else - as_fn_error $? "Could not find libpthread" "$LINENO" 5 + CFLAGS="$saved_CFLAGS" + + LDFLAGS="$saved_LDFLAGS" + + LIBS="$saved_LIBS" + +fi
tools/configure +11
-0+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_pthread_flags" >&5 +$as_echo "$ax_cv_pthread_flags" >&6; } + if test "x$ax_cv_pthread_flags" = xfailed; then + as_fn_error $? "-pthread does not work" "$LINENO" 5 + fi + + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for
clock_gettimein -lrt" >&5 $as_echo_n "checking forclock_gettimein -lrt... " >&6; }tools/configure.ac +0
-0@@ -23,6 +23,7 @@ AC_USE_SYSTEM_EXTENSIONSAC_CANONICAL_HOST
# M4 Macro includes
+m4_include([m4/savevar.m4])
m4_include([m4/enable_feature.m4])
m4_include([m4/disable_feature.m4])
m4_include([m4/path_or_fail.m4])tools/configure.ac +2
-2@@ -34,6 +35,7 @@ m4_include([m4/set_cflags_ldflags.m4]) m4_include([m4/uuid.m4]) m4_include([m4/pkg.m4]) m4_include([m4/curses.m4]) +m4_include([m4/pthread.m4]) # Enable/disable options AX_ARG_ENABLE_AND_EXPORT([githttp], [Download GIT repositories via HTTP])@@ -123,8 +125,7 @@ AC_CHECK_LIB([ext2fs], [ext2fs_open2], [libext2fs="y"], [libext2fs="n"]) AC_SUBST(libext2fs) AC_CHECK_LIB([gcrypt], [gcry_md_hash_buffer], [libgcrypt="y"], [libgcrypt="n"]) AC_SUBST(libgcrypt) -AC_CHECK_LIB([pthread], [pthread_create], [] , - [AC_MSG_ERROR([Could not find libpthread])]) +AX_CHECK_PTHREAD AC_CHECK_LIB([rt], [clock_gettime]) AC_CHECK_LIB([yajl], [yajl_alloc], [], [AC_MSG_ERROR([Could not find yajl])])tools/libxc/Makefile +0
-0@@ -73,6 +73,8 @@ CFLAGS += -I. $(CFLAGS_xeninclude) # Needed for posix_fadvise64() in xc_linux.cCFLAGS-$(CONFIG_Linux) += -D_GNU_SOURCE
tools/libxc/Makefile +2
-0+CFLAGS += $(PTHREAD_CFLAGS) +# Define this to make it possible to run valgrind on code linked with these
# libraries. #CFLAGS += -DVALGRIND -O0 -ggdb3tools/libxc/Makefile +0
-0@@ -157,7 +159,7 @@ libxenctrl.so.$(MAJOR): libxenctrl.so.$(MAJOR).$(MINOR)ln -sf $< $@
libxenctrl.so.$(MAJOR).$(MINOR): $(CTRL_PIC_OBJS)
- $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS)
+ $(CC) $(LDFLAGS) $(PTHREAD_LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libxenctrl.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(DLOPEN_LIBS) $(PTHREAD_LIBS) $(APPEND_LDFLAGS)# libxenguesttools/m4/pthread.m4 new file +41
-0@@ -0,0 +1,41 @@ +# We define, separately, PTHREAD_CFLAGS, _LDFLAGS and _LIBS +# even though currently we don't set them very separately. +# This means that the makefiles will not need to change in +# the future if we make the test more sophisticated. + +AC_DEFUN([AX_PTHREAD_CV2VARS],[ + PTHREAD_CFLAGS="$ax_cv_pthread_flags" + PTHREAD_LDFLAGS="$ax_cv_pthread_flags" + PTHREAD_LIBS="" +]) + +# We invoke AX_PTHREAD_VARS with the name of another macro +# which is then expanded once for each variable. +AC_DEFUN([AX_PTHREAD_VARS],[$1(CFLAGS) $1(LDFLAGS) $1(LIBS)]) + +AC_DEFUN([AX_PTHREAD_VAR_APPLY],[ + $1="$$1 $PTHREAD_$1" +]) +AC_DEFUN([AX_PTHREAD_VAR_SUBST],[AC_SUBST(PTHREAD_$1)]) + +AC_DEFUN([AX_CHECK_PTHREAD],[ + AC_CACHE_CHECK([for pthread flag], [ax_cv_pthread_flags], [ + ax_cv_pthread_flags=-pthread + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_SAVEVAR_SAVE]) + AX_PTHREAD_VARS([AX_PTHREAD_VAR_APPLY]) + AC_LINK_IFELSE([ +#include <pthread.h> +int main(void) { + pthread_atfork(0,0,0); + pthread_create(0,0,0,0); +} +],[],[ax_cv_pthread_flags=failed]) + AX_PTHREAD_VARS([AX_SAVEVAR_RESTORE]) + ]) + if test "x$ax_cv_pthread_flags" = xfailed; then + AC_MSG_ERROR([-pthread does not work]) + fi + AX_PTHREAD_CV2VARS + AX_PTHREAD_VARS([AX_PTHREAD_VAR_SUBST]) +])tools/m4/savevar.m4 new file +0
-1--- /dev/null
Quoted 10 lines
tools/m4/savevar.m4 line 6
Quoted 8 lines
+++ b/tools/m4/savevar.m4
tools/m4/savevar.m4 new file +6
-0@@ -0,0 +1,6 @@ +AC_DEFUN([AX_SAVEVAR_SAVE],[ + saved_$1="$$1" +]) +AC_DEFUN([AX_SAVEVAR_RESTORE],[ + $1="$saved_$1" +])
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 06/20] tools: Correct PTHREAD options in config/StdGNU.mk
Quoted 3 lines · Roger Pau Monné
Sorry, I've mean to send this to the list, but my phone doesn't like that, so I'm sending the mail again (you will receive this one two times Ian Campbell).
No problem.
Quoted 7 lines · Ian Campbell
Quoted 6 lines · Ian Jackson
Quoted 3 lines
It is not correct to say -lpthread. The correct option is -pthread, which may have sundry other effects on code generation etc. It needs to be passed both to compilation and linking.
Quoted 6 lines
Quoted 2 lines
I guess this is a gcc-ism rather than a Linux-ism and so applies to the BSDs too (at least so long as they use gcc and not clang)?
From what I've read (not tested) BSD is fine with -pthread, but Solaris seems to only accept -lpthread (again from the information I've found online).
I think we should end the pretence that Solaris is a supported dom0 platform any more. I'm reasonably certain it won't even build.
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
PATCH 7/20 libxl: Use PTHREAD_CFLAGS, LDFLAGS, LIBS
In reply to Ian JacksonThis is going to be needed for pthread_atfork. It is a mystery why it hasn't been needed before.
--- tools/libxl/Makefile | 4 ++++ 1 files changed, 4 insertions(+), 0 deletions(-)
tools/libxl/Makefile +4 -0
@@ -22,6 +22,10 @@ endif LIBXL_LIBS = LIBXL_LIBS = $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(LDLIBS_libxenstore) $(LDLIBS_libblktapctl) $(UTIL_LIBS) $(LIBUUID_LIBS) +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) +LIBXL_LIBS += $(PTHREAD_LIBS) + LIBXLU_LIBS = LIBXL_OBJS-y = osdeps.o libxl_paths.o libxl_bootloader.o flexarray.o
Signature · 1 line
1.7.2.5
Re: [PATCH 07/20] libxl: Use PTHREAD_CFLAGS, LDFLAGS, LIBS
Quoted 4 lines · Ian Jackson
This is going to be needed for
pthread_atfork. It is a mystery why it hasn't been needed before.Signed-off-by Ian Jackson <[email protected]>
Quoted 19 lines
--- tools/libxl/Makefile | 4 ++++ 1 files changed, 4 insertions(+), 0 deletions(-)tools/libxl/Makefile +4
-0@@ -22,6 +22,10 @@ endif LIBXL_LIBS = LIBXL_LIBS = $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(LDLIBS_libxenstore) $(LDLIBS_libblktapctl) $(UTIL_LIBS) $(LIBUUID_LIBS) +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) +LIBXL_LIBS += $(PTHREAD_LIBS) + LIBXLU_LIBS = LIBXL_OBJS-y = osdeps.o libxl_paths.o libxl_bootloader.o flexarray.o
PATCH 8/20 tools: Use PTHREAD_CFLAGS, _LDFLAGS, _LIBS
In reply to Ian JacksonReplace all literal occurrences of -lpthread and -pthread in Makefiles by references to PTHREAD_CFLAGS, PTHREAD_LDFLAGS and PTHREAD_LIBS. These are the new variables set by configure, and currently expand to -pthread on the compilation and link lines as is required.
--- tools/blktap/drivers/Makefile | 7 +++++-- tools/libfsimage/common/Makefile | 5 ++++- tools/vtpm_manager/manager/Makefile | 4 +++- tools/xenpaging/Makefile | 5 +++-- 4 files changed, 15 insertions(+), 6 deletions(-)
tools/blktap/drivers/Makefile +5 -2
@@ -35,8 +35,11 @@ else AIOLIBS := -laio endif -LDLIBS_blktapctrl := $(MEMSHRLIBS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -L../lib -lblktap -lrt -lm -lpthread -LDLIBS_img := $(AIOLIBS) $(CRYPT_LIB) -lpthread -lz +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) + +LDLIBS_blktapctrl := $(MEMSHRLIBS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -L../lib -lblktap -lrt -lm $(PTHREAD_LIBS) +LDLIBS_img := $(AIOLIBS) $(CRYPT_LIB) $(PTHREAD_LIBS) -lz BLK-OBJS-y := block-aio.o BLK-OBJS-y += block-sync.o
tools/libfsimage/common/Makefile +4 -1
@@ -8,6 +8,9 @@ LDFLAGS-$(CONFIG_SunOS) = -Wl,-M -Wl,mapfile-SunOS LDFLAGS-$(CONFIG_Linux) = -Wl,mapfile-GNU LDFLAGS = $(LDFLAGS-y) +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) + LIB_SRCS-y = fsimage.c fsimage_plugin.c fsimage_grub.c PIC_OBJS := $(patsubst %.c,%.opic,$(LIB_SRCS-y))
@@ -37,7 +40,7 @@ libfsimage.so.$(MAJOR): libfsimage.so.$(MAJOR).$(MINOR) ln -sf $< $@ libfsimage.so.$(MAJOR).$(MINOR): $(PIC_OBJS) - $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libfsimage.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ -lpthread + $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libfsimage.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(PTHREAD_LIBS) -include $(DEPS)
tools/vtpm_manager/manager/Makefile +3 -1
@@ -33,4 +33,6 @@ $(BIN): $(OBJS) # libraries LIBS += ../tcs/libTCS.a ../util/libTCGUtils.a ../crypto/libtcpaCrypto.a -LIBS += -lcrypto -lpthread -lm +LIBS += -lcrypto $(PTHREAD_LIBS) -lm +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS)
tools/xenpaging/Makefile +3 -2
@@ -1,8 +1,9 @@ XEN_ROOT=$(CURDIR)/../.. include $(XEN_ROOT)/tools/Rules.mk -CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenstore) -LDLIBS += $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -pthread +CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenstore) $(PTHREAD_CFLAGS) +LDLIBS += $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) $(PTHREAD_LIBS) +LDFLAGS += $(PTHREAD_LDFLAGS) POLICY = default
Signature · 1 line
1.7.2.5
Re: [PATCH 08/20] tools: Use PTHREAD_CFLAGS, _LDFLAGS, _LIBS
Quoted 6 lines · Ian Jackson
Replace all literal occurrences of -lpthread and -pthread in Makefiles by references to
PTHREAD_CFLAGS,PTHREAD_LDFLAGSandPTHREAD_LIBS. These are the new variables set by configure, and currently expand to -pthread on the compilation and link lines as is required.Signed-off-by Ian Jackson <[email protected]>
Quoted 76 lines
--- tools/blktap/drivers/Makefile | 7 +++++-- tools/libfsimage/common/Makefile | 5 ++++- tools/vtpm_manager/manager/Makefile | 4 +++- tools/xenpaging/Makefile | 5 +++-- 4 files changed, 15 insertions(+), 6 deletions(-)tools/blktap/drivers/Makefile +5
-2@@ -35,8 +35,11 @@ else AIOLIBS := -laio endif -LDLIBS_blktapctrl := $(MEMSHRLIBS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -L../lib -lblktap -lrt -lm -lpthread -LDLIBS_img := $(AIOLIBS) $(CRYPT_LIB) -lpthread -lz +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) + +LDLIBS_blktapctrl := $(MEMSHRLIBS) $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -L../lib -lblktap -lrt -lm $(PTHREAD_LIBS) +LDLIBS_img := $(AIOLIBS) $(CRYPT_LIB) $(PTHREAD_LIBS) -lz BLK-OBJS-y := block-aio.o BLK-OBJS-y += block-sync.otools/libfsimage/common/Makefile +4
-1@@ -8,6 +8,9 @@ LDFLAGS-$(CONFIG_SunOS) = -Wl,-M -Wl,mapfile-SunOS LDFLAGS-$(CONFIG_Linux) = -Wl,mapfile-GNU LDFLAGS = $(LDFLAGS-y) +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS) + LIB_SRCS-y = fsimage.c fsimage_plugin.c fsimage_grub.c PIC_OBJS := $(patsubst %.c,%.opic,$(LIB_SRCS-y))@@ -37,7 +40,7 @@ libfsimage.so.$(MAJOR): libfsimage.so.$(MAJOR).$(MINOR) ln -sf $< $@ libfsimage.so.$(MAJOR).$(MINOR): $(PIC_OBJS) - $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libfsimage.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ -lpthread + $(CC) $(LDFLAGS) -Wl,$(SONAME_LDFLAG) -Wl,libfsimage.so.$(MAJOR) $(SHLIB_LDFLAGS) -o $@ $^ $(PTHREAD_LIBS) -include $(DEPS)tools/vtpm_manager/manager/Makefile +3
-1@@ -33,4 +33,6 @@ $(BIN): $(OBJS) # libraries LIBS += ../tcs/libTCS.a ../util/libTCGUtils.a ../crypto/libtcpaCrypto.a -LIBS += -lcrypto -lpthread -lm +LIBS += -lcrypto $(PTHREAD_LIBS) -lm +CFLAGS += $(PTHREAD_CFLAGS) +LDFLAGS += $(PTHREAD_LDFLAGS)tools/xenpaging/Makefile +3
-2@@ -1,8 +1,9 @@ XEN_ROOT=$(CURDIR)/../.. include $(XEN_ROOT)/tools/Rules.mk -CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenstore) -LDLIBS += $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) -pthread +CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenstore) $(PTHREAD_CFLAGS) +LDLIBS += $(LDLIBS_libxenctrl) $(LDLIBS_libxenstore) $(PTHREAD_LIBS) +LDFLAGS += $(PTHREAD_LDFLAGS) POLICY = default
PATCH 9/20 libxl: Crash (more sensibly) on malloc failure
In reply to Ian JacksonFormally change the libxl memory allocation failure policy to "crash".
Previously we had a very uneven approach; much code assumed that libxl__sprintf (for example) would never return NULL, but some code was written more carefully.
We think it is unlikely that we will be able to make the library actually robust against allocation failure (since that would be an awful lot of never-tested error paths) and few calling environments will be able to cope anyway. So, instead, adopt the alternative
approach: provide allocation functions which never return null, but will crash the whole process instead.
Consequently,
- New noreturn function libxl__alloc_failed which may be used for printing a vaguely-useful error message, rather than simply dereferencing a null pointer.
- libxl__ptr_add now returns void as it crashes on failure.
- libxl__zalloc, _calloc, _strdup, _strndup, crash on failure using libxl__alloc_failed. So all the code that uses these can no longer dereference null on malloc failure.
While we're at it, make libxl__ptr_add use realloc rather than emulating it with calloc and free, and make it grow the array exponentially rather than linearly.
Things left to do:
- Provide versions of malloc, realloc and free which do the checking but which do not enroll the pointer in the gc.
- Remove a lot of now-spurious error handling.
- Remove the ERROR_NOMEM error code.
--- tools/libxl/libxl.h | 4 ++ tools/libxl/libxl_internal.c | 79 ++++++++++++++++++------------------------ tools/libxl/libxl_internal.h | 5 ++- 3 files changed, 42 insertions(+), 46 deletions(-)
tools/libxl/libxl.h +4 -0
@@ -123,6 +123,10 @@* No temporary objects allocated from the pool may be explicitly freed. * Therefore public functions which initialize a libxl__gc MUST call * libxl__free_all() before returning. +* +* Memory allocation failures are not handled gracefully. If malloc +* (or realloc) fails, libxl will cause the entire process to print +* a message to stderr and exit with status 255. */ /* * libxl types
tools/libxl/libxl_internal.c +33 -44
141 lines not on this page · raw message
tools/libxl/libxl_internal.h +4 -1
@@ -116,6 +116,9 @@ typedef struct libxl__gc libxl__gc;typedef struct libxl__egc libxl__egc ;typedef struct libxl__ao libxl__ao ; +void libxl__alloc_failed (const char *func,size_t nmemb,size_t size) + __attribute__((noreturn)); +typedef struct libxl__ev_fd libxl__ev_fd ;typedef void libxl__ev_fd_callback (libxl__egc *egc,libxl__ev_fd *ev,int fd,short events,short revents);
@@ -380,7 +383,7 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)* collection on exit from the outermost libxl callframe. */ /* register @ptr in @gc for free on exit from outermost libxl callframe. */ -_hidden int libxl__ptr_add(libxl__gc *gc, void *ptr); +_hidden void libxl__ptr_add(libxl__gc *gc, void *ptr);/* if this is the outermost libxl callframe then free all pointers in @gc */ _hidden void libxl__free_all(libxl__gc *gc);/* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */
Signature · 1 line
1.7.2.5
Re: [PATCH 09/20] libxl: Crash (more sensibly) on malloc failure
Quoted 13 lines · Ian Jackson
Formally change the libxl memory allocation failure policy to "crash".
Previously we had a very uneven approach; much code assumed that
libxl__sprintf(for example) would never return NULL, but some code was written more carefully.We think it is unlikely that we will be able to make the library actually robust against allocation failure (since that would be an awful lot of never-tested error paths) and few calling environments will be able to cope anyway. So, instead, adopt the alternative
approach: provide allocation functions which never return null, but will crash the whole process instead.
Quoted 4 lines
Consequently,
- New noreturn functionlibxl__alloc_failedwhich may be used for printing a vaguely-useful error message, rather than simply dereferencing a null pointer.
I guess the log infrastructure does (or could do) memory allocation and so can't be used here in the normal way.
Perhaps libxl could format a (short) message into a static emergency buffer and use a (new, optional) emergency variant of the logger callback which does not accept a format string, which should maximise the chances of writing to the log? Even if we could just get the message "Out of memory, aborting" into the logs that would be useful.
Alternatively perhaps an application could be allowed to provide a function which is called first in libxl__alloc_failed, the application ought should be in a better position to fprintf to the appropriate fd to log the issue somewhere useful.
My concern is that many users of libxl will not necessarily be capturing stderr and so the appearance will be of random unexplained exiting.
Quoted 4 lines
-
libxl__ptr_addnow returns void as it crashes on failure.
-libxl__zalloc,_calloc,_strdup,_strndup, crash on failure usinglibxl__alloc_failed. So all the code that uses these can no longer dereference null on malloc failure.
I took a look for a gcc __attribute__ which means "cannot return NULL" but sadly there doesn't seem to be one, this would have allowed gcc to warn us about (now) pointless error handling. I don't know if gcc is smart enough to catch this if we make each of these a macro which did
if (!res) abort()
(or something similar) after calling the inner-function which does the work, I don't think it's worth the effort anyway.
Quoted 37 lines
tools/libxl/libxl_internal.c +9
-7@@ -17,40 +17,40 @@#include "libxl_internal.h" -int libxl__error_set (libxl__gc *gc,int code) -{ -return 0 ; +void libxl__alloc_failed (const char *func,size_t nmemb,size_t size) { +fprintf (stderr, +"libxl: FATAL ERROR: memory allocation failure (%s, %lu x %lu)\n" , + func, (unsigned long )nmemb, (unsigned long )size); +fflush (stderr); +_exit (-1 ); } -int libxl__ptr_add (libxl__gc *gc,void *ptr) +void libxl__ptr_add (libxl__gc *gc,void *ptr) {int i; -void **re;if (!ptr) -return 0 ; +return ;/* fast case: we have space in the array for storing the pointer */ for (i =0 ; i < gc->alloc_maxsize; i++) {if (!gc->alloc_ptrs[i]) { gc->alloc_ptrs[i] = ptr; -return 0 ; +return ; } }
tools/libxl/libxl_internal.c line 43
Quoted 10 lines
tools/libxl/libxl_internal.c +2
-8-/* realloc alloc_ptrs manually with calloc/free/replace */ - re =calloc (gc->alloc_maxsize +25 ,sizeof (void *)); -if (!re) -return -1 ; -for (i =0 ; i < gc->alloc_maxsize; i++) - re[i] = gc->alloc_ptrs[i]; -/* assign the next pointer */ - re[i] = ptr; +int new_maxsize = gc->alloc_maxsize *2 +25 ; +assert (new_maxsize <INT_MAX /sizeof (void *) /2 );
This is not exactly the same as ENOMEM but there is an argument for treating it similarly rather than asserting? I suppose the counter argument is that the cap on max size is so huge that we "assert" it can never be reached in normal use?
[...]
tools/libxl/libxl_internal.c char *libxl__sprintf(libxl__gc *gc, const char *fmt, ...) · line 121
Quoted 8 lines
tools/libxl/libxl_internal.c +1
-3@@ -126,16 +118,13 @@ char *libxl__sprintf(libxl__gc *gc, const char *fmt, ...) ret =vsnprintf (NULL ,0 , fmt, ap);va_end (ap); -if (ret <0 ) { -return NULL ; - } +assert (ret >=0 );
If ret is -ve then it can be ENOMEM in which case we should call the emergency function?
Oh, it can't be ENOMEM because you called with NULL. I guess all the other possible returns (EILSEQ, EINVAL, EOVERFLOW) are abort-worthy.
tools/libxl/libxl_internal.c char *libxl__sprintf(libxl__gc *gc, const char *fmt, ...) · line 125
Quoted 9 lines
tools/libxl/libxl_internal.c +2
-5s =libxl__zalloc (gc, ret +1 ); -if (s) { -va_start (ap, fmt); - ret =vsnprintf (s, ret +1 , fmt, ap); -va_end (ap); - } +va_start (ap, fmt); + ret =vsnprintf (s, ret +1 , fmt, ap);
No check on ret here? In this case I think it can be ENOMEM.
Quoted 5 lines
tools/libxl/libxl_internal.c +2
-0+va_end (ap); +return s; }
Re: [PATCH 09/20] libxl: Crash (more sensibly) on malloc failure
Ian Campbell writes ("Re: [Xen-devel] [PATCH 09/20] libxl: Crash (more sensibly) on malloc failure"):
Quoted 2 lines
I guess the log infrastructure does (or could do) memory allocation and so can't be used here in the normal way.
Yes.
Quoted 5 lines
Perhaps libxl could format a (short) message into a static emergency buffer and use a (new, optional) emergency variant of the logger callback which does not accept a format string, which should maximise the chances of writing to the log? Even if we could just get the message "Out of memory, aborting" into the logs that would be useful.
In fact libxl__logv already has this special case built-in.
Quoted 2 lines
My concern is that many users of libxl will not necessarily be capturing stderr and so the appearance will be of random unexplained exiting.
Yes. Good point. I will fix this, and have it call libxl__log as well as printing to stderr.
Quoted 8 lines
Quoted 4 lines
-
libxl__ptr_addnow returns void as it crashes on failure.
-libxl__zalloc,_calloc,_strdup,_strndup, crash on failure usinglibxl__alloc_failed. So all the code that uses these can no longer dereference null on malloc failure.I took a look for a gcc
__attribute__which means "cannot return NULL" but sadly there doesn't seem to be one, this would have allowed gcc to warn us about (now) pointless error handling.
Do we really need a warning about this ? It's harmless.
Quoted 5 lines
I don't know if gcc is
smart enough to catch this if we make each of these a macro which didif (!res) abort()(or something similar) after calling the inner-function which does the work, I don't think it's worth the effort anyway.
Quite.
Ian.
Re: [PATCH 09/20] libxl: Crash (more sensibly) on malloc failure
Quoted 12 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 09/20] libxl: Crash (more sensibly) on malloc failure"):
Quoted 2 lines
I guess the log infrastructure does (or could do) memory allocation and so can't be used here in the normal way.
Yes.
Quoted 5 lines
Perhaps libxl could format a (short) message into a static emergency buffer and use a (new, optional) emergency variant of the logger callback which does not accept a format string, which should maximise the chances of writing to the log? Even if we could just get the message "Out of memory, aborting" into the logs that would be useful.
Quoted 7 lines
In fact
libxl__logvalready has this special case built-in.Quoted 2 lines
My concern is that many users of libxl will not necessarily be capturing stderr and so the appearance will be of random unexplained exiting.
Yes. Good point. I will fix this, and have it call
libxl__logas well as printing to stderr.
Great, thanks.
Quoted 10 lines
Quoted 8 lines
Quoted 4 lines
-
libxl__ptr_addnow returns void as it crashes on failure.
-libxl__zalloc,_calloc,_strdup,_strndup, crash on failure usinglibxl__alloc_failed. So all the code that uses these can no longer dereference null on malloc failure.I took a look for a gcc
__attribute__which means "cannot return NULL" but sadly there doesn't seem to be one, this would have allowed gcc to warn us about (now) pointless error handling.Do we really need a warning about this ? It's harmless.
More as a guide to help us to easily find and nuke all the unnecessary error handling, rather than because it's something to worry about.
Quoted 9 lines
Quoted 5 lines
I don't know if gcc is
smart enough to catch this if we make each of these a macro which didif (!res) abort()(or something similar) after calling the inner-function which does the work, I don't think it's worth the effort anyway.
Quite.
Ian.
PATCH 10/20 libxl: Make libxl__zalloc et al tolerate a NULL gc
In reply to Ian JacksonArrange that if we pass NULL as a gc, we simply don't register the pointer. This instantly gives us non-gc'ing but error-checking versions of malloc, realloc, vasprintf, etc.
--- tools/libxl/libxl_internal.c | 5 ++++- tools/libxl/libxl_internal.h | 21 +++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-)
tools/libxl/libxl_internal.c +4 -1
@@ -29,6 +29,9 @@ void libxl__ptr_add(libxl__gc *gc, void *ptr) {int i; +if (!gc) +return ; +if (!ptr)return ;
@@ -96,7 +99,7 @@ void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size)if (ptr ==NULL ) {libxl__ptr_add (gc, new_ptr); - }else if (new_ptr != ptr) { + }else if (new_ptr != ptr && gc !=NULL ) {for (i =0 ; i < gc->alloc_maxsize; i++) {if (gc->alloc_ptrs[i] == ptr) { gc->alloc_ptrs[i] = new_ptr;
tools/libxl/libxl_internal.h +13 -8
@@ -381,30 +381,35 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)* * All pointers returned by these functions are registered for garbage * collection on exit from the outermost libxl callframe. +* +* However, where the argument is stated to be "gc_opt", NULL may be +* passed instead, in which case no garbage collection will occur; the +* pointer must later be freed with free(). This is for memory +* allocations of types (b) and (c). */ /* register @ptr in @gc for free on exit from outermost libxl callframe. */ -_hidden void libxl__ptr_add(libxl__gc *gc, void *ptr); +_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr);/* if this is the outermost libxl callframe then free all pointers in @gc */ _hidden void libxl__free_all(libxl__gc *gc);/* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */ -_hidden void *libxl__zalloc(libxl__gc *gc, int bytes); +_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes);/* allocate and zero memory for an array of @nmemb members of @size each. * (similar to a gc'd calloc(3)). */ -_hidden void *libxl__calloc(libxl__gc *gc, size_t nmemb, size_t size); +_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size);/* change the size of the memory block pointed to by @ptr to @new_size bytes. * unlike other allocation functions here any additional space between the * oldsize and @new_size is not initialised (similar to a gc'd realloc(3)). */ -_hidden void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size); +_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size);/* print @fmt into an allocated string large enoughto contain the result. * (similar to gc'd asprintf(3)). */ -_hidden char *libxl__sprintf(libxl__gc *gc, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3); +_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);/* duplicate the string @c (similar to a gc'd strdup(3)). */ -_hidden char *libxl__strdup(libxl__gc *gc, const char *c); +_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c);/* duplicate at most @n bytes of string @c (similar to a gc'd strndup(3)). */ -_hidden char *libxl__strndup(libxl__gc *gc, const char *c, size_t n); +_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n);/* strip the last path component from @s and return as a newly allocated * string. (similar to a gc'd dirname(3)). */ -_hidden char *libxl__dirname(libxl__gc *gc, const char *s); +_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s); _hidden char **libxl__xs_kvs_of_flexarray(libxl__gc *gc, flexarray_t *array, int length);
Signature · 1 line
1.7.2.5
Re: [PATCH 10/20] libxl: Make libxl__zalloc et al tolerate a NULL gc
Quoted 5 lines · Ian Jackson
Arrange that if we pass NULL as a gc, we simply don't register the pointer. This instantly gives us non-gc'ing but error-checking versions of malloc, realloc, vasprintf, etc.
Signed-off-by Ian Jackson <[email protected]>
We could consider __attribute__((nonnull)) for the other helper functions in that section of libxl_internal.h.
Quoted 76 lines
--- tools/libxl/libxl_internal.c | 5 ++++- tools/libxl/libxl_internal.h | 21 +++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-)tools/libxl/libxl_internal.c +4
-1@@ -29,6 +29,9 @@ void libxl__ptr_add(libxl__gc *gc, void *ptr) {int i; +if (!gc) +return ; +if (!ptr)return ;@@ -96,7 +99,7 @@ void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size)if (ptr ==NULL ) {libxl__ptr_add (gc, new_ptr); - }else if (new_ptr != ptr) { + }else if (new_ptr != ptr && gc !=NULL ) {for (i =0 ; i < gc->alloc_maxsize; i++) {if (gc->alloc_ptrs[i] == ptr) { gc->alloc_ptrs[i] = new_ptr;tools/libxl/libxl_internal.h +13
-8@@ -381,30 +381,35 @@ static inline libxl_ctx *libxl__gc_owner(libxl__gc *gc)* * All pointers returned by these functions are registered for garbage * collection on exit from the outermost libxl callframe. +* +* However, where the argument is stated to be "gc_opt", NULL may be +* passed instead, in which case no garbage collection will occur; the +* pointer must later be freed with free(). This is for memory +* allocations of types (b) and (c). */ /* register @ptr in @gc for free on exit from outermost libxl callframe. */ -_hidden void libxl__ptr_add(libxl__gc *gc, void *ptr); +_hidden void libxl__ptr_add(libxl__gc *gc_opt, void *ptr);/* if this is the outermost libxl callframe then free all pointers in @gc */ _hidden void libxl__free_all(libxl__gc *gc);/* allocate and zero @bytes. (similar to a gc'd malloc(3)+memzero()) */ -_hidden void *libxl__zalloc(libxl__gc *gc, int bytes); +_hidden void *libxl__zalloc(libxl__gc *gc_opt, int bytes);/* allocate and zero memory for an array of @nmemb members of @size each. * (similar to a gc'd calloc(3)). */ -_hidden void *libxl__calloc(libxl__gc *gc, size_t nmemb, size_t size); +_hidden void *libxl__calloc(libxl__gc *gc_opt, size_t nmemb, size_t size);/* change the size of the memory block pointed to by @ptr to @new_size bytes. * unlike other allocation functions here any additional space between the * oldsize and @new_size is not initialised (similar to a gc'd realloc(3)). */ -_hidden void *libxl__realloc(libxl__gc *gc, void *ptr, size_t new_size); +_hidden void *libxl__realloc(libxl__gc *gc_opt, void *ptr, size_t new_size);/* print @fmt into an allocated string large enoughto contain the result. * (similar to gc'd asprintf(3)). */ -_hidden char *libxl__sprintf(libxl__gc *gc, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3); +_hidden char *libxl__sprintf(libxl__gc *gc_opt, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);/* duplicate the string @c (similar to a gc'd strdup(3)). */ -_hidden char *libxl__strdup(libxl__gc *gc, const char *c); +_hidden char *libxl__strdup(libxl__gc *gc_opt, const char *c);/* duplicate at most @n bytes of string @c (similar to a gc'd strndup(3)). */ -_hidden char *libxl__strndup(libxl__gc *gc, const char *c, size_t n); +_hidden char *libxl__strndup(libxl__gc *gc_opt, const char *c, size_t n);/* strip the last path component from @s and return as a newly allocated * string. (similar to a gc'd dirname(3)). */ -_hidden char *libxl__dirname(libxl__gc *gc, const char *s); +_hidden char *libxl__dirname(libxl__gc *gc_opt, const char *s); _hidden char **libxl__xs_kvs_of_flexarray(libxl__gc *gc, flexarray_t *array, int length);
Re: [PATCH 10/20] libxl: Make libxl__zalloc et al tolerate a NULL gc
Ian Campbell writes ("Re: [Xen-devel] [PATCH 10/20] libxl: Make libxl__zalloc et al tolerate a NULL gc"):
Quoted 4 lines · Ian Jackson
Quoted 3 lines
Arrange that if we pass NULL as a gc, we simply don't register the pointer. This instantly gives us non-gc'ing but error-checking versions of malloc, realloc, vasprintf, etc.
...
Quoted 1 line
Acked-by Ian Campbell <[email protected]>
Thanks.
Quoted 2 lines
We could consider __attribute__((nonnull)) for the other helper functions in that section of
libxl_internal.h.
The only function in that section which isn't declared as taking gc_opt (ie which can't be passed NULL) is libxl__free_all, and it seems unlikely anyone would mistakenly pass 0 to it (esp. since it has few callers).
Ian.
Re: [PATCH 10/20] libxl: Make libxl__zalloc et al tolerate a NULL gc
Quoted 10 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 10/20] libxl: Make
libxl__zallocet al tolerate a NULL gc"):Quoted 4 lines · Ian Jackson
Quoted 3 lines
Arrange that if we pass NULL as a gc, we simply don't register the pointer. This instantly gives us non-gc'ing but error-checking versions of malloc, realloc, vasprintf, etc.
...
Quoted 1 line
Acked-by Ian Campbell <[email protected]>Thanks.
Quoted 7 lines
Quoted 2 lines
We could consider __attribute__((nonnull)) for the other helper functions in that section of
libxl_internal.h.The only function in that section which isn't declared as taking
gc_opt(ie which can't be passed NULL) islibxl__free_all, and it seems unlikely anyone would mistakenly pass 0 to it (esp. since it has few callers).
Oh, right, I was looking at libxl__xs_kvs_of_flexarray etc but that's actually the next section I guess.
Ian.
PATCH 11/20 libxl: Introduce some convenience macros
In reply to Ian JacksonWe introduce:
<type> *GCNEW(<type> *var);
<type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb);
<type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb);
char *GCSPRINTF(const char *fmt, ...);
void LOG(<xtl_level_suffix>, const char *fmt, ...);
void LOGE(<xtl_level_suffix>, const char *fmt, ...); void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...);
all of which expect, in the calling context,
libxl__gc *gc;
--- tools/libxl/libxl_internal.h | 72 ++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 72 insertions(+), 0 deletions(-)
tools/libxl/libxl_internal.h +72 -0
@@ -1346,6 +1346,78 @@ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao);#define GC_FREE libxl__free_all(gc)#define CTX libxl__gc_owner(gc) +/* Allocation macros all of which use the gc. */ + +#define ARRAY_SIZE_OK (ptr, nmemb) ((nmemb) < INT_MAX / (sizeof(*(ptr)) * 2)) + +/* +* Expression statement <type> *GCNEW(<type> *var); +* Uses libxl__gc *gc; +* +* Allocates a new object of type <type> from the gc and zeroes it +* with memset. Sets var to point to the new object or zero (setting +* errno). Returns the new value of var. +*/ +#define GCNEW (var) \ + (((var) = libxl__zalloc((gc),sizeof(*(var))))) + +/* +* Expression statement <type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb); +* Uses libxl__gc *gc; +* +* Like GCNEW but allocates an array of nmemb elements, as if from +* calloc. Does check for integer overflow due to large nmemb. If +* nmemb is 0 may succeed by returning 0. +*/ +#define GCNEW_ARRAY (var, nmemb) \ + ((var) = libxl__calloc((gc), (nmemb), sizeof(*(var)))) + +/* +* Expression statement <type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb); +* Uses libxl__gc *gc; +* +* Reallocates the array var to be of size nmemb elements. Updates +* var and returns the new value of var. Does check for integer +* overflow due to large nmemb. +* +* Do not pass nmemb==0. old may be 0 on entry. +*/ +#define GCREALLOC_ARRAY (var, nmemb) \ + (assert(nmemb > 0), \ + assert(ARRAY_SIZE_OK((var), (nmemb))), \ + (var) = libxl__realloc((gc), (var), (nmemb)*sizeof(*(var))))) + + +/* +* Expression char *GCSPRINTF(const char *fmt, ...); +* Uses libxl__gc *gc; +* +* Trivial convenience wrapper for libxl__sprintf. +*/ +#define GCSPRINTF (fmt, ...) (libxl__sprintf((gc), (fmt), __VA_ARGS__)) + + +/* +* Expression statements +* void LOG(<xtl_level_suffix>, const char *fmt, ...); +* void LOGE(<xtl_level_suffix>, const char *fmt, ...); +* void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...); +* Use +* libxl__gc *gc; +* +* Trivial convenience wrappers for LIBXL__LOG, LIBXL__LOG_ERRNO and +* LIBXL__LOG_ERRNOVAL, respectively (and thus for libxl__log). +* +* XTL_<xtl_level_suffix> should exist and be an xentoollog.h log level +* So <xtl_level_suffix> should be one of +* DEBUG VERBOSE DETAIL PROGRESS INFO NOTICE WARN ERROR ERROR CRITICAL +* Of these, most of libxl uses +* DEBUG INFO WARN ERROR +*/ +#define LOG (l,f, ...) LIBXL__LOG(CTX,XTL_##l,(f),##__VA_ARGS__) +#define LOGE (l,f, ...) LIBXL__LOG_ERRNO(CTX,XTL_##l,(f),##__VA_ARGS__) +#define LOGEV (l,e,f, ...) LIBXL__LOG_ERRNOVAL(CTX,XTL_##l,(e),(f),##__VA_ARGS__) +/* Locking functions. See comment for "lock" member of libxl__ctx. */
Signature · 1 line
1.7.2.5
Re: [PATCH 11/20] libxl: Introduce some convenience macros
Quoted 10 lines · Ian Jackson
We introduce:
<type> *GCNEW(<type> *var); <type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb); <type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb); char *GCSPRINTF(const char *fmt, ...); void LOG(<xtl_level_suffix>, const char *fmt, ...); void LOGE(<xtl_level_suffix>, const char *fmt, ...); void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...);all of which expect, in the calling context,
libxl__gc*gc;
All of these get used later in the series?
Quoted 1 line
Signed-off-by Ian Jackson <[email protected]>
Quoted 87 lines
--- tools/libxl/libxl_internal.h | 72 ++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 72 insertions(+), 0 deletions(-)tools/libxl/libxl_internal.h +72
-0@@ -1346,6 +1346,78 @@ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao);#define GC_FREE libxl__free_all(gc)#define CTX libxl__gc_owner(gc) +/* Allocation macros all of which use the gc. */ + +#define ARRAY_SIZE_OK (ptr, nmemb) ((nmemb) < INT_MAX / (sizeof(*(ptr)) * 2)) + +/* +* Expression statement <type> *GCNEW(<type> *var); +* Uses libxl__gc *gc; +* +* Allocates a new object of type <type> from the gc and zeroes it +* with memset. Sets var to point to the new object or zero (setting +* errno). Returns the new value of var. +*/ +#define GCNEW (var) \ + (((var) = libxl__zalloc((gc),sizeof(*(var))))) + +/* +* Expression statement <type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb); +* Uses libxl__gc *gc; +* +* Like GCNEW but allocates an array of nmemb elements, as if from +* calloc. Does check for integer overflow due to large nmemb. If +* nmemb is 0 may succeed by returning 0. +*/ +#define GCNEW_ARRAY (var, nmemb) \ + ((var) = libxl__calloc((gc), (nmemb), sizeof(*(var)))) + +/* +* Expression statement <type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb); +* Uses libxl__gc *gc; +* +* Reallocates the array var to be of size nmemb elements. Updates +* var and returns the new value of var. Does check for integer +* overflow due to large nmemb. +* +* Do not pass nmemb==0. old may be 0 on entry. +*/ +#define GCREALLOC_ARRAY (var, nmemb) \ + (assert(nmemb > 0), \ + assert(ARRAY_SIZE_OK((var), (nmemb))), \ + (var) = libxl__realloc((gc), (var), (nmemb)*sizeof(*(var))))) + + +/* +* Expression char *GCSPRINTF(const char *fmt, ...); +* Uses libxl__gc *gc; +* +* Trivial convenience wrapper for libxl__sprintf. +*/ +#define GCSPRINTF (fmt, ...) (libxl__sprintf((gc), (fmt), __VA_ARGS__)) + + +/* +* Expression statements +* void LOG(<xtl_level_suffix>, const char *fmt, ...); +* void LOGE(<xtl_level_suffix>, const char *fmt, ...); +* void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...); +* Use +* libxl__gc *gc; +* +* Trivial convenience wrappers for LIBXL__LOG, LIBXL__LOG_ERRNO and +* LIBXL__LOG_ERRNOVAL, respectively (and thus for libxl__log). +* +* XTL_<xtl_level_suffix> should exist and be an xentoollog.h log level +* So <xtl_level_suffix> should be one of +* DEBUG VERBOSE DETAIL PROGRESS INFO NOTICE WARN ERROR ERROR CRITICAL +* Of these, most of libxl uses +* DEBUG INFO WARN ERROR +*/ +#define LOG (l,f, ...) LIBXL__LOG(CTX,XTL_##l,(f),##__VA_ARGS__) +#define LOGE (l,f, ...) LIBXL__LOG_ERRNO(CTX,XTL_##l,(f),##__VA_ARGS__) +#define LOGEV (l,e,f, ...) LIBXL__LOG_ERRNOVAL(CTX,XTL_##l,(e),(f),##__VA_ARGS__) +/* Locking functions. See comment for "lock" member of libxl__ctx. */
Re: [PATCH 11/20] libxl: Introduce some convenience macros
Ian Campbell writes ("Re: [Xen-devel] [PATCH 11/20] libxl: Introduce some convenience macros"):
Quoted 12 lines · Ian Jackson
Quoted 10 lines
We introduce:
<type> *GCNEW(<type> *var); <type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb); <type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb); char *GCSPRINTF(const char *fmt, ...); void LOG(<xtl_level_suffix>, const char *fmt, ...); void LOGE(<xtl_level_suffix>, const char *fmt, ...); void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...);all of which expect, in the calling context,
libxl__gc*gc;
Quoted 1 line
All of these get used later in the series?
Many of them do. I'm not sure I use all of the LOG* family but they're orthogonally necessary.
I supplied GCREALLOC_ARRAY because it seemed to fit in with the family which had malloc and an array malloc. It doesn't have a caller yet even in my tip; there's a potential call site in libxl_qmp.c but if that's not enough to justify it I can take it out for now.
Ian.
Re: [PATCH 11/20] libxl: Introduce some convenience macros
Quoted 13 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 11/20] libxl: Introduce some convenience macros"):
Quoted 12 lines · Ian Jackson
Quoted 10 lines
We introduce:
<type> *GCNEW(<type> *var); <type> *GCNEW_ARRAY(<type> *var, ssize_t nmemb); <type> *GCREALLOC_ARRAY(<type> *var, size_t nmemb); char *GCSPRINTF(const char *fmt, ...); void LOG(<xtl_level_suffix>, const char *fmt, ...); void LOGE(<xtl_level_suffix>, const char *fmt, ...); void LOGEV(<xtl_level_suffix>, int errnoval, const char *fmt, ...);all of which expect, in the calling context,
libxl__gc*gc;
Quoted 4 lines
Quoted 1 line
All of these get used later in the series?
Many of them do. I'm not sure I use all of the LOG* family but they're orthogonally necessary.
Makes sense.
Quoted 4 lines
I supplied
GCREALLOC_ARRAYbecause it seemed to fit in with the family which had malloc and an array malloc. It doesn't have a caller yet even in my tip; there's a potential call site inlibxl_qmp.cbut if that's not enough to justify it I can take it out for now.
Might as well keep it now you've written it.
Thanks,
Ian.
PATCH 12/20 libxl: Protect fds with CLOEXEC even with forking threads
In reply to Ian JacksonWe introduce a new "carefd" concept, which relates to fds that we care about not being inherited by long-lived children.
As yet we do not use this anywhere in libxl. Until all locations in libxl which make such fds are converted, libxl__postfork may not work entirely properly. If these locations do not use O_CLOEXEC (or use calls for which there is no O_CLOEXEC) then multithreaded programs may not work properly.
This introduces a new API call libxl_postfork_child_noexec which must be called by applications which make long-running non-execing children. Add the appropriate call to xl's postfork function.
--- tools/libxl/Makefile | 2 +- tools/libxl/libxl.c | 3 + tools/libxl/libxl_event.h | 12 ++++ tools/libxl/libxl_fork.c | 146 ++++++++++++++++++++++++++++++++++++++++++ tools/libxl/libxl_internal.h | 63 ++++++++++++++++++ tools/libxl/xl.c | 3 + 6 files changed, 228 insertions(+), 1 deletions(-) create mode 100644 tools/libxl/libxl_fork.c
tools/libxl/Makefile +1 -1
@@ -53,7 +53,7 @@ LIBXL_LIBS += -lyajl LIBXL_OBJS = flexarray.o libxl.o libxl_create.o libxl_dm.o libxl_pci.o \ libxl_dom.o libxl_exec.o libxl_xshelp.o libxl_device.o \ libxl_internal.o libxl_utils.o libxl_uuid.o libxl_json.o \ - libxl_qmp.o libxl_event.o $(LIBXL_OBJS-y) + libxl_qmp.o libxl_event.o libxl_fork.o $(LIBXL_OBJS-y) LIBXL_OBJS += _libxl_types.o libxl_flask.o _libxl_types_internal.o $(LIBXL_OBJS): CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenguest) $(CFLAGS_libxenstore) $(CFLAGS_libblktapctl) -include $(XEN_ROOT)/tools/config.h
tools/libxl/libxl.c +3 -0
@@ -68,6 +68,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,/* Now ctx is safe for ctx_free; failures simply set rc and "goto out" */ + rc =libxl__atfork_init (ctx); +if (rc) goto out; + rc =libxl__poller_init (ctx, &ctx->poller_app);if (rc) goto out;
tools/libxl/libxl_event.h +12 -0
@@ -371,6 +371,18 @@ void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl,*/ void libxl_osevent_occurred_timeout (libxl_ctx *ctx,void *for_libxl); + +/* +* An application which initialises a libxl_ctx in a parent process +* and then forks a child which does not quickly exec, must +* instead libxl__postfork_child_noexec in the child. One call +* on any existing (or specially made) ctx is sufficient; after +* this all previously existing libxl_ctx's are invalidated and +* must not be used - or even freed. +*/ +void libxl_postfork_child_noexec (libxl_ctx *ctx); + +#endif /*
tools/libxl/libxl_fork.c new file +146 -0
146 lines not on this page · raw message
tools/libxl/libxl_internal.h +63 -0
75 lines not on this page · raw message
tools/libxl/xl.c +3 -0
@@ -97,6 +97,9 @@ static void parse_global_config(const char *configfile,void postfork (void ) { +libxl_postfork_child_noexec (ctx);/* in case we don't exit/exec */ + ctx =0 ; +if (libxl_ctx_alloc (&ctx,LIBXL_VERSION ,0 , (xentoollog_logger *)logger)) {fprintf (stderr,"cannot reinit xl context after fork\n" );exit (-1 );
Signature · 1 line
1.7.2.5
Re: [PATCH 12/20] libxl: Protect fds with CLOEXEC even with forking threads
Quoted 9 lines · Ian Jackson
We introduce a new "carefd" concept, which relates to fds that we care about not being inherited by long-lived children.
As yet we do not use this anywhere in libxl. Until all locations in libxl which make such fds are converted,
libxl__postforkmay not work entirely properly. If these locations do not useO_CLOEXEC(or use calls for which there is noO_CLOEXEC) then multithreaded programs may not work properly.
Quoted 3 lines
This introduces a new API call
libxl_postfork_child_noexecwhich must be called by applications which make long-running non-execing children. Add the appropriate call to xl's postfork function.
One of the xl callers of postfork does quickly exec. I presume it is harmless to call the libxl noexec function anyway?
Quoted 44 lines
Signed-off-by Ian Jackson <[email protected]>--- tools/libxl/Makefile | 2 +- tools/libxl/libxl.c | 3 + tools/libxl/libxl_event.h | 12 ++++ tools/libxl/libxl_fork.c | 146 ++++++++++++++++++++++++++++++++++++++++++ tools/libxl/libxl_internal.h | 63 ++++++++++++++++++ tools/libxl/xl.c | 3 + 6 files changed, 228 insertions(+), 1 deletions(-) create mode 100644 tools/libxl/libxl_fork.ctools/libxl/Makefile +1
-1@@ -53,7 +53,7 @@ LIBXL_LIBS += -lyajl LIBXL_OBJS = flexarray.o libxl.o libxl_create.o libxl_dm.o libxl_pci.o \ libxl_dom.o libxl_exec.o libxl_xshelp.o libxl_device.o \ libxl_internal.o libxl_utils.o libxl_uuid.o libxl_json.o \ - libxl_qmp.o libxl_event.o $(LIBXL_OBJS-y) + libxl_qmp.o libxl_event.o libxl_fork.o $(LIBXL_OBJS-y) LIBXL_OBJS += _libxl_types.o libxl_flask.o _libxl_types_internal.o $(LIBXL_OBJS): CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenguest) $(CFLAGS_libxenstore) $(CFLAGS_libblktapctl) -include $(XEN_ROOT)/tools/config.htools/libxl/libxl.c +3
-0@@ -68,6 +68,9 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,/* Now ctx is safe for ctx_free; failures simply set rc and "goto out" */ + rc =libxl__atfork_init (ctx); +if (rc) goto out; + rc =libxl__poller_init (ctx, &ctx->poller_app);if (rc) goto out;tools/libxl/libxl_event.h +0
-0
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 378
Quoted 8 lines
tools/libxl/libxl_event.h +5
-0@@ -371,6 +371,18 @@ void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl,*/ void libxl_osevent_occurred_timeout (libxl_ctx *ctx,void *for_libxl); + +/* +* An application which initialises a libxl_ctx in a parent process +* and then forks a child which does not quickly exec, must +* instead libxl__postfork_child_noexec in the child. One call
One too many underscores after libxl here.
Quoted 77 lines
tools/libxl/libxl_event.h +7
-0+* on any existing (or specially made) ctx is sufficient; after +* this all previously existing libxl_ctx's are invalidated and +* must not be used - or even freed. +*/ +void libxl_postfork_child_noexec (libxl_ctx *ctx); + +#endif /* tools/libxl/libxl_fork.c new file +61
-0@@ -0,0 +1,146 @@ +/* +* Copyright (C) 2012 Citrix Ltd. +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU Lesser General Public License as published +* by the Free Software Foundation; version 2.1 only. with the special +* exception on linking described in file LICENSE. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Lesser General Public License for more details. +*/ +/* +* Internal child process machinery for use by other parts of libxl +*/ + +#include "libxl_osdeps.h" /* must come before any other headers */ + +#include "libxl_internal.h" + +/* +* carefd arrangements +* +* carefd_begin and _unlock take out the no_forking lock, which we +* also take and release in our pthread_atfork handlers. So when this +* lock is held the whole process cannot fork. We therefore protect +* our fds from leaking into children made by other threads. +* +* We maintain a list of all the carefds, so that if the application +* wants to fork a long-running but non-execing child, we can close +* them all. +* +* So the record function sets CLOEXEC for the benefit of execing +* children, and makes a note of the fd for the benefit of non-execing +* ones. +*/ + +struct libxl__carefd { +LIBXL_LIST_ENTRY (libxl__carefd) entry; +int fd; +}; + +static pthread_mutex_t no_forking =PTHREAD_MUTEX_INITIALIZER ; +static int atfork_registered; +static LIBXL_LIST_HEAD(, libxl__carefd) carefds = +LIBXL_LIST_HEAD_INITIALIZER (carefds); + +static void atfork_lock (void ) +{ +int r =pthread_mutex_lock (&no_forking); +assert (!r); +} + +static void atfork_unlock (void ) +{ +int r =pthread_mutex_unlock (&no_forking); +assert (!r); +} + +int libxl__atfork_init (libxl_ctx *ctx)
tools/libxl/libxl_fork.c line 71
Quoted 10 lines
tools/libxl/libxl_fork.c new file +10
-0+{ +int r, rc; + +atfork_lock (); +if (atfork_registered) { rc =0 ; goto out; } + + r =pthread_atfork (atfork_lock, atfork_unlock, atfork_unlock); +if (r) { +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_ERROR ,"pthread_atfork failed" ); + rc =ERROR_NOMEM ;
I thought we were calling the magic log+exit function on these now ;-)
Surprising that ENOMEM is the only error that can be returned here (you'd think all manner of things could go wrong when threads are involved). No matter.
Quoted 31 lines
tools/libxl/libxl_fork.c new file +31
-0+ goto out; + } + + atfork_registered =1 ; + rc =0 ; + out: +atfork_unlock (); +return rc; +} + +void libxl__carefd_begin (void ) {atfork_lock (); } +void libxl__carefd_unlock (void ) {atfork_unlock (); } + +libxl__carefd *libxl__carefd_record (libxl_ctx *ctx,int fd) +{ +libxl__carefd *cf =0 ; + +libxl_fd_set_cloexec (ctx, fd,1 ); + cf =libxl__zalloc (NULL ,sizeof (*cf)); + cf->fd = fd; +LIBXL_LIST_INSERT_HEAD (&carefds, cf, entry); +return cf; +} + +libxl__carefd *libxl__carefd_opened (libxl_ctx *ctx,int fd) +{ +libxl__carefd *cf =0 ; + + cf =libxl__carefd_record (ctx, fd); +libxl__carefd_unlock (); +return cf;
tools/libxl/libxl_fork.c line 112
Quoted 10 lines
tools/libxl/libxl_fork.c new file +10
-0+} + +void libxl_postfork_child_noexec (libxl_ctx *ctx) +{ +libxl__carefd *cf, *cf_tmp; +int r; + +atfork_lock (); + LIBXL_LIST_FOREACH_SAFE(cf, &carefds, entry, cf_tmp) { +if (cf->fd >=0 ) {
Where can an fd < 0 come from? Shouldn't we reject those at libxl__carefd_record? Or does it make error handling easier in the callers somehow?
tools/libxl/libxl_fork.c line 115
Quoted 3 lines
tools/libxl/libxl_fork.c new file +3
-0+ r =close (cf->fd); +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_WARNING ,"failed to close fd=%d" +" (perhaps of another libxl ctx)" , cf->fd);
Shouldn't there be an if (r < 0) before this logging?
tools/libxl/libxl_fork.c line 128
Quoted 13 lines
tools/libxl/libxl_fork.c new file +13
-0+ } +free (cf); + } +LIBXL_LIST_INIT (&carefds); +atfork_unlock (); +} + +int libxl__carefd_close (libxl__carefd *cf) +{ +if (!cf)return 0 ; +int r = cf->fd <0 ?0 :close (cf->fd); +int esave = errno; +LIBXL_LIST_REMOVE (cf, entry);
Are all the LIBXL_LIST_foo thread safe?
This function isn't called with the fork lock held.
Quoted 72 lines
tools/libxl/libxl_fork.c new file +18
-0+free (cf); + errno = esave; +return r; +} + +int libxl__carefd_fd (const libxl__carefd *cf) +{ +if (!cf)return -1 ; +return cf->fd; +} + +/* +* Local variables: +* mode: C +* c-basic-offset: 4 +* indent-tabs-mode: nil +* End: +*/ tools/libxl/libxl_internal.h +39
-0@@ -606,6 +606,9 @@ void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p);void libxl__poller_wakeup (libxl__egc *egc,libxl__poller *p); +int libxl__atfork_init (libxl_ctx *ctx); + +/* from xl_dom */ _hidden libxl_domain_type libxl__domain_type(libxl__gc *gc, uint32_t domid); _hidden int libxl__domain_shutdown_reason(libxl__gc *gc, uint32_t domid);@@ -1302,6 +1305,66 @@ _hidden void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc);/* For use by ao machinery ONLY */ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao); + +/* +* File descriptors and CLOEXEC +*/ + +/* +* For libxl functions which create file descriptors, at least one +* of the following must be true: +* (a) libxl does not care if copies of this open-file are inherited +* by random children and might remain open indefinitely +* (b) libxl must take extra care for the fd (the actual descriptor, +* not the open-file) as below. We call this a "carefd". +* +* The rules for opening a carefd are: +* (i) Before bringing any carefds into existence, +* libxl code must call libxl__carefd_begin. +* (ii) Then for each carefd brought into existence, +* libxl code must call libxl__carefd_record +* and remember the libxl__carefd_record*. +* (iii) Then it must call libxl__carefd_unlock. +* (iv) When in a child process the fd is to be passed across +* exec by libxl, the libxl code must unset FD_CLOEXEC +* on the fd eg by using libxl_fd_set_cloexec. +* (v) Later, when the fd is to be closed in the same process, +* libxl code must not call close. Instead, it must call +* libxl__carefd_close. +* Steps (ii) and (iii) can be combined by calling the convenience +* function libxl__carefd_opened. +*/ +/* libxl__carefd_begin and _unlock (or _opened) must be called always +* in pairs. They may be called with the CTX lock held. In between +* _begin and _unlock, the following are prohibited: +* - anything which might block +* - any callbacks to the application +* - nested calls to libxl__carefd_begin +* - fork (libxl__fork)
tools/libxl/libxl_internal.h _hidden void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc); · line 1353
Quoted 10 lines
tools/libxl/libxl_internal.h +10
-0+* In general nothing should be done before _unlock that could be done +* afterwards. +*/ +typedef struct libxl__carefd libxl__carefd ; + +void libxl__carefd_begin (void ); +void libxl__carefd_unlock (void ); + +/* fd may be -1, in which case this returns a dummy libxl__fd_record +* on which it _carefd_close is a no-op. Cannot fail. */
answers my earlier question about fd==-1.
Quoted 39 lines
tools/libxl/libxl_internal.h +14
-0+libxl__carefd *libxl__carefd_record (libxl_ctx *ctx,int fd); + +/* Combines _record and _unlock in a single call. If fd==-1, +* still does the unlock, but returns 0. Cannot fail. */ +libxl__carefd *libxl__carefd_opened (libxl_ctx *ctx,int fd); + +/* Works just like close(2). You may pass NULL, in which case it's +* a successful no-op. */ +int libxl__carefd_close (libxl__carefd *); + +/* You may pass NULL in which case the answer is -1. */ +int libxl__carefd_fd (const libxl__carefd *); + +/* * Convenience macros. */ tools/libxl/xl.c +3
-1@@ -97,6 +97,9 @@ static void parse_global_config(const char *configfile,void postfork (void ) { +libxl_postfork_child_noexec (ctx);/* in case we don't exit/exec */ + ctx =0 ; +if (libxl_ctx_alloc (&ctx,LIBXL_VERSION ,0 , (xentoollog_logger *)logger)) {fprintf (stderr,"cannot reinit xl context after fork\n" );exit (-1 ); --1.7.2.5
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 12/20] libxl: Protect fds with CLOEXEC even with forking threads
Ian Campbell writes ("Re: [Xen-devel] [PATCH 12/20] libxl: Protect fds with CLOEXEC even with forking threads"):
Quoted 7 lines · Ian Jackson
Quoted 3 lines
This introduces a new API call
libxl_postfork_child_noexecwhich must be called by applications which make long-running non-execing children. Add the appropriate call to xl's postfork function.One of the xl callers of postfork does quickly exec. I presume it is harmless to call the libxl noexec function anyway?
Yes. I have clarified the doc comment.
Quoted 5 lines
Quoted 3 lines
+ * An application which initialises a
libxl_ctxin a parent process
+ * and then forks a child which does not quickly exec, must
+ * insteadlibxl__postfork_child_noexecin the child. One callOne too many underscores after libxl here.
Fixed.
Quoted 6 lines
tools/libxl/libxl_fork.c line 71
Quoted 4 lines
tools/libxl/libxl_fork.c new file +4
-0+ r =pthread_atfork (atfork_lock, atfork_unlock, atfork_unlock); +if (r) { +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_ERROR ,"pthread_atfork failed" ); + rc =ERROR_NOMEM ;I thought we were calling the magic log+exit function on these now ;-)
Good point. I have fixed this. I'll also have to update the alloc failure handler not to always want to print the allocation size.
Quoted 5 lines
tools/libxl/libxl_fork.c line 115
Quoted 3 lines
tools/libxl/libxl_fork.c new file +3
-0+ r =close (cf->fd); +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_WARNING ,"failed to close fd=%d" +" (perhaps of another libxl ctx)" , cf->fd);Shouldn't there be an if (r < 0) before this logging?
Yes. I did say I hadn't executed it :-).
Quoted 8 lines
tools/libxl/libxl_fork.c line 128
Quoted 6 lines
tools/libxl/libxl_fork.c new file +6
-0+int libxl__carefd_close (libxl__carefd *cf) +{ +if (!cf)return 0 ; +int r = cf->fd <0 ?0 :close (cf->fd); +int esave = errno; +LIBXL_LIST_REMOVE (cf, entry);Are all the
LIBXL_LIST_foothread safe?
No.
Quoted 1 line
This function isn't called with the fork lock held.
Good point.
Thanks,
Ian.
PATCH 13/20 libxl: libxl_event.c:beforepoll_internal, REQUIRE_FDS
In reply to Ian JacksonIntroduce definition and use of a new function-local macro REQUIRE_FDS to avoid repeatedly spelling out which fds we are interested in.
We are going to introduce a new fd for the SIGCHLD self-pipe.
--- tools/libxl/libxl_event.c | 82 ++++++++++++++++++++++++++++++-------------- 1 files changed, 56 insertions(+), 26 deletions(-)
tools/libxl/libxl_event.c +56 -26
@@ -593,6 +593,45 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,int rc;/* +* We need to look at the fds we want twice: firstly, to count +* them so we can make the rindex array big enough, and secondly +* to actually fill the arrays in. +* +* To ensure correctness and avoid repeating the logic for +* deciding which fds are relevant, we define a macro +* REQUIRE_FDS( BODY ) +* which calls +* do{ +* int req_fd; +* int req_events; +* BODY; +* }while(0) +* for each fd with a nonzero events. This is invoked twice. +* +* The definition of REQUIRE_FDS is simplified with the helper +* macro +* void REQUIRE_FD(int req_fd, int req_events, BODY); +*/ + +#define REQUIRE_FDS (BODY ) do{ \ + \ + LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) \ + REQUIRE_FD(efd->fd, efd->events, BODY); \ + \ + REQUIRE_FD(poller->wakeup_pipe[0], POLLIN, BODY); \ + \ + }while(0) + +#define REQUIRE_FD (req_fd_, req_events_,BODY ) do{ \ + int req_events = (req_events_); \ + int req_fd = (req_fd_); \ + if (req_events) { \ + BODY; \ + } \ + }while(0) + + +/* * In order to be able to efficiently find the libxl__ev_fd * for a struct poll during _afterpoll, we maintain a shadow * data structure in CTX->fd_beforepolled: each slot in
@@ -609,13 +648,13 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,* not to mess with fd_rindex. */ -int maxfd = poller->wakeup_pipe[0 ] +1 ; - LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) { -if (!efd->events) -continue ; -if (efd->fd >= maxfd) - maxfd = efd->fd +1 ; - } +int maxfd =0 ; + +REQUIRE_FDS ({ +if (req_fd >= maxfd) + maxfd = req_fd +1 ; + }); +/* make sure our array is as big as *nfds_io */ if (poller->fd_rindex_allocd < maxfd) {assert (maxfd <INT_MAX /sizeof (int ) /2 );
@@ -630,25 +669,16 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,int used =0 ; -#define REQUIRE_FD (req_fd, req_events, efd) do{ \ - if ((req_events)) { \ - if (used < *nfds_io) { \ - fds[used].fd = (req_fd); \ - fds[used].events = (req_events); \ - fds[used].revents = 0; \ - assert((req_fd) < poller->fd_rindex_allocd); \ - poller->fd_rindex[(req_fd)] = used; \ - } \ - used++; \ - } \ - }while(0) - - LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) -REQUIRE_FD (efd->fd, efd->events, efd); - -REQUIRE_FD (poller->wakeup_pipe[0 ],POLLIN ,0 ); - -#undef REQUIRE_FD +REQUIRE_FDS ({ +if (used < *nfds_io) { + fds[used].fd = req_fd; + fds[used].events = req_events; + fds[used].revents =0 ; +assert (req_fd < poller->fd_rindex_allocd); + poller->fd_rindex[req_fd] = used; + } + used++; + }); rc = used <= *nfds_io ?0 :ERROR_BUFFERFULL ;
Signature · 1 line
1.7.2.5
Re: [PATCH 13/20] libxl: libxl_event.c:beforepoll_internal, REQUIRE_FDS
Quoted 6 lines · Ian Jackson
Introduce definition and use of a new function-local macro
REQUIRE_FDSto avoid repeatedly spelling out which fds we are interested in.We are going to introduce a new fd for the SIGCHLD self-pipe.
Signed-off-by Ian Jackson <[email protected]>
Quoted 111 lines
--- tools/libxl/libxl_event.c | 82 ++++++++++++++++++++++++++++++-------------- 1 files changed, 56 insertions(+), 26 deletions(-)tools/libxl/libxl_event.c +56
-26@@ -593,6 +593,45 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,int rc;/* +* We need to look at the fds we want twice: firstly, to count +* them so we can make the rindex array big enough, and secondly +* to actually fill the arrays in. +* +* To ensure correctness and avoid repeating the logic for +* deciding which fds are relevant, we define a macro +* REQUIRE_FDS( BODY ) +* which calls +* do{ +* int req_fd; +* int req_events; +* BODY; +* }while(0) +* for each fd with a nonzero events. This is invoked twice. +* +* The definition of REQUIRE_FDS is simplified with the helper +* macro +* void REQUIRE_FD(int req_fd, int req_events, BODY); +*/ + +#define REQUIRE_FDS (BODY ) do{ \ + \ + LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) \ + REQUIRE_FD(efd->fd, efd->events, BODY); \ + \ + REQUIRE_FD(poller->wakeup_pipe[0], POLLIN, BODY); \ + \ + }while(0) + +#define REQUIRE_FD (req_fd_, req_events_,BODY ) do{ \ + int req_events = (req_events_); \ + int req_fd = (req_fd_); \ + if (req_events) { \ + BODY; \ + } \ + }while(0) + + +/* * In order to be able to efficiently find the libxl__ev_fd * for a struct poll during _afterpoll, we maintain a shadow * data structure in CTX->fd_beforepolled: each slot in @@ -609,13 +648,13 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,* not to mess with fd_rindex. */ -int maxfd = poller->wakeup_pipe[0 ] +1 ; - LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) { -if (!efd->events) -continue ; -if (efd->fd >= maxfd) - maxfd = efd->fd +1 ; - } +int maxfd =0 ; + +REQUIRE_FDS ({ +if (req_fd >= maxfd) + maxfd = req_fd +1 ; + }); +/* make sure our array is as big as *nfds_io */ if (poller->fd_rindex_allocd < maxfd) {assert (maxfd <INT_MAX /sizeof (int ) /2 );@@ -630,25 +669,16 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller,int used =0 ; -#define REQUIRE_FD (req_fd, req_events, efd) do{ \ - if ((req_events)) { \ - if (used < *nfds_io) { \ - fds[used].fd = (req_fd); \ - fds[used].events = (req_events); \ - fds[used].revents = 0; \ - assert((req_fd) < poller->fd_rindex_allocd); \ - poller->fd_rindex[(req_fd)] = used; \ - } \ - used++; \ - } \ - }while(0) - - LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) -REQUIRE_FD (efd->fd, efd->events, efd); - -REQUIRE_FD (poller->wakeup_pipe[0 ],POLLIN ,0 ); - -#undef REQUIRE_FD +REQUIRE_FDS ({ +if (used < *nfds_io) { + fds[used].fd = req_fd; + fds[used].events = req_events; + fds[used].revents =0 ; +assert (req_fd < poller->fd_rindex_allocd); + poller->fd_rindex[req_fd] = used; + } + used++; + }); rc = used <= *nfds_io ?0 :ERROR_BUFFERFULL ;
PATCH 14/20 libxl: include <ctype.h> and introduce CTYPE helper macro
In reply to Ian Jackson--- tools/libxl/libxl_internal.h | 20 ++++++++++++++++++++ 1 files changed, 20 insertions(+), 0 deletions(-)
tools/libxl/libxl_internal.h +20 -0
@@ -33,6 +33,7 @@#include <stdlib.h> #include <string.h> #include <unistd.h> +#include <ctype.h> #include <sys/mman.h> #include <sys/poll.h>
@@ -1529,6 +1530,25 @@ static inline void libxl__ctx_unlock(libxl_ctx *ctx) { } while(0) +/* +* int CTYPE(ISFOO, char c); +* int CTYPE(toupper, char c); +* int CTYPE(tolower, char c); +* +* This is necessary because passing a simple char to a ctype.h +* is forbidden. ctype.h macros take ints derived from _unsigned_ chars. +* +* If you have a char which might be EOF then you should already have +* it in an int representing an unsigned char, and you can use the +* <ctype.h> macros directly. This generally happens only with values +* from fgetc et al. +* +* For any value known to be a character (eg, anything that came from +* a char[]), use CTYPE. + */ +#define CTYPE (isfoo,c) (isfoo((unsigned char)(c))) + +#endif /*
Signature · 1 line
1.7.2.5
Re: [PATCH 14/20] libxl: include <ctype.h> and introduce CTYPE helper macro
Quoted 1 line · Ian Jackson
Signed-off-by Ian Jackson <[email protected]>
Shouldn't there be a handful of cleanups off the back of this?
Huh, grep suggests onlytools/libxl/xl_cmdimpl.c: if (!isdigit((uint8_t)p[i])) {
which is not useful in the context of libxl_internal.h
I have a feeling the others I was thinking of are in blktap or something
Quoted 42 lines
--- tools/libxl/libxl_internal.h | 20 ++++++++++++++++++++ 1 files changed, 20 insertions(+), 0 deletions(-)tools/libxl/libxl_internal.h +20
-0@@ -33,6 +33,7 @@#include <stdlib.h> #include <string.h> #include <unistd.h> +#include <ctype.h> #include <sys/mman.h> #include <sys/poll.h> @@ -1529,6 +1530,25 @@ static inline void libxl__ctx_unlock(libxl_ctx *ctx) { } while(0) +/* +* int CTYPE(ISFOO, char c); +* int CTYPE(toupper, char c); +* int CTYPE(tolower, char c); +* +* This is necessary because passing a simple char to a ctype.h +* is forbidden. ctype.h macros take ints derived from _unsigned_ chars. +* +* If you have a char which might be EOF then you should already have +* it in an int representing an unsigned char, and you can use the +* <ctype.h> macros directly. This generally happens only with values +* from fgetc et al. +* +* For any value known to be a character (eg, anything that came from +* a char[]), use CTYPE. + */ +#define CTYPE (isfoo,c) (isfoo((unsigned char)(c))) + +#endif /*
Re: [PATCH 14/20] libxl: include <ctype.h> and introduce CTYPE helper macro
Ian Campbell writes ("Re: [Xen-devel] [PATCH 14/20] libxl: include <ctype.h> and introduce CTYPE helper macro"):
Quoted 3 lines
Huh, grep suggests only
tools/libxl/xl_cmdimpl.c: if (!isdigit((uint8_t)p[i])) {
which is not useful in the context oflibxl_internal.h
Right. And we don't really want to export some kind of LIBXL__CTYPE; it's supposed to be convenient, not longwinded.
Quoted 1 line
I have a feeling the others I was thinking of are in blktap or something
Very likely.
Thanks,
Ian.
PATCH 15/20 libxl: include <_libxl_paths.h> in libxl_internal.h
In reply to Ian JacksonIe, we permit general code in libxl direct access to the manifest constants such as XEN_RUN_DIR. This simplifies their use in (eg) format strings.
This might be controversial because it will make it difficult to make any of these runtime-configurable later without changing lots of use sites. But I don't think it's likely we'll want to do that.
For the moment, leave existing call sites of all the functions in libxl_paths.c unchanged. The simplified use arrangements can be used in new code and when we update call sites for other reasons.
--- tools/libxl/libxl_internal.h | 1 + tools/libxl/libxl_paths.c | 1 - 2 files changed, 1 insertions(+), 1 deletions(-)
tools/libxl/libxl_internal.h +1 -0
@@ -51,6 +51,7 @@#include <xen/io/xenbus.h> #include "libxl.h" +#include "_libxl_paths.h" #if __GNUC__ >3 || (__GNUC__ ==3 && __GNUC_MINOR__ >=1 )#define _hidden __attribute__((visibility("hidden")))
tools/libxl/libxl_paths.c +0 -1
@@ -14,7 +14,6 @@#include "libxl_osdeps.h" /* must come before any other headers */ #include "libxl_internal.h" -#include "_libxl_paths.h" const char *libxl_sbindir_path (void ) {
Signature · 1 line
1.7.2.5
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
Quoted 7 lines · Ian Jackson
Ie, we permit general code in libxl direct access to the manifest constants such as
XEN_RUN_DIR. This simplifies their use in (eg) format strings.This might be controversial because it will make it difficult to make any of these runtime-configurable later without changing lots of use sites. But I don't think it's likely we'll want to do that.
I don't have any particular feeling one way or the other about this
Quoted 36 lines
For the moment, leave existing call sites of all the functions in
libxl_paths.cunchanged. The simplified use arrangements can be used in new code and when we update call sites for other reasons.Signed-off-by Ian Jackson <[email protected]>--- tools/libxl/libxl_internal.h | 1 + tools/libxl/libxl_paths.c | 1 - 2 files changed, 1 insertions(+), 1 deletions(-)tools/libxl/libxl_internal.h +1
-0@@ -51,6 +51,7 @@#include <xen/io/xenbus.h> #include "libxl.h" +#include "_libxl_paths.h" #if __GNUC__ >3 || (__GNUC__ ==3 && __GNUC_MINOR__ >=1 )#define _hidden __attribute__((visibility("hidden")))tools/libxl/libxl_paths.c +0
-1@@ -14,7 +14,6 @@#include "libxl_osdeps.h" /* must come before any other headers */ #include "libxl_internal.h" -#include "_libxl_paths.h" const char *libxl_sbindir_path (void ) {
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
2012/3/20 Ian Campbell <[email protected]>:
Quoted 5 lines · Ian Jackson
Quoted 4 lines
Ie, we permit general code in libxl direct access to the manifest constants such as
XEN_RUN_DIR. This simplifies their use in (eg) format strings.
Quoted 7 lines
Quoted 3 lines
This might be controversial because it will make it difficult to make any of these runtime-configurable later without changing lots of use sites. But I don't think it's likely we'll want to do that.
I don't have any particular feeling one way or the other about this
Acked-by Ian Campbell <[email protected]>
_libxl_paths.h should be generated before trying to use libxl_internal.h, if not the build fails.
8<-------------------------------------------------------------
libxl: add _libxl_paths.h as a prerequisite to libxl_internal.h
--- tools/libxl/Makefile | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
tools/libxl/Makefile +1 -1
@@ -106,7 +106,7 @@ libxl_paths.c: _libxl_paths.h libxl.h: _libxl_types.h libxl_json.h: _libxl_types_json.h -libxl_internal.h: _libxl_types_internal.h +libxl_internal.h: _libxl_types_internal.h _libxl_paths.h libxl_internal_json.h: _libxl_types_internal_json.h $(LIBXL_OBJS) $(LIBXLU_OBJS) $(XL_OBJS): libxl.h
Signature · 6 lines
1.7.2.5 _______________________________________________ Xen-devel mailing list [email protected] http://lists.xen.org/xen-devel
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
2012/3/20 Roger Pau Monné <[email protected]>:
Quoted 10 lines
2012/3/20 Ian Campbell <[email protected]>:
Quoted 9 lines · Ian Jackson
Quoted 7 lines
Ie, we permit general code in libxl direct access to the manifest constants such as
XEN_RUN_DIR. This simplifies their use in (eg) format strings.This might be controversial because it will make it difficult to make any of these runtime-configurable later without changing lots of use sites. But I don't think it's likely we'll want to do that.
Quoted 6 lines
Quoted 3 lines
I don't have any particular feeling one way or the other about this
Acked-by Ian Campbell <[email protected]>
_libxl_paths.hshould be generated before trying to uselibxl_internal.h, if not the build fails.
This also removes the libxl_paths.c dependency, which is no longer necessary:
8<-------------------------------------------------------------
libxl: add _libxl_paths.h as a prerequisite to libxl_internal.h
Also remove the libxl_paths.c dependency, which is no longer necessary.
--- tools/libxl/Makefile | 4 +--- 1 files changed, 1 insertions(+), 3 deletions(-)
tools/libxl/Makefile +0 -0
@@ -102,11 +102,9 @@ _libxl_list.h:
$(XEN_INCLUDE)/xen-external/bsd-sys-queue-h-seddery $(XEN_INCLUDE
perl $^ --prefix=libxl >[email protected]
$(call move-if-changed,[email protected],$@)
-libxl_paths.c: _libxl_paths.h
-
libxl.h: _libxl_types.h
libxl_json.h: _libxl_types_json.h-libxl_internal.h: _libxl_types_internal.h +libxl_internal.h: _libxl_types_internal.h _libxl_paths.h
libxl_internal_json.h: _libxl_types_internal_json.h
$(LIBXL_OBJS) $(LIBXLU_OBJS) $(XL_OBJS): libxl.h
Signature · 6 lines
1.7.2.5 _______________________________________________ Xen-devel mailing list [email protected] http://lists.xen.org/xen-devel
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
In reply to Roger Pau MonnéRoger Pau Monné writes ("Re: [Xen-devel] [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h"):
Quoted 2 lines
_libxl_paths.hshould be generated before trying to uselibxl_internal.h, if not the build fails.
...
Quoted 1 line
libxl: add
_libxl_paths.has a prerequisite tolibxl_internal.h
Thanks. This patch seems like it should be folded into mine ?
Ian.
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
2012/3/21 Ian Jackson <[email protected]>:
Quoted 7 lines
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 15/20] libxl: include <
_libxl_paths.h> inlibxl_internal.h"):Quoted 2 lines
_libxl_paths.hshould be generated before trying to uselibxl_internal.h, if not the build fails....
Quoted 1 line
libxl: add
_libxl_paths.has a prerequisite tolibxl_internal.hThanks. This patch seems like it should be folded into mine ?
Sure!
Quoted 1 line
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 15/20] libxl: include <_libxl_paths.h> in libxl_internal.h"):
Quoted 10 lines
2012/3/21 Ian Jackson <[email protected]>:
Quoted 7 lines
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 15/20] libxl: include <
_libxl_paths.h> inlibxl_internal.h"):Quoted 2 lines
_libxl_paths.hshould be generated before trying to uselibxl_internal.h, if not the build fails....
Quoted 1 line
libxl: add
_libxl_paths.has a prerequisite tolibxl_internal.hThanks. This patch seems like it should be folded into mine ?
Sure!
I've done this, with the 2nd version.
Thanks,
Ian.
PATCH 16/20 libxl: event API: new facilities for waiting for subprocesses
In reply to Ian JacksonThe current arrangements in libxl for spawning subprocesses have two key problems: (i) they make unwarranted (and largely undocumented) assumptions about the caller's use of subprocesses, (ii) they aren't integrated into the event system and can't be made asynchronous etc.
So replace them with a new set of facilities.
Primarily, from the point of view of code inside libxl, this is libxl__ev_child_fork which is both (a) a version of fork() and (b) an event source which generates a callback when the child dies.
Quoted 1 line
From the point of view of the application, we fully document our use
of SIGCHLD. The application can tell us whether it wants to own SIGCHLD or not; if it does, it has to tell us about deaths of our children.
Currently there are no callers in libxl which use these facilities. All code in libxl which forks needs to be converted and libxl_fork needse to be be abolished.
--- tools/libxl/libxl.c | 17 +++- tools/libxl/libxl_event.c | 52 +++++++-- tools/libxl/libxl_event.h | 142 ++++++++++++++++++++++++- tools/libxl/libxl_fork.c | 243 ++++++++++++++++++++++++++++++++++++++++++ tools/libxl/libxl_internal.h | 61 ++++++++++- 5 files changed, 495 insertions(+), 20 deletions(-)
tools/libxl/libxl.c +16 -1
@@ -39,7 +39,7 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,memset (ctx,0 ,sizeof (libxl_ctx)); ctx->lg = lg; -/* First initialise pointers (cannot fail) */ +/* First initialise pointers etc. (cannot fail) */ LIBXL_TAILQ_INIT (&ctx->occurred);
@@ -58,6 +58,11 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,LIBXL_TAILQ_INIT (&ctx->death_list);libxl__ev_xswatch_init (&ctx->death_watch); + ctx->childproc_hooks = &libxl__childproc_default_hooks; + ctx->childproc_user =0 ; + + ctx->sigchld_selfpipe[0 ] =-1 ; +/* The mutex is special because we can't idempotently destroy it */ if (libxl__init_recursive_mutex (ctx, &ctx->lock) <0 ) {
@@ -160,6 +165,16 @@ int libxl_ctx_free(libxl_ctx *ctx)discard_events (&ctx->occurred); +/* If we have outstanding children, then the application inherits +* them; we wish the application good luck with understanding +* this if and when it reaps them. */ +libxl__sigchld_removehandler (ctx); + +if (ctx->sigchld_selfpipe[0 ] >=0 ) { +close (ctx->sigchld_selfpipe[0 ]); +close (ctx->sigchld_selfpipe[1 ]); + } +pthread_mutex_destroy (&ctx->lock);GC_FREE ;
tools/libxl/libxl_event.c +41 -11
84 lines not on this page · raw message
tools/libxl/libxl_event.h +137 -5
160 lines not on this page · raw message
tools/libxl/libxl_fork.c +243 -0
267 lines not on this page · raw message
tools/libxl/libxl_internal.h +58 -3
92 lines not on this page · raw message
Signature · 1 line
1.7.2.5
Re: [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses
Quoted 56 lines · Ian Jackson
The current arrangements in libxl for spawning subprocesses have two key problems: (i) they make unwarranted (and largely undocumented) assumptions about the caller's use of subprocesses, (ii) they aren't integrated into the event system and can't be made asynchronous etc.
So replace them with a new set of facilities.
Primarily, from the point of view of code inside libxl, this is
libxl__ev_child_forkwhich is both (a) a version offork()and (b) an event source which generates a callback when the child dies.From the point of view of the application, we fully document our use of SIGCHLD. The application can tell us whether it wants to own SIGCHLD or not; if it does, it has to tell us about deaths of our children.
Currently there are no callers in libxl which use these facilities. All code in libxl which forks needs to be converted and
libxl_forkneedse to be be abolished.Signed-off-by Ian Jackson <[email protected]>Cc Roger Pau Monne <[email protected]>--- tools/libxl/libxl.c | 17 +++- tools/libxl/libxl_event.c | 52 +++++++-- tools/libxl/libxl_event.h | 142 ++++++++++++++++++++++++- tools/libxl/libxl_fork.c | 243 ++++++++++++++++++++++++++++++++++++++++++ tools/libxl/libxl_internal.h | 61 ++++++++++- 5 files changed, 495 insertions(+), 20 deletions(-)tools/libxl/libxl.c +6
-1@@ -39,7 +39,7 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,memset (ctx,0 ,sizeof (libxl_ctx)); ctx->lg = lg; -/* First initialise pointers (cannot fail) */ +/* First initialise pointers etc. (cannot fail) */ LIBXL_TAILQ_INIT (&ctx->occurred);@@ -58,6 +58,11 @@ int libxl_ctx_alloc(libxl_ctx **pctx, int version,LIBXL_TAILQ_INIT (&ctx->death_list);libxl__ev_xswatch_init (&ctx->death_watch); + ctx->childproc_hooks = &libxl__childproc_default_hooks; + ctx->childproc_user =0 ; + + ctx->sigchld_selfpipe[0 ] =-1 ; +/* The mutex is special because we can't idempotently destroy it */ if (libxl__init_recursive_mutex (ctx, &ctx->lock) <0 ) {
tools/libxl/libxl.c int libxl_ctx_free(libxl_ctx *ctx) · line 170
Quoted 6 lines
tools/libxl/libxl.c +3
-0@@ -160,6 +165,16 @@ int libxl_ctx_free(libxl_ctx *ctx)discard_events (&ctx->occurred); +/* If we have outstanding children, then the application inherits +* them; we wish the application good luck with understanding +* this if and when it reaps them. */
:-)
Quoted 26 lines
tools/libxl/libxl.c +7
-0+libxl__sigchld_removehandler (ctx); + +if (ctx->sigchld_selfpipe[0 ] >=0 ) { +close (ctx->sigchld_selfpipe[0 ]); +close (ctx->sigchld_selfpipe[1 ]); + } +pthread_mutex_destroy (&ctx->lock);GC_FREE ;tools/libxl/libxl_event.c +4
-0@@ -620,6 +620,10 @@ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller, \REQUIRE_FD (poller->wakeup_pipe[0 ],POLLIN ,BODY ); \ \ +int selfpipe =libxl__fork_selfpipe_active (CTX ); \ +if (selfpipe >=0 ) \ +REQUIRE_FD (selfpipe,POLLIN ,BODY ); \ + \ }while(0)#define REQUIRE_FD (req_fd_, req_events_,BODY ) do{ \
tools/libxl/libxl_event.c static void afterpoll_internal(libxl__egc *egc, libxl__poller *poller, · line 756
Quoted 4 lines
tools/libxl/libxl_event.c +1
-0@@ -749,10 +753,11 @@ static void afterpoll_internal(libxl__egc *egc, libxl__poller *poller, int nfds, const struct pollfd *fds, struct timeval now) { +/* May make callbacks into the appliction for child processes.
Typo: application
Quoted 54 lines
tools/libxl/libxl_event.c +21
-11+* ctx must be locked exactly once */ EGC_GC ;libxl__ev_fd *efd; - LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) {if (!efd->events)continue ;@@ -763,11 +768,16 @@ static void afterpoll_internal(libxl__egc *egc, libxl__poller *poller, }if (afterpoll_check_fd (poller,fds,nfds, poller->wakeup_pipe[0 ],POLLIN )) { -char buf[256 ]; -int r =read (poller->wakeup_pipe[0 ], buf,sizeof (buf)); -if (r <0 ) -if (errno !=EINTR && errno !=EWOULDBLOCK ) -LIBXL__EVENT_DISASTER (egc,"read wakeup" , errno,0 ); +int e =libxl__self_pipe_eatall (poller->wakeup_pipe[0 ]); +if (e)LIBXL__EVENT_DISASTER (egc,"read wakeup" , e,0 ); + } + +int selfpipe =libxl__fork_selfpipe_active (CTX ); +if (selfpipe >=0 && +afterpoll_check_fd (poller,fds,nfds, selfpipe,POLLIN )) { +int e =libxl__self_pipe_eatall (selfpipe); +if (e)LIBXL__EVENT_DISASTER (egc,"read sigchld pipe" , e,0 ); +libxl__fork_selfpipe_woken (egc); }for (;;) {@@ -1063,16 +1073,36 @@ void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p)void libxl__poller_wakeup (libxl__egc *egc,libxl__poller *p) { +int e =libxl__self_pipe_wakeup (p->wakeup_pipe[1 ]); +if (e)LIBXL__EVENT_DISASTER (egc,"cannot poke watch pipe" , e,0 ); +} + +int libxl__self_pipe_wakeup (int fd) +{static const char buf[1 ] ="" ;for (;;) { -int r =write (p->wakeup_pipe[1 ], buf,1 ); -if (r==1 )return ; +int r =write (fd, buf,1 ); +if (r==1 )return 0 ;assert (r==-1 );if (errno ==EINTR )continue ; -if (errno ==EWOULDBLOCK )return ; -LIBXL__EVENT_DISASTER (egc,"cannot poke watch pipe" , errno,0 ); -return ; +if (errno ==EWOULDBLOCK )return 0 ; +assert (errno);
tools/libxl/libxl_event.c void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p) · line 1100
Quoted 10 lines
tools/libxl/libxl_event.c +10
-0+return errno; + } +} + +int libxl__self_pipe_eatall (int fd) +{ +char buf[256 ]; +for (;;) { +int r =read (fd, buf,sizeof (buf)); +if (r >=0 )return 0 ;
Is there some 256 byte limit on the number of bytes pending in the pipe somewhere? Wouldn't r==256 require us to (potentially) go round the loop again?
Quoted 25 lines
tools/libxl/libxl_event.c +5
-0+assert (r ==-1 ); +if (errno ==EINTR )continue ; +if (errno ==EWOULDBLOCK )return 0 ; +assert (errno); +return errno; } }tools/libxl/libxl_event.h +0
-5@@ -163,11 +163,6 @@ void libxl_event_register_callbacks(libxl_ctx *ctx,* After libxl_ctx_free, all corresponding evgen handles become * invalid and must no longer be passed to evdisable. * -* Events enabled with evenable prior to a fork and libxl_ctx_postfork -* are no longer generated after the fork/postfork; however the evgen -* structures are still valid and must be passed to evdisable if the -* memory they use should not be leaked. -* * Applications should ensure that they eventually retrieve every * event using libxl_event_check or libxl_event_wait, since events * which occur but are not retreived by the application will be queued
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 375
Quoted 9 lines
tools/libxl/libxl_event.h +6
-0@@ -372,6 +367,142 @@ void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl,void libxl_osevent_occurred_timeout (libxl_ctx *ctx,void *for_libxl); +/*======================================================================*/ + +/* +* Subprocess handling. +* +* Unfortunately the POSIX interface makes this very awkward.
To say the least...
Quoted 52 lines
tools/libxl/libxl_event.h +51
-0+* +* There are two possible arrangements for collecting statuses from +* wait/waitpid. +* +* For naive programs: +* +* libxl will keep a SIGCHLD handler installed whenever it has an +* active (unreaped) child. It will reap all children with +* wait(); any children it does not recognise will be passed to +* the application via an optional callback (and will result in +* logged warnings if no callback is provided or the callback +* denies responsibility for the child). +* +* libxl may have children whenever: +* +* - libxl is performing an operation which can be made +* asynchronous; ie one taking a libxl_asyncop_how, even +* if NULL is passed indicating that the operation is +* synchronous; or +* +* - events of any kind are being generated, as requested +* by libxl_evenable_.... +* +* A multithreaded application which is naive in this sense may +* block SIGCHLD on some of its threads, but there must be at +* least one thread that has SIGCHLD unblocked. libxl will not +* modify the blocking flag for SIGCHLD (except that it may create +* internal service threads with all signals blocked). +* +* A naive program must only have at any one time only +* one libxl context which might have children. +* For programs which run their own children alongside libxl's: +* +* The application must install a SIGCHLD handler and reap (at +* least) all of libxl's children and pass their exit status +* to libxl by calling libxl_childproc_exited. +* +* An application which does this must call +* libxl_childproc_setmode. +* +* An application which fails to call setmode, or which passes 0 for +* hooks, while it uses any libxl operation which might +* create or use child processes (see above): +* - Must not have any child processes running. +* - Must not install a SIGCHLD handler. +* - Must not reap any children. +*/ + + +typedef enum { + /* libxl owns SIGCHLD whenever it has a child. */
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 437
Quoted 10 lines
tools/libxl/libxl_event.h +10
-0+ libxl_sigchld_owner_libxl, + +/* Application promises to call libxl_childproc_exited but NOT +* from within a signal handler. libxl will not itself arrange to +* (un)block or catch SIGCHLD. */ + libxl_sigchld_owner_mainloop, + +/* libxl owns SIGCHLD all the time, and the application is +* relying on libxl's event loop for reaping its own children. */ + libxl_sigchld_owner_libxl_always,
The comment above doesn't seem to cover this third case?
Quoted 10 lines
tools/libxl/libxl_event.h +10
-0+} libxl_sigchld_owner; + +typedef struct { + libxl_sigchld_owner chldowner; + + /* All of these are optional: */ + + /* Called by libxl instead of fork. Should behave exactly like + * fork, including setting errno etc. May NOT reenter into libxl. + * Application may use this to discover pids of libxl's children,
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 457
Quoted 10 lines
tools/libxl/libxl_event.h +10
-0+* for example. +*/ +pid_t (*fork_replacement)(void *user); + +/* With libxl_sigchld_owner_libxl, called by libxl when it has +* reaped a pid. (Not permitted with _owner_mainloop.) +* +* Should return 0 if the child was recognised by the application +* (or if the application does not keep those kind of records), +* ERROR_NOT_READY if the application knows that the child is not
ERROR_NOT_READY seems like an odd name. ERROR_UNKNOWN_CHILD perhaps?
Quoted 52 lines
tools/libxl/libxl_event.h +48
-0+* the application's; if it returns another error code it is a +* disaster as described for libxl_event_register_callbacks. +* (libxl will report unexpected children to its error log.) +* +* If not supplied, the application is assumed not to start +* any children of its own. +* +* This function is NOT called from within the signal handler. +* Rather it will be called from inside a libxl's event handling +* code and thus only when libxl is running, for example from +* within libxl_event_wait. (libxl uses the self-pipe trick +* to implement this.) +* +* childproc_exited_callback may call back into libxl, but it +* is best to avoid making long-running libxl calls as that might +* stall the calling event loop while the nested operation +* completes. +*/ +int (*reaped_callback)(pid_t ,int status,void *user); +} libxl_childproc_hooks; + +/* hooks may be 0 in which is equivalent to &{ libxl_sigchld_owner_libxl, 0, 0 } +* +* May not be called when libxl might have any child processes, or the +* behaviour is undefined. So it is best to call this at +* initialisation. +*/ +void libxl_childproc_setmode (libxl_ctx *ctx,const libxl_childproc_hooks *hooks, +void *user); + +/* +* This function is for an application which owns SIGCHLD and which +* therefore reaps all of the process's children. +* +* May be called only by an application which has called setmode with +* chldowner == libxl_sigchld_owner_mainloop. If pid was a process started +* by this instance of libxl, returns 0 after doing whatever +* processing is appropriate. Otherwise silently returns +* ERROR_NOT_READY. No other error returns are possible. +* +* May NOT be called from within a signal handler which might +* interrupt any libxl operation. The application will almost +* certainly need to use the self-pipe trick (or a working pselect or +* ppoll) to implement this. +*/ +int libxl_childproc_reaped (libxl_ctx *ctx,pid_t ,int status); + +/* * An application which initialises a libxl_ctx in a parent process * and then forks a child which does not quickly exec, must
tools/libxl/libxl_event.h void libxl_osevent_occurred_timeout(libxl_ctx *ctx, void *for_libxl); · line 517
Quoted 4 lines
tools/libxl/libxl_event.h +1
-0@@ -383,6 +514,7 @@ void libxl_osevent_occurred_timeout(libxl_ctx *ctx, void *for_libxl);void libxl_postfork_child_noexec (libxl_ctx *ctx); +
The blank lines appear to be breeding ;-)
Quoted 19 lines
tools/libxl/libxl_event.h +0
-0#endif /* tools/libxl/libxl_fork.c +6
-0@@ -46,6 +46,12 @@ static int atfork_registered; static LIBXL_LIST_HEAD(, libxl__carefd) carefds =LIBXL_LIST_HEAD_INITIALIZER (carefds); +/* non-null iff installed, protected by no_forking */ +static libxl_ctx *sigchld_owner; +static struct sigaction sigchld_saved_action; + +static void sigchld_removehandler_core (void ); +static void atfork_lock (void ) {
[...]
Quoted 12 lines
tools/libxl/libxl_fork.c +4
-0@@ -117,6 +124,10 @@ void libxl_postfork_child_noexec(libxl_ctx *ctx)free (cf); }LIBXL_LIST_INIT (&carefds); + +if (sigchld_owner) +sigchld_removehandler_core (); +atfork_unlock (); }@@ -138,6 +149,238 @@ int libxl__carefd_fd(const libxl__carefd *cf)
[...]
Quoted 8 lines
tools/libxl/libxl_fork.c +8
-0+ +int libxl__sigchld_installhandler (libxl_ctx *ctx)/* non-reentrant */ +{ +int r, rc; + +if (ctx->sigchld_selfpipe[0 ] <0 ) { + r =pipe (ctx->sigchld_selfpipe); +if (r) {
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 197
Quoted 10 lines
tools/libxl/libxl_fork.c +10
-0+ ctx->sigchld_selfpipe[0 ] =-1 ; +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_ERROR , +"failed to create sigchld pipe" ); + rc =ERROR_FAIL ; + goto out; + } + } + +atfork_lock (); +if (sigchld_owner != ctx) {
A non-NULL sigchld_owner which is != ctx is a pretty serious error here, isn't it?
Quoted 23 lines
tools/libxl/libxl_fork.c +23
-0+struct sigaction ours; + +assert (!sigchld_owner); + sigchld_owner = ctx; + +memset (&ours,0 ,sizeof (ours)); + ours.sa_handler = sigchld_handler; +sigemptyset (&ours.sa_mask); + ours.sa_flags =SA_NOCLDSTOP |SA_RESTART ; + r =sigaction (SIGCHLD , &ours, &sigchld_saved_action); +assert (!r); + +assert (((void )"application must negotiate with libxl about SIGCHLD" , + !(sigchld_saved_action.sa_flags &SA_SIGINFO ) && + (sigchld_saved_action.sa_handler ==SIG_DFL || + sigchld_saved_action.sa_handler ==SIG_IGN ))); + } +atfork_unlock (); + + rc =0 ; + out: +return rc; +}
[...]
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 279
Quoted 2 lines
tools/libxl/libxl_fork.c +2
-0+void libxl__fork_selfpipe_woken (libxl__egc *egc) { +/* May make callbacks into the appliction for child processes.
application
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 283
Quoted 4 lines
tools/libxl/libxl_fork.c +4
-0+* ctx must be locked EXACTLY ONCE */ +EGC_GC ; + +while (chldmode_ours (CTX )/* in case the app changes the mode */ ) {
setmode takes the CTX lock and ctx must be locked here too, so can this happen? Ah, we unlock inside the loop, ok then.
Changing the mode in the callback seems, er, ambitious given you can't call it when libxl has any children and we recommend you do it once at start of day. Can we not just outlaw it?
Quoted 41 lines
tools/libxl/libxl_fork.c +41
-0+int status; +pid_t pid =waitpid (-1 , &status,WNOHANG ); + +if (pid ==0 )return ; + +if (pid ==-1 ) { +if (errno ==ECHILD )return ; +if (errno ==EINTR )continue ; +LIBXL__EVENT_DISASTER (egc,"waitpid() failed" , errno,0 ); +return ; + } + +int rc =childproc_reaped (egc, pid, status); + +if (rc) { +if (CTX ->childproc_hooks->reaped_callback) { +CTX_UNLOCK ; +CTX ->childproc_hooks->reaped_callback + (pid, status,CTX ->childproc_user); +CTX_LOCK ; + }else { +libxl_report_child_exitstatus (CTX ,XTL_WARN , +"unknown child" , (long )pid, status); + } + } + } +} + +pid_t libxl__ev_child_fork (libxl__gc *gc,libxl__ev_child *ch, +libxl__ev_child_callback *death) +{ +CTX_LOCK ; +int rc; + +if (chldmode_ours (CTX )) { + rc =libxl__sigchld_installhandler (CTX ); +if (rc) goto out; + } + +pid_t pid = +CTX ->childproc_hooks->fork_replacement
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 334
Quoted 10 lines
tools/libxl/libxl_fork.c +10
-0+ ?CTX ->childproc_hooks->fork_replacement (CTX ->childproc_user) + :fork (); +if (pid ==-1 ) { +LOGE (ERROR ,"fork failed" ); + rc =ERROR_FAIL ; + goto out; + } + +if (!pid) { +/* woohoo! */
\o/
Quoted 14 lines
tools/libxl/libxl_fork.c +14
-0+return 0 ;/* Yes, CTX is left locked in the child. */ + } + + ch->pid = pid; + ch->callback = death; +LIBXL_LIST_INSERT_HEAD (&CTX ->children, ch, entry); + rc = pid; + + out: +perhaps_removehandler (CTX ); +CTX_UNLOCK ; +return rc; +} +
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 358
Quoted 10 lines
tools/libxl/libxl_fork.c +10
-0+void libxl_childproc_setmode (libxl_ctx *ctx,const libxl_childproc_hooks *hooks, +void *user) +{ +GC_INIT (ctx); +CTX_LOCK ; + +assert (LIBXL_LIST_EMPTY (&CTX ->children)); + +if (!hooks) + hooks = &libxl__childproc_default_hooks;
user = NULL;
(probably doesn't matter much)
Quoted 53 lines
tools/libxl/libxl_fork.c +25
-0+ + ctx->childproc_hooks = hooks; + ctx->childproc_user = user; + +switch (ctx->childproc_hooks->chldowner) { +case libxl_sigchld_owner_mainloop: +case libxl_sigchld_owner_libxl: +libxl__sigchld_removehandler (ctx); +break ; +case libxl_sigchld_owner_libxl_always: +libxl__sigchld_installhandler (ctx); +break ; +default : +abort (); + } + +CTX_UNLOCK ; +GC_FREE ; +} + +const libxl_childproc_hooks libxl__childproc_default_hooks = { + libxl_sigchld_owner_libxl,0 ,0 +}; + +/* * Local variables: * mode: C * c-basic-offset: 4 tools/libxl/libxl_internal.h +13
-0@@ -184,6 +184,19 @@ typedef struct libxl__ev_watch_slot {libxl__ev_xswatch *libxl__watch_slot_contents (libxl__gc *gc,int slotnum); +typedef struct libxl__ev_child libxl__ev_child ; +typedef void libxl__ev_child_callback (libxl__egc *egc,libxl__ev_child *, +pid_t pid,int status); +struct libxl__ev_child { +/* caller should include this in their own struct */ +/* read-only for caller: */ +pid_t pid;/* -1 means unused ("unregistered", ie Idle) */ +libxl__ev_child_callback *callback; +/* remainder is private for libxl__ev_... */ +LIBXL_LIST_ENTRY (struct libxl__ev_child ) entry; +}; + +/* * evgen structures, which are the state we use for generating * events for the caller.
tools/libxl/libxl_internal.h struct libxl__ctx { · line 279
Quoted 4 lines
tools/libxl/libxl_internal.h +1
-0@@ -263,6 +276,8 @@ struct libxl__ctx {const libxl_event_hooks *event_hooks;void *event_hooks_user; +LIBXL_LIST_ENTRY (struct libxl__ctx );
Shouldn't there be a field name here? Or is it deliberately anon? (what if we get a second list)
Quoted 28 lines
tools/libxl/libxl_internal.h +10
-3+pthread_mutex_t lock;/* protects data structures hanging off the ctx */ /* Always use libxl__ctx_lock and _unlock (or the convenience * macors CTX_LOCK and CTX_UNLOCK) to manipulate this. @@ -303,10 +318,14 @@ struct libxl__ctx { LIBXL_LIST_HEAD(, libxl_evgen_disk_eject) disk_eject_evgens; -/* for callers who reap children willy-nilly; caller must only -* set this after libxl_init and before any other call - or -* may leave them untouched */ +const libxl_childproc_hooks *childproc_hooks; +void *childproc_user; +int sigchld_selfpipe[2 ];/* [0]==-1 means handler not installed */ + LIBXL_LIST_HEAD(, libxl__ev_child) children; + +/* This is obsolete and must be removed: */ int (*waitpid_instead)(pid_t pid,int *status,int flags); +libxl_version_info version_info; };@@ -554,6 +573,33 @@ static inline int libxl__ev_xswatch_isregistered(const libxl__ev_xswatch *xw)/* +* For making subprocesses. This is the only permitted mechanism for +* code in libxl to do so.
tools/libxl/libxl_internal.h static inline int libxl__ev_xswatch_isregistered(const libxl__ev_xswatch *xw) · line 587
Quoted 10 lines
tools/libxl/libxl_internal.h +10
-0+* +* In the parent, returns the pid, filling in childw_out. +* In the child, returns 0. +* If it fails, returns a libxl error (all of which are -ve). +* +* The child should go on to exec (or exit) soon, and should not make +* any further libxl event calls in the meantime. +* +* The parent may signal the child but it must not reap it. That will +* be done by the event machinery. Either death or cldstop may be
"cldstop" did you rename that childw_out and miss this comment or is it something else?
Quoted 42 lines
tools/libxl/libxl_internal.h +24
-1+* NULL in which case that kind of event is ignored. +* +* It is not possible to "deregister" the child death event source. +* It will generate exactly one event callback; until then the childw +* is Active and may not be reused. +*/ +_hidden pid_t libxl__ev_child_fork(libxl__gc *gc, libxl__ev_child *childw_out, +libxl__ev_child_callback *death); +static inline void libxl__ev_child_init (libxl__ev_child *childw_out) + { childw_out->pid =-1 ; } +static inline int libxl__ev_child_inuse (libxl__ev_child *childw_out) + {return childw_out->pid >=0 ; } + + +/* * Other event-handling support provided by the libxl event core to * the rest of libxl. */ @@ -607,6 +653,15 @@ void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p);* ctx must be locked. */ void libxl__poller_wakeup (libxl__egc *egc,libxl__poller *p); +/* Internal to fork and child reaping machinery */ +extern const libxl_childproc_hooks libxl__childproc_default_hooks; +int libxl__sigchld_installhandler (libxl_ctx *ctx);/* non-reentrant;logs errs */ +void libxl__sigchld_removehandler (libxl_ctx *ctx);/* non-reentrant */ +int libxl__fork_selfpipe_active (libxl_ctx *ctx);/* returns read fd or -1 */ +void libxl__fork_selfpipe_woken (libxl__egc *egc); +int libxl__self_pipe_wakeup (int fd);/* returns 0 or -1 setting errno */ +int libxl__self_pipe_eatall (int fd);/* returns 0 or -1 setting errno */ +int libxl__atfork_init (libxl_ctx *ctx); --1.7.2.5
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses
Thanks for the thorough review!
Ian Campbell writes ("Re: [Xen-devel] [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses"):
Quoted 4 lines · Ian Jackson
Quoted 1 line
+ /* May make callbacks into the appliction for child processes.
Typo: application
Fixed.
Quoted 10 lines
tools/libxl/libxl_event.c void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p) · line 1100
Quoted 6 lines
tools/libxl/libxl_event.c +6
-0+int libxl__self_pipe_eatall (int fd) +{ +char buf[256 ]; +for (;;) { +int r =read (fd, buf,sizeof (buf)); +if (r >=0 )return 0 ;Is there some 256 byte limit on the number of bytes pending in the pipe somewhere? Wouldn't r==256 require us to (potentially) go round the loop again?
If this loop has to go round again, it means we have had 256 wakeup events of some kind. I don't think this is really an efficiency concern and it makes the code simpler not to have to worry about it.
Quoted 6 lines
Quoted 6 lines
tools/libxl/libxl_event.h +6
-0+typedef enum { + /* libxl owns SIGCHLD whenever it has a child. */ + libxl_sigchld_owner_libxl, + + /* Application promises to call libxl_childproc_exited but NOT + * from within a signal handler. libxl will not itself arrange to
Quoted 8 lines
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 437
Quoted 6 lines
tools/libxl/libxl_event.h +6
-0+* (un)block or catch SIGCHLD. */ + libxl_sigchld_owner_mainloop, + +/* libxl owns SIGCHLD all the time, and the application is +* relying on libxl's event loop for reaping its own children. */ + libxl_sigchld_owner_libxl_always,The comment above doesn't seem to cover this third case?
Good point. I have improved this.
Quoted 8 lines
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 457
Quoted 6 lines
tools/libxl/libxl_event.h +6
-0+/* With libxl_sigchld_owner_libxl, called by libxl when it has +* reaped a pid. (Not permitted with _owner_mainloop.) +* +* Should return 0 if the child was recognised by the application +* (or if the application does not keep those kind of records), +* ERROR_NOT_READY if the application knows that the child is not
ERROR_NOT_READYseems like an odd name.ERROR_UNKNOWN_CHILDperhaps?
I was reusing an existing error code. Do you think it should have its own ?
Quoted 6 lines
Quoted 4 lines
void
libxl_postfork_child_noexec(libxl_ctx *ctx);+
The blank lines appear to be breeding ;-)
OK I think that is one too many :-).
Quoted 12 lines
Quoted 12 lines
tools/libxl/libxl_fork.c +12
-0+int libxl__sigchld_installhandler (libxl_ctx *ctx)/* non-reentrant */ +{ +int r, rc; + +if (ctx->sigchld_selfpipe[0 ] <0 ) { + r =pipe (ctx->sigchld_selfpipe); +if (r) { + ctx->sigchld_selfpipe[0 ] =-1 ; +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_ERROR , +"failed to create sigchld pipe" ); + rc =ERROR_FAIL ; + goto out;
Quoted 8 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 197
Quoted 5 lines
tools/libxl/libxl_fork.c +5
-0+ } + } + +atfork_lock (); +if (sigchld_owner != ctx) {A non-NULL
sigchld_ownerwhich is != ctx is a pretty serious error here, isn't it?
Yes.
Quoted 3 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 200
Quoted 3 lines
tools/libxl/libxl_fork.c +3
-0+struct sigaction ours; + +assert (!sigchld_owner);
Hence this assertion.
Quoted 5 lines
[...]
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 279
Quoted 2 lines
tools/libxl/libxl_fork.c +2
-0+void libxl__fork_selfpipe_woken (libxl__egc *egc) { +/* May make callbacks into the appliction for child processes. application
I'm rather afflicted (afflicated?) with these.
Quoted 11 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 283
Quoted 4 lines
tools/libxl/libxl_fork.c +4
-0+* ctx must be locked EXACTLY ONCE */ +EGC_GC ; + +while (chldmode_ours (CTX )/* in case the app changes the mode */ ) {setmode takes the CTX lock and ctx must be locked here too, so can this happen? Ah, we unlock inside the loop, ok then.
Changing the mode in the callback seems, er, ambitious given you can't call it when libxl has any children and we recommend you do it once at start of day. Can we not just outlaw it?
The callback might well be what makes the application decide it needs to change the mode. It would need an if() anyway since you might respond to the fd readability after the mode has been changed.
Quoted 12 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 358
Quoted 10 lines
tools/libxl/libxl_fork.c +10
-0+void libxl_childproc_setmode (libxl_ctx *ctx,const libxl_childproc_hooks *hooks, +void *user) +{ +GC_INIT (ctx); +CTX_LOCK ; + +assert (LIBXL_LIST_EMPTY (&CTX ->children)); + +if (!hooks) + hooks = &libxl__childproc_default_hooks;user = NULL;
Quoted 1 line
(probably doesn't matter much)
The default "hooks" naturally don't use user; in fact they are both null function pointers.
Quoted 8 lines
tools/libxl/libxl_internal.h struct libxl__ctx { · line 279
Quoted 5 lines
tools/libxl/libxl_internal.h +1
-0@@ -263,6 +276,8 @@ struct libxl__ctx {const libxl_event_hooks *event_hooks;void *event_hooks_user; +LIBXL_LIST_ENTRY (struct libxl__ctx );Shouldn't there be a field name here? Or is it deliberately anon? (what if we get a second list)
This is a leftover hunk. It can't actually be used because the LIBXL_LIST_* macros require an actual member name. I will remove it.
Quoted 19 lines
Quoted 6 lines
tools/libxl/libxl_internal.h +2
-0@@ -554,6 +573,33 @@ static inline int libxl__ev_xswatch_isregistered(const libxl__ev_xswatch *xw)/* +* For making subprocesses. This is the only permitted mechanism for +* code in libxl to do so. tools/libxl/libxl_internal.h static inline int libxl__ev_xswatch_isregistered(const libxl__ev_xswatch *xw) · line 587
Quoted 10 lines
tools/libxl/libxl_internal.h +10
-0+* +* In the parent, returns the pid, filling in childw_out. +* In the child, returns 0. +* If it fails, returns a libxl error (all of which are -ve). +* +* The child should go on to exec (or exit) soon, and should not make +* any further libxl event calls in the meantime. +* +* The parent may signal the child but it must not reap it. That will +* be done by the event machinery. Either death or cldstop may be "cldstop" did you rename that
childw_outand miss this comment or is it something else?
I was going to provide a mechanism analogous to waitpid's WUNTRACED but thought better of it. I have fixed the comment.
Thanks,
Ian.
Re: [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses
Quoted 21 lines · Ian Jackson
Thanks for the thorough review!
Ian Campbell writes ("Re: [Xen-devel] [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses"):
Quoted 4 lines · Ian Jackson
Quoted 1 line
+ /* May make callbacks into the appliction for child processes.
Typo: application
Fixed.
Quoted 10 lines
tools/libxl/libxl_event.c void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p) · line 1100
Quoted 6 lines
tools/libxl/libxl_event.c +6
-0+int libxl__self_pipe_eatall (int fd) +{ +char buf[256 ]; +for (;;) { +int r =read (fd, buf,sizeof (buf)); +if (r >=0 )return 0 ;Is there some 256 byte limit on the number of bytes pending in the pipe somewhere? Wouldn't r==256 require us to (potentially) go round the loop again?
Quoted 4 lines
If this loop has to go round again, it means we have had 256 wakeup events of some kind. I don't think this is really an efficiency concern and it makes the code simpler not to have to worry about it.
My concern is that we would exit the loop _without_ going round again because if r == 256 then also r>= 0 and we return i.e. we don't actually "eatall" the buffer, or does that not matter?
Quoted 11 lines
Quoted 8 lines
tools/libxl/libxl_event.h void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, · line 457
Quoted 6 lines
tools/libxl/libxl_event.h +6
-0+/* With libxl_sigchld_owner_libxl, called by libxl when it has +* reaped a pid. (Not permitted with _owner_mainloop.) +* +* Should return 0 if the child was recognised by the application +* (or if the application does not keep those kind of records), +* ERROR_NOT_READY if the application knows that the child is not
ERROR_NOT_READYseems like an odd name.ERROR_UNKNOWN_CHILDperhaps?I was reusing an existing error code. Do you think it should have its own ?
You once told me we shouldn't be shy about adding error codes for specific things..
Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
tools/libxl/libxl_fork.c +12
-0+int libxl__sigchld_installhandler (libxl_ctx *ctx)/* non-reentrant */ +{ +int r, rc; + +if (ctx->sigchld_selfpipe[0 ] <0 ) { + r =pipe (ctx->sigchld_selfpipe); +if (r) { + ctx->sigchld_selfpipe[0 ] =-1 ; +LIBXL__LOG_ERRNO (ctx,LIBXL__LOG_ERROR , +"failed to create sigchld pipe" ); + rc =ERROR_FAIL ; + goto out;Quoted 8 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 197
Quoted 5 lines
tools/libxl/libxl_fork.c +5
-0+ } + } + +atfork_lock (); +if (sigchld_owner != ctx) {A non-NULL
sigchld_ownerwhich is != ctx is a pretty serious error here, isn't it?
Quoted 7 lines
Yes.
Quoted 3 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 200
Quoted 3 lines
tools/libxl/libxl_fork.c +3
-0+struct sigaction ours; + +assert (!sigchld_owner);Hence this assertion.
Right.
Quoted 8 lines
Quoted 8 lines
tools/libxl/libxl_fork.c int libxl__carefd_fd(const libxl__carefd *cf) · line 283
Quoted 4 lines
tools/libxl/libxl_fork.c +4
-0+* ctx must be locked EXACTLY ONCE */ +EGC_GC ; + +while (chldmode_ours (CTX )/* in case the app changes the mode */ ) {setmode takes the CTX lock and ctx must be locked here too, so can this happen? Ah, we unlock inside the loop, ok then.
Quoted 7 lines
Quoted 3 lines
Changing the mode in the callback seems, er, ambitious given you can't call it when libxl has any children and we recommend you do it once at start of day. Can we not just outlaw it?
The callback might well be what makes the application decide it needs to change the mode. It would need an
if()anyway since you might respond to the fd readability after the mode has been changed.
OK
Ian.
Re: [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses
Ian Campbell writes ("Re: [Xen-devel] [PATCH 16/20] libxl: event API: new facilities for waiting for subprocesses"):
Quoted 9 lines · Ian Jackson
Quoted 4 lines
If this loop has to go round again, it means we have had 256 wakeup events of some kind. I don't think this is really an efficiency concern and it makes the code simpler not to have to worry about it.
My concern is that we would exit the loop _without_ going round again because if r == 256 then also r>= 0 and we return i.e. we don't actually "eatall" the buffer, or does that not matter?
So the fd stays readable and we will go round the event loop to read it again. Evidently this is too confusing, though, so I'll just make the function really eat all.
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
ERROR_NOT_READYseems like an odd name.ERROR_UNKNOWN_CHILDperhaps?I was reusing an existing error code. Do you think it should have its own ?
You once told me we shouldn't be shy about adding error codes for specific things..
OK, I'll add one. Also I notice that I actually ignore the return value from reaped_callback which is not right. So I will fix that too.
Thanks,
Ian.
PATCH 17/20 libxl: Provide libxl_string_list_length
In reply to Ian Jackson--- tools/libxl/libxl.c | 8 ++++++++ tools/libxl/libxl.h | 1 + 2 files changed, 9 insertions(+), 0 deletions(-)
tools/libxl/libxl.c +8 -0
@@ -195,6 +195,14 @@ void libxl_string_list_dispose(libxl_string_list *psl)free (sl); } +int libxl_string_list_length (const libxl_string_list *psl) +{ +if (!psl)return 0 ; +int i =0 ; +while (*psl++) i++; +return i; +} +void libxl_key_value_list_dispose (libxl_key_value_list *pkvl) {int i;
tools/libxl/libxl.h +1 -0
@@ -195,6 +195,7 @@ typedef uint8_t libxl_mac[6];typedef char **libxl_string_list ;void libxl_string_list_dispose (libxl_string_list *sl); +int libxl_string_list_length (const libxl_string_list *sl);typedef char **libxl_key_value_list ;void libxl_key_value_list_dispose (libxl_key_value_list *kvl);
Signature · 1 line
1.7.2.5
Re: [PATCH 17/20] libxl: Provide libxl_string_list_length
Quoted 1 line · Ian Jackson
Signed-off-by Ian Jackson <[email protected]>
Quoted 36 lines
--- tools/libxl/libxl.c | 8 ++++++++ tools/libxl/libxl.h | 1 + 2 files changed, 9 insertions(+), 0 deletions(-)tools/libxl/libxl.c +8
-0@@ -195,6 +195,14 @@ void libxl_string_list_dispose(libxl_string_list *psl)free (sl); } +int libxl_string_list_length (const libxl_string_list *psl) +{ +if (!psl)return 0 ; +int i =0 ; +while (*psl++) i++; +return i; +} +void libxl_key_value_list_dispose (libxl_key_value_list *pkvl) {int i;tools/libxl/libxl.h +1
-0@@ -195,6 +195,7 @@ typedef uint8_t libxl_mac[6];typedef char **libxl_string_list ;void libxl_string_list_dispose (libxl_string_list *sl); +int libxl_string_list_length (const libxl_string_list *sl);typedef char **libxl_key_value_list ;void libxl_key_value_list_dispose (libxl_key_value_list *kvl);
PATCH 18/20 libxl: Introduce libxl__sendmsg_fds and libxl__recvmsg_fds
In reply to Ian JacksonWe will want to reuse the fd-sending code, so break it out into its own function, and provide the corresponding sending function.
--- tools/libxl/libxl_internal.h | 11 ++++ tools/libxl/libxl_qmp.c | 31 ++----------- tools/libxl/libxl_utils.c | 104 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 27 deletions(-)
tools/libxl/libxl_internal.h +11 -0
@@ -1108,6 +1108,17 @@ _hidden void libxl__qmp_cleanup(libxl__gc *gc, uint32_t domid); _hidden int libxl__qmp_initializations(libxl__gc *gc, uint32_t domid,const libxl_domain_config *guest_config); +/* on failure, logs */ +int libxl__sendmsg_fds (libxl__gc *gc,int carrier, +const void *data,size_t datalen, +int nfds,const int fds[],const char *what); + +/* Insists on receiving exactly nfds and datalen. On failure, logs +* and leaves *fds untouched. */ +int libxl__recvmsg_fds (libxl__gc *gc,int carrier, +void *databuf,size_t datalen, +int nfds,int fds[],const char *what); +/* from libxl_json */ #include <yajl/yajl_gen.h>
tools/libxl/libxl_qmp.c +4 -27
@@ -544,38 +544,15 @@ static int qmp_send_fd(libxl__gc *gc, libxl__qmp_handler *qmp,qmp_request_context *context, int fd) { -struct msghdr msg = {0 }; -struct cmsghdr *cmsg; -char control[CMSG_SPACE (sizeof (fd))]; -struct iovec iov; char *buf = NULL; +int rc; buf =qmp_send_prepare (gc, qmp,"getfd" , args, callback, opaque, context); -/* Response data */ - iov.iov_base = buf; - iov.iov_len =strlen (buf); - -/* compose the message */ - msg.msg_iov = &iov; - msg.msg_iovlen =1 ; - msg.msg_control = control; - msg.msg_controllen =sizeof (control); - -/* attach open fd */ - cmsg =CMSG_FIRSTHDR (&msg); - cmsg->cmsg_level =SOL_SOCKET ; - cmsg->cmsg_type =SCM_RIGHTS ; - cmsg->cmsg_len =CMSG_LEN (sizeof (fd)); - *(int *)CMSG_DATA (cmsg) = fd; - - msg.msg_controllen = cmsg->cmsg_len; + rc =libxl__sendmsg_fds (gc, qmp->qmp_fd, buf,strlen (buf),1 , &fd, +"QMP message to QEMU" ); +if (rc)return rc; -if (sendmsg (qmp->qmp_fd, &msg,0 ) <0 ) { -LIBXL__LOG_ERRNO (qmp->ctx,LIBXL__LOG_ERROR , -"Failed to send a QMP message to QEMU." ); -return ERROR_FAIL ; - }if (libxl_write_exactly (qmp->ctx, qmp->qmp_fd,"\r\n" ,2 ,"CRLF" ,"QMP socket" )) {return ERROR_FAIL ;
tools/libxl/libxl_utils.c +104 -0
110 lines not on this page · raw message
Signature · 1 line
1.7.2.5
Re: [PATCH 18/20] libxl: Introduce libxl__sendmsg_fds and libxl__recvmsg_fds
Quoted 4 lines · Ian Jackson
We will want to reuse the fd-sending code, so break it out into its own function, and provide the corresponding sending function.
Signed-off-by Ian Jackson <[email protected]>
Quoted 190 lines
--- tools/libxl/libxl_internal.h | 11 ++++ tools/libxl/libxl_qmp.c | 31 ++----------- tools/libxl/libxl_utils.c | 104 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 27 deletions(-)tools/libxl/libxl_internal.h +11
-0@@ -1108,6 +1108,17 @@ _hidden void libxl__qmp_cleanup(libxl__gc *gc, uint32_t domid); _hidden int libxl__qmp_initializations(libxl__gc *gc, uint32_t domid,const libxl_domain_config *guest_config); +/* on failure, logs */ +int libxl__sendmsg_fds (libxl__gc *gc,int carrier, +const void *data,size_t datalen, +int nfds,const int fds[],const char *what); + +/* Insists on receiving exactly nfds and datalen. On failure, logs +* and leaves *fds untouched. */ +int libxl__recvmsg_fds (libxl__gc *gc,int carrier, +void *databuf,size_t datalen, +int nfds,int fds[],const char *what); +/* from libxl_json */ #include <yajl/yajl_gen.h> tools/libxl/libxl_qmp.c +4
-27@@ -544,38 +544,15 @@ static int qmp_send_fd(libxl__gc *gc, libxl__qmp_handler *qmp,qmp_request_context *context, int fd) { -struct msghdr msg = {0 }; -struct cmsghdr *cmsg; -char control[CMSG_SPACE (sizeof (fd))]; -struct iovec iov; char *buf = NULL; +int rc; buf =qmp_send_prepare (gc, qmp,"getfd" , args, callback, opaque, context); -/* Response data */ - iov.iov_base = buf; - iov.iov_len =strlen (buf); - -/* compose the message */ - msg.msg_iov = &iov; - msg.msg_iovlen =1 ; - msg.msg_control = control; - msg.msg_controllen =sizeof (control); - -/* attach open fd */ - cmsg =CMSG_FIRSTHDR (&msg); - cmsg->cmsg_level =SOL_SOCKET ; - cmsg->cmsg_type =SCM_RIGHTS ; - cmsg->cmsg_len =CMSG_LEN (sizeof (fd)); - *(int *)CMSG_DATA (cmsg) = fd; - - msg.msg_controllen = cmsg->cmsg_len; + rc =libxl__sendmsg_fds (gc, qmp->qmp_fd, buf,strlen (buf),1 , &fd, +"QMP message to QEMU" ); +if (rc)return rc; -if (sendmsg (qmp->qmp_fd, &msg,0 ) <0 ) { -LIBXL__LOG_ERRNO (qmp->ctx,LIBXL__LOG_ERROR , -"Failed to send a QMP message to QEMU." ); -return ERROR_FAIL ; - }if (libxl_write_exactly (qmp->ctx, qmp->qmp_fd,"\r\n" ,2 ,"CRLF" ,"QMP socket" )) {return ERROR_FAIL ;tools/libxl/libxl_utils.c +104
-0@@ -500,6 +500,110 @@ void libxl_cputopology_list_free(libxl_cputopology *list, int nr)free (list); } +int libxl__sendmsg_fds (libxl__gc *gc,int carrier, +const void *data,size_t datalen, +int nfds,const int fds[],const char *what) { +struct msghdr msg = {0 }; +struct cmsghdr *cmsg; +size_t spaceneeded = nfds *sizeof (fds[0 ]); +char control[CMSG_SPACE (spaceneeded)]; +struct iovec iov; +int r; + + iov.iov_base = (void *)data; + iov.iov_len = datalen; + +/* compose the message */ + msg.msg_iov = &iov; + msg.msg_iovlen =1 ; + msg.msg_control = control; + msg.msg_controllen =sizeof (control); + +/* attach open fd */ + cmsg =CMSG_FIRSTHDR (&msg); + cmsg->cmsg_level =SOL_SOCKET ; + cmsg->cmsg_type =SCM_RIGHTS ; + cmsg->cmsg_len =CMSG_LEN (spaceneeded); +memcpy (CMSG_DATA (cmsg), fds, spaceneeded); + + msg.msg_controllen = cmsg->cmsg_len; + + r =sendmsg (carrier, &msg,0 ); +if (r <0 ) { +LOGE (ERROR ,"failed to send fd-carrying message (%s)" , what); +return ERROR_FAIL ; + } + +return 0 ; +} + +int libxl__recvmsg_fds (libxl__gc *gc,int carrier, +void *databuf,size_t datalen, +int nfds,int fds[],const char *what) +{ +struct msghdr msg = {0 }; +struct cmsghdr *cmsg; +size_t spaceneeded = nfds *sizeof (fds[0 ]); +char control[CMSG_SPACE (spaceneeded)]; +struct iovec iov; +int r; + + iov.iov_base = databuf; + iov.iov_len = datalen; + + msg.msg_iov = &iov; + msg.msg_iovlen =1 ; + msg.msg_control = control; + msg.msg_controllen =sizeof (control); + +for (;;) { + r =recvmsg (carrier, &msg,0 ); +if (r <0 ) { +if (errno ==EINTR )continue ; +if (errno ==EWOULDBLOCK )return -1 ; +LOGE (ERROR ,"recvmsg failed (%s)" , what); +return ERROR_FAIL ; + } +if (r ==0 ) { +LOG (ERROR ,"recvmsg got EOF (%s)" , what); +return ERROR_FAIL ; + } + cmsg =CMSG_FIRSTHDR (&msg); +if (cmsg->cmsg_len <=CMSG_LEN (0 )) { +LOG (ERROR ,"recvmsg got no control msg" +" when expecting fds (%s)" , what); +return ERROR_FAIL ; + } +if (cmsg->cmsg_level !=SOL_SOCKET || cmsg->cmsg_type !=SCM_RIGHTS ) { +LOG (ERROR ,"recvmsg got unexpected" +" cmsg_level %d (!=%d) or _type %d (!=%d) (%s)" , + cmsg->cmsg_level,SOL_SOCKET , + cmsg->cmsg_type,SCM_RIGHTS , + what); +return ERROR_FAIL ; + } +if (cmsg->cmsg_len !=CMSG_LEN (spaceneeded) || + msg.msg_controllen != cmsg->cmsg_len) { +LOG (ERROR ,"recvmsg got unexpected" +" number of fds or extra control data" +" (%ld bytes' worth, expected %ld) (%s)" , + (long )CMSG_LEN (spaceneeded), (long )cmsg->cmsg_len, + what); +int i, fd; +unsigned char *p; +for (i=0 , p=CMSG_DATA (cmsg); +CMSG_SPACE (i *sizeof (fds[0 ])); + i++, i+=sizeof (fd)) { +memcpy (&fd, p,sizeof (fd)); +close (fd); + } +return ERROR_FAIL ; + } +memcpy (fds,CMSG_DATA (cmsg), spaceneeded); +return 0 ; + } +} +void libxl_dominfo_list_free (libxl_dominfo *list,int nr) {int i;
PATCH 19/20 libxl: Clean up setdefault in do_domain_create
In reply to Ian Jacksondo_domain_create called libxl__domain_create_info_setdefault twice.
--- tools/libxl/libxl_create.c | 3 --- 1 files changed, 0 insertions(+), 3 deletions(-)
tools/libxl/libxl_create.c +0 -3
@@ -539,9 +539,6 @@ static int do_domain_create(libxl__gc *gc, libxl_domain_config *d_config, ret =libxl__domain_create_info_setdefault (gc, &d_config->c_info);if (ret) goto error_out; - ret =libxl__domain_create_info_setdefault (gc, &d_config->c_info); -if (ret) goto error_out; - ret =libxl__domain_make (gc, &d_config->c_info, &domid);if (ret) {LIBXL__LOG (ctx,LIBXL__LOG_ERROR ,"cannot make domain: %d" , ret);
Signature · 1 line
1.7.2.5
Re: [PATCH 19/20] libxl: Clean up setdefault in do_domain_create
Quoted 1 line · Ian Jackson
do_domain_createcalledlibxl__domain_create_info_setdefaulttwice.
Thanks, probably some sort of rebase snafu while I was working on that series.
Quoted 1 line
Signed-off-by Ian Jackson <[email protected]>
Quoted 18 lines
--- tools/libxl/libxl_create.c | 3 --- 1 files changed, 0 insertions(+), 3 deletions(-)tools/libxl/libxl_create.c +0
-3@@ -539,9 +539,6 @@ static int do_domain_create(libxl__gc *gc, libxl_domain_config *d_config, ret =libxl__domain_create_info_setdefault (gc, &d_config->c_info);if (ret) goto error_out; - ret =libxl__domain_create_info_setdefault (gc, &d_config->c_info); -if (ret) goto error_out; - ret =libxl__domain_make (gc, &d_config->c_info, &domid);if (ret) {LIBXL__LOG (ctx,LIBXL__LOG_ERROR ,"cannot make domain: %d" , ret);
PATCH 20/20 libxl: ao: Convert libxl_run_bootloader
In reply to Ian JacksonConvert libxl_run_bootloader to an ao_how-taking function.
It's implemented in terms of libxl__bootloader_run, which can be used internally. The resulting code is pretty much a rewrite.
Significant changes include:
- We provide and use a new asynchronous internal facility for pty creation, which runs openpty in a child for SIGCHLD etc. safety (see the comment at the top of libxl__openptys).
- We direct the bootloader's results to a file, not a pipe. This makes it simpler to deal with as we don't have to read it concurrently along with everything else.
- We now issue a warning if we find unexpected statements in the bootloader results.
- The arrangements for buffering of bootloader input and output are completely changed. Now we have a fixed limit of 64k on output, and 4k on input, and discard the oldest data when this overflows (which it shouldn't). There is no timeout any more.
- This is implemented using a new asynchronous internal data- copying facility.
--- tools/libxl/libxl.c | 4 + tools/libxl/libxl.h | 3 +- tools/libxl/libxl_bootloader.c | 957 ++++++++++++++++++++++++++-------------- tools/libxl/libxl_create.c | 8 +- tools/libxl/libxl_internal.h | 97 ++++ 5 files changed, 733 insertions(+), 336 deletions(-)
tools/libxl/libxl.c +4 -0
@@ -1748,6 +1748,10 @@ int libxl_device_disk_local_detach(libxl_ctx *ctx, libxl_device_disk *disk)* For other device types assume that the blktap2 process is * needed by the soon to be started domain and do nothing. */ +/* +* FIXME +* This appears to leak the disk in failure paths +*/ return 0 ; }
tools/libxl/libxl.h +2 -1
@@ -415,7 +415,8 @@ int libxl_get_max_cpus(libxl_ctx *ctx);int libxl_run_bootloader (libxl_ctx *ctx,libxl_domain_build_info *info,libxl_device_disk *disk, -uint32_t domid); +uint32_t domid, +libxl_asyncop_how *ao_how);/* 0 means ERROR_ENOMEM, which we have logged */
tools/libxl/libxl_bootloader.c +624 -333
1,079 lines not on this page · raw message
tools/libxl/libxl_create.c +6 -2
@@ -559,8 +559,12 @@ static int do_domain_create(libxl__gc *gc, libxl_domain_config *d_config,if (ret) goto error_out; } -if ( restore_fd <0 ) { - ret =libxl_run_bootloader (ctx, &d_config->b_info, d_config->num_disks >0 ? &d_config->disks[0 ] :NULL , domid); +libxl_device_disk *bootdisk = + d_config->num_disks >0 ? &d_config->disks[0 ] :NULL ; + +if (restore_fd <0 && bootdisk) { + ret =libxl_run_bootloader (ctx, &d_config->b_info, bootdisk, domid, +0 /* fixme-ao */ );if (ret) {LIBXL__LOG (ctx,LIBXL__LOG_ERROR ,"failed to run bootloader: %d" , ret);
tools/libxl/libxl_internal.h +97 -0
109 lines not on this page · raw message
Signature · 1 line
1.7.2.5
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
Quoted 4 lines · Ian Jackson
Convert
libxl_run_bootloaderto an ao_how-taking function.It's implemented in terms of
libxl__bootloader_run, which can be used internally. The resulting code is pretty much a rewrite.
It's always annoying when diff fails to notice this and treats any blank line as a common point. I've stripped most of the - lines out to make something easier to review.
Quoted 96 lines
Significant changes include:
- We provide and use a new asynchronous internal facility for pty creation, which runs openpty in a child for SIGCHLD etc. safety (see the comment at the top of
libxl__openptys).- We direct the bootloader's results to a file, not a pipe. This makes it simpler to deal with as we don't have to read it concurrently along with everything else.
- We now issue a warning if we find unexpected statements in the bootloader results.
- The arrangements for buffering of bootloader input and output are completely changed. Now we have a fixed limit of 64k on output, and 4k on input, and discard the oldest data when this overflows (which it shouldn't). There is no timeout any more.
- This is implemented using a new asynchronous internal data- copying facility.
Signed-off-by Ian Jackson <[email protected]>--- tools/libxl/libxl.c | 4 + tools/libxl/libxl.h | 3 +- tools/libxl/libxl_bootloader.c | 957 ++++++++++++++++++++++++++-------------- tools/libxl/libxl_create.c | 8 +- tools/libxl/libxl_internal.h | 97 ++++ 5 files changed, 733 insertions(+), 336 deletions(-)tools/libxl/libxl_bootloader.c +45
-7@@ -15,70 +15,219 @@#include "libxl_osdeps.h" /* must come before any other headers */ #include <termios.h> +#include <utmp.h> #include "libxl_internal.h" -#define XENCONSOLED_BUF_SIZE 16 -#define BOOTLOADER_BUF_SIZE 4096 -#define BOOTLOADER_TIMEOUT 1 +#define BOOTLOADER_BUF_OUT 65536 +#define BOOTLOADER_BUF_IN 4096 -static char **make_bootloader_args (libxl__gc *gc, -libxl_domain_build_info *info, -uint32_t domid, -const char *fifo,char *disk) +static void bootloader_gotptys (libxl__egc *egc,libxl__openpty_state *op); +static void bootloader_keystrokes_copyfail (libxl__egc *egc, +libxl__datacopier_state *dc,int onwrite,int errnoval); +static void bootloader_display_copyfail (libxl__egc *egc, +libxl__datacopier_state *dc,int onwrite,int errnoval); +static void bootloader_finished (libxl__egc *egc,libxl__ev_child *child, +pid_t pid,int status); + +/*----- openpty -----*/ + +/* +* opens count (>0) ptys like count calls to openpty, and then +* calls back. On entry, all op[].master and op[].slave must be +* 0. On callback, either rc==0 and master and slave are non-0, +* or rc is a libxl error and they are both 0. If libxl__openpty +* returns non-0 no callback will happen and everything is left +* cleaned up. +*/ + +/* implementation */ + +static void openpty_cleanup (libxl__openpty_state *op) +{ +int i; + +for (i=0 ; i<op->count; i++) { +libxl__openpty_result *res = &op->results[i]; +libxl__carefd_close (res->master); res->master =0 ; +libxl__carefd_close (res->slave); res->slave =0 ; + } +} + +static void openpty_exited (libxl__egc *egc,libxl__ev_child *child, +pid_t pid,int status) { +libxl__openpty_state *op =CONTAINER_OF (child, *op, child); +EGC_GC ; + +if (status) { +/* Perhaps the child gave us the fds and then exited nonzero. +* Well that would be odd but we don't really care. */ + libxl_report_child_exitstatus(CTX, op->rc ? LIBXL__LOG_ERROR + : LIBXL__LOG_WARNING,
tools/libxl/libxl_bootloader.c line 76
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+ "openpty child", pid, status); + } +if (op->rc) +openpty_cleanup (op); + op->callback (egc, op); +} + +int libxl__openptys (libxl__gc *gc,libxl__openpty_state *op, +const struct termios *termp, +const struct winsize *winp) {
"{" on next line please, (here and elsewhere)
libxl__openptys might be deserving of its own home outside libxl_bootloader.c?
Quoted 45 lines
tools/libxl/libxl_bootloader.c +45
-0+/* +* This is completely crazy. openpty calls grantpt which the spec +* says may fork, and may not be called with a SIGCHLD handler. +* Now our application may have a SIGCHLD handler so that's bad. +* We could perhaps block it but we'd need to block it on all +* threads. This is just Too Hard. +* +* So instead, we run openpty in a child process. That child +* process then of course has only our own thread and our own +* signal handlers. We pass the fds back. +* +* Since our only current caller actually wants two ptys, we +* support calling openpty multiple times for a single fork. +*/ +int count = op->count; +int r, i, rc, sockets[2 ], ptyfds[count][2 ]; +libxl__carefd *for_child =0 ; +pid_t pid =-1 ; + +for (i=0 ; i<count; i++) { + ptyfds[i][0 ] = ptyfds[i][1 ] =-1 ; +libxl__openpty_result *res = &op->results[i]; +assert (!res->master); +assert (!res->slave); + } + sockets[0 ] = sockets[1 ] =-1 ;/* 0 is for us, 1 for our child */ + +libxl__carefd_begin (); + r =socketpair (AF_UNIX ,SOCK_STREAM ,0 , sockets); +if (r) { sockets[0 ] = sockets[1 ] =-1 ; } + for_child =libxl__carefd_opened (CTX , sockets[1 ]); +if (r) {LOGE (ERROR ,"socketpair failed" ); rc =ERROR_FAIL ; goto out; } + + pid =libxl__ev_child_fork (gc, &op->child, openpty_exited); +if (pid ==-1 ) { + rc =ERROR_FAIL ; + goto out; + } + +if (!pid) { +/* child */ +close (sockets[0 ]); +signal (SIGCHLD ,SIG_DFL ); + +for (i=0 ; i<count; i++) {
tools/libxl/libxl_bootloader.c line 131
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+ r =openpty (&ptyfds[i][0 ], &ptyfds[i][1 ],NULL , termp, winp); +if (r) {LOGE (ERROR ,"openpty failed" );_exit (-1 ); } + } + rc =libxl__sendmsg_fds (gc, sockets[1 ],"" ,1 , +2 *count, &ptyfds[0 ][0 ],"ptys" ); +if (rc) {LOGE (ERROR ,"sendmsg to parent failed" );_exit (-1 ); } +_exit (0 ); + } + +libxl__carefd_close (for_child);
this is sockets[1], which we then read below (via recvmsg_fds)? I suspect one or the other is wrong (I think the read).
Quoted 16 lines
tools/libxl/libxl_bootloader.c +16
-0+ for_child =0 ; + +/* this should be fast so do it synchronously */ + +libxl__carefd_begin (); +char buf[1 ]; + rc =libxl__recvmsg_fds (gc, sockets[1 ], buf,1 , +2 *count, &ptyfds[0 ][0 ],"ptys" ); +if (!rc) { +for (i=0 ; i<count; i++) { +libxl__openpty_result *res = &op->results[i]; + res->master =libxl__carefd_record (CTX , ptyfds[i][0 ]); + res->slave =libxl__carefd_record (CTX , ptyfds[i][1 ]); + } + } +/* now the pty fds are in the carefds, if they were ever open */
tools/libxl/libxl_bootloader.c line 157
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+libxl__carefd_unlock (); +if (rc) + goto out; + + rc =0 ; + + out: +if (sockets[0 ] >=0 )close (sockets[0 ]); +if (sockets[1 ] >=0 )close (sockets[1 ]); +libxl__carefd_close (for_child);
for_child == sockets[1], so now we've closed it twice.
Quoted 7 lines
tools/libxl/libxl_bootloader.c +7
-0+if (libxl__ev_child_inuse (&op->child)) { + op->rc = rc; +/* we will get a callback when the child dies */ +return 0 ; + } + +assert (rc);
tools/libxl/libxl_bootloader.c line 174
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+openpty_cleanup (op); +return rc; +} + +/*----- bootloader arguments -----*/ + +static void bootloader_arg (libxl__bootloader_state *bl,const char *arg) { +assert (bl->nargs < bl->argsspace); + bl->args[bl->nargs++] = arg; +}
I'm not a huge fan of the flexarray stuff but is reinventing them again useful?
Quoted 20 lines
tools/libxl/libxl_bootloader.c +11
-3+ +static void make_bootloader_args (libxl__gc *gc,libxl__bootloader_state *bl) { +const libxl_domain_build_info *info = bl->info; + + bl->argsspace =7 +libxl_string_list_length (&info->u.pv.bootloader_args); + +GCNEW_ARRAY (bl->args, bl->argsspace); +#define ARG (arg) bootloader_arg(bl, (arg)) +ARG (info->u.pv.bootloader);if (info->u.pv.kernel.path) -flexarray_set (args, nr++,libxl__sprintf (gc,"--kernel=%s" , - info->u.pv.kernel.path)); +ARG (libxl__sprintf (gc,"--kernel=%s" , info->u.pv.kernel.path));if (info->u.pv.ramdisk.path) -flexarray_set (args, nr++,libxl__sprintf (gc,"--ramdisk=%s" , info->u.pv.ramdisk.path)); +ARG (libxl__sprintf (gc,"--ramdisk=%s" , info->u.pv.ramdisk.path));
tools/libxl/libxl_bootloader.c line 197
Quoted 10 lines
tools/libxl/libxl_bootloader.c +4
-4if (info->u.pv.cmdline && *info->u.pv.cmdline !='\0' ) -flexarray_set (args, nr++,libxl__sprintf (gc,"--args=%s" , info->u.pv.cmdline)); +ARG (libxl__sprintf (gc,"--args=%s" , info->u.pv.cmdline)); -flexarray_set (args, nr++,libxl__sprintf (gc,"--output=%s" , fifo)); -flexarray_set (args, nr++,"--output-format=simple0" ); -flexarray_set (args, nr++,libxl__sprintf (gc,"--output-directory=%s" ,"/var/run/libxl/" )); +ARG (libxl__sprintf (gc,"--output=%s" , bl->outputpath)); +ARG ("--output-format=simple0" ); +ARG (libxl__sprintf (gc,"--output-directory=%s" ,"/var/run/xen/" ));
Output path changed? If we are going to do that then perhaps it should include an additional element from mkdtemp()?
(comes back later.. why not use XEN_RUN_DIR? Also you seem to have created bl->outputdir for this purpose anyway?)
tools/libxl/libxl_bootloader.c line 209
Quoted 13 lines
tools/libxl/libxl_bootloader.c +2
-2if (info->u.pv.bootloader_args) {char **p = info->u.pv.bootloader_args;while (*p) { -flexarray_set (args, nr++, *p); +ARG (*p); p++; } } -flexarray_set (args, nr++, disk); +ARG (bl->diskpath);/* Sentinal for execv */
Pre-existing:
Sentinel
tools/libxl/libxl_bootloader.c line 64
Quoted 4 lines
tools/libxl/libxl_bootloader.c +1
-2-flexarray_set (args, nr++,NULL ); +ARG (NULL ); -return (char **)flexarray_contents (args);/* Frees args */
Hopefully I'll find blargs getting free'd later on...
Quoted 27 lines
tools/libxl/libxl_bootloader.c +16
-0+#undef ARG } +/*----- synchronous subroutines -----*/ + +static int setup_xenconsoled_pty (libxl__egc *egc,libxl__bootloader_state *bl, +char *slave_path,size_t slave_path_len) { +EGC_GC ;struct termios termattr; +int r, rc; +int slave =libxl__carefd_fd (bl->ptys[1 ].slave); +int master =libxl__carefd_fd (bl->ptys[1 ].master); + + r =ttyname_r (slave, slave_path, slave_path_len); +if (r ==-1 ) { +LOGE (ERROR ,"ttyname_r failed" ); + rc =ERROR_FAIL ; + goto out; }/* @@ -92,309 +241,360 @@ static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_* for it. */ #if !defined(__sun__) && !defined(__NetBSD__) +tcgetattr (master, &termattr);
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 254
Quoted 10 lines
tools/libxl/libxl_bootloader.c +5
-0cfmakeraw (&termattr); +tcsetattr (master,TCSANOW , &termattr); +close (slave); + slave =-1 ;#else +tcgetattr (slave, &termattr);cfmakeraw (&termattr); +tcsetattr (slave,TCSANOW , &termattr);#endif
Could this stuff be usefully pushed into libxl__openpty?
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 100
Quoted 2 lines
tools/libxl/libxl_bootloader.c +0
-1-fcntl (*master,F_SETFL ,O_NDELAY );
Why not?
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 108
Quoted 1 line
tools/libxl/libxl_bootloader.c +0
-1-fcntl (*master,F_SETFD ,FD_CLOEXEC );
This one I understand (done by carefd stuff already)
Quoted 1 line
tools/libxl/libxl_bootloader.c +0
-0return 0 ;
[...]
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 133
Quoted 13 lines
+ out:
tools/libxl/libxl_bootloader.c +2
-9+return rc; +} -/* -* On Solaris, the master pty side does not have terminal semantics, -* so don't try to set any attributes, as it will fail. -*/ -#if !defined(__sun__) -tcgetattr (*master, &termattr); -cfmakeraw (&termattr); -tcsetattr (*master,TCSANOW , &termattr); -#endif
I think we are right to give up any pretence of supporting Solaris now. [....]
Quoted 17 lines
tools/libxl/libxl_bootloader.c +16
-0+/*----- data copier -----*/ +static void datacopier_check_state (libxl__egc *egc,libxl__datacopier_state *dc) +{ +EGC_GC ; +int rc; + +if (dc->used) { +if (!libxl__ev_fd_isregistered (&dc->towrite)) { + rc =libxl__ev_fd_register (gc, &dc->towrite, datacopier_writable, + dc->writefd,POLLOUT ); +if (!rc) { +LOG (ERROR ,"unable to establish write event" +" during copy (%s)" , dc->what); +datacopier_callback (egc, dc,-1 ,0 ); +return ; + } }
[...]
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 390
Quoted 8 lines
tools/libxl/libxl_bootloader.c +8
-0+ }else if (!libxl__ev_fd_isregistered (&dc->toread)) { +/* we have had eof */ +libxl__datacopier_kill (gc, dc); + dc->callback (egc, dc,0 ,0 ); +return ; + }else { +/* nothing buffered, but still reading */ +libxl__ev_fd_deregister (gc, &dc->towrite);
is it worth the effort to handle only registering for write events when something is buffered? It would be simpler to just set it up at start of day and leave it until done?
Quoted 7 lines
tools/libxl/libxl_bootloader.c +7
-0+ } +} + +static void datacopier_readable (libxl__egc *egc,libxl__ev_fd *ev, +int fd,short events,short revents) { +libxl__datacopier_state *dc =CONTAINER_OF (ev, *dc, toread); +EGC_GC ;
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 407
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+ +if (revents & ~POLLIN ) { +LOG (ERROR ,"unexpected poll event 0x%x (should be POLLIN)" +" during copy (%s)" , revents, dc->what); +datacopier_callback (egc, dc,-1 ,0 ); +return ; + } +assert (revents &POLLIN ); +for (;;) { +while (dc->used >= dc->maxsz) {
This is the overflow discard loop, correct? (took me a while to figure that out, in the meantime I was v. confused ;-))
Quoted 7 lines
tools/libxl/libxl_bootloader.c +5
-0+libxl__datacopier_buf *rm =LIBXL_TAILQ_FIRST (&dc->bufs); + dc->used -= rm->used; +assert (dc->used >=0 ); +LIBXL_TAILQ_REMOVE (&dc->bufs, rm, entry); +free (rm); }
[...]
Quoted 4 lines
tools/libxl/libxl_bootloader.c +3
-0+/*----- init and cleanup -----*/ + +void libxl__bootloader_init (libxl__bootloader_state *bl) {
[...]
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 505
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+ bl->diskpath =NULL ; + bl->ptys[0 ].master = bl->ptys[0 ].slave =0 ; + bl->ptys[1 ].master = bl->ptys[1 ].slave =0 ;
Not -1? A more typical "invalid" fd value.
Quoted 11 lines
tools/libxl/libxl_bootloader.c +10
-0+libxl__ev_child_init (&bl->child); +libxl__datacopier_init (&bl->keystrokes); +libxl__datacopier_init (&bl->display); +} +static void bootloader_cleanup (libxl__egc *egc,libxl__bootloader_state *bl) +{ +libxl__ao *ao = bl->ao; +AO_GC ; +int i; +
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 526
Quoted 10 lines
tools/libxl/libxl_bootloader.c +10
-0+if (bl->diskpath) { +libxl_device_disk_local_detach (CTX , bl->disk); +free (bl->diskpath); + bl->diskpath =0 ; + } +libxl__datacopier_kill (gc, &bl->keystrokes); +libxl__datacopier_kill (gc, &bl->display); +for (i=0 ; i<2 ; i++) { +libxl__carefd_close (bl->ptys[0 ].master); +libxl__carefd_close (bl->ptys[0 ].slave);
Don't you mean [i] rather than [0] both times here?
Quoted 2 lines
}}
[...]
Quoted 20 lines
tools/libxl/libxl_bootloader.c +13
-1+/*----- main flow of control -----*/ +void libxl__bootloader_run (libxl__egc *egc,libxl__bootloader_state *bl) +{ +libxl__ao *ao = bl->ao; +AO_GC ; +libxl_domain_build_info *info = bl->info; +uint32_t domid = bl->domid; +int rc, r; +libxl__bootloader_init (bl); -if (info->type !=LIBXL_DOMAIN_TYPE_PV || !info->u.pv.bootloader) +if (info->type !=LIBXL_DOMAIN_TYPE_PV || !info->u.pv.bootloader) { + bl->callback (egc, bl,0 ); + rc =0 ; goto out; + }
[...]
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 556
Quoted 2 lines
tools/libxl/libxl_bootloader.c +2
-0+ bl->outputdir =GCSPRINTF (XEN_RUN_DIR "/bootloader.%" PRIu32".d" , domid); + bl->outputpath =GCSPRINTF (XEN_RUN_DIR "/bootloader.%" PRIu32".out" , domid);
You should use this instead of the hardcoded /var/run/xen way above?
Quoted 1 line
[...]
Quoted 10 lines
tools/libxl/libxl_bootloader.c +8
-0+for (;;) { + r =mkdir (bl->outputdir,0600 ); +if (!r)break ; +if (errno ==EINTR )continue ; +if (errno ==EEXIST )break ; +LOGE (ERROR ,"failed to create bootloader dir %s" , bl->outputdir); + rc =ERROR_FAIL ; goto out; + }
[...]
Quoted 2 lines
+
make_bootloader_args(gc, bl);
[...]
Quoted 6 lines
tools/libxl/libxl_bootloader.c +4
-0+ bl->diskpath =libxl_device_disk_local_attach (CTX , bl->disk); +if (!bl->diskpath) { + rc =ERROR_FAIL ; goto out; + }
[...]
Quoted 6 lines
tools/libxl/libxl_bootloader.c +5
-0+ bl->openpty.callback = bootloader_gotptys; + bl->openpty.count =2 ; + bl->openpty.results = bl->ptys; + rc =libxl__openptys (gc, &bl->openpty,0 ,0 ); +if (rc) goto out;
[...]
Quoted 2 lines
+ return;
[...]
Quoted 5 lines
+ out:
tools/libxl/libxl_bootloader.c +3
-0+assert (rc); +bootloader_callback (egc, bl, rc); +}
[...]
Quoted 6 lines
tools/libxl/libxl_bootloader.c +5
-0+static void bootloader_gotptys (libxl__egc *egc,libxl__openpty_state *op) +{ +libxl__bootloader_state *bl =CONTAINER_OF (op, *bl, openpty); +EGC_GC ; +int rc, r;
[...]
Quoted 10 lines
tools/libxl/libxl_bootloader.c +3
-0+if (bl->openpty.rc) { + rc = bl->openpty.rc; + goto out; }/* @@ -407,76 +607,167 @@ int libxl_run_bootloader(libxl_ctx *ctx,* where we copy characters between the two master fds, as well as * listening on the bootloader's fifo for the results. */
[...]
Quoted 6 lines
tools/libxl/libxl_bootloader.c +4
-0+ +char *dom_console_xs_path; +char dom_console_slave_tty_path[PATH_MAX ]; + rc =setup_xenconsoled_pty (egc, bl, &dom_console_slave_tty_path[0 ],sizeof (dom_console_slave_tty_path));
[...]
Quoted 5 lines
tools/libxl/libxl_bootloader.c +4
-0+if (rc) goto out; + +char *dompath =libxl__xs_get_dompath (gc, bl->domid); +if (!dompath) { rc =ERROR_FAIL ; goto out; }
[...]
Quoted 2 lines
+
dom_console_xs_path=GCSPRINTF("%s/console/tty", dompath);
[...]
Quoted 9 lines
tools/libxl/libxl_bootloader.c +7
-0+ rc =libxl__xs_write (gc,XBT_NULL , dom_console_xs_path,"%s" , + dom_console_slave_tty_path); +if (!rc) { +LOGE (ERROR ,"xs write console path %s := %s failed" , + dom_console_xs_path, dom_console_slave_tty_path); + rc =ERROR_FAIL ; + goto out; }
[...]
Quoted 3 lines
tools/libxl/libxl_bootloader.c +2
-0+int bootloader_master =libxl__carefd_fd (bl->ptys[0 ].master); +int xenconsole_master =libxl__carefd_fd (bl->ptys[1 ].master);
[...]
Quoted 3 lines
tools/libxl/libxl_bootloader.c +2
-0+libxl_fd_set_nonblock (CTX , bootloader_master,1 ); +libxl_fd_set_nonblock (CTX , xenconsole_master,1 );
[...]
Quoted 8 lines
tools/libxl/libxl_bootloader.c +7
-0+ bl->keystrokes.readfd = xenconsole_master; + bl->keystrokes.writefd = bootloader_master; + bl->keystrokes.maxsz =BOOTLOADER_BUF_OUT ; + bl->keystrokes.what =GCSPRINTF ("bootloader input for %" PRIu32, bl->domid); + bl->keystrokes.callback = bootloader_keystrokes_copyfail; + rc =libxl__datacopier_start (gc, &bl->keystrokes); +if (rc) goto out;
[...]
Quoted 8 lines
tools/libxl/libxl_bootloader.c +7
-0+ bl->display.readfd = bootloader_master; + bl->display.writefd = xenconsole_master; + bl->display.maxsz =BOOTLOADER_BUF_IN ; + bl->display.what =GCSPRINTF ("bootloader output for %" PRIu32, bl->domid); + bl->display.callback = bootloader_display_copyfail; + rc =libxl__datacopier_start (gc, &bl->display); +if (rc) goto out;
[...]
Quoted 2 lines
+ struct termios termattr;
[...]
Quoted 6 lines
tools/libxl/libxl_bootloader.c +4
-0+pid_t pid =libxl__ev_child_fork (gc, &bl->child, bootloader_finished); +if (pid ==-1 ) { + rc =ERROR_FAIL ; + goto out; }
[...]
tools/libxl/libxl_bootloader.c int libxl_run_bootloader(libxl_ctx *ctx, · line 664
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+if (!pid) { +/* child */ + r =login_tty (libxl__carefd_fd (bl->ptys[0 ].slave));
login_tty is a new one to me. When I lookup up the manpage I happened to notice:
Link with -lutil.
Quoted 6 lines
tools/libxl/libxl_bootloader.c +4
-0+if (r) {LOGE (ERROR ,"login_tty failed" );exit (-1 ); } +setenv ("TERM" ,"vt100" ,1 ); +libxl__exec (-1 ,-1 ,-1 , bl->args[0 ], (char **)bl->args); +exit (-1 ); }
[...]
Quoted 4 lines
tools/libxl/libxl_bootloader.c +3
-0+/* parent */ +libxl__carefd_close (bl->ptys[0 ].slave); + bl->ptys[0 ].slave =0 ;
[...]
tools/libxl/libxl_bootloader.c int libxl_run_bootloader(libxl_ctx *ctx, · line 678
Quoted 4 lines
tools/libxl/libxl_bootloader.c +4
-0+/* +* On Solaris, the master pty side does not have terminal semantics, +* so don't try to set any attributes, as it will fail. +*/
/insert comment about supporting Solaris again here too...
Quoted 12 lines
tools/libxl/libxl_bootloader.c +12
-0+#if !defined(__sun__) +tcgetattr (bootloader_master, &termattr); +cfmakeraw (&termattr); +tcsetattr (bootloader_master,TCSANOW , &termattr); +#endif + +return ; + + out: +bootloader_callback (egc, bl, rc); +} +
[...]
Quoted 15 lines
tools/libxl/libxl_internal.h +1
-0@@ -42,6 +42,7 @@#include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> +#include <sys/socket.h> #include <xs.h> #include <xenctrl.h> @@ -1433,6 +1434,102 @@ int libxl__carefd_close(libxl__carefd*);int libxl__carefd_fd (const libxl__carefd *);
[...]
tools/libxl/libxl_internal.h int libxl__carefd_close(libxl__carefd*); · line 1469
Quoted 7 lines
tools/libxl/libxl_internal.h +7
-0+/*----- datacopier: copies data from one fd to another -----*/ + +typedef struct libxl__datacopier_state libxl__datacopier_state ; +typedef struct libxl__datacopier_buf libxl__datacopier_buf ; + +/* onwrite==1 means failure happend when writing, logged, errno is valid +* onwrite==0 means failure happend when reading
happened (twice)
[...]
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
Ian Campbell writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader"):
Quoted 6 lines · Ian Jackson
tools/libxl/libxl_bootloader.c line 76
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+int libxl__openptys (libxl__gc *gc,libxl__openpty_state *op, +const struct termios *termp, +const struct winsize *winp) {"{" on next line please, (here and elsewhere)
Oops.
Quoted 2 lines
libxl__openptysmight be deserving of its own home outsidelibxl_bootloader.c?
I considered this but it's not that long and there are currently no other callers.
Quoted 8 lines
tools/libxl/libxl_bootloader.c line 131
Quoted 5 lines
tools/libxl/libxl_bootloader.c +5
-0+if (rc) {LOGE (ERROR ,"sendmsg to parent failed" );_exit (-1 ); } +_exit (0 ); + } + +libxl__carefd_close (for_child);this is sockets[1], which we then read below (via
recvmsg_fds)? I suspect one or the other is wrong (I think the read).
Yes, the read is wrong.
Quoted 6 lines
tools/libxl/libxl_bootloader.c line 157
Quoted 4 lines
+ out:
tools/libxl/libxl_bootloader.c +3
-0+if (sockets[0 ] >=0 )close (sockets[0 ]); +if (sockets[1 ] >=0 )close (sockets[1 ]); +libxl__carefd_close (for_child);
for_child== sockets[1], so now we've closed it twice.
Well spotted.
Quoted 7 lines
tools/libxl/libxl_bootloader.c line 174
Quoted 4 lines
tools/libxl/libxl_bootloader.c +4
-0+static void bootloader_arg (libxl__bootloader_state *bl,const char *arg) { +assert (bl->nargs < bl->argsspace); + bl->args[bl->nargs++] = arg; +}I'm not a huge fan of the flexarray stuff but is reinventing them again useful?
The flexarray stuff doesn't use the gc. And we don't need a variable-sized buffer. So I don't think it buys us much here.
Quoted 2 lines
(comes back later.. why not use
XEN_RUN_DIR? Also you seem to have createdbl->outputdirfor this purpose anyway?)
The bug is that I wasn't using bl->outputdir. It needs to have the domid in it for obvious reasons.
Quoted 4 lines
Quoted 1 line
/* Sentinal for execv */Pre-existing:
Sentinel
I'll fix that.
Quoted 6 lines
tools/libxl/libxl_bootloader.c line 64
Quoted 4 lines
tools/libxl/libxl_bootloader.c +1
-2-flexarray_set (args, nr++,NULL ); +ARG (NULL ); -return (char **)flexarray_contents (args);/* Frees args */ Hopefully I'll find blargs getting free'd later on...
bl->args is from the gc.
More later...
Ian.
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
In reply to Ian CampbellIan Campbell writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader"):
Quoted 9 lines · Ian Jackson
Quoted 8 lines
tools/libxl/libxl_bootloader.c +2
-0@@ -92,309 +241,360 @@ static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_* for it. */ #if !defined(__sun__) && !defined(__NetBSD__) +tcgetattr (master, &termattr);cfmakeraw (&termattr); +tcsetattr (master,TCSANOW , &termattr);
Quoted 9 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 254
Quoted 7 lines
tools/libxl/libxl_bootloader.c +4
-0+close (slave); + slave =-1 ;#else +tcgetattr (slave, &termattr);cfmakeraw (&termattr); +tcsetattr (slave,TCSANOW , &termattr);#endif Could this stuff be usefully pushed into
libxl__openpty?
Hmm. This is a bit of a can of worms I think. When I wrote my patch I left it well alone. TBH I think the current code is arguably wrong. I can see no reason why we would try to do termios operations on the pty master at all. I think these functions should be performed on the slave on all platforms.
But I don't want to introduce a perhaps-not-wonderfully-portable change like that in this series.
Quoted 3 lines
Review static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 100
Quoted 1 line
(quoted diff) +0
-1- fcntl(*master, F_SETFL, O_NDELAY);Why not?
This is now done with libxl_fd_set_nonblock immediately after the call to carefd.
Quoted 11 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 133
Quoted 9 lines
tools/libxl/libxl_bootloader.c +0
-9-/* -* On Solaris, the master pty side does not have terminal semantics, -* so don't try to set any attributes, as it will fail. -*/ -#if !defined(__sun__) -tcgetattr (*master, &termattr); -cfmakeraw (&termattr); -tcsetattr (*master,TCSANOW , &termattr); -#endif I think we are right to give up any pretence of supporting Solaris now.
This code has not actually been removed by my patch. It's still there at the end of bootloader_gotptys.
Quoted 9 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 390
Quoted 8 lines
tools/libxl/libxl_bootloader.c +8
-0+ }else if (!libxl__ev_fd_isregistered (&dc->toread)) { +/* we have had eof */ +libxl__datacopier_kill (gc, dc); + dc->callback (egc, dc,0 ,0 ); +return ; + }else { +/* nothing buffered, but still reading */ +libxl__ev_fd_deregister (gc, &dc->towrite);
Quoted 3 lines
is it worth the effort to handle only registering for write events when something is buffered? It would be simpler to just set it up at start of day and leave it until done?
If you register for write events that means the event loop will spin continually offering you the chance to write something. Or to put it another way, the event callback function must either make the original condition it was triggering on not true, or it must disable the event.
Quoted 6 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 407
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+assert (revents &POLLIN ); +for (;;) { +while (dc->used >= dc->maxsz) {This is the overflow discard loop, correct? (took me a while to figure that out, in the meantime I was v. confused ;-))
Yes. We discard a whole buffer at a time.
Quoted 8 lines
Quoted 2 lines
tools/libxl/libxl_bootloader.c +1
-0+void libxl__bootloader_init (libxl__bootloader_state *bl) {[...]
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 505
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+ bl->diskpath =NULL ; + bl->ptys[0 ].master = bl->ptys[0 ].slave =0 ; + bl->ptys[1 ].master = bl->ptys[1 ].slave =0 ;Not -1? A more typical "invalid" fd value.
These are libxl__carefd*.
Quoted 5 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 526
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+for (i=0 ; i<2 ; i++) { +libxl__carefd_close (bl->ptys[0 ].master); +libxl__carefd_close (bl->ptys[0 ].slave);Don't you mean [i] rather than [0] both times here?
Yes, oops.
Quoted 8 lines
[...]
tools/libxl/libxl_bootloader.c int libxl_run_bootloader(libxl_ctx *ctx, · line 664
Quoted 3 lines
tools/libxl/libxl_bootloader.c +3
-0+if (!pid) { +/* child */ + r =login_tty (libxl__carefd_fd (bl->ptys[0 ].slave));
login_ttyis a new one to me. When I lookup up the manpage I happened to notice:
Link with -lutil.
Hmm. The BSD manpage is more forthcoming and suggests we need something different there. (This isn't a particularly portable function.)
I think we need some more autoconfery.
Quoted 4 lines
Quoted 2 lines
+/* onwrite==1 means failure happend when writing, logged, errno is valid
+ * onwrite==0 means failure happend when readinghappened (twice)
Fixed.
Ian.
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
Quoted 20 lines · Ian Jackson
Ian Campbell writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert
libxl_run_bootloader"):Quoted 9 lines · Ian Jackson
Quoted 8 lines
tools/libxl/libxl_bootloader.c +2
-0@@ -92,309 +241,360 @@ static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_* for it. */ #if !defined(__sun__) && !defined(__NetBSD__) +tcgetattr (master, &termattr);cfmakeraw (&termattr); +tcsetattr (master,TCSANOW , &termattr);Quoted 9 lines
tools/libxl/libxl_bootloader.c static int open_xenconsoled_pty(int *master, int *slave, char *slave_path, size_ · line 254
Quoted 7 lines
tools/libxl/libxl_bootloader.c +4
-0+close (slave); + slave =-1 ;#else +tcgetattr (slave, &termattr);cfmakeraw (&termattr); +tcsetattr (slave,TCSANOW , &termattr);#endif Could this stuff be usefully pushed into
libxl__openpty?
Quoted 8 lines
Hmm. This is a bit of a can of worms I think. When I wrote my patch I left it well alone. TBH I think the current code is arguably wrong. I can see no reason why we would try to do termios operations on the pty master at all. I think these functions should be performed on the slave on all platforms.
But I don't want to introduce a perhaps-not-wonderfully-portable change like that in this series.
That's very reasonable...
FWIW most of this code was copied from the xend equivalent (actually a C python binding) which I think was actually cobbled together from actual users of the platforms in question, not that this makes it correct necessarily.
Quoted 2 lines
This is now done with
libxl_fd_set_nonblockimmediately after the call to carefd.
[...]
Quoted 2 lines
This code has not actually been removed by my patch. It's still there at the end of
bootloader_gotptys.
Sorry, I spotted both of these later and neglected to come back and remove these comments.
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
tools/libxl/libxl_bootloader.c +8
-0+ }else if (!libxl__ev_fd_isregistered (&dc->toread)) { +/* we have had eof */ +libxl__datacopier_kill (gc, dc); + dc->callback (egc, dc,0 ,0 ); +return ; + }else { +/* nothing buffered, but still reading */ +libxl__ev_fd_deregister (gc, &dc->towrite);
Quoted 8 lines
Quoted 3 lines
is it worth the effort to handle only registering for write events when something is buffered? It would be simpler to just set it up at start of day and leave it until done?
If you register for write events that means the event loop will spin continually offering you the chance to write something. Or to put it another way, the event callback function must either make the original condition it was triggering on not true, or it must disable the event.
Right, this is obvious when you put it that way. In my defence it had been a long review session...
Ian.
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
In reply to Ian JacksonIan Jackson writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader"):
Quoted 11 lines
Ian Campbell writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert
libxl_run_bootloader"):Quoted 1 line
Could this stuff be usefully pushed into
libxl__openpty?Hmm. This is a bit of a can of worms I think. When I wrote my patch I left it well alone. TBH I think the current code is arguably wrong. I can see no reason why we would try to do termios operations on the pty master at all. I think these functions should be performed on the slave on all platforms.
But I don't want to introduce a perhaps-not-wonderfully-portable change like that in this series.
Just to be clear: I left all of this pty termios code alone in my series; it just shuffles about a bit but is otherwise unchanged as far as possible. The only intentional difference is that I replaced forkpty with our own fork + openpty + login_tty.
Quoted 9 lines
Quoted 3 lines
login_ttyis a new one to me. When I lookup up the manpage I happened to notice:
Link with -lutil.Hmm. The BSD manpage is more forthcoming and suggests we need something different there. (This isn't a particularly portable function.)
I think we need some more autoconfery.
Like the below. Previously libxl was linking with -lutil by virtue of using UTIL_LIBS which came from config/StdGNU.mk.
Ian.
From: Ian Jackson <[email protected]>
Subject: [PATCH] autoconf: New test for openpty et al.
We may need to #include <libutil.h>, and/or link with -lutil, to use openpty, login_tty, and the like. Provide INCLUDE_LIBUTIL_H (preprocessor constant, not always defined) and PTYFUNCS_LIBS (makefile variable).
We link libxl against PTYFUNCS_LIBS (which comes from autoconf) rather than UTIL_LIBS, and #include <libutil.h> where appropriate.
--- config/Tools.mk.in | 2 + tools/configure | 57 ++++++++++++++++++++++++++++++++++++++++ tools/configure.ac | 2 + tools/libxl/Makefile | 2 +- tools/libxl/libxl_bootloader.c | 4 +++ tools/m4/ptyfuncs.m4 | 24 +++++++++++++++++ 6 files changed, 90 insertions(+), 1 deletions(-)
config/Tools.mk.in +2 -0
@@ -27,6 +27,8 @@ PTHREAD_CFLAGS := @PTHREAD_CFLAGS@ PTHREAD_LDFLAGS := @PTHREAD_LDFLAGS@ PTHREAD_LIBS := @PTHREAD_LIBS@ +PTYFUNCS_LIBS := @PTYFUNCS_LIBS@ + # Download GIT repositories via HTTP or GIT's own protocol? # GIT's protocol is faster and more robust, when it works at all (firewalls # may block it). We make it the default, but if your GIT repository downloads
tools/configure +57 -0
78 lines not on this page · raw message
tools/configure.ac +2 -0
@@ -36,6 +36,7 @@ m4_include([m4/uuid.m4]) m4_include([m4/pkg.m4]) m4_include([m4/curses.m4]) m4_include([m4/pthread.m4]) +m4_include([m4/ptyfuncs.m4]) # Enable/disable options AX_ARG_ENABLE_AND_EXPORT([githttp], [Download GIT repositories via HTTP])
@@ -126,6 +127,7 @@ AC_SUBST(libext2fs) AC_CHECK_LIB([gcrypt], [gcry_md_hash_buffer], [libgcrypt="y"], [libgcrypt="n"]) AC_SUBST(libgcrypt) AX_CHECK_PTHREAD +AX_CHECK_PTYFUNCS AC_CHECK_LIB([rt], [clock_gettime]) AC_CHECK_LIB([yajl], [yajl_alloc], [], [AC_MSG_ERROR([Could not find yajl])])
tools/libxl/Makefile +1 -1
@@ -20,7 +20,7 @@ LIBUUID_LIBS += -luuid endif LIBXL_LIBS = -LIBXL_LIBS = $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(LDLIBS_libxenstore) $(LDLIBS_libblktapctl) $(UTIL_LIBS) $(LIBUUID_LIBS) +LIBXL_LIBS = $(LDLIBS_libxenctrl) $(LDLIBS_libxenguest) $(LDLIBS_libxenstore) $(LDLIBS_libblktapctl) $(PTYFUNCS_LIBS) $(LIBUUID_LIBS) CFLAGS += $(PTHREAD_CFLAGS) LDFLAGS += $(PTHREAD_LDFLAGS)
tools/libxl/libxl_bootloader.c +4 -0
@@ -16,6 +16,10 @@#include <termios.h> +#ifdef INCLUDE_LIBUTIL_H +#include INCLUDE_LIBUTIL_H +#endif +#include "libxl_internal.h" #define XENCONSOLED_BUF_SIZE 16
tools/m4/ptyfuncs.m4 new file +24 -0
@@ -0,0 +1,24 @@ +AC_DEFUN([AX_CHECK_PTYFUNCS], [ + AC_CHECK_HEADER([libutil.h],[ + AC_DEFINE([INCLUDE_LIBUTIL_H],[<libutil.h>],[libutil header file name]) + ]) + AC_CACHE_CHECK([for openpty et al], [ax_cv_ptyfuncs_libs], [ + ax_cv_ptyfuncs_libs=-lutil + AX_SAVEVAR_SAVE(LIBS) + LIBS="$LIBS $ax_cv_ptyfuncs_libs" + AC_LINK_IFELSE([ +#ifdef INCLUDE_LIBUTIL_H +#include INCLUDE_LIBUTIL_H +#endif +int main(void) { + openpty(0,0,0,0,0); + login_tty(0); +} +]) + AX_SAVEVAR_RESTORE(LIBS)], + [],[ + AC_MSG_FAILURE([Unable to find -lutil for openpty and login_tty]) + ]) + PTYFUNCS_LIBS="$ax_cv_ptyfuncs_libs" + AC_SUBST(PTYFUNCS_LIBS) +])
Signature · 1 line
tg: (154e097..) t/xen/tools/ptyfuncs (depends on: t/xen/xl.event.children)
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
2012/3/21 Ian Jackson <[email protected]>:
Quoted 54 lines
Ian Jackson writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert
libxl_run_bootloader"):Quoted 11 lines
Ian Campbell writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert
libxl_run_bootloader"):Quoted 1 line
Could this stuff be usefully pushed into
libxl__openpty?Hmm. This is a bit of a can of worms I think. When I wrote my patch I left it well alone. TBH I think the current code is arguably wrong. I can see no reason why we would try to do termios operations on the pty master at all. I think these functions should be performed on the slave on all platforms.
But I don't want to introduce a perhaps-not-wonderfully-portable change like that in this series.
Just to be clear: I left all of this pty termios code alone in my series; it just shuffles about a bit but is otherwise unchanged as far as possible. The only intentional difference is that I replaced forkpty with our own fork + openpty +
login_tty.Quoted 9 lines
Quoted 3 lines
login_ttyis a new one to me. When I lookup up the manpage I happened to notice:
Link with -lutil.Hmm. The BSD manpage is more forthcoming and suggests we need something different there. (This isn't a particularly portable function.)
I think we need some more autoconfery.
Like the below. Previously libxl was linking with -lutil by virtue of using
UTIL_LIBSwhich came fromconfig/StdGNU.mk.Ian.
From: Ian Jackson <[email protected]>
Subject: [PATCH] autoconf: New test for openpty et al.We may need to #include <
libutil.h>, and/or link with -lutil, to use openpty,login_tty, and the like. ProvideINCLUDE_LIBUTIL_H(preprocessor constant, not always defined) andPTYFUNCS_LIBS(makefile variable).We link libxl against
PTYFUNCS_LIBS(which comes from autoconf) rather thanUTIL_LIBS, and #include <libutil.h> where appropriate.Signed-off-by Ian Jackson <[email protected]>---
config/Tools.mk.in | 2 +
tools/configure | 57 ++++++++++++++++++++++++++++++++++++++++tools/configure.ac| 2 +
tools/libxl/Makefile | 2 +-tools/libxl/libxl_bootloader.c| 4 +++
tools/m4/ptyfuncs.m4 | 24 +++++++++++++++++6 files changed, 90 insertions(+), 1 deletions(-)
[...]
Quoted 8 lines
tools/m4/ptyfuncs.m4 new file +2
-0@@ -0,0 +1,24 @@ +AC_DEFUN([AX_CHECK_PTYFUNCS], [ + AC_CHECK_HEADER([libutil.h],[
tools/m4/ptyfuncs.m4 line 12
Quoted 10 lines
tools/m4/ptyfuncs.m4 new file +10
-0+ AC_DEFINE([INCLUDE_LIBUTIL_H],[<libutil.h>],[libutil header file name]) + ]) + AC_CACHE_CHECK([for openpty et al], [ax_cv_ptyfuncs_libs], [ + ax_cv_ptyfuncs_libs=-lutil + AX_SAVEVAR_SAVE(LIBS) + LIBS="$LIBS $ax_cv_ptyfuncs_libs" + AC_LINK_IFELSE([ +#ifdef INCLUDE_LIBUTIL_H +#include INCLUDE_LIBUTIL_H +#endif
Shouldn't you add something like this (or perhaps add the necessary AC_CHECK_HEADER for this headers, so we can get rid of the OS conditional include dependency):
#if defined(__NetBSD__) || defined(__OpenBSD__)
#include <util.h>
#elif defined(__linux__)
#include <pty.h>
#elif defined(__sun__)
#include <stropts.h>
#endif
#include <utmp.h>
Quoted 15 lines
tools/m4/ptyfuncs.m4 new file +12
-1+int main(void) { + openpty(0,0,0,0,0); + login_tty(0); +} +]) + AX_SAVEVAR_RESTORE(LIBS)], + [],[ + AC_MSG_FAILURE([Unable to find -lutil for openpty and login_tty]) + ]) + PTYFUNCS_LIBS="$ax_cv_ptyfuncs_libs" + AC_SUBST(PTYFUNCS_LIBS) +]) --tg: (154e097..) t/xen/tools/ptyfuncs (depends on: t/xen/xl.event.children)
Quoted 4 lines
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader"):
Quoted 3 lines
Quoted 3 lines
+ AC_CHECK_HEADER([libutil.h],[
+ AC_DEFINE([INCLUDE_LIBUTIL_H],[<libutil.h>],[libutil header file name])
+ ])
...
Quoted 4 lines
Shouldn't you add something like this (or perhaps add the necessary
AC_CHECK_HEADERfor this headers, so we can get rid of the OS conditional include dependency):
Quoted 8 lines
#if
defined(__NetBSD__)||defined(__OpenBSD__)
#include <util.h>
#elifdefined(__linux__)
#include <pty.h>
#elifdefined(__sun__)
#include <stropts.h>
#endif
#include <utmp.h>
No, I don't think so. Currently the only two platforms we really support are *BSD and Linux, and I think what I have (include <libutil.h> if it exists, and nothing non-portable otherwise) is correct.
Does this test not work on *BSD ?
Certainly we don't want these kind of os-specific #ifdefs. If there are multiple possible headers we should call AC_CHECK_HEADER for them.
Ian.
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
2012/3/22 Ian Jackson <[email protected]>:
Quoted 18 lines
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert
libxl_run_bootloader"):Quoted 3 lines
Quoted 3 lines
+ AC_CHECK_HEADER([libutil.h],[
+ AC_DEFINE([INCLUDE_LIBUTIL_H],[<libutil.h>],[libutil header file name])
+ ])...
Quoted 4 lines
Shouldn't you add something like this (or perhaps add the necessary
AC_CHECK_HEADERfor this headers, so we can get rid of the OS conditional include dependency):Quoted 8 lines
#if
defined(__NetBSD__)||defined(__OpenBSD__)
#include <util.h>
#elifdefined(__linux__)
#include <pty.h>
#elifdefined(__sun__)
#include <stropts.h>
#endif
#include <utmp.h>
Quoted 6 lines
No, I don't think so. Currently the only two platforms we really support are *BSD and Linux, and I think what I have (include <
libutil.h> if it exists, and nothing non-portable otherwise) is correct.Does this test not work on *BSD ?
I haven't tried yet, in fact I have not tried this patch, it's just that the manpage states that on NetBSD at least you have to include util.h, it doesn't mention libutil.h.
http://netbsd.gw.com/cgi-bin/man-cgi?forkpty++NetBSD-current
And the linux man page states that pty.h and utmp.h
(http://linux.die.net/man/3/forkpty) should be included to use this functions under Linux, but I think you have that covered. Anyway, those includes are inside libxl_osdeps.h, so if they are not necessary we should get rid of them, or add the necessary autoconf stuff to handle that without all the OS conditionals.
Quoted 4 lines
Certainly we don't want these kind of os-specific #ifdefs. If there are multiple possible headers we should call
AC_CHECK_HEADERfor them.Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
In reply to Ian Jackson2012/3/16 Ian Jackson <[email protected]>:
Quoted 24 lines
Convert
libxl_run_bootloaderto an ao_how-taking function.It's implemented in terms of
libxl__bootloader_run, which can be used internally. The resulting code is pretty much a rewrite.Significant changes include:
- We provide and use a new asynchronous internal facility for pty creation, which runs openpty in a child for SIGCHLD etc. safety (see the comment at the top of
libxl__openptys).- We direct the bootloader's results to a file, not a pipe. This makes it simpler to deal with as we don't have to read it concurrently along with everything else.
- We now issue a warning if we find unexpected statements in the bootloader results.
- The arrangements for buffering of bootloader input and output are completely changed. Now we have a fixed limit of 64k on output, and 4k on input, and discard the oldest data when this overflows (which it shouldn't). There is no timeout any more.
Quoted 4 lines
- This is implemented using a new asynchronous internal data- copying facility.
Signed-off-by Ian Jackson <[email protected]>
I'm getting the following error when trying to launch DomUs using this patch:
Parsing config file debian.cfg
libxl: debug: libxl_device.c:183:libxl__device_disk_set_backend: Disk vdev=xvda spec.backend=unknown
libxl: debug: libxl_device.c:137:disk_try_backend: Disk vdev=xvda, backend phy unsuitable as phys path not a block device
libxl: debug: libxl_device.c:144:disk_try_backend: Disk vdev=xvda, backend tap unsuitable because blktap not available
libxl: debug: libxl_device.c:219:libxl__device_disk_set_backend: Disk vdev=xvda, using backend qdisk
libxl: debug: libxl_device.c:183:libxl__device_disk_set_backend: Disk vdev=xvda spec.backend=qdisk
libxl: debug: libxl.c:1732:libxl_device_disk_local_attach: locally attaching qdisk /root/vm/disk.img
libxl: error: libxl_utils.c:564:libxl__recvmsg_fds: recvmsg failed (ptys): Bad file descriptor
libxl: error: libxl_exec.c:124:libxl_report_child_exitstatus: openpty child [1598] died due to fatal signal Broken pipe
libxl: error: libxl_create.c:570:do_domain_create: failed to run bootloader: -3
xc: debug: hypercall buffer: total allocations:21 total releases:21
xc: debug: hypercall buffer: current allocations:0 maximum allocations:2
xc: debug: hypercall buffer: cache current size:2
xc: debug: hypercall buffer: cache hits:18 misses:2 toobig:1
I haven't tackled down the issue yet, but bisection says it is caused by this patch.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader
Roger Pau Monné writes ("Re: [Xen-devel] [PATCH 20/20] libxl: ao: Convert libxl_run_bootloader"):
Quoted 1 line
I'm getting the following error when trying to launch DomUs using this patch:
Thanks for the report. You're very brave :-). I hadn't executed it myself.
Quoted 10 lines
libxl: error: libxl_utils.c:564:libxl__recvmsg_fds: recvmsg failed (ptys): Bad file descriptor
libxl: error: libxl_exec.c:124:libxl_report_child_exitstatus: openpty child [1598] died due to fatal signal Broken pipe
libxl: error: libxl_create.c:570:do_domain_create: failed to run bootloader: -3
xc: debug: hypercall buffer: total allocations:21 total releases:21
xc: debug: hypercall buffer: current allocations:0 maximum allocations:2
xc: debug: hypercall buffer: cache current size:2
xc: debug: hypercall buffer: cache hits:18 misses:2 toobig:1
Quoted 2 lines
I haven't tackled down the issue yet, but bisection says it is caused by this patch.
I'm sure you have better things to do than debug up my untested patches...
Ian.