NetBSD/x68k 1.6L の clock.c 解説コーナー。
$Id: clock.c.html,v 1.8 2003/01/15 05:53:23 isaki Exp $

Inside X68000 そのままですが(汗)、 X68000 のタイマ割り込みのうち NetBSD/x68k に関係あるところだけ 抜き出すとこうなります。
        +------------+   +--------------+
4MHz -->| pre scaler |-->| 8bitカウンタ |---> タイマ割り込み
        | (TCDCR)    |   | (TCDR)       |
        +------------+   +--------------+
4MHz のクロックをまずプリスケーラで分周し、その 分周されたクロックが入るたびに8ビットカウンタを減算していき 0になればタイマ割り込みが発生するということになっているようです。 プリスケーラの分周値と8ビットカウンタの初期値は MFP の TCDCR, TCDR レジスタで指定します。
/*	$NetBSD: clock.c,v 1.15 2002/10/02 16:02:45 thorpej Exp $	*/

/*
 * Copyright (c) 1988 University of Utah.
 * Copyright (c) 1982, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * the Systems Programming Group of the University of Utah Computer
 * Science Department.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * from: Utah $Hdr: clock.c 1.18 91/01/21$
 *
 *	@(#)clock.c	8.2 (Berkeley) 1/12/94
 */

#include "clock.h"

#if NCLOCK > 0

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/device.h>

#include <machine/psl.h>
#include <machine/cpu.h>
#include <machine/bus.h>

#include <dev/clock_subr.h>

#include <arch/x68k/dev/mfp.h>
#include <arch/x68k/dev/rtclock_var.h>


struct clock_softc {
	struct device		sc_dev;
};

static int clock_match __P((struct device *, struct cfdata *, void *));
static void clock_attach __P((struct device *, struct device *, void *));

CFATTACH_DECL(clock, sizeof(struct clock_softc),
    clock_match, clock_attach, NULL, NULL);

static int
clock_match(parent, cf, aux)
	struct device *parent;
	struct cfdata *cf;
	void *aux;
{
	if (strcmp (aux, "clock") != 0)
		return (0);
	if (cf->cf_unit != 0)
		return (0);
	return 1;
}


static void
clock_attach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	printf (": MFP timer C\n");

	return;
}


/*
 * MFP of X68k uses 4MHz clock always and we use 1/200 prescaler here.
 * Therefore, clock interval is 50 usec.
 * NetBSD/x68k ではプリスケーラ(分周器)として常に 1/200 を指定している。
 * つまりクロックの分解能は 50 μ秒 (= CLK_RESOLUTION) となる。
 */
#define CLK_RESOLUTION	(50)
#define CLOCKS_PER_SEC	(1000000 / CLK_RESOLUTION)

static int clkint;		/* clock interval */

static int clkread __P((void));

/*
 * Machine-dependent clock routines.
 *
 * Startrtclock restarts the real-time clock, which provides
 * hardclock interrupts to kern_clock.c.
 *
 * Inittodr initializes the time of day hardware which provides
 * date functions.
 *
 * Resettodr restores the time of day hardware after a time change.
 *
 * A note on the real-time clock:
 * We actually load the clock with CLK_INTERVAL-1 instead of CLK_INTERVAL.
 * This is because the counter decrements to zero after N+1 enabled clock
 * periods where N is the value loaded into the counter.
 */

/*
 * Set up the real-time and statistics clocks.  Leave stathz 0 only if
 * no alternative timer is available.
 *
 */
void
cpu_initclocks()
{
	/*
	 * hz の正当性チェック。hz が CLOCKS_PER_SEC で割り切れなかったり
	 * 範囲外になるときは hz = 100 にしてしまう。
	 */
	if (CLOCKS_PER_SEC % hz ||
	    hz <= (CLOCKS_PER_SEC / 256) || hz > CLOCKS_PER_SEC) {
		printf("cannot set %d Hz clock. using 100 Hz\n", hz);
		hz = 100;
	}
	/*
	 * clkint は TCDR に指定する値。
	 * つまり 50 μ秒ごとのクロックを何回数えた時点で hz 割り込みを
	 * 上げるかを指定するもの。
	 * TCDR は 8ビットレジスタなので CLOCKS_PER_SEC (= 20000) を
	 * hz で割って出来る値には制限があり、hz = 79 〜 20000 の範囲しか
	 * 指定できない (実用上問題はないと思う...)。
	 * そのあたりのチェックはこの直前の if 文で行なってる。
	 */
	clkint = CLOCKS_PER_SEC / hz;

	/*
	 * 一旦 Timer C をとめてから設定する?
	 * プリスケーラを 1/200 ディレイモードに設定し...
	 */
	mfp_set_tcdcr(mfp_get_tcdcr() & 0x0f); /* stop timer C */
	mfp_set_tcdcr(mfp_get_tcdcr() | 0x70); /* 1/200 delay mode */

	/*
	 * TCDR に clkint を書き込んでから、再びタイマを有効にする。
	 */
	mfp_set_tcdr(clkint);
	mfp_bit_set_ierb(MFP_INTR_TIMER_C);
}

/*
 * We assume newhz is either stathz or profhz, and that neither will
 * change after being set up above.  Could recalculate intervals here
 * but that would be a drag.
 */
void
setstatclockrate(hz)
	int hz;
{
}

/*
 * Returns number of usec since last recorded clock "tick"
 * (i.e. clock interrupt).
 * 前回の clock tick からの経過時間をμ秒単位で返すらしい。
 */
int
clkread()
{
	/*
	 * TCDR を読めば現在のカウンタ値が読めるが、減算カウンタなので
	 * clkint (初期値) から引いてから、CLK_RESOLUTION を掛けて
	 * μ秒単位に直して返す。
	 *
	return (clkint - mfp_get_tcdr()) * CLK_RESOLUTION;
}


#if 0
void
DELAY(mic)
	int mic;
{
	u_long n;
	short hpos;

	/*
	 * busy-poll for mic microseconds. This is *no* general timeout function,
	 * it's meant for timing in hardware control, and as such, may not lower
	 * interrupt priorities to really `sleep'.
	 */

	/*
	 * this function uses HSync pulses as base units. The custom chips 
	 * display only deals with 31.6kHz/2 refresh, this gives us a
	 * resolution of 1/15800 s, which is ~63us (add some fuzz so we really
	 * wait awhile, even if using small timeouts)
	 */
	n = mic/32 + 2;
	do {
		while ((mfp.gpip & MFP_GPIP_HSYNC) != 0)
			asm("nop");
		while ((mfp.gpip & MFP_GPIP_HSYNC) == 0)
			asm("nop");
	} while (n--);
}
#endif


#if notyet

/* implement this later. I'd suggest using both timers in CIA-A, they're
   not yet used. */

/*
 * /dev/clock: mappable high resolution timer.
 *
 * This code implements a 32-bit recycling counter (with a 4 usec period)
 * using timers 2 & 3 on the 6840 clock chip.  The counter can be mapped
 * RO into a user's address space to achieve low overhead (no system calls),
 * high-precision timing.
 *
 * Note that timer 3 is also used for the high precision profiling timer
 * (PROFTIMER code above).  Care should be taken when both uses are
 * configured as only a token effort is made to avoid conflicting use.
 */
#include <sys/proc.h>
#include <sys/resourcevar.h>
#include <sys/ioctl.h>
#include <sys/malloc.h>
#include <uvm/uvm_extern.h>	/* XXX needed? */
#include <x68k/x68k/clockioctl.h>
#include <sys/specdev.h>
#include <sys/vnode.h>
#include <sys/mman.h>

int clockon = 0;		/* non-zero if high-res timer enabled */
#ifdef PROFTIMER
int  profprocs = 0;		/* # of procs using profiling timer */
#endif
#ifdef DEBUG
int clockdebug = 0;
#endif

/*ARGSUSED*/
clockopen(dev, flags)
	dev_t dev;
{
#ifdef PROFTIMER
#ifdef PROF
	/*
	 * Kernel profiling enabled, give up.
	 */
	if (profiling)
		return(EBUSY);
#endif	/* PROF */
	/*
	 * If any user processes are profiling, give up.
	 */
	if (profprocs)
		return(EBUSY);
#endif	/* PROFTIMER */
	if (!clockon) {
		startclock();
		clockon++;
	}
	return(0);
}

/*ARGSUSED*/
clockclose(dev, flags)
	dev_t dev;
{
	(void) clockunmmap(dev, (caddr_t)0, curproc);	/* XXX */
	stopclock();
	clockon = 0;
	return(0);
}

/*ARGSUSED*/
clockioctl(dev, cmd, data, flag, p)
	dev_t dev;
	caddr_t data;
	struct proc *p;
{
	int error = 0;
	
	switch (cmd) {

	case CLOCKMAP:
		error = clockmmap(dev, (caddr_t *)data, p);
		break;

	case CLOCKUNMAP:
		error = clockunmmap(dev, *(caddr_t *)data, p);
		break;

	case CLOCKGETRES:
		*(int *)data = CLK_RESOLUTION;
		break;

	default:
		error = EINVAL;
		break;
	}
	return(error);
}

/*ARGSUSED*/
clockmap(dev, off, prot)
	dev_t dev;
{
	return((off + (INTIOBASE+CLKBASE+CLKSR-1)) >> PGSHIFT);
}

clockmmap(dev, addrp, p)
	dev_t dev;
	caddr_t *addrp;
	struct proc *p;
{
	int error;
	struct vnode vn;
	struct specinfo si;
	int flags;

	flags = MAP_FILE|MAP_SHARED;
	if (*addrp)
		flags |= MAP_FIXED;
	else
		*addrp = (caddr_t)0x1000000;	/* XXX */
	vn.v_type = VCHR;			/* XXX */
	vn.v_specinfo = &si;			/* XXX */
	vn.v_rdev = dev;			/* XXX */
	error = vm_mmap(&p->p_vmspace->vm_map, (vaddr_t *)addrp,
			PAGE_SIZE, VM_PROT_ALL, flags, (caddr_t)&vn, 0);
	return(error);
}

clockunmmap(dev, addr, p)
	dev_t dev;
	caddr_t addr;
	struct proc *p;
{
	int rv;

	if (addr == 0)
		return(EINVAL);		/* XXX: how do we deal with this? */
	uvm_deallocate(p->p_vmspace->vm_map, (vaddr_t)addr, PAGE_SIZE);
	return 0;
}

startclock()
{
	register struct clkreg *clk = (struct clkreg *)clkstd[0];

	clk->clk_msb2 = -1; clk->clk_lsb2 = -1;
	clk->clk_msb3 = -1; clk->clk_lsb3 = -1;

	clk->clk_cr2 = CLK_CR3;
	clk->clk_cr3 = CLK_OENAB|CLK_8BIT;
	clk->clk_cr2 = CLK_CR1;
	clk->clk_cr1 = CLK_IENAB;
}

stopclock()
{
	register struct clkreg *clk = (struct clkreg *)clkstd[0];

	clk->clk_cr2 = CLK_CR3;
	clk->clk_cr3 = 0;
	clk->clk_cr2 = CLK_CR1;
	clk->clk_cr1 = CLK_IENAB;
}

#endif	/* notyet */


#ifdef PROFTIMER
/*
 * This code allows the amiga kernel to use one of the extra timers on
 * the clock chip for profiling, instead of the regular system timer.
 * The advantage of this is that the profiling timer can be turned up to
 * a higher interrupt rate, giving finer resolution timing. The profclock
 * routine is called from the lev6intr in locore, and is a specialized
 * routine that calls addupc. The overhead then is far less than if
 * hardclock/softclock was called. Further, the context switch code in
 * locore has been changed to turn the profile clock on/off when switching
 * into/out of a process that is profiling (startprofclock/stopprofclock).
 * This reduces the impact of the profiling clock on other users, and might
 * possibly increase the accuracy of the profiling. 
 */
int  profint   = PRF_INTERVAL;	/* Clock ticks between interrupts */
int  profscale = 0;		/* Scale factor from sys clock to prof clock */
char profon    = 0;		/* Is profiling clock on? */

/* profon values - do not change, locore.s assumes these values */
#define PRF_NONE	0x00
#define	PRF_USER	0x01
#define	PRF_KERNEL	0x80

initprofclock()
{
	struct proc *p = curproc;		/* XXX */

	/*
	 * If the high-res timer is running, force profiling off.
	 * Unfortunately, this gets reflected back to the user not as
	 * an error but as a lack of results.
	 */
	if (clockon) {
		p->p_stats->p_prof.pr_scale = 0;
		return;
	}
	/*
	 * Keep track of the number of user processes that are profiling
	 * by checking the scale value.
	 *
	 * XXX: this all assumes that the profiling code is well behaved;
	 * i.e. profil() is called once per process with pcscale non-zero
	 * to turn it on, and once with pcscale zero to turn it off.
	 * Also assumes you don't do any forks or execs.  Oh well, there
	 * is always adb...
	 */
	if (p->p_stats->p_prof.pr_scale)
		profprocs++;
	else
		profprocs--;
	/*
	 * The profile interrupt interval must be an even divisor
	 * of the CLK_INTERVAL so that scaling from a system clock
	 * tick to a profile clock tick is possible using integer math.
	 */
	if (profint > CLK_INTERVAL || (CLK_INTERVAL % profint) != 0)
		profint = CLK_INTERVAL;
	profscale = CLK_INTERVAL / profint;
}

startprofclock()
{
}

stopprofclock()
{
}

#ifdef PROF
/*
 * profclock() is expanded in line in lev6intr() unless profiling kernel.
 * Assumes it is called with clock interrupts blocked.
 */
profclock(pc, ps)
	caddr_t pc;
	int ps;
{
	/*
	 * Came from user mode.
	 * If this process is being profiled record the tick.
	 */
	if (USERMODE(ps)) {
		if (p->p_stats.p_prof.pr_scale)
			addupc(pc, &curproc->p_stats.p_prof, 1);
	}
	/*
	 * Came from kernel (supervisor) mode.
	 * If we are profiling the kernel, record the tick.
	 */
	else if (profiling < 2) {
		register int s = pc - s_lowpc;

		if (s < s_textsize)
			kcount[s / (HISTFRACTION * sizeof (*kcount))]++;
	}
	/*
	 * Kernel profiling was on but has been disabled.
	 * Mark as no longer profiling kernel and if all profiling done,
	 * disable the clock.
	 */
	if (profiling && (profon & PRF_KERNEL)) {
		profon &= ~PRF_KERNEL;
		if (profon == PRF_NONE)
			stopprofclock();
	}
}
#endif	/* PROF */
#endif	/* PROFTIMER */

/*
 * Return the best possible estimate of the current time.
 */
void
microtime(tvp)
	register struct timeval *tvp;
{
	static struct timeval lasttime;

	*tvp = time;
	tvp->tv_usec += clkread();
	while (tvp->tv_usec >= 1000000) {
		tvp->tv_sec++;
		tvp->tv_usec -= 1000000;
	}
	if (tvp->tv_sec == lasttime.tv_sec &&
	    tvp->tv_usec <= lasttime.tv_usec &&
	    (tvp->tv_usec = lasttime.tv_usec + 1) >= 1000000) {
		tvp->tv_sec++;
		tvp->tv_usec -= 1000000;
	}
	lasttime = *tvp;
}

/* this is a hook set by a clock driver for the configured realtime clock,
   returning plain current unix-time */
time_t (*gettod) __P((void)) = 0;
int    (*settod) __P((long)) = 0;

/*
 * Initialize the time of day register, based on the time base which is, e.g.
 * from a filesystem.
 * ファイルシステムとかの base time とかを元に time of day レジスタを
 * 初期化する。?
 *
 * xxx_mountroot (各ルートファイルシステムをマウントする処理) から
 * 呼ばれる。引数 base はそのルートファイルシステムに格納されている(最後に
 * umount した?) 時間。内蔵時計が有効かどうかを調べ有効ならそれで初期化。
 * 有効でなければ仕方ないので前回 umount した時間を現在時刻として初期化する。
 */
void
inittodr(base)
	time_t base;
{
	/*
	 * まずは内蔵時計が使えないものと仮定した初期値 (前回 umount
	 * された時間) を入れておく
	 */
	u_long timbuf = base;	/* assume no battery clock exists */
  
	/*
	 * gettod() が定義されてなければ内蔵時計の時刻は取得できないので
	 * warning を表示。gettod() が定義されてればそれを呼び出して内蔵
	 * 時計の時刻を得る。
	 * gettod() (と settod()) は dev/rtclock.c が rtc0 をアタッチする
	 * 時に RTC にアクセス可能なことを確認してからセットされる。
	 */
	if (!gettod)
		/* RTC にアクセスできなかった */
		printf ("WARNING: no battery clock\n");
	else
		/* RTC から現在時刻を取得 */
		timbuf = gettod();
  
	/*
	 * 今の時刻(timbuf)が、前回 umount された時刻(base)より古いはずは
	 * ないので、そのような状況になれば warning を表示して、現在時刻を
	 * 新しい方である base (前回 umount された時刻) に合わせる。
	 */
	if (timbuf < base) {
		printf ("WARNING: bad date in battery clock\n");
		timbuf = base;
	}
	/*
	 * 5 * SECYR は5年を秒数に直したもので、時刻は 1970年から始まる。
	 * つまり、最後に umount された時刻 base が 1975 年以前を示して
	 * いれば、そんな訳はないので warning を表示して現在時刻を適当に
	 * でっちあげて 1976/07/04 12:00:00 GMT としておく。
	 * XXX ここでやっても、なんか意味ないような...
	 */
	if (base < 5*SECYR) {
		printf("WARNING: preposterous time in file system");
		timbuf = 6*SECYR + 186*SECDAY + SECDAY/2;
		printf(" -- CHECK AND RESET THE DATE!\n");
	}

	/* Battery clock does not store usec's, so forget about it. */
	/*
	 * 結果を大域変数 time に格納。内蔵時計には秒以下の分解能はない
	 * ので tv_usec のことは気にしなくてよい。
	 */
	time.tv_sec = timbuf;
}

void
resettodr()
{
	if (settod)
		if (settod (time.tv_sec) != 1)
			printf("Cannot set battery backed clock\n");
}
#else	/* NCLOCK */
/* NCLOCK は必須なので、なければコンパイルさせない */
#error loose.
#endif

井崎のホームページへ戻る
isaki@NetBSD.org / isaki@x68k.net