/* 
 * 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/stdio.h>
#include <metalsvm/string.h>
#include <metalsvm/stdarg.h>
#include <metalsvm/tasks.h>
#include <metalsvm/semaphore.h>
#include <asm/atomic.h>
#ifdef CONFIG_VGA
#include <asm/vga.h>
#endif

static atomic_int32_t kmsg_counter = ATOMIC_INIT(0);
static unsigned char kmessages[KMSG_SIZE] = {[0 ... KMSG_SIZE-1] = 0};

#ifdef CONFIG_VGA
static sem_t sem_output = SEM_INIT(0); 

static int STDCALL output_task(void* arg)
{
	uint32_t rpos = 0;

	do {
		sem_wait(&sem_output);
		vga_putchar((int) kmessages[rpos]);
		rpos = (rpos + 1) % KMSG_SIZE;
	} while(1);

	return 0;
}
#endif

int koutput_init(void)
{
#ifdef CONFIG_VGA
	tid_t id;

	vga_init();
	create_kernel_task(&id, output_task, NULL);
#endif

	return 0;
}

int kputchar(int c)
{
	int pos;
	int ret = 1;

	pos = atomic_int32_inc(&kmsg_counter);
	kmessages[pos % KMSG_SIZE] = c;
#ifdef CONFIG_VGA
	sem_post(&sem_output);
#endif 

	return ret;
}

int kputs(const char *str)
{
	int pos;
	int i;

	for(i=0; str[i] != '\0'; i++) {
		pos = atomic_int32_inc(&kmsg_counter);
		kmessages[pos % KMSG_SIZE] = str[i];
#ifdef CONFIG_VGA
		sem_post(&sem_output);
#endif
	}

	return i;
}