code:
/*-
 * Copyright (c) 1982, 1988, 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * 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.
 * 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.
 *
 *	@(#)systm.h	8.7 (Berkeley) 3/29/95
 * $FreeBSD: release/9.0.0/sys/sys/systm.h 224307 2011-07-25 09:12:48Z avg $
 */

#ifndef _SYS_SYSTM_H_
#define	_SYS_SYSTM_H_

#include <machine/atomic.h>
#include <machine/cpufunc.h>
#include <sys/callout.h>
#include <sys/cdefs.h>
#include <sys/queue.h>
#include <sys/stdint.h>		/* for people using printf mainly */

extern int cold;		/* nonzero if we are doing a cold boot */
extern int rebooting;		/* kern_reboot() has been called. */
extern const char *panicstr;	/* panic message */
extern char version[];		/* system version */
extern char copyright[];	/* system copyright */
extern int kstack_pages;	/* number of kernel stack pages */

extern u_long pagesizes[];	/* supported page sizes */
extern long physmem;		/* physical memory */
extern long realmem;		/* 'real' memory */

extern char *rootdevnames[2];	/* names of possible root devices */

extern int boothowto;		/* reboot flags, from console subsystem */
extern int bootverbose;		/* nonzero to print verbose messages */

extern int maxusers;		/* system tune hint */
extern int ngroups_max;		/* max # of supplemental groups */
extern int vm_guest;		/* Running as virtual machine guest? */

/*
 * Detected virtual machine guest types. The intention is to expand
 * and/or add to the VM_GUEST_VM type if specific VM functionality is
 * ever implemented (e.g. vendor-specific paravirtualization features).
 */
enum VM_GUEST { VM_GUEST_NO = 0, VM_GUEST_VM, VM_GUEST_XEN };

#ifdef	INVARIANTS		/* The option is always available */
#define	KASSERT(exp,msg) do {						\
	if (__predict_false(!(exp)))					\
		panic msg;						\
} while (0)
#define	VNASSERT(exp, vp, msg) do {					\
	if (__predict_false(!(exp))) {					\
		vn_printf(vp, "VNASSERT failed\n");			\
		panic msg;						\
	}								\
} while (0)
#else
#define	KASSERT(exp,msg) do { \
} while (0)

#define	VNASSERT(exp, vp, msg) do { \
} while (0)
#endif

#ifndef CTASSERT		/* Allow lint to override */
#define	CTASSERT(x)		_CTASSERT(x, __LINE__)
#define	_CTASSERT(x, y)		__CTASSERT(x, y)
#define	__CTASSERT(x, y)	typedef char __assert ## y[(x) ? 1 : -1]
#endif

/*
 * Assert that a pointer can be loaded from memory atomically.
 *
 * This assertion enforces stronger alignment than necessary.  For example,
 * on some architectures, atomicity for unaligned loads will depend on
 * whether or not the load spans multiple cache lines.
 */
#define	ASSERT_ATOMIC_LOAD_PTR(var, msg)				\
	KASSERT(sizeof(var) == sizeof(void *) &&			\
	    ((uintptr_t)&(var) & (sizeof(void *) - 1)) == 0, msg)

/*
 * XXX the hints declarations are even more misplaced than most declarations
 * in this file, since they are needed in one file (per arch) and only used
 * in two files.
 * XXX most of these variables should be const.
 */
extern int osreldate;
extern int envmode;
extern int hintmode;		/* 0 = off. 1 = config, 2 = fallback */
extern int dynamic_kenv;
extern struct mtx kenv_lock;
extern char *kern_envp;
extern char static_env[];
extern char static_hints[];	/* by config for now */

extern char **kenvp;

extern const void *zero_region;	/* address space maps to a zeroed page	*/

/*
 * General function declarations.
 */

struct inpcb;
struct lock_object;
struct malloc_type;
struct mtx;
struct proc;
struct socket;
struct thread;
struct tty;
struct ucred;
struct uio;
struct _jmp_buf;
struct trapframe;

int	setjmp(struct _jmp_buf *);
void	longjmp(struct _jmp_buf *, int) __dead2;
int	dumpstatus(vm_offset_t addr, off_t count);
int	nullop(void);
int	eopnotsupp(void);
int	ureadc(int, struct uio *);
void	hashdestroy(void *, struct malloc_type *, u_long);
void	*hashinit(int count, struct malloc_type *type, u_long *hashmask);
void	*hashinit_flags(int count, struct malloc_type *type,
    u_long *hashmask, int flags);
#define	HASH_NOWAIT	0x00000001
#define	HASH_WAITOK	0x00000002

void	*phashinit(int count, struct malloc_type *type, u_long *nentries);
void	g_waitidle(void);

void	panic(const char *, ...) __dead2 __printflike(1, 2);

void	cpu_boot(int);
void	cpu_flush_dcache(void *, size_t);
void	cpu_rootconf(void);
void	critical_enter(void);
void	critical_exit(void);
void	init_param1(void);
void	init_param2(long physpages);
void	init_static_kenv(char *, size_t);
void	tablefull(const char *);
int	kvprintf(char const *, void (*)(int, void*), void *, int,
	    __va_list) __printflike(1, 0);
void	log(int, const char *, ...) __printflike(2, 3);
void	log_console(struct uio *);
int	printf(const char *, ...) __printflike(1, 2);
int	snprintf(char *, size_t, const char *, ...) __printflike(3, 4);
int	sprintf(char *buf, const char *, ...) __printflike(2, 3);
int	uprintf(const char *, ...) __printflike(1, 2);
int	vprintf(const char *, __va_list) __printflike(1, 0);
int	vsnprintf(char *, size_t, const char *, __va_list) __printflike(3, 0);
int	vsnrprintf(char *, size_t, int, const char *, __va_list) __printflike(4, 0);
int	vsprintf(char *buf, const char *, __va_list) __printflike(2, 0);
int	ttyprintf(struct tty *, const char *, ...) __printflike(2, 3);
int	sscanf(const char *, char const *, ...) __nonnull(1) __nonnull(2);
int	vsscanf(const char *, char const *, __va_list) __nonnull(1) __nonnull(2);
long	strtol(const char *, char **, int) __nonnull(1);
u_long	strtoul(const char *, char **, int) __nonnull(1);
quad_t	strtoq(const char *, char **, int) __nonnull(1);
u_quad_t strtouq(const char *, char **, int) __nonnull(1);
void	tprintf(struct proc *p, int pri, const char *, ...) __printflike(3, 4);
void	hexdump(const void *ptr, int length, const char *hdr, int flags);
#define	HD_COLUMN_MASK	0xff
#define	HD_DELIM_MASK	0xff00
#define	HD_OMIT_COUNT	(1 << 16)
#define	HD_OMIT_HEX	(1 << 17)
#define	HD_OMIT_CHARS	(1 << 18)

#define ovbcopy(f, t, l) bcopy((f), (t), (l))
void	bcopy(const void *from, void *to, size_t len) __nonnull(1) __nonnull(2);
void	bzero(void *buf, size_t len) __nonnull(1);

void	*memcpy(void *to, const void *from, size_t len) __nonnull(1) __nonnull(2);
void	*memmove(void *dest, const void *src, size_t n) __nonnull(1) __nonnull(2);

int	copystr(const void * __restrict kfaddr, void * __restrict kdaddr,
	    size_t len, size_t * __restrict lencopied)
	    __nonnull(1) __nonnull(2);
int	copyinstr(const void * __restrict udaddr, void * __restrict kaddr,
	    size_t len, size_t * __restrict lencopied)
	    __nonnull(1) __nonnull(2);
int	copyin(const void * __restrict udaddr, void * __restrict kaddr,
	    size_t len) __nonnull(1) __nonnull(2);
int	copyin_nofault(const void * __restrict udaddr, void * __restrict kaddr,
	    size_t len) __nonnull(1) __nonnull(2);
int	copyout(const void * __restrict kaddr, void * __restrict udaddr,
	    size_t len) __nonnull(1) __nonnull(2);
int	copyout_nofault(const void * __restrict kaddr, void * __restrict udaddr,
	    size_t len) __nonnull(1) __nonnull(2);

int	fubyte(const void *base);
long	fuword(const void *base);
int	fuword16(void *base);
int32_t	fuword32(const void *base);
int64_t	fuword64(const void *base);
int	subyte(void *base, int byte);
int	suword(void *base, long word);
int	suword16(void *base, int word);
int	suword32(void *base, int32_t word);
int	suword64(void *base, int64_t word);
uint32_t casuword32(volatile uint32_t *base, uint32_t oldval, uint32_t newval);
u_long	 casuword(volatile u_long *p, u_long oldval, u_long newval);

void	realitexpire(void *);

int	sysbeep(int hertz, int period);

void	hardclock(int usermode, uintfptr_t pc);
void	hardclock_anycpu(int cnt, int usermode);
void	hardclock_cpu(int usermode);
void	hardclock_sync(int cpu);
void	softclock(void *);
void	statclock(int usermode);
void	profclock(int usermode, uintfptr_t pc);

int	hardclockintr(void);

void	startprofclock(struct proc *);
void	stopprofclock(struct proc *);
void	cpu_startprofclock(void);
void	cpu_stopprofclock(void);
void	cpu_idleclock(void);
void	cpu_activeclock(void);
extern int	cpu_can_deep_sleep;
extern int	cpu_disable_deep_sleep;

int	cr_cansee(struct ucred *u1, struct ucred *u2);
int	cr_canseesocket(struct ucred *cred, struct socket *so);
int	cr_canseeinpcb(struct ucred *cred, struct inpcb *inp);

char	*getenv(const char *name);
void	freeenv(char *env);
int	getenv_int(const char *name, int *data);
int	getenv_uint(const char *name, unsigned int *data);
int	getenv_long(const char *name, long *data);
int	getenv_ulong(const char *name, unsigned long *data);
int	getenv_string(const char *name, char *data, int size);
int	getenv_quad(const char *name, quad_t *data);
int	setenv(const char *name, const char *value);
int	unsetenv(const char *name);
int	testenv(const char *name);

typedef uint64_t (cpu_tick_f)(void);
void set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var);
extern cpu_tick_f *cpu_ticks;
uint64_t cpu_tickrate(void);
uint64_t cputick2usec(uint64_t tick);

#ifdef APM_FIXUP_CALLTODO
struct timeval;
void	adjust_timeout_calltodo(struct timeval *time_change);
#endif /* APM_FIXUP_CALLTODO */

#include <sys/libkern.h>

/* Initialize the world */
void	consinit(void);
void	cpu_initclocks(void);
void	cpu_initclocks_bsp(void);
void	cpu_initclocks_ap(void);
void	usrinfoinit(void);

/* Finalize the world */
void	kern_reboot(int) __dead2;
void	shutdown_nice(int);

/* Timeouts */
typedef void timeout_t(void *);	/* timeout function type */
#define CALLOUT_HANDLE_INITIALIZER(handle)	\
	{ NULL }

void	callout_handle_init(struct callout_handle *);
struct	callout_handle timeout(timeout_t *, void *, int);
void	untimeout(timeout_t *, void *, struct callout_handle);
caddr_t	kern_timeout_callwheel_alloc(caddr_t v);
void	kern_timeout_callwheel_init(void);

/* Stubs for obsolete functions that used to be for interrupt management */
static __inline void		spl0(void)		{ return; }
static __inline intrmask_t	splbio(void)		{ return 0; }
static __inline intrmask_t	splcam(void)		{ return 0; }
static __inline intrmask_t	splclock(void)		{ return 0; }
static __inline intrmask_t	splhigh(void)		{ return 0; }
static __inline intrmask_t	splimp(void)		{ return 0; }
static __inline intrmask_t	splnet(void)		{ return 0; }
static __inline intrmask_t	splsoftcam(void)	{ return 0; }
static __inline intrmask_t	splsoftclock(void)	{ return 0; }
static __inline intrmask_t	splsofttty(void)	{ return 0; }
static __inline intrmask_t	splsoftvm(void)		{ return 0; }
static __inline intrmask_t	splsofttq(void)		{ return 0; }
static __inline intrmask_t	splstatclock(void)	{ return 0; }
static __inline intrmask_t	spltty(void)		{ return 0; }
static __inline intrmask_t	splvm(void)		{ return 0; }
static __inline void		splx(intrmask_t ipl __unused)	{ return; }

/*
 * Common `proc' functions are declared here so that proc.h can be included
 * less often.
 */
int	_sleep(void *chan, struct lock_object *lock, int pri, const char *wmesg,
	    int timo) __nonnull(1);
#define	msleep(chan, mtx, pri, wmesg, timo)				\
	_sleep((chan), &(mtx)->lock_object, (pri), (wmesg), (timo))
int	msleep_spin(void *chan, struct mtx *mtx, const char *wmesg, int timo)
	    __nonnull(1);
int	pause(const char *wmesg, int timo);
#define	tsleep(chan, pri, wmesg, timo)					\
	_sleep((chan), NULL, (pri), (wmesg), (timo))
void	wakeup(void *chan) __nonnull(1);
void	wakeup_one(void *chan) __nonnull(1);

/*
 * Common `struct cdev *' stuff are declared here to avoid #include poisoning
 */

struct cdev;
dev_t dev2udev(struct cdev *x);
const char *devtoname(struct cdev *cdev);

int poll_no_poll(int events);

/* XXX: Should be void nanodelay(u_int nsec); */
void	DELAY(int usec);

/* Root mount holdback API */
struct root_hold_token;

struct root_hold_token *root_mount_hold(const char *identifier);
void root_mount_rel(struct root_hold_token *h);
void root_mount_wait(void);
int root_mounted(void);

/*
 * Unit number allocation API. (kern/subr_unit.c)
 */
struct unrhdr;
struct unrhdr *new_unrhdr(int low, int high, struct mtx *mutex);
void delete_unrhdr(struct unrhdr *uh);
void clean_unrhdr(struct unrhdr *uh);
void clean_unrhdrl(struct unrhdr *uh);
int alloc_unr(struct unrhdr *uh);
int alloc_unr_specific(struct unrhdr *uh, u_int item);
int alloc_unrl(struct unrhdr *uh);
void free_unr(struct unrhdr *uh, u_int item);

/*
 * Population count algorithm using SWAR approach
 * - "SIMD Within A Register".
 */
static __inline uint32_t
bitcount32(uint32_t x)
{

	x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1);
	x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2);
	x = (x + (x >> 4)) & 0x0f0f0f0f;
	x = (x + (x >> 8));
	x = (x + (x >> 16)) & 0x000000ff;
	return (x);
}

static __inline uint16_t
bitcount16(uint32_t x)
{

	x = (x & 0x5555) + ((x & 0xaaaa) >> 1);
	x = (x & 0x3333) + ((x & 0xcccc) >> 2);
	x = (x + (x >> 4)) & 0x0f0f;
	x = (x + (x >> 8)) & 0x00ff;
	return (x);
}

#endif /* !_SYS_SYSTM_H_ */

repo_name: veiledmerc/mira

license: mit


code:
/*-
 * Copyright (c) 2000 Doug Rabson
 * All rights reserved.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 *
 * $FreeBSD: release/9.0.0/sys/sys/taskqueue.h 221059 2011-04-26 11:39:56Z kib $
 */

#ifndef _SYS_TASKQUEUE_H_
#define _SYS_TASKQUEUE_H_

#ifndef _KERNEL
#error "no user-servicable parts inside"
#endif

#include <sys/queue.h>
#include <sys/_task.h>
#include <sys/_callout.h>

struct taskqueue;
struct thread;

struct timeout_task {
	struct taskqueue *q;
	struct task t;
	struct callout c;
	int    f;
};

/*
 * A notification callback function which is called from
 * taskqueue_enqueue().  The context argument is given in the call to
 * taskqueue_create().  This function would normally be used to allow the
 * queue to arrange to run itself later (e.g., by scheduling a software
 * interrupt or waking a kernel thread).
 */
typedef void (*taskqueue_enqueue_fn)(void *context);

struct taskqueue *taskqueue_create(const char *name, int mflags,
				    taskqueue_enqueue_fn enqueue,
				    void *context);
int	taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
				const char *name, ...) __printflike(4, 5);
int	taskqueue_enqueue(struct taskqueue *queue, struct task *task);
int	taskqueue_enqueue_timeout(struct taskqueue *queue,
	    struct timeout_task *timeout_task, int ticks);
int	taskqueue_cancel(struct taskqueue *queue, struct task *task,
	    u_int *pendp);
int	taskqueue_cancel_timeout(struct taskqueue *queue,
	    struct timeout_task *timeout_task, u_int *pendp);
void	taskqueue_drain(struct taskqueue *queue, struct task *task);
void	taskqueue_drain_timeout(struct taskqueue *queue,
	    struct timeout_task *timeout_task);
void	taskqueue_free(struct taskqueue *queue);
void	taskqueue_run(struct taskqueue *queue);
void	taskqueue_block(struct taskqueue *queue);
void	taskqueue_unblock(struct taskqueue *queue);
int	taskqueue_member(struct taskqueue *queue, struct thread *td);

/*
 * Functions for dedicated thread taskqueues
 */
void	taskqueue_thread_loop(void *arg);
void	taskqueue_thread_enqueue(void *context);

/*
 * Initialise a task structure.
 */
#define TASK_INIT(task, priority, func, context) do {	\
	(task)->ta_pending = 0;				\
	(task)->ta_priority = (priority);		\
	(task)->ta_func = (func);			\
	(task)->ta_context = (context);			\
} while (0)

void _timeout_task_init(struct taskqueue *queue,
	    struct timeout_task *timeout_task, int priority, task_fn_t func,
	    void *context);
#define	TIMEOUT_TASK_INIT(queue, timeout_task, priority, func, context) \
	_timeout_task_init(queue, timeout_task, priority, func, context);

/*
 * Declare a reference to a taskqueue.
 */
#define TASKQUEUE_DECLARE(name)			\
extern struct taskqueue *taskqueue_##name

/*
 * Define and initialise a global taskqueue that uses sleep mutexes.
 */
#define TASKQUEUE_DEFINE(name, enqueue, context, init)			\
									\
struct taskqueue *taskqueue_##name;					\
									\
static void								\
taskqueue_define_##name(void *arg)					\
{									\
	taskqueue_##name =						\
	    taskqueue_create(#name, M_WAITOK, (enqueue), (context));	\
	init;								\
}									\
									\
SYSINIT(taskqueue_##name, SI_SUB_CONFIGURE, SI_ORDER_SECOND,		\
	taskqueue_define_##name, NULL);					\
									\
struct __hack
#define TASKQUEUE_DEFINE_THREAD(name)					\
TASKQUEUE_DEFINE(name, taskqueue_thread_enqueue, &taskqueue_##name,	\
	taskqueue_start_threads(&taskqueue_##name, 1, PWAIT,		\
	"%s taskq", #name))

/*
 * Define and initialise a global taskqueue that uses spin mutexes.
 */
#define TASKQUEUE_FAST_DEFINE(name, enqueue, context, init)		\
									\
struct taskqueue *taskqueue_##name;					\
									\
static void								\
taskqueue_define_##name(void *arg)					\
{									\
	taskqueue_##name =						\
	    taskqueue_create_fast(#name, M_WAITOK, (enqueue),		\
	    (context));							\
	init;								\
}									\
									\
SYSINIT(taskqueue_##name, SI_SUB_CONFIGURE, SI_ORDER_SECOND,		\
	taskqueue_define_##name, NULL);					\
									\
struct __hack
#define TASKQUEUE_FAST_DEFINE_THREAD(name)				\
TASKQUEUE_FAST_DEFINE(name, taskqueue_thread_enqueue,			\
	&taskqueue_##name, taskqueue_start_threads(&taskqueue_##name	\
	1, PWAIT, "%s taskq", #name))

/*
 * These queues are serviced by software interrupt handlers.  To enqueue
 * a task, call taskqueue_enqueue(taskqueue_swi, &task) or
 * taskqueue_enqueue(taskqueue_swi_giant, &task).
 */
TASKQUEUE_DECLARE(swi_giant);
TASKQUEUE_DECLARE(swi);

/*
 * This queue is serviced by a kernel thread.  To enqueue a task, call
 * taskqueue_enqueue(taskqueue_thread, &task).
 */
TASKQUEUE_DECLARE(thread);

/*
 * Queue for swi handlers dispatched from fast interrupt handlers.
 * These are necessarily different from the above because the queue
 * must be locked with spinlocks since sleep mutex's cannot be used
 * from a fast interrupt handler context.
 */
TASKQUEUE_DECLARE(fast);
int	taskqueue_enqueue_fast(struct taskqueue *queue, struct task *task);
struct taskqueue *taskqueue_create_fast(const char *name, int mflags,
				    taskqueue_enqueue_fn enqueue,
				    void *context);

#endif /* !_SYS_TASKQUEUE_H_ */


code:
/* $FreeBSD: release/9.0.0/sys/sys/termios.h 199898 2009-11-28 23:50:48Z ed $ */
#ifdef __GNUC__
#warning "this file includes <sys/termios.h> which is deprecated, use <termios.h> instead"
#endif
#include <termios.h>


code:
/*-
 * Copyright (c) 2003, Jeffrey Roberson <jeff@freebsd.org>
 * All rights reserved.
 *
 * 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 unmodified, 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 *
 * $FreeBSD: release/9.0.0/sys/sys/thr.h 206903 2010-04-20 17:57:43Z imp $
 *
 */

#ifndef _SYS_THR_H_
#define	_SYS_THR_H_

#include <sys/cdefs.h>
#include <sys/_types.h>
#include <sys/sched.h>

#ifndef _SIZE_T_DECLARED
typedef __size_t	size_t;
#define _SIZE_T_DECLARED
#endif

/* Create the thread in the suspended state. */
#define	THR_SUSPENDED		0x0001
/* Create the system scope thread. */
#define	THR_SYSTEM_SCOPE	0x0002

struct thr_param {
    void	(*start_func)(void *);	/* thread entry function. */
    void	*arg;			/* argument for entry function. */
    char	*stack_base;		/* stack base address. */
    size_t	stack_size;		/* stack size. */
    char	*tls_base;		/* tls base address. */
    size_t	tls_size;		/* tls size. */
    long	*child_tid;		/* address to store new TID. */
    long	*parent_tid;		/* parent accesses the new TID here. */
    int		flags;			/* thread flags. */
    struct rtprio	*rtp;		/* Real-time scheduling priority */
    void	*spare[3];		/* TODO: cpu affinity mask etc. */
};

/*
 * See pthread_*
 */
#ifndef _KERNEL
#include <sys/ucontext.h>

#ifndef _PID_T_DECLARED
typedef __pid_t		pid_t;
#define _PID_T_DECLARED
#endif

__BEGIN_DECLS
int thr_create(ucontext_t *ctx, long *id, int flags);
int thr_new(struct thr_param *param, int param_size);
int thr_self(long *id);
void thr_exit(long *state);
int thr_kill(long id, int sig);
int thr_kill2(pid_t pid, long id, int sig);
int thr_suspend(const struct timespec *timeout);
int thr_wake(long id);
int thr_set_name(long id, const char *name);
__END_DECLS
#endif /* !_KERNEL */

#endif /* ! _SYS_THR_H_ */


code:
/*-
 * Copyright (c) 1999, 2000 Kenneth D. Merry.
 * All rights reserved.
 *
 * 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,
 *    without modification, immediately at the beginning of the file.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 *
 *	$FreeBSD: release/9.0.0/sys/sys/tiio.h 98849 2002-06-26 03:37:47Z ken $
 */
/*
 * The ti_stats structure below is from code with the following copyright,
 * and originally comes from the Alteon firmware documentation.
 */
/*
 * Copyright (c) 1997, 1998, 1999
 *	Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
 *
 * 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 Bill Paul.
 * 4. Neither the name of the author nor the names of any co-contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Bill Paul 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 Bill Paul OR THE VOICES IN HIS HEAD
 * 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: if_tireg.h,v 1.8 1999/07/23 18:46:24 wpaul Exp $
 */

#ifndef _SYS_TIIO_H_
#define _SYS_TIIO_H_

#include <sys/ioccom.h>

/*
 * Tigon statistics counters.
 */
struct ti_stats {
	/*
	 * MAC stats, taken from RFC 1643, ethernet-like MIB
	 */
	volatile u_int32_t dot3StatsAlignmentErrors;		/* 0 */
	volatile u_int32_t dot3StatsFCSErrors;			/* 1 */
	volatile u_int32_t dot3StatsSingleCollisionFrames;	/* 2 */
	volatile u_int32_t dot3StatsMultipleCollisionFrames;	/* 3 */
	volatile u_int32_t dot3StatsSQETestErrors;		/* 4 */
	volatile u_int32_t dot3StatsDeferredTransmissions;	/* 5 */
	volatile u_int32_t dot3StatsLateCollisions;		/* 6 */
	volatile u_int32_t dot3StatsExcessiveCollisions;	/* 7 */
	volatile u_int32_t dot3StatsInternalMacTransmitErrors;	/* 8 */
	volatile u_int32_t dot3StatsCarrierSenseErrors;		/* 9 */
	volatile u_int32_t dot3StatsFrameTooLongs;		/* 10 */
	volatile u_int32_t dot3StatsInternalMacReceiveErrors;	/* 11 */
	/*
	 * interface stats, taken from RFC 1213, MIB-II, interfaces group
	 */
	volatile u_int32_t ifIndex;				/* 12 */
	volatile u_int32_t ifType;				/* 13 */
	volatile u_int32_t ifMtu;				/* 14 */
	volatile u_int32_t ifSpeed;				/* 15 */
	volatile u_int32_t ifAdminStatus;			/* 16 */
#define IF_ADMIN_STATUS_UP      1
#define IF_ADMIN_STATUS_DOWN    2
#define IF_ADMIN_STATUS_TESTING 3
	volatile u_int32_t ifOperStatus;			/* 17 */
#define IF_OPER_STATUS_UP       1
#define IF_OPER_STATUS_DOWN     2
#define IF_OPER_STATUS_TESTING  3
#define IF_OPER_STATUS_UNKNOWN  4
#define IF_OPER_STATUS_DORMANT  5
	volatile u_int32_t ifLastChange;			/* 18 */
	volatile u_int32_t ifInDiscards;			/* 19 */
	volatile u_int32_t ifInErrors;				/* 20 */
	volatile u_int32_t ifInUnknownProtos;			/* 21 */
	volatile u_int32_t ifOutDiscards;			/* 22 */
	volatile u_int32_t ifOutErrors;				/* 23 */
	volatile u_int32_t ifOutQLen;     /* deprecated */	/* 24 */
	volatile u_int8_t  ifPhysAddress[8]; /* 8 bytes */	/* 25 - 26 */
	volatile u_int8_t  ifDescr[32];				/* 27 - 34 */
	u_int32_t alignIt;      /* align to 64 bit for u_int64_ts following */
	/*
	 * more interface stats, taken from RFC 1573, MIB-IIupdate,
	 * interfaces group
	 */
	volatile u_int64_t ifHCInOctets;			/* 36 - 37 */
	volatile u_int64_t ifHCInUcastPkts;			/* 38 - 39 */
	volatile u_int64_t ifHCInMulticastPkts;			/* 40 - 41 */
	volatile u_int64_t ifHCInBroadcastPkts;			/* 42 - 43 */
	volatile u_int64_t ifHCOutOctets;			/* 44 - 45 */
	volatile u_int64_t ifHCOutUcastPkts;			/* 46 - 47 */
	volatile u_int64_t ifHCOutMulticastPkts;		/* 48 - 49 */
	volatile u_int64_t ifHCOutBroadcastPkts;		/* 50 - 51 */
	volatile u_int32_t ifLinkUpDownTrapEnable;		/* 52 */
	volatile u_int32_t ifHighSpeed;				/* 53 */
	volatile u_int32_t ifPromiscuousMode; 			/* 54 */
	volatile u_int32_t ifConnectorPresent; /* follow link state 55 */
	/*
	 * Host Commands
	 */
	volatile u_int32_t nicCmdsHostState;			/* 56 */
	volatile u_int32_t nicCmdsFDRFiltering;			/* 57 */
	volatile u_int32_t nicCmdsSetRecvProdIndex;		/* 58 */
	volatile u_int32_t nicCmdsUpdateGencommStats;		/* 59 */
	volatile u_int32_t nicCmdsResetJumboRing;		/* 60 */
	volatile u_int32_t nicCmdsAddMCastAddr;			/* 61 */
	volatile u_int32_t nicCmdsDelMCastAddr;			/* 62 */
	volatile u_int32_t nicCmdsSetPromiscMode;		/* 63 */
	volatile u_int32_t nicCmdsLinkNegotiate;		/* 64 */
	volatile u_int32_t nicCmdsSetMACAddr;			/* 65 */
	volatile u_int32_t nicCmdsClearProfile;			/* 66 */
	volatile u_int32_t nicCmdsSetMulticastMode;		/* 67 */
	volatile u_int32_t nicCmdsClearStats;			/* 68 */
	volatile u_int32_t nicCmdsSetRecvJumboProdIndex;	/* 69 */
	volatile u_int32_t nicCmdsSetRecvMiniProdIndex;		/* 70 */
	volatile u_int32_t nicCmdsRefreshStats;			/* 71 */
	volatile u_int32_t nicCmdsUnknown;			/* 72 */
	/*
	 * NIC Events
	 */
	volatile u_int32_t nicEventsNICFirmwareOperational;	/* 73 */
	volatile u_int32_t nicEventsStatsUpdated;		/* 74 */
	volatile u_int32_t nicEventsLinkStateChanged;		/* 75 */
	volatile u_int32_t nicEventsError;			/* 76 */
	volatile u_int32_t nicEventsMCastListUpdated;		/* 77 */
	volatile u_int32_t nicEventsResetJumboRing;		/* 78 */
	/*
	 * Ring manipulation
	 */
	volatile u_int32_t nicRingSetSendProdIndex;		/* 79 */
	volatile u_int32_t nicRingSetSendConsIndex;		/* 80 */
	volatile u_int32_t nicRingSetRecvReturnProdIndex;	/* 81 */
	/*
	 * Interrupts
	 */
	volatile u_int32_t nicInterrupts;			/* 82 */
	volatile u_int32_t nicAvoidedInterrupts;		/* 83 */
	/*
	 * BD Coalessing Thresholds
	 */
	volatile u_int32_t nicEventThresholdHit;		/* 84 */
	volatile u_int32_t nicSendThresholdHit;			/* 85 */
	volatile u_int32_t nicRecvThresholdHit;			/* 86 */
	/*
	 * DMA Attentions
	 */
	volatile u_int32_t nicDmaRdOverrun;			/* 87 */
	volatile u_int32_t nicDmaRdUnderrun;			/* 88 */
	volatile u_int32_t nicDmaWrOverrun;			/* 89 */
	volatile u_int32_t nicDmaWrUnderrun;			/* 90 */
	volatile u_int32_t nicDmaWrMasterAborts;		/* 91 */
	volatile u_int32_t nicDmaRdMasterAborts;		/* 92 */
	/*
	 * NIC Resources
	 */
	volatile u_int32_t nicDmaWriteRingFull;			/* 93 */
	volatile u_int32_t nicDmaReadRingFull;			/* 94 */
	volatile u_int32_t nicEventRingFull;			/* 95 */
	volatile u_int32_t nicEventProducerRingFull;		/* 96 */
	volatile u_int32_t nicTxMacDescrRingFull;		/* 97 */
	volatile u_int32_t nicOutOfTxBufSpaceFrameRetry;	/* 98 */
	volatile u_int32_t nicNoMoreWrDMADescriptors;		/* 99 */
	volatile u_int32_t nicNoMoreRxBDs;			/* 100 */
	volatile u_int32_t nicNoSpaceInReturnRing;		/* 101 */
	volatile u_int32_t nicSendBDs;            /* current count 102 */
	volatile u_int32_t nicRecvBDs;            /* current count 103 */
	volatile u_int32_t nicJumboRecvBDs;       /* current count 104 */
	volatile u_int32_t nicMiniRecvBDs;        /* current count 105 */
	volatile u_int32_t nicTotalRecvBDs;       /* current count 106 */
	volatile u_int32_t nicTotalSendBDs;       /* current count 107 */
	volatile u_int32_t nicJumboSpillOver;			/* 108 */
	volatile u_int32_t nicSbusHangCleared;			/* 109 */
	volatile u_int32_t nicEnqEventDelayed;			/* 110 */
	/*
	 * Stats from MAC rx completion
	 */
	volatile u_int32_t nicMacRxLateColls;			/* 111 */
	volatile u_int32_t nicMacRxLinkLostDuringPkt;		/* 112 */
	volatile u_int32_t nicMacRxPhyDecodeErr;		/* 113 */
	volatile u_int32_t nicMacRxMacAbort;			/* 114 */
	volatile u_int32_t nicMacRxTruncNoResources;		/* 115 */
	/*
	 * Stats from the mac_stats area
	 */
	volatile u_int32_t nicMacRxDropUla;			/* 116 */
	volatile u_int32_t nicMacRxDropMcast;			/* 117 */
	volatile u_int32_t nicMacRxFlowControl;			/* 118 */
	volatile u_int32_t nicMacRxDropSpace;			/* 119 */
	volatile u_int32_t nicMacRxColls;			/* 120 */
	/*
 	 * MAC RX Attentions
	 */
	volatile u_int32_t nicMacRxTotalAttns;			/* 121 */
	volatile u_int32_t nicMacRxLinkAttns;			/* 122 */
	volatile u_int32_t nicMacRxSyncAttns;			/* 123 */
	volatile u_int32_t nicMacRxConfigAttns;			/* 124 */
	volatile u_int32_t nicMacReset;				/* 125 */
	volatile u_int32_t nicMacRxBufDescrAttns;		/* 126 */
	volatile u_int32_t nicMacRxBufAttns;			/* 127 */
	volatile u_int32_t nicMacRxZeroFrameCleanup;		/* 128 */
	volatile u_int32_t nicMacRxOneFrameCleanup;		/* 129 */
	volatile u_int32_t nicMacRxMultipleFrameCleanup;	/* 130 */
	volatile u_int32_t nicMacRxTimerCleanup;		/* 131 */
	volatile u_int32_t nicMacRxDmaCleanup;			/* 132 */
	/*
	 * Stats from the mac_stats area
	 */
	volatile u_int32_t nicMacTxCollisionHistogram[15];	/* 133 */
	/*
	 * MAC TX Attentions
	 */
	volatile u_int32_t nicMacTxTotalAttns;			/* 134 */
	/*
	 * NIC Profile
	 */
	volatile u_int32_t nicProfile[32];			/* 135 */
	/*
	 * Pat to 1024 bytes.
	 */
	u_int32_t		pad[75];
};

struct tg_reg {
	u_int32_t	data;
	u_int32_t	addr;
};

struct tg_mem {
	u_int32_t	tgAddr;
	caddr_t		userAddr;
	int		len;
};

typedef enum {
	TI_PARAM_NONE		= 0x00,
	TI_PARAM_STAT_TICKS	= 0x01,
	TI_PARAM_RX_COAL_TICKS	= 0x02,
	TI_PARAM_TX_COAL_TICKS	= 0x04,
	TI_PARAM_RX_COAL_BDS	= 0x08,
	TI_PARAM_TX_COAL_BDS	= 0x10,
	TI_PARAM_TX_BUF_RATIO	= 0x20,
	TI_PARAM_ALL		= 0x2f
} ti_param_mask;

struct ti_params {
	u_int32_t	ti_stat_ticks;
	u_int32_t	ti_rx_coal_ticks;
	u_int32_t	ti_tx_coal_ticks;
	u_int32_t	ti_rx_max_coal_bds;
	u_int32_t	ti_tx_max_coal_bds;
	u_int32_t	ti_tx_buf_ratio;
	ti_param_mask	param_mask;
};

typedef enum {
	TI_TRACE_TYPE_NONE	= 0x00000000,
	TI_TRACE_TYPE_SEND	= 0x00000001,
	TI_TRACE_TYPE_RECV	= 0x00000002,
	TI_TRACE_TYPE_DMA	= 0x00000004,
	TI_TRACE_TYPE_EVENT	= 0x00000008,
	TI_TRACE_TYPE_COMMAND	= 0x00000010,
	TI_TRACE_TYPE_MAC	= 0x00000020,
	TI_TRACE_TYPE_STATS	= 0x00000040,
	TI_TRACE_TYPE_TIMER	= 0x00000080,
	TI_TRACE_TYPE_DISP	= 0x00000100,
	TI_TRACE_TYPE_MAILBOX	= 0x00000200,
	TI_TRACE_TYPE_RECV_BD	= 0x00000400,
	TI_TRACE_TYPE_LNK_PHY	= 0x00000800,
	TI_TRACE_TYPE_LNK_NEG	= 0x00001000,
	TI_TRACE_LEVEL_1	= 0x10000000,
	TI_TRACE_LEVEL_2	= 0x20000000
} ti_trace_type;

struct ti_trace_buf {
	u_long	*buf;
	int	buf_len;
	int	fill_len;
	u_long	cur_trace_ptr;
};

#define	TIIOCGETSTATS	_IOR('T', 1, struct ti_stats)
#define	TIIOCGETPARAMS	_IOR('T', 2, struct ti_params)
#define	TIIOCSETPARAMS	_IOW('T', 3, struct ti_params)
#define TIIOCSETTRACE	_IOW('T', 11, ti_trace_type)
#define TIIOCGETTRACE	_IOWR('T', 12, struct ti_trace_buf)

/*
 * Taken from Alteon's altioctl.h.  Alteon's ioctl numbers 1-6 aren't
 * used by the FreeBSD driver.
 */
#define ALT_ATTACH		_IO('a', 7)
#define ALT_READ_TG_MEM		_IOWR('a', 10, struct tg_mem)
#define ALT_WRITE_TG_MEM	_IOWR('a', 11, struct tg_mem)
#define ALT_READ_TG_REG		_IOWR('a', 12, struct tg_reg)
#define ALT_WRITE_TG_REG	_IOWR('a', 13, struct tg_reg)

#endif /* _SYS_TIIO_H_  */


code:
/*-
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * 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.
 * 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.
 *
 *	@(#)time.h	8.5 (Berkeley) 5/4/95
 * $FreeBSD: release/9.0.0/sys/sys/time.h 224732 2011-08-09 14:06:50Z jonathan $
 */

#ifndef _SYS_TIME_H_
#define _SYS_TIME_H_

#include <sys/_timeval.h>
#include <sys/types.h>
#include <sys/timespec.h>

struct timezone {
	int	tz_minuteswest;	/* minutes west of Greenwich */
	int	tz_dsttime;	/* type of dst correction */
};
#define	DST_NONE	0	/* not on dst */
#define	DST_USA		1	/* USA style dst */
#define	DST_AUST	2	/* Australian style dst */
#define	DST_WET		3	/* Western European dst */
#define	DST_MET		4	/* Middle European dst */
#define	DST_EET		5	/* Eastern European dst */
#define	DST_CAN		6	/* Canada */

#if __BSD_VISIBLE
struct bintime {
	time_t	sec;
	uint64_t frac;
};

static __inline void
bintime_addx(struct bintime *bt, uint64_t x)
{
	uint64_t u;

	u = bt->frac;
	bt->frac += x;
	if (u > bt->frac)
		bt->sec++;
}

static __inline void
bintime_add(struct bintime *bt, const struct bintime *bt2)
{
	uint64_t u;

	u = bt->frac;
	bt->frac += bt2->frac;
	if (u > bt->frac)
		bt->sec++;
	bt->sec += bt2->sec;
}

static __inline void
bintime_sub(struct bintime *bt, const struct bintime *bt2)
{
	uint64_t u;

	u = bt->frac;
	bt->frac -= bt2->frac;
	if (u < bt->frac)
		bt->sec--;
	bt->sec -= bt2->sec;
}

static __inline void
bintime_mul(struct bintime *bt, u_int x)
{
	uint64_t p1, p2;

	p1 = (bt->frac & 0xffffffffull) * x;
	p2 = (bt->frac >> 32) * x + (p1 >> 32);
	bt->sec *= x;
	bt->sec += (p2 >> 32);
	bt->frac = (p2 << 32) | (p1 & 0xffffffffull);
}

#define	bintime_clear(a)	((a)->sec = (a)->frac = 0)
#define	bintime_isset(a)	((a)->sec || (a)->frac)
#define	bintime_cmp(a, b, cmp)						\
	(((a)->sec == (b)->sec) ?					\
	    ((a)->frac cmp (b)->frac) :					\
	    ((a)->sec cmp (b)->sec))

/*-
 * Background information:
 *
 * When converting between timestamps on parallel timescales of differing
 * resolutions it is historical and scientific practice to round down rather
 * than doing 4/5 rounding.
 *
 *   The date changes at midnight, not at noon.
 *
 *   Even at 15:59:59.999999999 it's not four'o'clock.
 *
 *   time_second ticks after N.999999999 not after N.4999999999
 */

static __inline void
bintime2timespec(const struct bintime *bt, struct timespec *ts)
{

	ts->tv_sec = bt->sec;
	ts->tv_nsec = ((uint64_t)1000000000 * (uint32_t)(bt->frac >> 32)) >> 32;
}

static __inline void
timespec2bintime(const struct timespec *ts, struct bintime *bt)
{

	bt->sec = ts->tv_sec;
	/* 18446744073 = int(2^64 / 1000000000) */
	bt->frac = ts->tv_nsec * (uint64_t)18446744073LL;
}

static __inline void
bintime2timeval(const struct bintime *bt, struct timeval *tv)
{

	tv->tv_sec = bt->sec;
	tv->tv_usec = ((uint64_t)1000000 * (uint32_t)(bt->frac >> 32)) >> 32;
}

static __inline void
timeval2bintime(const struct timeval *tv, struct bintime *bt)
{

	bt->sec = tv->tv_sec;
	/* 18446744073709 = int(2^64 / 1000000) */
	bt->frac = tv->tv_usec * (uint64_t)18446744073709LL;
}
#endif /* __BSD_VISIBLE */

#ifdef _KERNEL

/* Operations on timespecs */
#define	timespecclear(tvp)	((tvp)->tv_sec = (tvp)->tv_nsec = 0)
#define	timespecisset(tvp)	((tvp)->tv_sec || (tvp)->tv_nsec)
#define	timespeccmp(tvp, uvp, cmp)					\
	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
	    ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :			\
	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
#define timespecadd(vvp, uvp)						\
	do {								\
		(vvp)->tv_sec += (uvp)->tv_sec;				\
		(vvp)->tv_nsec += (uvp)->tv_nsec;			\
		if ((vvp)->tv_nsec >= 1000000000) {			\
			(vvp)->tv_sec++;				\
			(vvp)->tv_nsec -= 1000000000;			\
		}							\
	} while (0)
#define timespecsub(vvp, uvp)						\
	do {								\
		(vvp)->tv_sec -= (uvp)->tv_sec;				\
		(vvp)->tv_nsec -= (uvp)->tv_nsec;			\
		if ((vvp)->tv_nsec < 0) {				\
			(vvp)->tv_sec--;				\
			(vvp)->tv_nsec += 1000000000;			\
		}							\
	} while (0)

/* Operations on timevals. */

#define	timevalclear(tvp)		((tvp)->tv_sec = (tvp)->tv_usec = 0)
#define	timevalisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
#define	timevalcmp(tvp, uvp, cmp)					\
	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
	    ((tvp)->tv_sec cmp (uvp)->tv_sec))

/* timevaladd and timevalsub are not inlined */

#endif /* _KERNEL */

#ifndef _KERNEL			/* NetBSD/OpenBSD compatible interfaces */

#define	timerclear(tvp)		((tvp)->tv_sec = (tvp)->tv_usec = 0)
#define	timerisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
#define	timercmp(tvp, uvp, cmp)					\
	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
#define timeradd(tvp, uvp, vvp)						\
	do {								\
		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;	\
		if ((vvp)->tv_usec >= 1000000) {			\
			(vvp)->tv_sec++;				\
			(vvp)->tv_usec -= 1000000;			\
		}							\
	} while (0)
#define timersub(tvp, uvp, vvp)						\
	do {								\
		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
		if ((vvp)->tv_usec < 0) {				\
			(vvp)->tv_sec--;				\
			(vvp)->tv_usec += 1000000;			\
		}							\
	} while (0)
#endif

/*
 * Names of the interval timers, and structure
 * defining a timer setting.
 */
#define	ITIMER_REAL	0
#define	ITIMER_VIRTUAL	1
#define	ITIMER_PROF	2

struct itimerval {
	struct	timeval it_interval;	/* timer interval */
	struct	timeval it_value;	/* current value */
};

/*
 * Getkerninfo clock information structure
 */
struct clockinfo {
	int	hz;		/* clock frequency */
	int	tick;		/* micro-seconds per hz tick */
	int	spare;
	int	stathz;		/* statistics clock frequency */
	int	profhz;		/* profiling clock frequency */
};

/* These macros are also in time.h. */
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME	0
#define CLOCK_VIRTUAL	1
#define CLOCK_PROF	2
#define CLOCK_MONOTONIC	4
#define CLOCK_UPTIME	5		/* FreeBSD-specific. */
#define CLOCK_UPTIME_PRECISE	7	/* FreeBSD-specific. */
#define CLOCK_UPTIME_FAST	8	/* FreeBSD-specific. */
#define CLOCK_REALTIME_PRECISE	9	/* FreeBSD-specific. */
#define CLOCK_REALTIME_FAST	10	/* FreeBSD-specific. */
#define CLOCK_MONOTONIC_PRECISE	11	/* FreeBSD-specific. */
#define CLOCK_MONOTONIC_FAST	12	/* FreeBSD-specific. */
#define CLOCK_SECOND	13		/* FreeBSD-specific. */
#define CLOCK_THREAD_CPUTIME_ID	14
#endif

#ifndef TIMER_ABSTIME
#define TIMER_RELTIME	0x0	/* relative timer */
#define TIMER_ABSTIME	0x1	/* absolute timer */
#endif

#ifdef _KERNEL

/*
 * Kernel to clock driver interface.
 */
void	inittodr(time_t base);
void	resettodr(void);

extern time_t	time_second;
extern time_t	time_uptime;
extern struct bintime boottimebin;
extern struct timeval boottime;

/*
 * Functions for looking at our clock: [get]{bin,nano,micro}[up]time()
 *
 * Functions without the "get" prefix returns the best timestamp
 * we can produce in the given format.
 *
 * "bin"   == struct bintime  == seconds + 64 bit fraction of seconds.
 * "nano"  == struct timespec == seconds + nanoseconds.
 * "micro" == struct timeval  == seconds + microseconds.
 *
 * Functions containing "up" returns time relative to boot and
 * should be used for calculating time intervals.
 *
 * Functions without "up" returns GMT time.
 *
 * Functions with the "get" prefix returns a less precise result
 * much faster than the functions without "get" prefix and should
 * be used where a precision of 1/hz seconds is acceptable or where
 * performance is priority. (NB: "precision", _not_ "resolution" !)
 *
 */

void	binuptime(struct bintime *bt);
void	nanouptime(struct timespec *tsp);
void	microuptime(struct timeval *tvp);

void	bintime(struct bintime *bt);
void	nanotime(struct timespec *tsp);
void	microtime(struct timeval *tvp);

void	getbinuptime(struct bintime *bt);
void	getnanouptime(struct timespec *tsp);
void	getmicrouptime(struct timeval *tvp);

void	getbintime(struct bintime *bt);
void	getnanotime(struct timespec *tsp);
void	getmicrotime(struct timeval *tvp);

/* Other functions */
int	itimerdecr(struct itimerval *itp, int usec);
int	itimerfix(struct timeval *tv);
int	ppsratecheck(struct timeval *, int *, int);
int	ratecheck(struct timeval *, const struct timeval *);
void	timevaladd(struct timeval *t1, const struct timeval *t2);
void	timevalsub(struct timeval *t1, const struct timeval *t2);
int	tvtohz(struct timeval *tv);
#else /* !_KERNEL */
#include <time.h>

#include <sys/cdefs.h>
#include <sys/select.h>

__BEGIN_DECLS
int	setitimer(int, const struct itimerval *, struct itimerval *);
int	utimes(const char *, const struct timeval *);

#if __BSD_VISIBLE
int	adjtime(const struct timeval *, struct timeval *);
int	futimes(int, const struct timeval *);
int	futimesat(int, const char *, const struct timeval [2]);
int	lutimes(const char *, const struct timeval *);
int	settimeofday(const struct timeval *, const struct timezone *);
#endif

#if __XSI_VISIBLE
int	getitimer(int, struct itimerval *);
int	gettimeofday(struct timeval *, struct timezone *);
#endif

__END_DECLS

#endif /* !_KERNEL */

#endif /* !_SYS_TIME_H_ */


code:
/*-
 * Copyright (c) 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * 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.
 * 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.
 *
 *	@(#)timeb.h	8.2 (Berkeley) 1/21/94
 * $FreeBSD: release/9.0.0/sys/sys/timeb.h 204926 2010-03-09 21:01:12Z ed $
 */

#ifndef _SYS_TIMEB_H_
#define _SYS_TIMEB_H_

#ifdef __GNUC__
#warning "this file includes <sys/timeb.h> which is deprecated"
#endif

#include <sys/_types.h>

#ifndef _TIME_T_DECLARED
typedef	__time_t	time_t;
#define	_TIME_T_DECLARED
#endif

/* The ftime(2) system call structure -- deprecated. */
struct timeb {
	time_t	time;			/* seconds since the Epoch */
	unsigned short millitm;		/* + milliseconds since the Epoch */
	short	timezone;		/* minutes west of CUT */
	short	dstflag;		/* DST == non-zero */
};

#ifndef _KERNEL
#include <sys/cdefs.h>

__BEGIN_DECLS
int ftime(struct timeb *);
__END_DECLS
#endif /* _KERNEL */

#endif /* !_SYS_TIMEB_H_ */


code:
/*-
 * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
 * All rights reserved.
 *
 * 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,
 *    without modification, immediately at the beginning of the file.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 *
 * $FreeBSD: release/9.0.0/sys/sys/timeet.h 212541 2010-09-13 07:25:35Z mav $
 */

#ifndef _SYS_TIMEEC_H_
#define	_SYS_TIMEEC_H_

#ifndef _KERNEL
#error "no user-serviceable parts inside"
#endif

#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/queue.h>
#include <sys/time.h>

/*
 * `struct eventtimer' is the interface between the hardware which implements
 * a event timer and the MI code which uses this to receive time events.
 */

struct eventtimer;
typedef int et_start_t(struct eventtimer *et,
    struct bintime *first, struct bintime *period);
typedef int et_stop_t(struct eventtimer *et);
typedef void et_event_cb_t(struct eventtimer *et, void *arg);
typedef int et_deregister_cb_t(struct eventtimer *et, void *arg);

struct eventtimer {
	SLIST_ENTRY(eventtimer)	et_all;
		/* Pointer to the next event timer. */
	char			*et_name;
		/* Name of the event timer. */
	int			et_flags;
		/* Set of capabilities flags: */
#define ET_FLAGS_PERIODIC	1
#define ET_FLAGS_ONESHOT	2
#define ET_FLAGS_PERCPU		4
#define ET_FLAGS_C3STOP		8
#define ET_FLAGS_POW2DIV	16
	int			et_quality;
		/*
		 * Used to determine if this timecounter is better than
		 * another timecounter. Higher means better.
		 */
	int			et_active;
	u_int64_t		et_frequency;
		/* Base frequency in Hz. */
	struct bintime		et_min_period;
	struct bintime		et_max_period;
	et_start_t		*et_start;
	et_stop_t		*et_stop;
	et_event_cb_t		*et_event_cb;
	et_deregister_cb_t	*et_deregister_cb;
	void 			*et_arg;
	void			*et_priv;
	struct sysctl_oid	*et_sysctl;
		/* Pointer to the event timer's private parts. */
};

extern struct mtx	et_eventtimers_mtx;
#define	ET_LOCK()	mtx_lock(&et_eventtimers_mtx)
#define	ET_UNLOCK()	mtx_unlock(&et_eventtimers_mtx)

/* Driver API */
int	et_register(struct eventtimer *et);
int	et_deregister(struct eventtimer *et);
/* Consumer API  */
struct eventtimer *et_find(const char *name, int check, int want);
int	et_init(struct eventtimer *et, et_event_cb_t *event,
    et_deregister_cb_t *deregister, void *arg);
int	et_start(struct eventtimer *et,
    struct bintime *first, struct bintime *period);
int	et_stop(struct eventtimer *et);
int	et_ban(struct eventtimer *et);
int	et_free(struct eventtimer *et);

#ifdef SYSCTL_DECL
SYSCTL_DECL(_kern_eventtimer);
#endif
#endif /* !_SYS_TIMETC_H_ */


code:
/*-
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <phk@FreeBSD.org> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
 * ----------------------------------------------------------------------------
 *
 * $FreeBSD: release/9.0.0/sys/sys/timepps.h 139825 2005-01-07 02:29:27Z imp $
 *
 * The is a FreeBSD version of the RFC 2783 API for Pulse Per Second
 * timing interfaces.
 */

#ifndef _SYS_TIMEPPS_H_
#define _SYS_TIMEPPS_H_

#include <sys/ioccom.h>
#include <sys/time.h>

#define PPS_API_VERS_1	1

typedef int pps_handle_t;

typedef unsigned pps_seq_t;

typedef struct ntp_fp {
	unsigned int	integral;
	unsigned int	fractional;
} ntp_fp_t;

typedef union pps_timeu {
	struct timespec	tspec;
	ntp_fp_t	ntpfp;
	unsigned long	longpad[3];
} pps_timeu_t;

typedef struct {
	pps_seq_t	assert_sequence;	/* assert event seq # */
	pps_seq_t	clear_sequence;		/* clear event seq # */
	pps_timeu_t	assert_tu;
	pps_timeu_t	clear_tu;
	int		current_mode;		/* current mode bits */
} pps_info_t;

#define assert_timestamp        assert_tu.tspec
#define clear_timestamp         clear_tu.tspec

#define assert_timestamp_ntpfp  assert_tu.ntpfp
#define clear_timestamp_ntpfp   clear_tu.ntpfp

typedef struct {
	int api_version;			/* API version # */
	int mode;				/* mode bits */
	pps_timeu_t assert_off_tu;
	pps_timeu_t clear_off_tu;
} pps_params_t;

#define assert_offset   assert_off_tu.tspec
#define clear_offset    clear_off_tu.tspec

#define assert_offset_ntpfp     assert_off_tu.ntpfp
#define clear_offset_ntpfp      clear_off_tu.ntpfp

#define PPS_CAPTUREASSERT	0x01
#define PPS_CAPTURECLEAR	0x02
#define PPS_CAPTUREBOTH		0x03

#define PPS_OFFSETASSERT	0x10
#define PPS_OFFSETCLEAR		0x20

#define PPS_ECHOASSERT		0x40
#define PPS_ECHOCLEAR		0x80

#define PPS_CANWAIT		0x100
#define PPS_CANPOLL		0x200

#define PPS_TSFMT_TSPEC		0x1000
#define PPS_TSFMT_NTPFP		0x2000

#define PPS_KC_HARDPPS		0
#define PPS_KC_HARDPPS_PLL	1
#define PPS_KC_HARDPPS_FLL	2

struct pps_fetch_args {
	int tsformat;
	pps_info_t	pps_info_buf;
	struct timespec	timeout;
};

struct pps_kcbind_args {
	int kernel_consumer;
	int edge;
	int tsformat;
};

#define PPS_IOC_CREATE		_IO('1', 1)
#define PPS_IOC_DESTROY		_IO('1', 2)
#define PPS_IOC_SETPARAMS	_IOW('1', 3, pps_params_t)
#define PPS_IOC_GETPARAMS	_IOR('1', 4, pps_params_t)
#define PPS_IOC_GETCAP		_IOR('1', 5, int)
#define PPS_IOC_FETCH		_IOWR('1', 6, struct pps_fetch_args)
#define PPS_IOC_KCBIND		_IOW('1', 7, struct pps_kcbind_args)

#ifdef _KERNEL

struct pps_state {
	/* Capture information. */
	struct timehands *capth;
	unsigned	capgen;
	unsigned	capcount;

	/* State information. */
	pps_params_t	ppsparam;
	pps_info_t	ppsinfo;
	int		kcmode;
	int		ppscap;
	struct timecounter *ppstc;
	unsigned	ppscount[3];
};

void pps_capture(struct pps_state *pps);
void pps_event(struct pps_state *pps, int event);
void pps_init(struct pps_state *pps);
int pps_ioctl(unsigned long cmd, caddr_t data, struct pps_state *pps);
void hardpps(struct timespec *tsp, long nsec);

#else /* !_KERNEL */

static __inline int
time_pps_create(int filedes, pps_handle_t *handle)
{
	int error;

	*handle = -1;
	error = ioctl(filedes, PPS_IOC_CREATE, 0);
	if (error < 0)
		return (-1);
	*handle = filedes;
	return (0);
}

static __inline int
time_pps_destroy(pps_handle_t handle)
{
	return (ioctl(handle, PPS_IOC_DESTROY, 0));
}

static __inline int
time_pps_setparams(pps_handle_t handle, const pps_params_t *ppsparams)
{
	return (ioctl(handle, PPS_IOC_SETPARAMS, ppsparams));
}

static __inline int
time_pps_getparams(pps_handle_t handle, pps_params_t *ppsparams)
{
	return (ioctl(handle, PPS_IOC_GETPARAMS, ppsparams));
}

static __inline int
time_pps_getcap(pps_handle_t handle, int *mode)
{
	return (ioctl(handle, PPS_IOC_GETCAP, mode));
}

static __inline int
time_pps_fetch(pps_handle_t handle, const int tsformat,
	pps_info_t *ppsinfobuf, const struct timespec *timeout)
{
	int error;
	struct pps_fetch_args arg;

	arg.tsformat = tsformat;
	if (timeout == NULL) {
		arg.timeout.tv_sec = -1;
		arg.timeout.tv_nsec = -1;
	} else
		arg.timeout = *timeout;
	error = ioctl(handle, PPS_IOC_FETCH, &arg);
	*ppsinfobuf = arg.pps_info_buf;
	return (error);
}

static __inline int
time_pps_kcbind(pps_handle_t handle, const int kernel_consumer,
	const int edge, const int tsformat)
{
	struct pps_kcbind_args arg;

	arg.kernel_consumer = kernel_consumer;
	arg.edge = edge;
	arg.tsformat = tsformat;
	return (ioctl(handle, PPS_IOC_KCBIND, &arg));
}

#endif /* KERNEL */

#endif /* !_SYS_TIMEPPS_H_ */


code:
/*-
 * Copyright (c) 2005 David Xu <davidxu@freebsd.org>
 * Copyright (c) 1994 by Chris Provenzano, proven@mit.edu
 * All rights reserved.
 *
 * 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 Chris Provenzano.
 * 4. The name of Chris Provenzano may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY CHRIS PROVENZANO ``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 CHRIS PROVENZANO 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.
 *
 * $FreeBSD: release/9.0.0/sys/sys/timers.h 156137 2006-03-01 06:48:31Z davidxu $
 *
 * Description : Basic timers header.
 */

#ifndef _SYS_TIMERS_H_
#define _SYS_TIMERS_H_

#include <sys/time.h>

#ifdef _KERNEL
/*
 * Structures used to manage POSIX timers in a process.
 */
struct itimer {
	struct mtx  		it_mtx;
	struct sigevent		it_sigev;
	struct itimerspec	it_time;
	struct proc 		*it_proc;
	int	it_flags;
	int	it_usecount;
	int	it_overrun;		/* Overruns currently accumulating */
	int	it_overrun_last;	/* Overruns associated w/ a delivery */
	int	it_clockid;
	int	it_timerid;
	ksiginfo_t	it_ksi;
	union {
		/* realtime */
		struct {
			struct callout it_callout;
		} _rt;

		/* cpu timer */
		struct {
			LIST_ENTRY(itimer)	it_link;
			TAILQ_ENTRY(itimer)	it_worklink;
			int			it_active;
			int			it_cflags;
		} _cpu;
	} _data;
};

#define it_callout	_data._rt.it_callout
#define it_link		_data._cpu.it_link
#define it_active	_data._cpu.it_active
#define	it_worklink	_data._cpu.it_worklink
#define	it_cflags	_data._cpu.it_cflags

#define	ITF_DELETING	0x01
#define	ITF_WANTED	0x02

#define	ITCF_ONWORKLIST	0x01

#define	TIMER_MAX	32

#define	ITIMER_LOCK(it)		mtx_lock(&(it)->it_mtx)
#define	ITIMER_UNLOCK(it)	mtx_unlock(&(it)->it_mtx)

LIST_HEAD(itimerlist, itimer);

struct	itimers {
	struct itimerlist	its_virtual;
	struct itimerlist	its_prof;
	TAILQ_HEAD(, itimer)	its_worklist;
	struct itimer		*its_timers[TIMER_MAX];
};

struct	kclock {
	int (*timer_create)(struct itimer *timer);
	int (*timer_settime)(struct itimer * timer, int flags,
		struct itimerspec * new_value,
		struct itimerspec * old_value);
	int (*timer_delete)(struct itimer * timer);
	int (*timer_gettime)(struct itimer * timer,
		struct itimerspec * cur_value);
	void (*event_hook)(struct proc *p, clockid_t clock_id, int event);
};

/* Event values for event_hook() */
#define	ITIMER_EV_EXEC	0
#define	ITIMER_EV_EXIT	1

int	itimer_accept(struct proc *p, int tid, ksiginfo_t *ksi);
#endif
#endif /* !_SYS_TIMERS_H_ */


code:
/*-
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * 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.
 * 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.
 *
 *	@(#)times.h	8.4 (Berkeley) 1/21/94
 * $FreeBSD: release/9.0.0/sys/sys/times.h 127976 2004-04-07 04:19:52Z imp $
 */

#ifndef	_SYS_TIMES_H_
#define	_SYS_TIMES_H_

#include <sys/_types.h>

#ifndef _CLOCK_T_DECLARED
typedef	__clock_t	clock_t;
#define	_CLOCK_T_DECLARED
#endif

struct tms {
	clock_t tms_utime;	/* User CPU time */
	clock_t tms_stime;	/* System CPU time */
	clock_t tms_cutime;	/* User CPU time of terminated child procs */
	clock_t tms_cstime;	/* System CPU time of terminated child procs */
};

#ifndef _KERNEL
#include <sys/cdefs.h>

__BEGIN_DECLS
clock_t	times(struct tms *);
__END_DECLS
#endif
#endif /* !_SYS_TIMES_H_ */


code:
/*-
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * 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.
 * 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.
 *
 *	@(#)time.h	8.5 (Berkeley) 5/4/95
 * from: FreeBSD: src/sys/sys/time.h,v 1.43 2000/03/20 14:09:05 phk Exp
 *	$FreeBSD: release/9.0.0/sys/sys/timespec.h 205792 2010-03-28 13:13:22Z ed $
 */

#ifndef _SYS_TIMESPEC_H_
#define _SYS_TIMESPEC_H_

#include <sys/cdefs.h>
#include <sys/_timespec.h>

#if __BSD_VISIBLE
#define	TIMEVAL_TO_TIMESPEC(tv, ts)					\
	do {								\
		(ts)->tv_sec = (tv)->tv_sec;				\
		(ts)->tv_nsec = (tv)->tv_usec * 1000;			\
	} while (0)
#define	TIMESPEC_TO_TIMEVAL(tv, ts)					\
	do {								\
		(tv)->tv_sec = (ts)->tv_sec;				\
		(tv)->tv_usec = (ts)->tv_nsec / 1000;			\
	} while (0)

#endif /* __BSD_VISIBLE */

/*
 * Structure defined by POSIX.1b to be like a itimerval, but with
 * timespecs. Used in the timer_*() system calls.
 */
struct itimerspec {
	struct timespec  it_interval;
	struct timespec  it_value;
};

#endif /* _SYS_TIMESPEC_H_ */


code:
/*-
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
 * ----------------------------------------------------------------------------
 *
 * $FreeBSD: release/9.0.0/sys/sys/timetc.h 224043 2011-07-14 21:02:15Z jkim $
 */

#ifndef _SYS_TIMETC_H_
#define	_SYS_TIMETC_H_

#ifndef _KERNEL
#error "no user-serviceable parts inside"
#endif

/*-
 * `struct timecounter' is the interface between the hardware which implements
 * a timecounter and the MI code which uses this to keep track of time.
 *
 * A timecounter is a binary counter which has two properties:
 *    * it runs at a fixed, known frequency.
 *    * it has sufficient bits to not roll over in less than approximately
 *      max(2 msec, 2/HZ seconds).  (The value 2 here is really 1 + delta,
 *      for some indeterminate value of delta.)
 */

struct timecounter;
typedef u_int timecounter_get_t(struct timecounter *);
typedef void timecounter_pps_t(struct timecounter *);

struct timecounter {
	timecounter_get_t	*tc_get_timecount;
		/*
		 * This function reads the counter.  It is not required to
		 * mask any unimplemented bits out, as long as they are
		 * constant.
		 */
	timecounter_pps_t	*tc_poll_pps;
		/*
		 * This function is optional.  It will be called whenever the
		 * timecounter is rewound, and is intended to check for PPS
		 * events.  Normal hardware does not need it but timecounters
		 * which latch PPS in hardware (like sys/pci/xrpu.c) do.
		 */
	u_int 			tc_counter_mask;
		/* This mask should mask off any unimplemented bits. */
	uint64_t		tc_frequency;
		/* Frequency of the counter in Hz. */
	char			*tc_name;
		/* Name of the timecounter. */
	int			tc_quality;
		/*
		 * Used to determine if this timecounter is better than
		 * another timecounter higher means better.  Negative
		 * means "only use at explicit request".
		 */
	u_int			tc_flags;
#define	TC_FLAGS_C3STOP		1	/* Timer dies in C3. */

	void			*tc_priv;
		/* Pointer to the timecounter's private parts. */
	struct timecounter	*tc_next;
		/* Pointer to the next timecounter. */
};

extern struct timecounter *timecounter;
extern int tc_min_ticktock_freq; /*
				  * Minimal tc_ticktock() call frequency,
				  * required to handle counter wraps.
				  */

u_int64_t tc_getfrequency(void);
void	tc_init(struct timecounter *tc);
void	tc_setclock(struct timespec *ts);
void	tc_ticktock(int cnt);
void	cpu_tick_calibration(void);

#ifdef SYSCTL_DECL
SYSCTL_DECL(_kern_timecounter);
#endif

#endif /* !_SYS_TIMETC_H_ */


code:
/*-
 ***********************************************************************
 *								       *
 * Copyright (c) David L. Mills 1993-2001			       *
 *								       *
 * Permission to use, copy, modify, and distribute this software and   *
 * its documentation for any purpose and without fee is hereby	       *
 * granted, provided that the above copyright notice appears in all    *
 * copies and that both the copyright notice and this permission       *
 * notice appear in supporting documentation, and that the name        *
 * University of Delaware not be used in advertising or publicity      *
 * pertaining to distribution of the software without specific,	       *
 * written prior permission. The University of Delaware makes no       *
 * representations about the suitability this software for any	       *
 * purpose. It is provided "as is" without express or implied	       *
 * warranty.							       *
 *								       *
 **********************************************************************/

/*
 * Modification history timex.h
 *
 * 16 Aug 00	David L. Mills
 *	API Version 4. Added MOD_TAI and tai member of ntptimeval
 *	structure.
 *
 * 17 Nov 98	David L. Mills
 *	Revised for nanosecond kernel and user interface.
 *
 * 26 Sep 94	David L. Mills
 *	Added defines for hybrid phase/frequency-lock loop.
 *
 * 19 Mar 94	David L. Mills
 *	Moved defines from kernel routines to header file and added new
 *	defines for PPS phase-lock loop.
 *
 * 20 Feb 94	David L. Mills
 *	Revised status codes and structures for external clock and PPS
 *	signal discipline.
 *
 * 28 Nov 93	David L. Mills
 *	Adjusted parameters to improve stability and increase poll
 *	interval.
 *
 * 17 Sep 93    David L. Mills
 *      Created file
 *
 * $FreeBSD: release/9.0.0/sys/sys/timex.h 139825 2005-01-07 02:29:27Z imp $
 */
/*
 * This header file defines the Network Time Protocol (NTP) interfaces
 * for user and daemon application programs. These are implemented using
 * defined syscalls and data structures and require specific kernel
 * support.
 *
 * The original precision time kernels developed from 1993 have an
 * ultimate resolution of one microsecond; however, the most recent
 * kernels have an ultimate resolution of one nanosecond. In these
 * kernels, a ntp_adjtime() syscalls can be used to determine which
 * resolution is in use and to select either one at any time. The
 * resolution selected affects the scaling of certain fields in the
 * ntp_gettime() and ntp_adjtime() syscalls, as described below.
 *
 * NAME
 *	ntp_gettime - NTP user application interface
 *
 * SYNOPSIS
 *	#include <sys/timex.h>
 *
 *	int ntp_gettime(struct ntptimeval *ntv);
 *
 * DESCRIPTION
 *	The time returned by ntp_gettime() is in a timespec structure,
 *	but may be in either microsecond (seconds and microseconds) or
 *	nanosecond (seconds and nanoseconds) format. The particular
 *	format in use is determined by the STA_NANO bit of the status
 *	word returned by the ntp_adjtime() syscall.
 *
 * NAME
 *	ntp_adjtime - NTP daemon application interface
 *
 * SYNOPSIS
 *	#include <sys/timex.h>
 *	#include <sys/syscall.h>
 *
 *	int syscall(SYS_ntp_adjtime, tptr);
 *	int SYS_ntp_adjtime;
 *	struct timex *tptr;
 *
 * DESCRIPTION
 *	Certain fields of the timex structure are interpreted in either
 *	microseconds or nanoseconds according to the state of the
 *	STA_NANO bit in the status word. See the description below for
 *	further information.
 */
#ifndef _SYS_TIMEX_H_
#define _SYS_TIMEX_H_ 1
#define NTP_API		4	/* NTP API version */

#ifndef MSDOS			/* Microsoft specific */
#include <sys/syscall.h>
#endif /* MSDOS */

/*
 * The following defines establish the performance envelope of the
 * kernel discipline loop. Phase or frequency errors greater than
 * NAXPHASE or MAXFREQ are clamped to these maxima. For update intervals
 * less than MINSEC, the loop always operates in PLL mode; while, for
 * update intervals greater than MAXSEC, the loop always operates in FLL
 * mode. Between these two limits the operating mode is selected by the
 * STA_FLL bit in the status word.
 */
#define MAXPHASE	500000000L /* max phase error (ns) */
#define MAXFREQ		500000L	/* max freq error (ns/s) */
#define MINSEC		256	/* min FLL update interval (s) */
#define MAXSEC		2048	/* max PLL update interval (s) */
#define NANOSECOND	1000000000L /* nanoseconds in one second */
#define SCALE_PPM	(65536 / 1000) /* crude ns/s to scaled PPM */
#define MAXTC		10	/* max time constant */

/*
 * The following defines and structures define the user interface for
 * the ntp_gettime() and ntp_adjtime() syscalls.
 *
 * Control mode codes (timex.modes)
 */
#define MOD_OFFSET	0x0001	/* set time offset */
#define MOD_FREQUENCY	0x0002	/* set frequency offset */
#define MOD_MAXERROR	0x0004	/* set maximum time error */
#define MOD_ESTERROR	0x0008	/* set estimated time error */
#define MOD_STATUS	0x0010	/* set clock status bits */
#define MOD_TIMECONST	0x0020	/* set PLL time constant */
#define MOD_PPSMAX	0x0040	/* set PPS maximum averaging time */
#define MOD_TAI		0x0080	/* set TAI offset */
#define	MOD_MICRO	0x1000	/* select microsecond resolution */
#define	MOD_NANO	0x2000	/* select nanosecond resolution */
#define MOD_CLKB	0x4000	/* select clock B */
#define MOD_CLKA	0x8000	/* select clock A */

/*
 * Status codes (timex.status)
 */
#define STA_PLL		0x0001	/* enable PLL updates (rw) */
#define STA_PPSFREQ	0x0002	/* enable PPS freq discipline (rw) */
#define STA_PPSTIME	0x0004	/* enable PPS time discipline (rw) */
#define STA_FLL		0x0008	/* enable FLL mode (rw) */
#define STA_INS		0x0010	/* insert leap (rw) */
#define STA_DEL		0x0020	/* delete leap (rw) */
#define STA_UNSYNC	0x0040	/* clock unsynchronized (rw) */
#define STA_FREQHOLD	0x0080	/* hold frequency (rw) */
#define STA_PPSSIGNAL	0x0100	/* PPS signal present (ro) */
#define STA_PPSJITTER	0x0200	/* PPS signal jitter exceeded (ro) */
#define STA_PPSWANDER	0x0400	/* PPS signal wander exceeded (ro) */
#define STA_PPSERROR	0x0800	/* PPS signal calibration error (ro) */
#define STA_CLOCKERR	0x1000	/* clock hardware fault (ro) */
#define STA_NANO	0x2000	/* resolution (0 = us, 1 = ns) (ro) */
#define STA_MODE	0x4000	/* mode (0 = PLL, 1 = FLL) (ro) */
#define STA_CLK		0x8000	/* clock source (0 = A, 1 = B) (ro) */

#define STA_RONLY (STA_PPSSIGNAL | STA_PPSJITTER | STA_PPSWANDER | \
    STA_PPSERROR | STA_CLOCKERR | STA_NANO | STA_MODE | STA_CLK)

/*
 * Clock states (time_state)
 */
#define TIME_OK		0	/* no leap second warning */
#define TIME_INS	1	/* insert leap second warning */
#define TIME_DEL	2	/* delete leap second warning */
#define TIME_OOP	3	/* leap second in progress */
#define TIME_WAIT	4	/* leap second has occured */
#define TIME_ERROR	5	/* error (see status word) */

/*
 * NTP user interface (ntp_gettime()) - used to read kernel clock values
 *
 * Note: The time member is in microseconds if STA_NANO is zero and
 * nanoseconds if not.
 */
struct ntptimeval {
	struct timespec time;	/* current time (ns) (ro) */
	long maxerror;		/* maximum error (us) (ro) */
	long esterror;		/* estimated error (us) (ro) */
	long tai;		/* TAI offset */
	int time_state;		/* time status */
};

/*
 * NTP daemon interface (ntp_adjtime()) - used to discipline CPU clock
 * oscillator and determine status.
 *
 * Note: The offset, precision and jitter members are in microseconds if
 * STA_NANO is zero and nanoseconds if not.
 */
struct timex {
	unsigned int modes;	/* clock mode bits (wo) */
	long	offset;		/* time offset (ns/us) (rw) */
	long	freq;		/* frequency offset (scaled PPM) (rw) */
	long	maxerror;	/* maximum error (us) (rw) */
	long	esterror;	/* estimated error (us) (rw) */
	int	status;		/* clock status bits (rw) */
	long	constant;	/* poll interval (log2 s) (rw) */
	long	precision;	/* clock precision (ns/us) (ro) */
	long	tolerance;	/* clock frequency tolerance (scaled
				 * PPM) (ro) */
	/*
	 * The following read-only structure members are implemented
	 * only if the PPS signal discipline is configured in the
	 * kernel. They are included in all configurations to insure
	 * portability.
	 */
	long	ppsfreq;	/* PPS frequency (scaled PPM) (ro) */
	long	jitter;		/* PPS jitter (ns/us) (ro) */
	int	shift;		/* interval duration (s) (shift) (ro) */
	long	stabil;		/* PPS stability (scaled PPM) (ro) */
	long	jitcnt;		/* jitter limit exceeded (ro) */
	long	calcnt;		/* calibration intervals (ro) */
	long	errcnt;		/* calibration errors (ro) */
	long	stbcnt;		/* stability limit exceeded (ro) */
};

#ifdef __FreeBSD__

#ifdef _KERNEL
void	ntp_update_second(int64_t *adjustment, time_t *newsec);
#else /* !_KERNEL */
#include <sys/cdefs.h>

__BEGIN_DECLS
int	ntp_adjtime(struct timex *);
int	ntp_gettime(struct ntptimeval *);
__END_DECLS
#endif /* _KERNEL */

#endif /* __FreeBSD__ */

#endif /* !_SYS_TIMEX_H_ */