/* 
 * Copyright 2010 Stefan Lankes, Chair for Operating Systems,
 *                               RWTH Aachen University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file is part of MetalSVM. 
 */

#include <metalsvm/stddef.h>
#include <metalsvm/stdio.h>
#include <metalsvm/time.h>
#include <metalsvm/tasks.h>
#include <metalsvm/semaphore.h>
#include <metalsvm/mailbox.h>
#include <metalsvm/syscall.h>

static sem_t 		consuming, producing;
static mailbox_int32_t	mbox;
static int 		val = 0;

static int STDCALL consumer(void* arg)
{
	int 	i, m = 0;

	for(i=0; i<5; i++) {
		sem_wait(&consuming);
                kprintf("Consumer got %d\n", val);
                val = 0;
                sem_post(&producing);
        }

	for(i=0; i<5; i++) {
		mailbox_int32_fetch(&mbox, &m);
		kprintf("Got mail %d\n", m);
	}

	return 0;
}

static int STDCALL producer(void* arg)
{
	int 	i;
	int 	mail[5] = {1, 2, 3, 4, 5};

	for(i=0; i<5; i++) {
		sem_wait(&producing);
		kprintf("Produce value: current val %d\n", val);
		val = 42;
		sem_post(&consuming);
	}

	for(i=0; i<5; i++) {
		//kprintf("Send mail %d\n", mail[i]);
		mailbox_int32_post(&mbox, mail[i]);
	}

	return 0;
}

static int STDCALL foo(void* arg)
{
	int i;

	if (!arg)
		return 0;

	for(i=0; i<5; i++) {
		kputs((char*) arg);
		sleep(1);
	}

	return 42;
}

static int STDCALL join_test(void* arg)
{
	tid_t 	id, ret;
	int 	result = -1234;

	create_kernel_task(&id, foo, "Hello from foo2\n");

	kprintf("Wait for child %u\n", id);
	do {
		ret = wait(&result);
	} while(ret != id);

	kprintf("Child %u finished: result = %d\n", id, result);

	return 0;
}

int test_init(void)
{
	char* argv[] = {"/bin/tests", NULL};

	sem_init(&producing, 1);
	sem_init(&consuming, 0);
	mailbox_int32_init(&mbox);

	create_kernel_task(NULL, foo, "Hello from foo1\n");
	//create_kernel_task(NULL, join_test, NULL);
	//create_kernel_task(NULL, producer, NULL);
	//create_kernel_task(NULL, consumer, NULL);
	//create_user_task(NULL, "/bin/hello", argv);
	create_user_task(NULL, "/bin/tests", argv);

	return 0;
}