shared: add nm_utils_getpagesize() and use it in netlink code

Since we already cached the result of getpagesize() in a static variable (at
two places), move the code to nm-shared-utils, so it is reusable.

Also, use sysconf() instead of getpagesize(), like suggested by `man
getpagesize`.
This commit is contained in:
Thomas Haller
2018-12-23 13:51:21 +01:00
parent 6ae04654f7
commit aab3e14883
3 changed files with 39 additions and 20 deletions

View File

@@ -2285,3 +2285,35 @@ nm_utils_invoke_on_idle (NMUtilsInvokeOnIdleCallback callback,
data->cancelled_id = 0;
data->idle_id = g_idle_add (_nm_utils_invoke_on_idle_cb_idle, data);
}
/*****************************************************************************/
int
nm_utils_getpagesize (void)
{
static volatile int val = 0;
long l;
int v;
v = g_atomic_int_get (&val);
if (G_UNLIKELY (v == 0)) {
l = sysconf (_SC_PAGESIZE);
g_return_val_if_fail (l > 0 && l < G_MAXINT, 4*1024);
v = (int) l;
if (!g_atomic_int_compare_and_exchange (&val, 0, v)) {
v = g_atomic_int_get (&val);
g_return_val_if_fail (v > 0, 4*1024);
}
}
nm_assert (v > 0);
#if NM_MORE_ASSERTS > 5
nm_assert (v == getpagesize ());
nm_assert (v == sysconf (_SC_PAGESIZE));
#endif
return v;
}

View File

@@ -1086,4 +1086,8 @@ nm_strv_ptrarray_take_gstring (GPtrArray *cmd,
FALSE));
}
/*****************************************************************************/
int nm_utils_getpagesize (void);
#endif /* __NM_SHARED_UTILS_H__ */

View File

@@ -255,20 +255,6 @@ nla_reserve (struct nl_msg *msg, int attrtype, int attrlen)
/*****************************************************************************/
static int
get_default_page_size (void)
{
static int val = 0;
int v;
if (G_UNLIKELY (val == 0)) {
v = getpagesize ();
g_assert (v > 0);
val = v;
}
return val;
}
struct nl_msg *
nlmsg_alloc_size (size_t len)
{
@@ -298,7 +284,7 @@ nlmsg_alloc_size (size_t len)
struct nl_msg *
nlmsg_alloc (void)
{
return nlmsg_alloc_size (get_default_page_size ());
return nlmsg_alloc_size (nm_utils_getpagesize ());
}
struct nl_msg *
@@ -1334,7 +1320,6 @@ nl_recv (struct nl_sock *sk, struct sockaddr_nl *nla,
{
ssize_t n;
int flags = 0;
static int page_size = 0;
struct iovec iov;
struct msghdr msg = {
.msg_name = (void *) nla,
@@ -1354,10 +1339,8 @@ nl_recv (struct nl_sock *sk, struct sockaddr_nl *nla,
&& sk->s_bufsize == 0))
flags |= MSG_PEEK | MSG_TRUNC;
if (page_size == 0)
page_size = getpagesize () * 4;
iov.iov_len = sk->s_bufsize ?: page_size;
iov.iov_len = sk->s_bufsize
?: (((size_t) nm_utils_getpagesize ()) * 4u);
iov.iov_base = g_malloc (iov.iov_len);
if ( creds