/*
 * sys_gettimeofday: get current time
 * 
 * Copyright (c) 2015 UPMC Sorbonne Universites
 *
 * This file is part of ALMOS-kernel.
 *
 * ALMOS-kernel is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2.0 of the License.
 *
 * ALMOS-kernel 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ALMOS-kernel; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <cpu.h>
#include <thread.h>
#include <time.h>

int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
{
	error_t err;
	uint_t tm_ms, tm_us;
	struct timeval time;

	if((tv == NULL) || NOT_IN_USPACE(tv) || NOT_IN_USPACE(tv+sizeof(*tv)))
	{
		err = EINVAL;
		goto fail_inval;
	}

	if(tz) 
		return ENOTSUPPORTED;

	cpu_get_time(current_cpu, &tm_ms, &tm_us);
	time.tv_sec = tm_ms/1000;
	time.tv_usec = ((tm_ms%1000)*1000)+tm_us;

	//printk(INFO, "%s: [%d] (%u ms) sec %u, usec %u\n", __FUNCTION__, 
	//current_cpu->gid, tm_ms, (uint32_t)time.tv_sec, (uint32_t)time.tv_usec);

	err    = cpu_copy_to_uspace(tv, &time, sizeof(time));

fail_inval:
	current_thread->info.errno = err;
	return err; 
}
