/* @(#)xdelay.c	1.9 00/05/07 Copyright 1991 J. Schilling */
#ifndef lint
static	char sccsid[] =
	"@(#)xdelay.c	1.9 00/05/07 Copyright 1991 J. Schilling";
#endif
/*
 *	Delay for disks that cannot disconnect
 *
 *	Copyright (c) 1991 J. Schilling
 */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ifdef	sun

#include <mconfig.h>
#include <unixstd.h>
#include <kvm.h>
#include <fctldefs.h>
#include <nlist.h>
#include <sys/param.h>
#include <standard.h>
#include <schily.h>

#ifdef	FMT
#include "fmt.h"
#endif

static int initialized;
static kvm_t *kd;

static long avenrun[3];

struct nlist nl[] = {
#ifdef	SVR4
	{ "avenrun"},
#else
	{ "_avenrun"},
#endif
	{ 0 }, 
} ;

LOCAL	void	xinit	__PR((void));
EXPORT	void	xdelay	__PR((void));

LOCAL void
xinit()
{
	initialized = 1;

	kd = kvm_open(0, 0, 0, O_RDONLY, 0);
	if (!kd) return;

	kvm_nlist(kd, nl);
	if (nl[0].n_type==0) {
		kvm_close(kd);
		kd = 0;
		return;
	}
/*	printf("avenrun: %X\n", nl[0].n_value);*/
}

EXPORT void
xdelay()
{
	static long oavrun = 0;
	long avrun;
	long x;

	if (!initialized)
		xinit();
	if (!kd) {
		usleep(10000);
		return;
	}
	if (kvm_read(kd, nl[0].n_value, (char *)avenrun, sizeof(avenrun)) !=
		sizeof(avenrun) )
		errmsg("kvm_read\n");

/*	printf("\n%f %d\n", (double)avenrun[0]/FSCALE, avenrun[0]*1000/FSCALE);*/
	avrun = avenrun[0]*100/FSCALE;
	x = avrun - 95;
	x *= 4;
	if (x < 20) x = 20;
	printf("\r\t\tload %ld.%02ld wtime: %ld ms  \r",
						avrun/100, avrun%100, x);
	if (x > 2000) x = 2000;
	usleep(x*1000);
	if ((oavrun - avrun) > 10)
		usleep(100000);
	oavrun = avrun;
}

#else	/* sun */

#include <mconfig.h>
#include <unixstd.h>
#include <standard.h>

#include "fmt.h"

EXPORT	void	xdelay	__PR((void));

EXPORT void
xdelay()
{
	usleep(10000);
}
#endif	/* sun */
