lib/utils.c: lazy initialize user_hz and psched_hz

Rather than initializing user_hz and psched_hz when libnl is loaded,
defer initialization of these variables to the first time they are used.
This has several advantages:

1) Avoids an unnecessary permission denied error on /proc/net/psched,
which can occur on systems where /proc/net isn't readable due to
security policy.
2) Allows program code to initialize the environment variables
PROC_NET_PSCHED and/or PROC_ROOT prior to the first libnl call, giving a
program more flexibility about where libnl should look.
3) Trivially faster startup time (although unlikely to be significant).
4) Compiler may be able to prove that the get_psched_settings() function
is unreachable and optimize appropriately, because the callers never
(directly or indirectly) use this method. This could occur, for
instance, in doing dead code elimination for programs which statically
link libnl.

Signed-off-by: Nick Kralevich <nnk@google.com>

https://github.com/thom311/libnl/pull/123
This commit is contained in:
Nick Kralevich 2017-01-14 11:11:34 -08:00 committed by Thomas Haller
parent faf9d9060f
commit 8e0ead4b5b

View File

@ -427,11 +427,15 @@ static double ticks_per_usec = 1.0f;
* Supports the environment variables:
* PROC_NET_PSCHED - may point to psched file in /proc
* PROC_ROOT - may point to /proc fs */
static void __init get_psched_settings(void)
static void get_psched_settings(void)
{
char name[FILENAME_MAX];
FILE *fd;
int got_hz = 0;
static int initialized = 0;
if (initialized == 1) {
return;
}
if (getenv("HZ")) {
long hz = strtol(getenv("HZ"), NULL, 0);
@ -480,6 +484,7 @@ static void __init get_psched_settings(void)
fclose(fd);
}
}
initialized = 1;
}
@ -488,6 +493,7 @@ static void __init get_psched_settings(void)
*/
int nl_get_user_hz(void)
{
get_psched_settings();
return user_hz;
}
@ -496,6 +502,7 @@ int nl_get_user_hz(void)
*/
int nl_get_psched_hz(void)
{
get_psched_settings();
return psched_hz;
}