code:
/*-
 * Copyright (c) 1982, 1986, 1989, 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.
 *
 *	@(#)buf.h	8.9 (Berkeley) 3/30/95
 * $FreeBSD: release/9.0.0/sys/sys/buf.h 225448 2011-09-08 12:56:26Z attilio $
 */

#ifndef _SYS_BUF_H_
#define	_SYS_BUF_H_

#include <sys/bufobj.h>
#include <sys/queue.h>
#include <sys/lock.h>
#include <sys/lockmgr.h>

struct bio;
struct buf;
struct bufobj;
struct mount;
struct vnode;
struct uio;

/*
 * To avoid including <ufs/ffs/softdep.h>
 */
LIST_HEAD(workhead, worklist);
/*
 * These are currently used only by the soft dependency code, hence
 * are stored once in a global variable. If other subsystems wanted
 * to use these hooks, a pointer to a set of bio_ops could be added
 * to each buffer.
 */
extern struct bio_ops {
	void	(*io_start)(struct buf *);
	void	(*io_complete)(struct buf *);
	void	(*io_deallocate)(struct buf *);
	int	(*io_countdeps)(struct buf *, int);
} bioops;

struct vm_object;

typedef unsigned char b_xflags_t;

/*
 * The buffer header describes an I/O operation in the kernel.
 *
 * NOTES:
 *	b_bufsize, b_bcount.  b_bufsize is the allocation size of the
 *	buffer, either DEV_BSIZE or PAGE_SIZE aligned.  b_bcount is the
 *	originally requested buffer size and can serve as a bounds check
 *	against EOF.  For most, but not all uses, b_bcount == b_bufsize.
 *
 *	b_dirtyoff, b_dirtyend.  Buffers support piecemeal, unaligned
 *	ranges of dirty data that need to be written to backing store.
 *	The range is typically clipped at b_bcount ( not b_bufsize ).
 *
 *	b_resid.  Number of bytes remaining in I/O.  After an I/O operation
 *	completes, b_resid is usually 0 indicating 100% success.
 *
 *	All fields are protected by the buffer lock except those marked:
 *		V - Protected by owning bufobj lock
 *		Q - Protected by the buf queue lock
 *		D - Protected by an dependency implementation specific lock
 */
struct buf {
	struct bufobj	*b_bufobj;
	long		b_bcount;
	void		*b_caller1;
	caddr_t		b_data;
	int		b_error;
	uint8_t		b_iocmd;
	uint8_t		b_ioflags;
	off_t		b_iooffset;
	long		b_resid;
	void	(*b_iodone)(struct buf *);
	daddr_t b_blkno;		/* Underlying physical block number. */
	off_t	b_offset;		/* Offset into file. */
	TAILQ_ENTRY(buf) b_bobufs;	/* (V) Buffer's associated vnode. */
	struct buf	*b_left;	/* (V) splay tree link */
	struct buf	*b_right;	/* (V) splay tree link */
	uint32_t	b_vflags;	/* (V) BV_* flags */
	TAILQ_ENTRY(buf) b_freelist;	/* (Q) Free list position inactive. */
	unsigned short b_qindex;	/* (Q) buffer queue index */
	uint32_t	b_flags;	/* B_* flags. */
	b_xflags_t b_xflags;		/* extra flags */
	struct lock b_lock;		/* Buffer lock */
	long	b_bufsize;		/* Allocated buffer size. */
	long	b_runningbufspace;	/* when I/O is running, pipelining */
	caddr_t	b_kvabase;		/* base kva for buffer */
	int	b_kvasize;		/* size of kva for buffer */
	daddr_t b_lblkno;		/* Logical block number. */
	struct	vnode *b_vp;		/* Device vnode. */
	int	b_dirtyoff;		/* Offset in buffer of dirty region. */
	int	b_dirtyend;		/* Offset of end of dirty region. */
	struct	ucred *b_rcred;		/* Read credentials reference. */
	struct	ucred *b_wcred;		/* Write credentials reference. */
	void	*b_saveaddr;		/* Original b_addr for physio. */
	union	pager_info {
		int	pg_reqpage;
	} b_pager;
	union	cluster_info {
		TAILQ_HEAD(cluster_list_head, buf) cluster_head;
		TAILQ_ENTRY(buf) cluster_entry;
	} b_cluster;
	struct	vm_page *b_pages[btoc(MAXPHYS)];
	int		b_npages;
	struct	workhead b_dep;		/* (D) List of filesystem dependencies. */
	void	*b_fsprivate1;
	void	*b_fsprivate2;
	void	*b_fsprivate3;
	int	b_pin_count;
};

#define b_object	b_bufobj->bo_object

/*
 * These flags are kept in b_flags.
 *
 * Notes:
 *
 *	B_ASYNC		VOP calls on bp's are usually async whether or not
 *			B_ASYNC is set, but some subsystems, such as NFS, like
 *			to know what is best for the caller so they can
 *			optimize the I/O.
 *
 *	B_PAGING	Indicates that bp is being used by the paging system or
 *			some paging system and that the bp is not linked into
 *			the b_vp's clean/dirty linked lists or ref counts.
 *			Buffer vp reassignments are illegal in this case.
 *
 *	B_CACHE		This may only be set if the buffer is entirely valid.
 *			The situation where B_DELWRI is set and B_CACHE is
 *			clear MUST be committed to disk by getblk() so
 *			B_DELWRI can also be cleared.  See the comments for
 *			getblk() in kern/vfs_bio.c.  If B_CACHE is clear,
 *			the caller is expected to clear BIO_ERROR and B_INVAL,
 *			set BIO_READ, and initiate an I/O.
 *
 *			The 'entire buffer' is defined to be the range from
 *			0 through b_bcount.
 *
 *	B_MALLOC	Request that the buffer be allocated from the malloc
 *			pool, DEV_BSIZE aligned instead of PAGE_SIZE aligned.
 *
 *	B_CLUSTEROK	This flag is typically set for B_DELWRI buffers
 *			by filesystems that allow clustering when the buffer
 *			is fully dirty and indicates that it may be clustered
 *			with other adjacent dirty buffers.  Note the clustering
 *			may not be used with the stage 1 data write under NFS
 *			but may be used for the commit rpc portion.
 *
 *	B_VMIO		Indicates that the buffer is tied into an VM object.
 *			The buffer's data is always PAGE_SIZE aligned even
 *			if b_bufsize and b_bcount are not.  ( b_bufsize is
 *			always at least DEV_BSIZE aligned, though ).
 *
 *	B_DIRECT	Hint that we should attempt to completely free
 *			the pages underlying the buffer.  B_DIRECT is
 *			sticky until the buffer is released and typically
 *			only has an effect when B_RELBUF is also set.
 *
 */

#define	B_AGE		0x00000001	/* Move to age queue when I/O done. */
#define	B_NEEDCOMMIT	0x00000002	/* Append-write in progress. */
#define	B_ASYNC		0x00000004	/* Start I/O, do not wait. */
#define	B_DIRECT	0x00000008	/* direct I/O flag (pls free vmio) */
#define	B_DEFERRED	0x00000010	/* Skipped over for cleaning */
#define	B_CACHE		0x00000020	/* Bread found us in the cache. */
#define	B_VALIDSUSPWRT	0x00000040	/* Valid write during suspension. */
#define	B_DELWRI	0x00000080	/* Delay I/O until buffer reused. */
#define	B_PERSISTENT	0x00000100	/* Perm. ref'ed while EXT2FS mounted. */
#define	B_DONE		0x00000200	/* I/O completed. */
#define	B_EINTR		0x00000400	/* I/O was interrupted */
#define	B_00000800	0x00000800	/* Available flag. */
#define	B_00001000	0x00001000	/* Available flag. */
#define	B_INVAL		0x00002000	/* Does not contain valid info. */
#define	B_00004000	0x00004000	/* Available flag. */
#define	B_NOCACHE	0x00008000	/* Do not cache block after use. */
#define	B_MALLOC	0x00010000	/* malloced b_data */
#define	B_CLUSTEROK	0x00020000	/* Pagein op, so swap() can count it. */
#define	B_000400000	0x00040000	/* Available flag. */
#define	B_000800000	0x00080000	/* Available flag. */
#define	B_00100000	0x00100000	/* Available flag. */
#define	B_DIRTY		0x00200000	/* Needs writing later (in EXT2FS). */
#define	B_RELBUF	0x00400000	/* Release VMIO buffer. */
#define	B_00800000	0x00800000	/* Available flag. */
#define	B_NOCOPY	0x01000000	/* Don't copy-on-write this buf. */
#define	B_NEEDSGIANT	0x02000000	/* Buffer's vnode needs giant. */
#define	B_PAGING	0x04000000	/* volatile paging I/O -- bypass VMIO */
#define B_MANAGED	0x08000000	/* Managed by FS. */
#define B_RAM		0x10000000	/* Read ahead mark (flag) */
#define B_VMIO		0x20000000	/* VMIO flag */
#define B_CLUSTER	0x40000000	/* pagein op, so swap() can count it */
#define B_REMFREE	0x80000000	/* Delayed bremfree */

#define PRINT_BUF_FLAGS "\20\40remfree\37cluster\36vmio\35ram\34b27" \
	"\33paging\32b25\31b24\30b23\27relbuf\26dirty\25b20" \
	"\24b19\23b18\22clusterok\21malloc\20nocache\17b14\16inval" \
	"\15b12\14b11\13eintr\12done\11persist\10delwri\7validsuspwrt" \
	"\6cache\5deferred\4direct\3async\2needcommit\1age"

/*
 * These flags are kept in b_xflags.
 */
#define	BX_VNDIRTY	0x00000001	/* On vnode dirty list */
#define	BX_VNCLEAN	0x00000002	/* On vnode clean list */
#define	BX_BKGRDWRITE	0x00000010	/* Do writes in background */
#define BX_BKGRDMARKER	0x00000020	/* Mark buffer for splay tree */
#define	BX_ALTDATA	0x00000040	/* Holds extended data */

#define	NOOFFSET	(-1LL)		/* No buffer offset calculated yet */

/*
 * These flags are kept in b_vflags.
 */
#define	BV_SCANNED	0x00000001	/* VOP_FSYNC funcs mark written bufs */
#define	BV_BKGRDINPROG	0x00000002	/* Background write in progress */
#define	BV_BKGRDWAIT	0x00000004	/* Background write waiting */
#define	BV_INFREECNT	0x80000000	/* buf is counted in numfreebufs */

#ifdef _KERNEL
/*
 * Buffer locking
 */
extern const char *buf_wmesg;		/* Default buffer lock message */
#define BUF_WMESG "bufwait"
#include <sys/proc.h>			/* XXX for curthread */
#include <sys/mutex.h>

/*
 * Initialize a lock.
 */
#define BUF_LOCKINIT(bp)						\
	lockinit(&(bp)->b_lock, PRIBIO + 4, buf_wmesg, 0, 0)
/*
 *
 * Get a lock sleeping non-interruptably until it becomes available.
 */
#define	BUF_LOCK(bp, locktype, interlock)				\
	_lockmgr_args(&(bp)->b_lock, (locktype), (interlock),		\
	    LK_WMESG_DEFAULT, LK_PRIO_DEFAULT, LK_TIMO_DEFAULT,		\
	    LOCK_FILE, LOCK_LINE)

/*
 * Get a lock sleeping with specified interruptably and timeout.
 */
#define	BUF_TIMELOCK(bp, locktype, interlock, wmesg, catch, timo)	\
	_lockmgr_args(&(bp)->b_lock, (locktype) | LK_TIMELOCK,		\
	    (interlock), (wmesg), (PRIBIO + 4) | (catch), (timo),	\
	    LOCK_FILE, LOCK_LINE)

/*
 * Release a lock. Only the acquiring process may free the lock unless
 * it has been handed off to biodone.
 */
#define	BUF_UNLOCK(bp) do {						\
	KASSERT(((bp)->b_flags & B_REMFREE) == 0,			\
	    ("BUF_UNLOCK %p while B_REMFREE is still set.", (bp)));	\
									\
	(void)_lockmgr_args(&(bp)->b_lock, LK_RELEASE, NULL,		\
	    LK_WMESG_DEFAULT, LK_PRIO_DEFAULT, LK_TIMO_DEFAULT,		\
	    LOCK_FILE, LOCK_LINE);					\
} while (0)

/*
 * Check if a buffer lock is recursed.
 */
#define	BUF_LOCKRECURSED(bp)						\
	lockmgr_recursed(&(bp)->b_lock)

/*
 * Check if a buffer lock is currently held.
 */
#define	BUF_ISLOCKED(bp)						\
	lockstatus(&(bp)->b_lock)
/*
 * Free a buffer lock.
 */
#define BUF_LOCKFREE(bp) 						\
	lockdestroy(&(bp)->b_lock)

/*
 * Print informations on a buffer lock.
 */
#define BUF_LOCKPRINTINFO(bp) 						\
	lockmgr_printinfo(&(bp)->b_lock)

/*
 * Buffer lock assertions.
 */
#if defined(INVARIANTS) && defined(INVARIANT_SUPPORT)
#define	BUF_ASSERT_LOCKED(bp)						\
	_lockmgr_assert(&(bp)->b_lock, KA_LOCKED, LOCK_FILE, LOCK_LINE)
#define	BUF_ASSERT_SLOCKED(bp)						\
	_lockmgr_assert(&(bp)->b_lock, KA_SLOCKED, LOCK_FILE, LOCK_LINE)
#define	BUF_ASSERT_XLOCKED(bp)						\
	_lockmgr_assert(&(bp)->b_lock, KA_XLOCKED, LOCK_FILE, LOCK_LINE)
#define	BUF_ASSERT_UNLOCKED(bp)						\
	_lockmgr_assert(&(bp)->b_lock, KA_UNLOCKED, LOCK_FILE, LOCK_LINE)
#define	BUF_ASSERT_HELD(bp)
#define	BUF_ASSERT_UNHELD(bp)
#else
#define	BUF_ASSERT_LOCKED(bp)
#define	BUF_ASSERT_SLOCKED(bp)
#define	BUF_ASSERT_XLOCKED(bp)
#define	BUF_ASSERT_UNLOCKED(bp)
#define	BUF_ASSERT_HELD(bp)
#define	BUF_ASSERT_UNHELD(bp)
#endif

#ifdef _SYS_PROC_H_	/* Avoid #include <sys/proc.h> pollution */
/*
 * When initiating asynchronous I/O, change ownership of the lock to the
 * kernel. Once done, the lock may legally released by biodone. The
 * original owning process can no longer acquire it recursively, but must
 * wait until the I/O is completed and the lock has been freed by biodone.
 */
#define	BUF_KERNPROC(bp)						\
	_lockmgr_disown(&(bp)->b_lock, LOCK_FILE, LOCK_LINE)
#endif

/*
 * Find out if the lock has waiters or not.
 */
#define	BUF_LOCKWAITERS(bp)						\
	lockmgr_waiters(&(bp)->b_lock)

#endif /* _KERNEL */

struct buf_queue_head {
	TAILQ_HEAD(buf_queue, buf) queue;
	daddr_t last_pblkno;
	struct	buf *insert_point;
	struct	buf *switch_point;
};

/*
 * This structure describes a clustered I/O.  It is stored in the b_saveaddr
 * field of the buffer on which I/O is done.  At I/O completion, cluster
 * callback uses the structure to parcel I/O's to individual buffers, and
 * then free's this structure.
 */
struct cluster_save {
	long	bs_bcount;		/* Saved b_bcount. */
	long	bs_bufsize;		/* Saved b_bufsize. */
	void	*bs_saveaddr;		/* Saved b_addr. */
	int	bs_nchildren;		/* Number of associated buffers. */
	struct buf **bs_children;	/* List of associated buffers. */
};

#ifdef _KERNEL

static __inline int
bwrite(struct buf *bp)
{

	KASSERT(bp->b_bufobj != NULL, ("bwrite: no bufobj bp=%p", bp));
	KASSERT(bp->b_bufobj->bo_ops != NULL, ("bwrite: no bo_ops bp=%p", bp));
	KASSERT(bp->b_bufobj->bo_ops->bop_write != NULL,
	    ("bwrite: no bop_write bp=%p", bp));
	return (BO_WRITE(bp->b_bufobj, bp));
}

static __inline void
bstrategy(struct buf *bp)
{

	KASSERT(bp->b_bufobj != NULL, ("bstrategy: no bufobj bp=%p", bp));
	KASSERT(bp->b_bufobj->bo_ops != NULL,
	    ("bstrategy: no bo_ops bp=%p", bp));
	KASSERT(bp->b_bufobj->bo_ops->bop_strategy != NULL,
	    ("bstrategy: no bop_strategy bp=%p", bp));
	BO_STRATEGY(bp->b_bufobj, bp);
}

static __inline void
buf_start(struct buf *bp)
{
	if (bioops.io_start)
		(*bioops.io_start)(bp);
}

static __inline void
buf_complete(struct buf *bp)
{
	if (bioops.io_complete)
		(*bioops.io_complete)(bp);
}

static __inline void
buf_deallocate(struct buf *bp)
{
	if (bioops.io_deallocate)
		(*bioops.io_deallocate)(bp);
	BUF_LOCKFREE(bp);
}

static __inline int
buf_countdeps(struct buf *bp, int i)
{
	if (bioops.io_countdeps)
		return ((*bioops.io_countdeps)(bp, i));
	else
		return (0);
}

#endif /* _KERNEL */

/*
 * Zero out the buffer's data area.
 */
#define	clrbuf(bp) {							\
	bzero((bp)->b_data, (u_int)(bp)->b_bcount);			\
	(bp)->b_resid = 0;						\
}

/*
 * Flags for getblk's last parameter.
 */
#define	GB_LOCK_NOWAIT	0x0001		/* Fail if we block on a buf lock. */
#define	GB_NOCREAT	0x0002		/* Don't create a buf if not found. */
#define	GB_NOWAIT_BD	0x0004		/* Do not wait for bufdaemon */

#ifdef _KERNEL
extern int	nbuf;			/* The number of buffer headers */
extern long	maxswzone;		/* Max KVA for swap structures */
extern long	maxbcache;		/* Max KVA for buffer cache */
extern long	runningbufspace;
extern long	hibufspace;
extern int	dirtybufthresh;
extern int	bdwriteskip;
extern int	dirtybufferflushes;
extern int	altbufferflushes;
extern int      buf_maxio;              /* nominal maximum I/O for buffer */
extern struct	buf *buf;		/* The buffer headers. */
extern char	*buffers;		/* The buffer contents. */
extern int	bufpages;		/* Number of memory pages in the buffer pool. */
extern struct	buf *swbuf;		/* Swap I/O buffer headers. */
extern int	nswbuf;			/* Number of swap I/O buffer headers. */
extern int	cluster_pbuf_freecnt;	/* Number of pbufs for clusters */
extern int	vnode_pbuf_freecnt;	/* Number of pbufs for vnode pager */

void	runningbufwakeup(struct buf *);
void	waitrunningbufspace(void);
caddr_t	kern_vfs_bio_buffer_alloc(caddr_t v, long physmem_est);
void	bufinit(void);
void	bwillwrite(void);
int	buf_dirty_count_severe(void);
void	bremfree(struct buf *);
void	bremfreef(struct buf *);	/* XXX Force bremfree, only for nfs. */
int	bread(struct vnode *, daddr_t, int, struct ucred *, struct buf **);
void	breada(struct vnode *, daddr_t *, int *, int, struct ucred *);
int	breadn(struct vnode *, daddr_t, int, daddr_t *, int *, int,
	    struct ucred *, struct buf **);
void	bdwrite(struct buf *);
void	bawrite(struct buf *);
void	bdirty(struct buf *);
void	bundirty(struct buf *);
void	bufstrategy(struct bufobj *, struct buf *);
void	brelse(struct buf *);
void	bqrelse(struct buf *);
int	vfs_bio_awrite(struct buf *);
struct buf *     getpbuf(int *);
struct buf *incore(struct bufobj *, daddr_t);
struct buf *gbincore(struct bufobj *, daddr_t);
struct buf *getblk(struct vnode *, daddr_t, int, int, int, int);
struct buf *geteblk(int, int);
int	bufwait(struct buf *);
int	bufwrite(struct buf *);
void	bufdone(struct buf *);
void	bufdone_finish(struct buf *);
void	bd_speedup(void);

int	cluster_read(struct vnode *, u_quad_t, daddr_t, long,
	    struct ucred *, long, int, struct buf **);
int	cluster_wbuild(struct vnode *, long, daddr_t, int);
void	cluster_write(struct vnode *, struct buf *, u_quad_t, int);
void	vfs_bio_set_valid(struct buf *, int base, int size);
void	vfs_bio_clrbuf(struct buf *);
void	vfs_busy_pages(struct buf *, int clear_modify);
void	vfs_unbusy_pages(struct buf *);
int	vmapbuf(struct buf *);
void	vunmapbuf(struct buf *);
void	relpbuf(struct buf *, int *);
void	brelvp(struct buf *);
void	bgetvp(struct vnode *, struct buf *);
void	pbgetbo(struct bufobj *bo, struct buf *bp);
void	pbgetvp(struct vnode *, struct buf *);
void	pbrelbo(struct buf *);
void	pbrelvp(struct buf *);
int	allocbuf(struct buf *bp, int size);
void	reassignbuf(struct buf *);
struct	buf *trypbuf(int *);
void	bwait(struct buf *, u_char, const char *);
void	bdone(struct buf *);
void	bpin(struct buf *);
void	bunpin(struct buf *);
void 	bunpin_wait(struct buf *);

#endif /* _KERNEL */

#endif /* !_SYS_BUF_H_ */


code:
/*-
 * Copyright (c) 2007-2009 Kip Macy <kmacy@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.
 * 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/buf_ring.h 207673 2010-05-05 20:39:02Z joel $
 *
 */

#ifndef	_SYS_BUF_RING_H_
#define	_SYS_BUF_RING_H_

#include <machine/cpu.h>

#if defined(INVARIANTS) && !defined(DEBUG_BUFRING)
#define DEBUG_BUFRING 1
#endif

#ifdef DEBUG_BUFRING
#include <sys/lock.h>
#include <sys/mutex.h>
#endif

struct buf_ring {
	volatile uint32_t	br_prod_head;
	volatile uint32_t	br_prod_tail;
	int              	br_prod_size;
	int              	br_prod_mask;
	uint64_t		br_drops;
	uint64_t		br_prod_bufs;
	uint64_t		br_prod_bytes;
	/*
	 * Pad out to next L2 cache line
	 */
	uint64_t	  	_pad0[11];

	volatile uint32_t	br_cons_head;
	volatile uint32_t	br_cons_tail;
	int		 	br_cons_size;
	int              	br_cons_mask;

	/*
	 * Pad out to next L2 cache line
	 */
	uint64_t	  	_pad1[14];
#ifdef DEBUG_BUFRING
	struct mtx		*br_lock;
#endif
	void			*br_ring[0];
};

/*
 * multi-producer safe lock-free ring buffer enqueue
 *
 */
static __inline int
buf_ring_enqueue_bytes(struct buf_ring *br, void *buf, int nbytes)
{
	uint32_t prod_head, prod_next;
	uint32_t cons_tail;
	int success;
#ifdef DEBUG_BUFRING
	int i;
	for (i = br->br_cons_head; i != br->br_prod_head;
	     i = ((i + 1) & br->br_cons_mask))
		if(br->br_ring[i] == buf)
			panic("buf=%p already enqueue at %d prod=%d cons=%d",
			    buf, i, br->br_prod_tail, br->br_cons_tail);
#endif
	critical_enter();
	do {
		prod_head = br->br_prod_head;
		cons_tail = br->br_cons_tail;

		prod_next = (prod_head + 1) & br->br_prod_mask;

		if (prod_next == cons_tail) {
			critical_exit();
			return (ENOBUFS);
		}

		success = atomic_cmpset_int(&br->br_prod_head, prod_head,
		    prod_next);
	} while (success == 0);
#ifdef DEBUG_BUFRING
	if (br->br_ring[prod_head] != NULL)
		panic("dangling value in enqueue");
#endif
	br->br_ring[prod_head] = buf;
	wmb();

	/*
	 * If there are other enqueues in progress
	 * that preceeded us, we need to wait for them
	 * to complete
	 */
	while (br->br_prod_tail != prod_head)
		cpu_spinwait();
	br->br_prod_bufs++;
	br->br_prod_bytes += nbytes;
	br->br_prod_tail = prod_next;
	critical_exit();
	return (0);
}

static __inline int
buf_ring_enqueue(struct buf_ring *br, void *buf)
{

	return (buf_ring_enqueue_bytes(br, buf, 0));
}

/*
 * multi-consumer safe dequeue
 *
 */
static __inline void *
buf_ring_dequeue_mc(struct buf_ring *br)
{
	uint32_t cons_head, cons_next;
	uint32_t prod_tail;
	void *buf;
	int success;

	critical_enter();
	do {
		cons_head = br->br_cons_head;
		prod_tail = br->br_prod_tail;

		cons_next = (cons_head + 1) & br->br_cons_mask;

		if (cons_head == prod_tail) {
			critical_exit();
			return (NULL);
		}

		success = atomic_cmpset_int(&br->br_cons_head, cons_head,
		    cons_next);
	} while (success == 0);

	buf = br->br_ring[cons_head];
#ifdef DEBUG_BUFRING
	br->br_ring[cons_head] = NULL;
#endif
	rmb();

	/*
	 * If there are other dequeues in progress
	 * that preceeded us, we need to wait for them
	 * to complete
	 */
	while (br->br_cons_tail != cons_head)
		cpu_spinwait();

	br->br_cons_tail = cons_next;
	critical_exit();

	return (buf);
}

/*
 * single-consumer dequeue
 * use where dequeue is protected by a lock
 * e.g. a network driver's tx queue lock
 */
static __inline void *
buf_ring_dequeue_sc(struct buf_ring *br)
{
	uint32_t cons_head, cons_next, cons_next_next;
	uint32_t prod_tail;
	void *buf;

	cons_head = br->br_cons_head;
	prod_tail = br->br_prod_tail;

	cons_next = (cons_head + 1) & br->br_cons_mask;
	cons_next_next = (cons_head + 2) & br->br_cons_mask;

	if (cons_head == prod_tail)
		return (NULL);

#ifdef PREFETCH_DEFINED
	if (cons_next != prod_tail) {
		prefetch(br->br_ring[cons_next]);
		if (cons_next_next != prod_tail)
			prefetch(br->br_ring[cons_next_next]);
	}
#endif
	br->br_cons_head = cons_next;
	buf = br->br_ring[cons_head];

#ifdef DEBUG_BUFRING
	br->br_ring[cons_head] = NULL;
	if (!mtx_owned(br->br_lock))
		panic("lock not held on single consumer dequeue");
	if (br->br_cons_tail != cons_head)
		panic("inconsistent list cons_tail=%d cons_head=%d",
		    br->br_cons_tail, cons_head);
#endif
	br->br_cons_tail = cons_next;
	return (buf);
}

/*
 * return a pointer to the first entry in the ring
 * without modifying it, or NULL if the ring is empty
 * race-prone if not protected by a lock
 */
static __inline void *
buf_ring_peek(struct buf_ring *br)
{

#ifdef DEBUG_BUFRING
	if ((br->br_lock != NULL) && !mtx_owned(br->br_lock))
		panic("lock not held on single consumer dequeue");
#endif
	/*
	 * I believe it is safe to not have a memory barrier
	 * here because we control cons and tail is worst case
	 * a lagging indicator so we worst case we might
	 * return NULL immediately after a buffer has been enqueued
	 */
	if (br->br_cons_head == br->br_prod_tail)
		return (NULL);

	return (br->br_ring[br->br_cons_head]);
}

static __inline int
buf_ring_full(struct buf_ring *br)
{

	return (((br->br_prod_head + 1) & br->br_prod_mask) == br->br_cons_tail);
}

static __inline int
buf_ring_empty(struct buf_ring *br)
{

	return (br->br_cons_head == br->br_prod_tail);
}

static __inline int
buf_ring_count(struct buf_ring *br)
{

	return ((br->br_prod_size + br->br_prod_tail - br->br_cons_tail)
	    & br->br_prod_mask);
}

struct buf_ring *buf_ring_alloc(int count, struct malloc_type *type, int flags,
    struct mtx *);
void buf_ring_free(struct buf_ring *br, struct malloc_type *type);

#endif

repo_name: veiledmerc/mira

license: mit


code:
/*-
 * Copyright (c) 2004 Poul-Henning Kamp
 * 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/bufobj.h 183754 2008-10-10 21:23:50Z attilio $
 */

/*
 * Architectural notes:
 *
 * bufobj is a new object which is what buffers hang from in the buffer
 * cache.
 *
 * This used to be vnodes, but we need non-vnode code to be able
 * to use the buffer cache as well, specifically geom classes like gbde,
 * raid3 and raid5.
 *
 * All vnodes will contain a bufobj initially, but down the road we may
 * want to only allocate bufobjs when they are needed.  There could be a
 * large number of vnodes in the system which wouldn't need a bufobj during
 * their lifetime.
 *
 * The exact relationship to the vmobject is not determined at this point,
 * it may in fact be that we find them to be two sides of the same object
 * once things starts to crystalize.
 */

#ifndef _SYS_BUFOBJ_H_
#define _SYS_BUFOBJ_H_

#if defined(_KERNEL) || defined(_KVM_VNODE)

#include <sys/queue.h>
#include <sys/_lock.h>
#include <sys/_mutex.h>

struct bufobj;
struct buf_ops;

extern struct buf_ops buf_ops_bio;

TAILQ_HEAD(buflists, buf);

/* A Buffer splay list */
struct bufv {
	struct buflists	bv_hd;		/* Sorted blocklist */
	struct buf	*bv_root;	/* Buf splay tree */
	int		bv_cnt;		/* Number of buffers */
};

typedef void b_strategy_t(struct bufobj *, struct buf *);
typedef int b_write_t(struct buf *);
typedef int b_sync_t(struct bufobj *, int waitfor);
typedef void b_bdflush_t(struct bufobj *, struct buf *);

struct buf_ops {
	char		*bop_name;
	b_write_t	*bop_write;
	b_strategy_t	*bop_strategy;
	b_sync_t	*bop_sync;
	b_bdflush_t	*bop_bdflush;
};

#define BO_STRATEGY(bo, bp)	((bo)->bo_ops->bop_strategy((bo), (bp)))
#define BO_SYNC(bo, w)		((bo)->bo_ops->bop_sync((bo), (w)))
#define BO_WRITE(bo, bp)	((bo)->bo_ops->bop_write((bp)))
#define BO_BDFLUSH(bo, bp)	((bo)->bo_ops->bop_bdflush((bo), (bp)))

struct bufobj {
	struct mtx	bo_mtx;		/* Mutex which protects "i" things */
	struct bufv	bo_clean;	/* i Clean buffers */
	struct bufv	bo_dirty;	/* i Dirty buffers */
	long		bo_numoutput;	/* i Writes in progress */
	u_int		bo_flag;	/* i Flags */
	struct buf_ops	*bo_ops;	/* - Buffer operations */
	int		bo_bsize;	/* - Block size for i/o */
	struct vm_object *bo_object;	/* v Place to store VM object */
	LIST_ENTRY(bufobj) bo_synclist;	/* S dirty vnode list */
	void		*bo_private;	/* private pointer */
	struct vnode	*__bo_vnode;	/*
					 * XXX: This vnode pointer is here
					 * XXX: only to keep the syncer working
					 * XXX: for now.
					 */
};

/*
 * XXX BO_ONWORKLST could be replaced with a check for NULL list elements
 * in v_synclist.
 */
#define	BO_ONWORKLST	(1 << 0)	/* On syncer work-list */
#define	BO_WWAIT	(1 << 1)	/* Wait for output to complete */
#define	BO_NEEDSGIANT	(1 << 2)	/* Require giant for child buffers. */

#define	BO_MTX(bo)		(&(bo)->bo_mtx)
#define	BO_LOCK(bo)		mtx_lock(BO_MTX((bo)))
#define	BO_UNLOCK(bo)		mtx_unlock(BO_MTX((bo)))
#define	ASSERT_BO_LOCKED(bo)	mtx_assert(BO_MTX((bo)), MA_OWNED)
#define	ASSERT_BO_UNLOCKED(bo)	mtx_assert(BO_MTX((bo)), MA_NOTOWNED)

void bufobj_wdrop(struct bufobj *bo);
void bufobj_wref(struct bufobj *bo);
void bufobj_wrefl(struct bufobj *bo);
int bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo);
int bufobj_wwait(struct bufobj *bo, int slpflag, int timeo);
int bufsync(struct bufobj *bo, int waitfor);
void bufbdflush(struct bufobj *bo, struct buf *bp);

#endif /* defined(_KERNEL) || defined(_KVM_VNODE) */
#endif /* _SYS_BUFOBJ_H_ */


code:
/*-
 * Copyright (c) 1997,1998,2003 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/bus.h 227977 2011-11-25 17:07:27Z marius $
 */

#ifndef _SYS_BUS_H_
#define _SYS_BUS_H_

#include <machine/_limits.h>
#include <sys/_bus_dma.h>

/**
 * @defgroup NEWBUS newbus - a generic framework for managing devices
 * @{
 */

/**
 * @brief Interface information structure.
 */
struct u_businfo {
	int	ub_version;		/**< @brief interface version */
#define BUS_USER_VERSION	1
	int	ub_generation;		/**< @brief generation count */
};

/**
 * @brief State of the device.
 */
typedef enum device_state {
	DS_NOTPRESENT = 10,		/**< @brief not probed or probe failed */
	DS_ALIVE = 20,			/**< @brief probe succeeded */
	DS_ATTACHED = 30,		/**< @brief attach method called */
	DS_BUSY = 40			/**< @brief device is open */
} device_state_t;

/**
 * @brief Device information exported to userspace.
 */
struct u_device {
	uintptr_t	dv_handle;
	uintptr_t	dv_parent;

	char		dv_name[32];		/**< @brief Name of device in tree. */
	char		dv_desc[32];		/**< @brief Driver description */
	char		dv_drivername[32];	/**< @brief Driver name */
	char		dv_pnpinfo[128];	/**< @brief Plug and play info */
	char		dv_location[128];	/**< @brief Where is the device? */
	uint32_t	dv_devflags;		/**< @brief API Flags for device */
	uint16_t	dv_flags;		/**< @brief flags for dev date */
	device_state_t	dv_state;		/**< @brief State of attachment */
	/* XXX more driver info? */
};

#ifdef _KERNEL

#include <sys/queue.h>
#include <sys/kobj.h>

/**
 * devctl hooks.  Typically one should use the devctl_notify
 * hook to send the message.  However, devctl_queue_data is also
 * included in case devctl_notify isn't sufficiently general.
 */
boolean_t devctl_process_running(void);
void devctl_notify_f(const char *__system, const char *__subsystem,
    const char *__type, const char *__data, int __flags);
void devctl_notify(const char *__system, const char *__subsystem,
    const char *__type, const char *__data);
void devctl_queue_data_f(char *__data, int __flags);
void devctl_queue_data(char *__data);

/**
 * @brief A device driver (included mainly for compatibility with
 * FreeBSD 4.x).
 */
typedef struct kobj_class	driver_t;

/**
 * @brief A device class
 *
 * The devclass object has two main functions in the system. The first
 * is to manage the allocation of unit numbers for device instances
 * and the second is to hold the list of device drivers for a
 * particular bus type. Each devclass has a name and there cannot be
 * two devclasses with the same name. This ensures that unique unit
 * numbers are allocated to device instances.
 *
 * Drivers that support several different bus attachments (e.g. isa,
 * pci, pccard) should all use the same devclass to ensure that unit
 * numbers do not conflict.
 *
 * Each devclass may also have a parent devclass. This is used when
 * searching for device drivers to allow a form of inheritance. When
 * matching drivers with devices, first the driver list of the parent
 * device's devclass is searched. If no driver is found in that list,
 * the search continues in the parent devclass (if any).
 */
typedef struct devclass		*devclass_t;

/**
 * @brief A device method (included mainly for compatibility with
 * FreeBSD 4.x).
 */
#define device_method_t		kobj_method_t

/**
 * @brief Driver interrupt filter return values
 *
 * If a driver provides an interrupt filter routine it must return an
 * integer consisting of oring together zero or more of the following
 * flags:
 *
 *	FILTER_STRAY	- this device did not trigger the interrupt
 *	FILTER_HANDLED	- the interrupt has been fully handled and can be EOId
 *	FILTER_SCHEDULE_THREAD - the threaded interrupt handler should be
 *			  scheduled to execute
 *
 * If the driver does not provide a filter, then the interrupt code will
 * act is if the filter had returned FILTER_SCHEDULE_THREAD.  Note that it
 * is illegal to specify any other flag with FILTER_STRAY and that it is
 * illegal to not specify either of FILTER_HANDLED or FILTER_SCHEDULE_THREAD
 * if FILTER_STRAY is not specified.
 */
#define	FILTER_STRAY		0x01
#define	FILTER_HANDLED		0x02
#define	FILTER_SCHEDULE_THREAD	0x04

/**
 * @brief Driver interrupt service routines
 *
 * The filter routine is run in primary interrupt context and may not
 * block or use regular mutexes.  It may only use spin mutexes for
 * synchronization.  The filter may either completely handle the
 * interrupt or it may perform some of the work and defer more
 * expensive work to the regular interrupt handler.  If a filter
 * routine is not registered by the driver, then the regular interrupt
 * handler is always used to handle interrupts from this device.
 *
 * The regular interrupt handler executes in its own thread context
 * and may use regular mutexes.  However, it is prohibited from
 * sleeping on a sleep queue.
 */
typedef int driver_filter_t(void*);
typedef void driver_intr_t(void*);

/**
 * @brief Interrupt type bits.
 *
 * These flags are used both by newbus interrupt
 * registration (nexus.c) and also in struct intrec, which defines
 * interrupt properties.
 *
 * XXX We should probably revisit this and remove the vestiges of the
 * spls implicit in names like INTR_TYPE_TTY. In the meantime, don't
 * confuse things by renaming them (Grog, 18 July 2000).
 *
 * We define this in terms of bits because some devices may belong
 * to multiple classes (and therefore need to be included in
 * multiple interrupt masks, which is what this really serves to
 * indicate. Buses which do interrupt remapping will want to
 * change their type to reflect what sort of devices are underneath.
 */
enum intr_type {
	INTR_TYPE_TTY = 1,
	INTR_TYPE_BIO = 2,
	INTR_TYPE_NET = 4,
	INTR_TYPE_CAM = 8,
	INTR_TYPE_MISC = 16,
	INTR_TYPE_CLK = 32,
	INTR_TYPE_AV = 64,
	INTR_EXCL = 256,		/* exclusive interrupt */
	INTR_MPSAFE = 512,		/* this interrupt is SMP safe */
	INTR_ENTROPY = 1024,		/* this interrupt provides entropy */
	INTR_MD1 = 4096,		/* flag reserved for MD use */
	INTR_MD2 = 8192,		/* flag reserved for MD use */
	INTR_MD3 = 16384,		/* flag reserved for MD use */
	INTR_MD4 = 32768		/* flag reserved for MD use */
};

enum intr_trigger {
	INTR_TRIGGER_CONFORM = 0,
	INTR_TRIGGER_EDGE = 1,
	INTR_TRIGGER_LEVEL = 2
};

enum intr_polarity {
	INTR_POLARITY_CONFORM = 0,
	INTR_POLARITY_HIGH = 1,
	INTR_POLARITY_LOW = 2
};

typedef int (*devop_t)(void);

/**
 * @brief This structure is deprecated.
 *
 * Use the kobj(9) macro DEFINE_CLASS to
 * declare classes which implement device drivers.
 */
struct driver {
	KOBJ_CLASS_FIELDS;
};

/*
 * Definitions for drivers which need to keep simple lists of resources
 * for their child devices.
 */
struct	resource;

/**
 * @brief An entry for a single resource in a resource list.
 */
struct resource_list_entry {
	STAILQ_ENTRY(resource_list_entry) link;
	int	type;			/**< @brief type argument to alloc_resource */
	int	rid;			/**< @brief resource identifier */
	int	flags;			/**< @brief resource flags */
	struct	resource *res;		/**< @brief the real resource when allocated */
	u_long	start;			/**< @brief start of resource range */
	u_long	end;			/**< @brief end of resource range */
	u_long	count;			/**< @brief count within range */
};
STAILQ_HEAD(resource_list, resource_list_entry);

#define	RLE_RESERVED		0x0001	/* Reserved by the parent bus. */
#define	RLE_ALLOCATED		0x0002	/* Reserved resource is allocated. */
#define	RLE_PREFETCH		0x0004	/* Resource is a prefetch range. */

void	resource_list_init(struct resource_list *rl);
void	resource_list_free(struct resource_list *rl);
struct resource_list_entry *
	resource_list_add(struct resource_list *rl,
			  int type, int rid,
			  u_long start, u_long end, u_long count);
int	resource_list_add_next(struct resource_list *rl,
			  int type,
			  u_long start, u_long end, u_long count);
int	resource_list_busy(struct resource_list *rl,
			   int type, int rid);
int	resource_list_reserved(struct resource_list *rl, int type, int rid);
struct resource_list_entry*
	resource_list_find(struct resource_list *rl,
			   int type, int rid);
void	resource_list_delete(struct resource_list *rl,
			     int type, int rid);
struct resource *
	resource_list_alloc(struct resource_list *rl,
			    device_t bus, device_t child,
			    int type, int *rid,
			    u_long start, u_long end,
			    u_long count, u_int flags);
int	resource_list_release(struct resource_list *rl,
			      device_t bus, device_t child,
			      int type, int rid, struct resource *res);
struct resource *
	resource_list_reserve(struct resource_list *rl,
			      device_t bus, device_t child,
			      int type, int *rid,
			      u_long start, u_long end,
			      u_long count, u_int flags);
int	resource_list_unreserve(struct resource_list *rl,
				device_t bus, device_t child,
				int type, int rid);
void	resource_list_purge(struct resource_list *rl);
int	resource_list_print_type(struct resource_list *rl,
				 const char *name, int type,
				 const char *format);

/*
 * The root bus, to which all top-level busses are attached.
 */
extern device_t root_bus;
extern devclass_t root_devclass;
void	root_bus_configure(void);

/*
 * Useful functions for implementing busses.
 */

int	bus_generic_activate_resource(device_t dev, device_t child, int type,
				      int rid, struct resource *r);
device_t
	bus_generic_add_child(device_t dev, u_int order, const char *name,
			      int unit);
int	bus_generic_adjust_resource(device_t bus, device_t child, int type,
				    struct resource *r, u_long start,
				    u_long end);
struct resource *
	bus_generic_alloc_resource(device_t bus, device_t child, int type,
				   int *rid, u_long start, u_long end,
				   u_long count, u_int flags);
int	bus_generic_attach(device_t dev);
int	bus_generic_bind_intr(device_t dev, device_t child,
			      struct resource *irq, int cpu);
int	bus_generic_child_present(device_t dev, device_t child);
int	bus_generic_config_intr(device_t, int, enum intr_trigger,
				enum intr_polarity);
int	bus_generic_describe_intr(device_t dev, device_t child,
				  struct resource *irq, void *cookie,
				  const char *descr);
int	bus_generic_deactivate_resource(device_t dev, device_t child, int type,
					int rid, struct resource *r);
int	bus_generic_detach(device_t dev);
void	bus_generic_driver_added(device_t dev, driver_t *driver);
bus_dma_tag_t
	bus_generic_get_dma_tag(device_t dev, device_t child);
struct resource_list *
	bus_generic_get_resource_list (device_t, device_t);
void	bus_generic_new_pass(device_t dev);
int	bus_print_child_header(device_t dev, device_t child);
int	bus_print_child_footer(device_t dev, device_t child);
int	bus_generic_print_child(device_t dev, device_t child);
int	bus_generic_probe(device_t dev);
int	bus_generic_read_ivar(device_t dev, device_t child, int which,
			      uintptr_t *result);
int	bus_generic_release_resource(device_t bus, device_t child,
				     int type, int rid, struct resource *r);
int	bus_generic_resume(device_t dev);
int	bus_generic_setup_intr(device_t dev, device_t child,
			       struct resource *irq, int flags,
			       driver_filter_t *filter, driver_intr_t *intr,
			       void *arg, void **cookiep);

struct resource *
	bus_generic_rl_alloc_resource (device_t, device_t, int, int *,
				       u_long, u_long, u_long, u_int);
void	bus_generic_rl_delete_resource (device_t, device_t, int, int);
int	bus_generic_rl_get_resource (device_t, device_t, int, int, u_long *,
				     u_long *);
int	bus_generic_rl_set_resource (device_t, device_t, int, int, u_long,
				     u_long);
int	bus_generic_rl_release_resource (device_t, device_t, int, int,
					 struct resource *);

int	bus_generic_shutdown(device_t dev);
int	bus_generic_suspend(device_t dev);
int	bus_generic_teardown_intr(device_t dev, device_t child,
				  struct resource *irq, void *cookie);
int	bus_generic_write_ivar(device_t dev, device_t child, int which,
			       uintptr_t value);

/*
 * Wrapper functions for the BUS_*_RESOURCE methods to make client code
 * a little simpler.
 */

struct resource_spec {
	int	type;
	int	rid;
	int	flags;
};

int	bus_alloc_resources(device_t dev, struct resource_spec *rs,
			    struct resource **res);
void	bus_release_resources(device_t dev, const struct resource_spec *rs,
			      struct resource **res);

int	bus_adjust_resource(device_t child, int type, struct resource *r,
			    u_long start, u_long end);
struct	resource *bus_alloc_resource(device_t dev, int type, int *rid,
				     u_long start, u_long end, u_long count,
				     u_int flags);
int	bus_activate_resource(device_t dev, int type, int rid,
			      struct resource *r);
int	bus_deactivate_resource(device_t dev, int type, int rid,
				struct resource *r);
bus_dma_tag_t bus_get_dma_tag(device_t dev);
int	bus_release_resource(device_t dev, int type, int rid,
			     struct resource *r);
int	bus_free_resource(device_t dev, int type, struct resource *r);
int	bus_setup_intr(device_t dev, struct resource *r, int flags,
		       driver_filter_t filter, driver_intr_t handler,
		       void *arg, void **cookiep);
int	bus_teardown_intr(device_t dev, struct resource *r, void *cookie);
int	bus_bind_intr(device_t dev, struct resource *r, int cpu);
int	bus_describe_intr(device_t dev, struct resource *irq, void *cookie,
			  const char *fmt, ...);
int	bus_set_resource(device_t dev, int type, int rid,
			 u_long start, u_long count);
int	bus_get_resource(device_t dev, int type, int rid,
			 u_long *startp, u_long *countp);
u_long	bus_get_resource_start(device_t dev, int type, int rid);
u_long	bus_get_resource_count(device_t dev, int type, int rid);
void	bus_delete_resource(device_t dev, int type, int rid);
int	bus_child_present(device_t child);
int	bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen);
int	bus_child_location_str(device_t child, char *buf, size_t buflen);
void	bus_enumerate_hinted_children(device_t bus);

static __inline struct resource *
bus_alloc_resource_any(device_t dev, int type, int *rid, u_int flags)
{
	return (bus_alloc_resource(dev, type, rid, 0ul, ~0ul, 1, flags));
}

/*
 * Access functions for device.
 */
device_t	device_add_child(device_t dev, const char *name, int unit);
device_t	device_add_child_ordered(device_t dev, u_int order,
					 const char *name, int unit);
void	device_busy(device_t dev);
int	device_delete_child(device_t dev, device_t child);
int	device_attach(device_t dev);
int	device_detach(device_t dev);
void	device_disable(device_t dev);
void	device_enable(device_t dev);
device_t	device_find_child(device_t dev, const char *classname,
				  int unit);
const char	*device_get_desc(device_t dev);
devclass_t	device_get_devclass(device_t dev);
driver_t	*device_get_driver(device_t dev);
u_int32_t	device_get_flags(device_t dev);
device_t	device_get_parent(device_t dev);
int	device_get_children(device_t dev, device_t **listp, int *countp);
void	*device_get_ivars(device_t dev);
void	device_set_ivars(device_t dev, void *ivars);
const	char *device_get_name(device_t dev);
const	char *device_get_nameunit(device_t dev);
void	*device_get_softc(device_t dev);
device_state_t	device_get_state(device_t dev);
int	device_get_unit(device_t dev);
struct sysctl_ctx_list *device_get_sysctl_ctx(device_t dev);
struct sysctl_oid *device_get_sysctl_tree(device_t dev);
int	device_is_alive(device_t dev);	/* did probe succeed? */
int	device_is_attached(device_t dev);	/* did attach succeed? */
int	device_is_enabled(device_t dev);
int	device_is_quiet(device_t dev);
int	device_print_prettyname(device_t dev);
int	device_printf(device_t dev, const char *, ...) __printflike(2, 3);
int	device_probe(device_t dev);
int	device_probe_and_attach(device_t dev);
int	device_probe_child(device_t bus, device_t dev);
int	device_quiesce(device_t dev);
void	device_quiet(device_t dev);
void	device_set_desc(device_t dev, const char* desc);
void	device_set_desc_copy(device_t dev, const char* desc);
int	device_set_devclass(device_t dev, const char *classname);
int	device_set_driver(device_t dev, driver_t *driver);
void	device_set_flags(device_t dev, u_int32_t flags);
void	device_set_softc(device_t dev, void *softc);
int	device_set_unit(device_t dev, int unit);	/* XXX DONT USE XXX */
int	device_shutdown(device_t dev);
void	device_unbusy(device_t dev);
void	device_verbose(device_t dev);

/*
 * Access functions for devclass.
 */
int		devclass_add_driver(devclass_t dc, driver_t *driver,
				    int pass, devclass_t *dcp);
devclass_t	devclass_create(const char *classname);
int		devclass_delete_driver(devclass_t busclass, driver_t *driver);
devclass_t	devclass_find(const char *classname);
const char	*devclass_get_name(devclass_t dc);
device_t	devclass_get_device(devclass_t dc, int unit);
void	*devclass_get_softc(devclass_t dc, int unit);
int	devclass_get_devices(devclass_t dc, device_t **listp, int *countp);
int	devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp);
int	devclass_get_count(devclass_t dc);
int	devclass_get_maxunit(devclass_t dc);
int	devclass_find_free_unit(devclass_t dc, int unit);
void	devclass_set_parent(devclass_t dc, devclass_t pdc);
devclass_t	devclass_get_parent(devclass_t dc);
struct sysctl_ctx_list *devclass_get_sysctl_ctx(devclass_t dc);
struct sysctl_oid *devclass_get_sysctl_tree(devclass_t dc);

/*
 * Access functions for device resources.
 */

int	resource_int_value(const char *name, int unit, const char *resname,
			   int *result);
int	resource_long_value(const char *name, int unit, const char *resname,
			    long *result);
int	resource_string_value(const char *name, int unit, const char *resname,
			      const char **result);
int	resource_disabled(const char *name, int unit);
int	resource_find_match(int *anchor, const char **name, int *unit,
			    const char *resname, const char *value);
int	resource_find_dev(int *anchor, const char *name, int *unit,
			  const char *resname, const char *value);
int	resource_set_int(const char *name, int unit, const char *resname,
			 int value);
int	resource_set_long(const char *name, int unit, const char *resname,
			  long value);
int	resource_set_string(const char *name, int unit, const char *resname,
			    const char *value);
/*
 * Functions for maintaining and checking consistency of
 * bus information exported to userspace.
 */
int	bus_data_generation_check(int generation);
void	bus_data_generation_update(void);

/**
 * Some convenience defines for probe routines to return.  These are just
 * suggested values, and there's nothing magical about them.
 * BUS_PROBE_SPECIFIC is for devices that cannot be reprobed, and that no
 * possible other driver may exist (typically legacy drivers who don't fallow
 * all the rules, or special needs drivers).  BUS_PROBE_VENDOR is the
 * suggested value that vendor supplied drivers use.  This is for source or
 * binary drivers that are not yet integrated into the FreeBSD tree.  Its use
 * in the base OS is prohibited.  BUS_PROBE_DEFAULT is the normal return value
 * for drivers to use.  It is intended that nearly all of the drivers in the
 * tree should return this value.  BUS_PROBE_LOW_PRIORITY are for drivers that
 * have special requirements like when there are two drivers that support
 * overlapping series of hardware devices.  In this case the one that supports
 * the older part of the line would return this value, while the one that
 * supports the newer ones would return BUS_PROBE_DEFAULT.  BUS_PROBE_GENERIC
 * is for drivers that wish to have a generic form and a specialized form,
 * like is done with the pci bus and the acpi pci bus.  BUS_PROBE_HOOVER is
 * for those busses that implement a generic device place-holder for devices on
 * the bus that have no more specific river for them (aka ugen).
 * BUS_PROBE_NOWILDCARD or lower means that the device isn't really bidding
 * for a device node, but accepts only devices that its parent has told it
 * use this driver.
 */
#define BUS_PROBE_SPECIFIC	0	/* Only I can use this device */
#define BUS_PROBE_VENDOR	(-10)	/* Vendor supplied driver */
#define BUS_PROBE_DEFAULT	(-20)	/* Base OS default driver */
#define BUS_PROBE_LOW_PRIORITY	(-40)	/* Older, less desirable drivers */
#define BUS_PROBE_GENERIC	(-100)	/* generic driver for dev */
#define BUS_PROBE_HOOVER	(-500)	/* Generic dev for all devs on bus */
#define BUS_PROBE_NOWILDCARD	(-2000000000) /* No wildcard device matches */

/**
 * During boot, the device tree is scanned multiple times.  Each scan,
 * or pass, drivers may be attached to devices.  Each driver
 * attachment is assigned a pass number.  Drivers may only probe and
 * attach to devices if their pass number is less than or equal to the
 * current system-wide pass number.  The default pass is the last pass
 * and is used by most drivers.  Drivers needed by the scheduler are
 * probed in earlier passes.
 */
#define	BUS_PASS_ROOT		0	/* Used to attach root0. */
#define	BUS_PASS_BUS		10	/* Busses and bridges. */
#define	BUS_PASS_CPU		20	/* CPU devices. */
#define	BUS_PASS_RESOURCE	30	/* Resource discovery. */
#define	BUS_PASS_INTERRUPT	40	/* Interrupt controllers. */
#define	BUS_PASS_TIMER		50	/* Timers and clocks. */
#define	BUS_PASS_SCHEDULER	60	/* Start scheduler. */
#define	BUS_PASS_DEFAULT	__INT_MAX /* Everything else. */

extern int bus_current_pass;

void	bus_set_pass(int pass);

/**
 * Shorthands for constructing method tables.
 */
#define	DEVMETHOD	KOBJMETHOD
#define	DEVMETHOD_END	KOBJMETHOD_END

/*
 * Some common device interfaces.
 */
#include "device_if.h"
#include "bus_if.h"

struct	module;

int	driver_module_handler(struct module *, int, void *);

/**
 * Module support for automatically adding drivers to busses.
 */
struct driver_module_data {
	int		(*dmd_chainevh)(struct module *, int, void *);
	void		*dmd_chainarg;
	const char	*dmd_busname;
	kobj_class_t	dmd_driver;
	devclass_t	*dmd_devclass;
	int		dmd_pass;
};

#define	EARLY_DRIVER_MODULE_ORDERED(name, busname, driver, devclass,	\
    evh, arg, order, pass)						\
									\
static struct driver_module_data name##_##busname##_driver_mod = {	\
	evh, arg,							\
	#busname,							\
	(kobj_class_t) &driver,						\
	&devclass,							\
	pass								\
};									\
									\
static moduledata_t name##_##busname##_mod = {				\
	#busname "/" #name,						\
	driver_module_handler,						\
	&name##_##busname##_driver_mod					\
};									\
DECLARE_MODULE(name##_##busname, name##_##busname##_mod,		\
	       SI_SUB_DRIVERS, order)

#define	EARLY_DRIVER_MODULE(name, busname, driver, devclass, evh, arg, pass) \
	EARLY_DRIVER_MODULE_ORDERED(name, busname, driver, devclass,	\
	    evh, arg, SI_ORDER_MIDDLE, pass)

#define	DRIVER_MODULE_ORDERED(name, busname, driver, devclass, evh, arg,\
    order)								\
	EARLY_DRIVER_MODULE_ORDERED(name, busname, driver, devclass,	\
	    evh, arg, order, BUS_PASS_DEFAULT)

#define	DRIVER_MODULE(name, busname, driver, devclass, evh, arg)	\
	EARLY_DRIVER_MODULE(name, busname, driver, devclass, evh, arg,	\
	    BUS_PASS_DEFAULT)

/**
 * Generic ivar accessor generation macros for bus drivers
 */
#define __BUS_ACCESSOR(varp, var, ivarp, ivar, type)			\
									\
static __inline type varp ## _get_ ## var(device_t dev)			\
{									\
	uintptr_t v;							\
	BUS_READ_IVAR(device_get_parent(dev), dev,			\
	    ivarp ## _IVAR_ ## ivar, &v);				\
	return ((type) v);						\
}									\
									\
static __inline void varp ## _set_ ## var(device_t dev, type t)		\
{									\
	uintptr_t v = (uintptr_t) t;					\
	BUS_WRITE_IVAR(device_get_parent(dev), dev,			\
	    ivarp ## _IVAR_ ## ivar, v);				\
}

/**
 * Shorthand macros, taking resource argument
 * Generated with sys/tools/bus_macro.sh
 */

#define bus_barrier(r, o, l, f) \
	bus_space_barrier((r)->r_bustag, (r)->r_bushandle, (o), (l), (f))
#define bus_read_1(r, o) \
	bus_space_read_1((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_1(r, o, d, c) \
	bus_space_read_multi_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_1(r, o, d, c) \
	bus_space_read_region_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_1(r, o, v, c) \
	bus_space_set_multi_1((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_1(r, o, v, c) \
	bus_space_set_region_1((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_1(r, o, v) \
	bus_space_write_1((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_1(r, o, d, c) \
	bus_space_write_multi_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_1(r, o, d, c) \
	bus_space_write_region_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_stream_1(r, o) \
	bus_space_read_stream_1((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_stream_1(r, o, d, c) \
	bus_space_read_multi_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_stream_1(r, o, d, c) \
	bus_space_read_region_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_stream_1(r, o, v, c) \
	bus_space_set_multi_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_stream_1(r, o, v, c) \
	bus_space_set_region_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_stream_1(r, o, v) \
	bus_space_write_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_stream_1(r, o, d, c) \
	bus_space_write_multi_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_stream_1(r, o, d, c) \
	bus_space_write_region_stream_1((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_2(r, o) \
	bus_space_read_2((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_2(r, o, d, c) \
	bus_space_read_multi_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_2(r, o, d, c) \
	bus_space_read_region_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_2(r, o, v, c) \
	bus_space_set_multi_2((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_2(r, o, v, c) \
	bus_space_set_region_2((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_2(r, o, v) \
	bus_space_write_2((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_2(r, o, d, c) \
	bus_space_write_multi_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_2(r, o, d, c) \
	bus_space_write_region_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_stream_2(r, o) \
	bus_space_read_stream_2((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_stream_2(r, o, d, c) \
	bus_space_read_multi_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_stream_2(r, o, d, c) \
	bus_space_read_region_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_stream_2(r, o, v, c) \
	bus_space_set_multi_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_stream_2(r, o, v, c) \
	bus_space_set_region_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_stream_2(r, o, v) \
	bus_space_write_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_stream_2(r, o, d, c) \
	bus_space_write_multi_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_stream_2(r, o, d, c) \
	bus_space_write_region_stream_2((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_4(r, o) \
	bus_space_read_4((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_4(r, o, d, c) \
	bus_space_read_multi_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_4(r, o, d, c) \
	bus_space_read_region_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_4(r, o, v, c) \
	bus_space_set_multi_4((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_4(r, o, v, c) \
	bus_space_set_region_4((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_4(r, o, v) \
	bus_space_write_4((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_4(r, o, d, c) \
	bus_space_write_multi_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_4(r, o, d, c) \
	bus_space_write_region_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_stream_4(r, o) \
	bus_space_read_stream_4((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_stream_4(r, o, d, c) \
	bus_space_read_multi_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_stream_4(r, o, d, c) \
	bus_space_read_region_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_stream_4(r, o, v, c) \
	bus_space_set_multi_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_stream_4(r, o, v, c) \
	bus_space_set_region_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_stream_4(r, o, v) \
	bus_space_write_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_stream_4(r, o, d, c) \
	bus_space_write_multi_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_stream_4(r, o, d, c) \
	bus_space_write_region_stream_4((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_8(r, o) \
	bus_space_read_8((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_8(r, o, d, c) \
	bus_space_read_multi_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_8(r, o, d, c) \
	bus_space_read_region_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_8(r, o, v, c) \
	bus_space_set_multi_8((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_8(r, o, v, c) \
	bus_space_set_region_8((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_8(r, o, v) \
	bus_space_write_8((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_8(r, o, d, c) \
	bus_space_write_multi_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_8(r, o, d, c) \
	bus_space_write_region_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_stream_8(r, o) \
	bus_space_read_stream_8((r)->r_bustag, (r)->r_bushandle, (o))
#define bus_read_multi_stream_8(r, o, d, c) \
	bus_space_read_multi_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_read_region_stream_8(r, o, d, c) \
	bus_space_read_region_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_set_multi_stream_8(r, o, v, c) \
	bus_space_set_multi_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_set_region_stream_8(r, o, v, c) \
	bus_space_set_region_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (v), (c))
#define bus_write_stream_8(r, o, v) \
	bus_space_write_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (v))
#define bus_write_multi_stream_8(r, o, d, c) \
	bus_space_write_multi_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#define bus_write_region_stream_8(r, o, d, c) \
	bus_space_write_region_stream_8((r)->r_bustag, (r)->r_bushandle, (o), (d), (c))
#endif /* _KERNEL */

#endif /* !_SYS_BUS_H_ */


code:
/*	$NetBSD: bus.h,v 1.12 1997/10/01 08:25:15 fvdl Exp $	*/

/*-
 * Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
 * NASA Ames Research Center.
 *
 * 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 NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
 */

/*-
 * Copyright (c) 1996 Charles M. Hannum.  All rights reserved.
 * Copyright (c) 1996 Christopher G. Demetriou.  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 Christopher G. Demetriou
 *	for the NetBSD Project.
 * 4. 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 ``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/bus_dma.h 188350 2009-02-08 22:54:58Z imp $ */

#ifndef _BUS_DMA_H_
#define _BUS_DMA_H_

#include <sys/_bus_dma.h>

/*
 * Machine independent interface for mapping physical addresses to peripheral
 * bus 'physical' addresses, and assisting with DMA operations.
 *
 * XXX This file is always included from <machine/bus_dma.h> and should not
 *     (yet) be included directly.
 */

/*
 * Flags used in various bus DMA methods.
 */
#define	BUS_DMA_WAITOK		0x00	/* safe to sleep (pseudo-flag) */
#define	BUS_DMA_NOWAIT		0x01	/* not safe to sleep */
#define	BUS_DMA_ALLOCNOW	0x02	/* perform resource allocation now */
#define	BUS_DMA_COHERENT	0x04	/* hint: map memory in a coherent way */
#define	BUS_DMA_ZERO		0x08	/* allocate zero'ed memory */
#define	BUS_DMA_BUS1		0x10	/* placeholders for bus functions... */
#define	BUS_DMA_BUS2		0x20
#define	BUS_DMA_BUS3		0x40
#define	BUS_DMA_BUS4		0x80

/*
 * The following two flags are non-standard or specific to only certain
 * architectures
 */
#define	BUS_DMA_NOWRITE		0x100
#define	BUS_DMA_NOCACHE		0x200

/*
 * The following flag is a DMA tag hint that the page offset of the
 * loaded kernel virtual address must be preserved in the first
 * physical segment address, when the KVA is loaded into DMA.
 */
#define	BUS_DMA_KEEP_PG_OFFSET	0x400

/* Forwards needed by prototypes below. */
struct mbuf;
struct uio;

/*
 * Operations performed by bus_dmamap_sync().
 */
#define	BUS_DMASYNC_PREREAD	1
#define	BUS_DMASYNC_POSTREAD	2
#define	BUS_DMASYNC_PREWRITE	4
#define	BUS_DMASYNC_POSTWRITE	8

/*
 *	bus_dma_segment_t
 *
 *	Describes a single contiguous DMA transaction.  Values
 *	are suitable for programming into DMA registers.
 */
typedef struct bus_dma_segment {
	bus_addr_t	ds_addr;	/* DMA address */
	bus_size_t	ds_len;		/* length of transfer */
} bus_dma_segment_t;

/*
 * A function that returns 1 if the address cannot be accessed by
 * a device and 0 if it can be.
 */
typedef int bus_dma_filter_t(void *, bus_addr_t);

/*
 * Generic helper function for manipulating mutexes.
 */
void busdma_lock_mutex(void *arg, bus_dma_lock_op_t op);

/*
 * Allocate a device specific dma_tag encapsulating the constraints of
 * the parent tag in addition to other restrictions specified:
 *
 *	alignment:	Alignment for segments.
 *	boundary:	Boundary that segments cannot cross.
 *	lowaddr:	Low restricted address that cannot appear in a mapping.
 *	highaddr:	High restricted address that cannot appear in a mapping.
 *	filtfunc:	An optional function to further test if an address
 *			within the range of lowaddr and highaddr cannot appear
 *			in a mapping.
 *	filtfuncarg:	An argument that will be passed to filtfunc in addition
 *			to the address to test.
 *	maxsize:	Maximum mapping size supported by this tag.
 *	nsegments:	Number of discontinuities allowed in maps.
 *	maxsegsz:	Maximum size of a segment in the map.
 *	flags:		Bus DMA flags.
 *	lockfunc:	An optional function to handle driver-defined lock
 *			operations.
 *	lockfuncarg:	An argument that will be passed to lockfunc in addition
 *			to the lock operation.
 *	dmat:		A pointer to set to a valid dma tag should the return
 *			value of this function indicate success.
 */
/* XXX Should probably allow specification of alignment */
int bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
		       bus_size_t boundary, bus_addr_t lowaddr,
		       bus_addr_t highaddr, bus_dma_filter_t *filtfunc,
		       void *filtfuncarg, bus_size_t maxsize, int nsegments,
		       bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
		       void *lockfuncarg, bus_dma_tag_t *dmat);

int bus_dma_tag_destroy(bus_dma_tag_t dmat);

/*
 * A function that processes a successfully loaded dma map or an error
 * from a delayed load map.
 */
typedef void bus_dmamap_callback_t(void *, bus_dma_segment_t *, int, int);

/*
 * Like bus_dmamap_callback but includes map size in bytes.  This is
 * defined as a separate interface to maintain compatibility for users
 * of bus_dmamap_callback_t--at some point these interfaces should be merged.
 */
typedef void bus_dmamap_callback2_t(void *, bus_dma_segment_t *, int, bus_size_t, int);

/*
 * XXX sparc64 uses the same interface, but a much different implementation.
 *     <machine/bus_dma.h> for the sparc64 arch contains the equivalent
 *     declarations.
 */
#if !defined(__sparc64__)

/*
 * Allocate a handle for mapping from kva/uva/physical
 * address space into bus device space.
 */
int bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp);

/*
 * Destroy a handle for mapping from kva/uva/physical
 * address space into bus device space.
 */
int bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map);

/*
 * Allocate a piece of memory that can be efficiently mapped into
 * bus device space based on the constraints listed in the dma tag.
 * A dmamap to for use with dmamap_load is also allocated.
 */
int bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
		     bus_dmamap_t *mapp);

/*
 * Free a piece of memory and its allocated dmamap, that was allocated
 * via bus_dmamem_alloc.
 */
void bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map);

/*
 * Map the buffer buf into bus space using the dmamap map.
 */
int bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
		    bus_size_t buflen, bus_dmamap_callback_t *callback,
		    void *callback_arg, int flags);

/*
 * Like bus_dmamap_load but for mbufs.  Note the use of the
 * bus_dmamap_callback2_t interface.
 */
int bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map,
			 struct mbuf *mbuf,
			 bus_dmamap_callback2_t *callback, void *callback_arg,
			 int flags);

int bus_dmamap_load_mbuf_sg(bus_dma_tag_t dmat, bus_dmamap_t map,
			    struct mbuf *mbuf, bus_dma_segment_t *segs,
			    int *nsegs, int flags);

/*
 * Like bus_dmamap_load but for uios.  Note the use of the
 * bus_dmamap_callback2_t interface.
 */
int bus_dmamap_load_uio(bus_dma_tag_t dmat, bus_dmamap_t map,
			struct uio *ui,
			bus_dmamap_callback2_t *callback, void *callback_arg,
			int flags);

/*
 * Perform a synchronization operation on the given map.
 */
void _bus_dmamap_sync(bus_dma_tag_t, bus_dmamap_t, bus_dmasync_op_t);
#define bus_dmamap_sync(dmat, dmamap, op) 			\
	do {							\
		if ((dmamap) != NULL)				\
			_bus_dmamap_sync(dmat, dmamap, op);	\
	} while (0)

/*
 * Release the mapping held by map.
 */
void _bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map);
#define bus_dmamap_unload(dmat, dmamap) 			\
	do {							\
		if ((dmamap) != NULL)				\
			_bus_dmamap_unload(dmat, dmamap);	\
	} while (0)

#endif /* __sparc64__ */

#endif /* _BUS_DMA_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.
 *
 *	@(#)callout.h	8.2 (Berkeley) 1/21/94
 * $FreeBSD: release/9.0.0/sys/sys/callout.h 221059 2011-04-26 11:39:56Z kib $
 */

#ifndef _SYS_CALLOUT_H_
#define _SYS_CALLOUT_H_

#include <sys/_callout.h>

#define	CALLOUT_LOCAL_ALLOC	0x0001 /* was allocated from callfree */
#define	CALLOUT_ACTIVE		0x0002 /* callout is currently active */
#define	CALLOUT_PENDING		0x0004 /* callout is waiting for timeout */
#define	CALLOUT_MPSAFE		0x0008 /* callout handler is mp safe */
#define	CALLOUT_RETURNUNLOCKED	0x0010 /* handler returns with mtx unlocked */
#define	CALLOUT_SHAREDLOCK	0x0020 /* callout lock held in shared mode */

struct callout_handle {
	struct callout *callout;
};

#ifdef _KERNEL
extern int ncallout;

#define	callout_active(c)	((c)->c_flags & CALLOUT_ACTIVE)
#define	callout_deactivate(c)	((c)->c_flags &= ~CALLOUT_ACTIVE)
#define	callout_drain(c)	_callout_stop_safe(c, 1)
void	callout_init(struct callout *, int);
void	_callout_init_lock(struct callout *, struct lock_object *, int);
#define	callout_init_mtx(c, mtx, flags)					\
	_callout_init_lock((c), ((mtx) != NULL) ? &(mtx)->lock_object :	\
	    NULL, (flags))
#define	callout_init_rw(c, rw, flags)					\
	_callout_init_lock((c), ((rw) != NULL) ? &(rw)->lock_object :	\
	   NULL, (flags))
#define	callout_pending(c)	((c)->c_flags & CALLOUT_PENDING)
int	callout_reset_on(struct callout *, int, void (*)(void *), void *, int);
#define	callout_reset(c, on_tick, fn, arg)				\
    callout_reset_on((c), (on_tick), (fn), (arg), (c)->c_cpu)
#define	callout_reset_curcpu(c, on_tick, fn, arg)			\
    callout_reset_on((c), (on_tick), (fn), (arg), PCPU_GET(cpuid))
int	callout_schedule(struct callout *, int);
int	callout_schedule_on(struct callout *, int, int);
#define	callout_schedule_curcpu(c, on_tick)				\
    callout_schedule_on((c), (on_tick), PCPU_GET(cpuid))
#define	callout_stop(c)		_callout_stop_safe(c, 0)
int	_callout_stop_safe(struct callout *, int);
void	callout_tick(void);
int	callout_tickstofirst(int limit);
extern void (*callout_new_inserted)(int cpu, int ticks);

#endif

#endif /* _SYS_CALLOUT_H_ */


code:
/*-
 * Copyright (c) 2008-2010 Robert N. M. Watson
 * All rights reserved.
 *
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, 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.
 *
 * 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/capability.h 224987 2011-08-18 22:51:30Z jonathan $
 */

/*
 * Definitions for FreeBSD capabilities facility.
 */
#ifndef _SYS_CAPABILITY_H_
#define	_SYS_CAPABILITY_H_

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

#include <sys/file.h>

/*
 * Possible rights on capabilities.
 *
 * Notes:
 * Some system calls don't require a capability in order to perform an
 * operation on an fd.  These include: close, dup, dup2.
 *
 * sendfile is authorized using CAP_READ on the file and CAP_WRITE on the
 * socket.
 *
 * mmap() and aio*() system calls will need special attention as they may
 * involve reads or writes depending a great deal on context.
 */

/* General file I/O. */
#define	CAP_READ		0x0000000000000001ULL	/* read/recv */
#define	CAP_WRITE		0x0000000000000002ULL	/* write/send */
#define	CAP_MMAP		0x0000000000000004ULL	/* mmap */
#define	CAP_MAPEXEC		0x0000000000000008ULL	/* mmap(2) as exec */
#define	CAP_FEXECVE		0x0000000000000010ULL
#define	CAP_FSYNC		0x0000000000000020ULL
#define	CAP_FTRUNCATE		0x0000000000000040ULL
#define	CAP_SEEK		0x0000000000000080ULL

/* VFS methods. */
#define	CAP_FCHFLAGS		0x0000000000000100ULL
#define	CAP_FCHDIR		0x0000000000000200ULL
#define	CAP_FCHMOD		0x0000000000000400ULL
#define	CAP_FCHOWN		0x0000000000000800ULL
#define	CAP_FCNTL		0x0000000000001000ULL
#define	CAP_FPATHCONF		0x0000000000002000ULL
#define	CAP_FLOCK		0x0000000000004000ULL
#define	CAP_FSCK		0x0000000000008000ULL
#define	CAP_FSTAT		0x0000000000010000ULL
#define	CAP_FSTATFS		0x0000000000020000ULL
#define	CAP_FUTIMES		0x0000000000040000ULL
#define	CAP_CREATE		0x0000000000080000ULL
#define	CAP_DELETE		0x0000000000100000ULL
#define	CAP_MKDIR		0x0000000000200000ULL
#define	CAP_RMDIR		0x0000000000400000ULL
#define	CAP_MKFIFO		0x0000000000800000ULL

/* Lookups - used to constrain *at() calls. */
#define	CAP_LOOKUP		0x0000000001000000ULL

/* Extended attributes. */
#define	CAP_EXTATTR_DELETE	0x0000000002000000ULL
#define	CAP_EXTATTR_GET		0x0000000004000000ULL
#define	CAP_EXTATTR_LIST	0x0000000008000000ULL
#define	CAP_EXTATTR_SET		0x0000000010000000ULL

/* Access Control Lists. */
#define	CAP_ACL_CHECK		0x0000000020000000ULL
#define	CAP_ACL_DELETE		0x0000000040000000ULL
#define	CAP_ACL_GET		0x0000000080000000ULL
#define	CAP_ACL_SET		0x0000000100000000ULL

/* Socket operations. */
#define	CAP_ACCEPT		0x0000000200000000ULL
#define	CAP_BIND		0x0000000400000000ULL
#define	CAP_CONNECT		0x0000000800000000ULL
#define	CAP_GETPEERNAME		0x0000001000000000ULL
#define	CAP_GETSOCKNAME		0x0000002000000000ULL
#define	CAP_GETSOCKOPT		0x0000004000000000ULL
#define	CAP_LISTEN		0x0000008000000000ULL
#define	CAP_PEELOFF		0x0000010000000000ULL
#define	CAP_SETSOCKOPT		0x0000020000000000ULL
#define	CAP_SHUTDOWN		0x0000040000000000ULL

#define	CAP_SOCK_ALL \
	(CAP_ACCEPT | CAP_BIND | CAP_CONNECT \
	 | CAP_GETPEERNAME | CAP_GETSOCKNAME | CAP_GETSOCKOPT \
	 | CAP_LISTEN | CAP_PEELOFF | CAP_SETSOCKOPT | CAP_SHUTDOWN)

/* Mandatory Access Control. */
#define	CAP_MAC_GET		0x0000080000000000ULL
#define	CAP_MAC_SET		0x0000100000000000ULL

/* Methods on semaphores. */
#define	CAP_SEM_GETVALUE	0x0000200000000000ULL
#define	CAP_SEM_POST		0x0000400000000000ULL
#define	CAP_SEM_WAIT		0x0000800000000000ULL

/* kqueue events. */
#define	CAP_POLL_EVENT		0x0001000000000000ULL
#define	CAP_POST_EVENT		0x0002000000000000ULL

/* Strange and powerful rights that should not be given lightly. */
#define	CAP_IOCTL		0x0004000000000000ULL
#define	CAP_TTYHOOK		0x0008000000000000ULL

/* Process management via process descriptors. */
#define	CAP_PDGETPID		0x0010000000000000ULL
#define	CAP_PDWAIT		0x0020000000000000ULL
#define	CAP_PDKILL		0x0040000000000000ULL

/* The mask of all valid method rights. */
#define	CAP_MASK_VALID		0x007fffffffffffffULL

#ifdef _KERNEL

#define IN_CAPABILITY_MODE(td) (td->td_ucred->cr_flags & CRED_FLAG_CAPMODE)

/*
 * Create a capability to wrap a file object.
 */
int	kern_capwrap(struct thread *td, struct file *fp, cap_rights_t rights,
	    int *capfd);

/*
 * Unwrap a capability if its rights mask is a superset of 'rights'.
 *
 * Unwrapping a non-capability is effectively a no-op; the value of fp_cap
 * is simply copied into fpp.
 */
int	cap_funwrap(struct file *fp_cap, cap_rights_t rights,
	    struct file **fpp);
int	cap_funwrap_mmap(struct file *fp_cap, cap_rights_t rights,
	    u_char *maxprotp, struct file **fpp);

/*
 * For the purposes of procstat(1) and similar tools, allow kern_descrip.c to
 * extract the rights from a capability.  However, this should not be used by
 * kernel code generally, instead cap_funwrap() should be used in order to
 * keep all access control in one place.
 */
cap_rights_t	cap_rights(struct file *fp_cap);

#else /* !_KERNEL */

__BEGIN_DECLS

/*
 * cap_enter(): Cause the process to enter capability mode, which will
 * prevent it from directly accessing global namespaces.  System calls will
 * be limited to process-local, process-inherited, or file descriptor
 * operations.  If already in capability mode, a no-op.
 *
 * Currently, process-inherited operations are not properly handled -- in
 * particular, we're interested in things like waitpid(2), kill(2), etc,
 * being properly constrained.  One possible solution is to introduce process
 * descriptors.
 */
int	cap_enter(void);

/*
 * cap_getmode(): Are we in capability mode?
 */
int	cap_getmode(u_int* modep);

/*
 * cap_new(): Create a new capability derived from an existing file
 * descriptor with the specified rights.  If the existing file descriptor is
 * a capability, then the new rights must be a subset of the existing rights.
 */
int	cap_new(int fd, cap_rights_t rights);

/*
 * cap_getrights(): Query the rights on a capability.
 */
int	cap_getrights(int fd, cap_rights_t *rightsp);

__END_DECLS

#endif /* !_KERNEL */

#endif /* !_SYS_CAPABILITY_H_ */