/*
 *
 *  Embedded Linux library
 *
 *  Copyright (C) 2015  Intel Corporation. All rights reserved.
 *
 *  This library 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; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define _GNU_SOURCE
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/syscall.h>

#include "random.h"
#include "private.h"
#include "missing.h"

#ifndef GRND_NONBLOCK
#define GRND_NONBLOCK	0x0001
#endif

#ifndef GRND_RANDOM
#define GRND_RANDOM	0x0002
#endif

static inline int getrandom(void *buffer, size_t count, unsigned flags) {
        return syscall(__NR_getrandom, buffer, count, flags);
}

/**
 * l_getrandom:
 * @buf: buffer to fill with random data
 * @len: length of random data requested
 *
 * Request a number of randomly generated bytes given by @len and put them
 * into buffer @buf.
 *
 * Returns: true if the random data could be generated, false otherwise.
 **/
LIB_EXPORT bool l_getrandom(void *buf, size_t len)
{
	while (len) {
		int ret;

		ret = L_TFR(getrandom(buf, len, 0));
		if (ret < 0)
			return false;

		buf += ret;
		len -= ret;
	}

	return true;
}

LIB_EXPORT bool l_getrandom_is_supported()
{
	static bool initialized = false;
	static bool supported = true;
	uint8_t buf[4];
	int ret;

	if (initialized)
		return supported;

	ret = getrandom(buf, sizeof(buf), GRND_NONBLOCK);

	if (ret < 0 && errno == ENOSYS)
		supported = false;

	initialized = true;
	return supported;
}

LIB_EXPORT uint32_t l_getrandom_uint32(void)
{
	int ret;
	uint32_t u;

	ret = getrandom(&u, sizeof(u), GRND_NONBLOCK);

	if (ret == sizeof(u))
		return u;

        return random() * RAND_MAX + random();
}
