/* 
 * 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/string.h>
#include <metalsvm/time.h>
#include <metalsvm/memory.h>
#include <metalsvm/tasks.h>
#include <metalsvm/processor.h>
#include <metalsvm/errno.h>
#include <metalsvm/init.h>
#include <metalsvm/fs.h>
#include <asm/irq.h>
#include <asm/irqflags.h>
#include <asm/page.h>
#include <asm/kb.h>
#ifdef CONFIG_ROCKCREEK
#include <asm/icc.h>
#include <asm/svm.h>
#endif

/* 
 * Note that linker symbols are not variables, they have no memory allocated for
 * maintaining a value, rather their address is their value.
 */
extern const void kernel_start;
extern const void kernel_end;
extern char __BUILD_DATE;
extern char __BUILD_TIME;

#if MAX_CORES > 1
// idle loop of the application processors
int smp_main(void)
{
	irq_enable();

#ifdef CONFIG_TICKLESS
	disable_timer_irq();
#endif

	while(1) {
		check_workqueues();
		HALT;
	}

	return 0;
}
#endif

int main(void)
{
	tid_t id;

	lowlevel_init();

	pushbg(COL_BLUE);
	kprintf("This is MetalSVM %s Build %u, %u\n", 
		METALSVM_VERSION, &__BUILD_DATE, &__BUILD_TIME);
	popbg();

	system_init();
	irq_init();
	timer_init();
#ifdef CONFIG_KEYBOARD
	keyboard_init();
#endif
	multitasking_init();
	mmu_init();
#ifdef CONFIG_ROCKCREEK
	icc_init();
	svm_init();
#endif
	initrd_init();

	irq_enable();

	kprintf("Kernel starts at %p and ends at %p\n", &kernel_start, &kernel_end);
	system_calibration();

	kprintf("Processor frequency: %u MHz\n", get_cpu_frequency());
	kprintf("Total memory: %u MBytes\n", atomic_int32_read(&total_pages)/((1024*1024)/PAGE_SIZE));
	kprintf("Current allocated memory: %u KBytes\n", atomic_int32_read(&total_allocated_pages)*(PAGE_SIZE/1024));
	kprintf("Current available memory: %u MBytes\n", atomic_int32_read(&total_available_pages)/((1024*1024)/PAGE_SIZE));

#ifdef CONFIG_TICKLESS
	disable_timer_irq();
#endif

	sleep(2);
	create_kernel_task(&id, initd, NULL, NORMAL_PRIO);
	kprintf("Create initd with id %u\n", id);

	reschedule();

	while(1) {
		check_workqueues(); 
		HALT;
	}

	return 0;
}