/**********************************************************************
 
	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	<unistd.h>
#include	<stdlib.h>
#include	<sys/resource.h>
#include	<sys/types.h>
#include	<sys/time.h>
#include	<sys/param.h>
#include	<procfs.h>
#include	"machine/fork_lock.h"
#include	"utils.h"
#include	"limits.h"


void
_print_rlim(int type)
{
int er;
struct rlimit r;
	er = getrlimit(type,&r);
	if ( er < 0 ) {
		fprintf(stderr,"%i\t",type);
		perror("");
	}
	else {
		fprintf(stderr,"%i :\t%i - %i\n",
			type,
			(int)r.rlim_cur,
			(int)r.rlim_max);
	}
}


/*
INTEGER64
_get_mem_size()
{
static unsigned int mem_size;
int p[2];
int id;
char buf[100];
char * ptr;
int er;
INTEGER64 ret;
struct rlimit rr;

	if ( mem_size )
		return mem_size;
	pipe(p);

	wlock_fork();

	id = fork();
	if ( id == 0 ) {
		close(1);
		dup(p[1]);
		close(p[0]);
		for ( id = 3 ; id <= sys_param.max_fd ; id ++ )
			close(id);
		system("prtconf | egrep Memory");
		exit(0);
	}

	wunlock_fork();

	close(p[1]);
	er = read(p[0],buf,100);
	close(p[0]);
	if ( er < 0 )
		return 100000000;
	buf[er] = 0;
	for ( ptr = buf ; *ptr ; ptr ++ )
		if ( '0' <= *ptr && *ptr <= '9' )
			break;
	ret = atoi(ptr);
	for ( ; *ptr && *ptr != ' ' ; ptr ++ );
	for ( ; *ptr && *ptr == ' ' ; ptr ++ );
	if ( strcmp(ptr,"Megabytes\n") == 0 )
		ret *= 1024*1024;
	else if ( strcmp(ptr,"Gigabytes\n") == 0 )
		ret *= 1024*1024*1024;
	getrlimit(RLIMIT_DATA,&rr);
	if ( rr.rlim_max && ret > (unsigned int)rr.rlim_max )
		ret = rr.rlim_max;
	mem_size = ret;
	return ret;
}
*/


INTEGER64
_get_mem_size()
{
static unsigned int mem_size;
INTEGER64 ret;
struct rlimit rr;
long map_size,map_nos;
	if ( mem_size )
		return mem_size;
	
	map_size = sysconf(_SC_PAGESIZE);
	map_nos = sysconf(_SC_PHYS_PAGES);
	ret = ((INTEGER64)map_size)*((INTEGER64)map_nos);
	getrlimit(RLIMIT_DATA,&rr);
	if ( rr.rlim_max && ret > (unsigned int)rr.rlim_max )
		ret = rr.rlim_max;
	mem_size = ret;
	return ret;
}

