/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program 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.

**********************************************************************/


#include	"task.h"
#include	"gbview.h"
#include	"lock_level.h"
#include	"pri_level.h"

SEM	om_lock;
int obj_mem_size;
void om_task();

void
init_obj_memory()
{
	om_lock = new_lock(LL_OBJ_MEM);
	create_task(om_task,0,PRI_FETCH);
}

void
touch_obj_mem(int size)
{
	lock_task(om_lock);
	obj_mem_size += size;
	if ( obj_mem_size < 0 )
		er_panic("touch_obj_mem");
	unlock_task(om_lock,"touch_obj_mem");
}

int
print_mem_size()
{
	printf("obj_mem_size = %i\n",obj_mem_size);
	return 0;
}

void
om_task()
{
int ac_dm,ac_tc;
int dm_ret,tc_ret;
unsigned int max,min,m;
int cnt;
	cnt = 0;
	for ( ; ; ) {
		if ( cnt == 0 || cnt >= 20 ) {
			m = get_mem_size();
			if ( m > 256*1024*1024 )
				m = 256*1024*1024;
			max = (m - 25*1024*1024)/2;
			min = (m - 25*1024*1024)/3;
			cnt = 0;
		}
		sleep_sec(1);
		cnt ++;
		if ( obj_mem_size < max )
			continue;
		for ( ; obj_mem_size > min ; ) {
			dm_ret = dm_last_access(&ac_dm);
			tc_ret = tc_last_access(&ac_tc);

printf("dm (%i %i) (%i %i)\n",dm_ret,ac_dm,tc_ret,ac_tc);

			if ( dm_ret == -1 && tc_ret == -1 )
				break;
			if ( dm_ret == -1 ) {
				tc_gc_obj();
			}
			else if ( tc_ret == -1 ) {
				dm_gc_obj();
			}
			else if ( cmp_access(ac_dm,ac_tc) < 0 ) {
				dm_gc_obj();
			}
			else {
				tc_gc_obj();
			}
		}
	}
}
