code:
/*	$KAME: altq_classq.h,v 1.6 2003/01/07 07:33:38 kjc Exp $	*/

/*
 * Copyright (c) 1991-1997 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Network Research
 *	Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory 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.
 */
/*
 * class queue definitions extracted from rm_class.h.
 */
#ifndef _ALTQ_ALTQ_CLASSQ_H_
#define	_ALTQ_ALTQ_CLASSQ_H_

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Packet Queue types: RED or DROPHEAD.
 */
#define	Q_DROPHEAD	0x00
#define	Q_RED		0x01
#define	Q_RIO		0x02
#define	Q_DROPTAIL	0x03

#ifdef _KERNEL

/*
 * Packet Queue structures and macros to manipulate them.
 */
struct _class_queue_ {
	struct mbuf	*tail_;	/* Tail of packet queue */
	int	qlen_;		/* Queue length (in number of packets) */
	int	qlim_;		/* Queue limit (in number of packets*) */
	int	qtype_;		/* Queue type */
};

typedef struct _class_queue_	class_queue_t;

#define	qtype(q)	(q)->qtype_		/* Get queue type */
#define	qlimit(q)	(q)->qlim_		/* Max packets to be queued */
#define	qlen(q)		(q)->qlen_		/* Current queue length. */
#define	qtail(q)	(q)->tail_		/* Tail of the queue */
#define	qhead(q)	((q)->tail_ ? (q)->tail_->m_nextpkt : NULL)

#define	qempty(q)	((q)->qlen_ == 0)	/* Is the queue empty?? */
#define	q_is_red(q)	((q)->qtype_ == Q_RED)	/* Is the queue a red queue */
#define	q_is_rio(q)	((q)->qtype_ == Q_RIO)	/* Is the queue a rio queue */
#define	q_is_red_or_rio(q)	((q)->qtype_ == Q_RED || (q)->qtype_ == Q_RIO)

#if !defined(__GNUC__) || defined(ALTQ_DEBUG)

extern void		_addq(class_queue_t *, struct mbuf *);
extern struct mbuf	*_getq(class_queue_t *);
extern struct mbuf	*_getq_tail(class_queue_t *);
extern struct mbuf	*_getq_random(class_queue_t *);
extern void		_removeq(class_queue_t *, struct mbuf *);
extern void		_flushq(class_queue_t *);

#else /* __GNUC__ && !ALTQ_DEBUG */
/*
 * inlined versions
 */
static __inline void
_addq(class_queue_t *q, struct mbuf *m)
{
        struct mbuf *m0;

	if ((m0 = qtail(q)) != NULL)
		m->m_nextpkt = m0->m_nextpkt;
	else
		m0 = m;
	m0->m_nextpkt = m;
	qtail(q) = m;
	qlen(q)++;
}

static __inline struct mbuf *
_getq(class_queue_t *q)
{
	struct mbuf  *m, *m0;

	if ((m = qtail(q)) == NULL)
		return (NULL);
	if ((m0 = m->m_nextpkt) != m)
		m->m_nextpkt = m0->m_nextpkt;
	else
		qtail(q) = NULL;
	qlen(q)--;
	m0->m_nextpkt = NULL;
	return (m0);
}

/* drop a packet at the tail of the queue */
static __inline struct mbuf *
_getq_tail(class_queue_t *q)
{
	struct mbuf *m, *m0, *prev;

	if ((m = m0 = qtail(q)) == NULL)
		return NULL;
	do {
		prev = m0;
		m0 = m0->m_nextpkt;
	} while (m0 != m);
	prev->m_nextpkt = m->m_nextpkt;
	if (prev == m)
		qtail(q) = NULL;
	else
		qtail(q) = prev;
	qlen(q)--;
	m->m_nextpkt = NULL;
	return (m);
}

/* randomly select a packet in the queue */
static __inline struct mbuf *
_getq_random(class_queue_t *q)
{
	struct mbuf *m;
	int i, n;

	if ((m = qtail(q)) == NULL)
		return NULL;
	if (m->m_nextpkt == m)
		qtail(q) = NULL;
	else {
		struct mbuf *prev = NULL;

		n = random() % qlen(q) + 1;
		for (i = 0; i < n; i++) {
			prev = m;
			m = m->m_nextpkt;
		}
		prev->m_nextpkt = m->m_nextpkt;
		if (m == qtail(q))
			qtail(q) = prev;
	}
	qlen(q)--;
	m->m_nextpkt = NULL;
	return (m);
}

static __inline void
_removeq(class_queue_t *q, struct mbuf *m)
{
	struct mbuf *m0, *prev;

	m0 = qtail(q);
	do {
		prev = m0;
		m0 = m0->m_nextpkt;
	} while (m0 != m);
	prev->m_nextpkt = m->m_nextpkt;
	if (prev == m)
		qtail(q) = NULL;
	else if (qtail(q) == m)
		qtail(q) = prev;
	qlen(q)--;
}

static __inline void
_flushq(class_queue_t *q)
{
	struct mbuf *m;

	while ((m = _getq(q)) != NULL)
		m_freem(m);
}

#endif /* __GNUC__ && !ALTQ_DEBUG */

#endif /* _KERNEL */

#ifdef __cplusplus
}
#endif

#endif /* _ALTQ_ALTQ_CLASSQ_H_ */


code:
/*	$KAME: altq_hfsc.h,v 1.12 2003/12/05 05:40:46 kjc Exp $	*/

/*
 * Copyright (c) 1997-1999 Carnegie Mellon University. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation is hereby granted (including for commercial or
 * for-profit use), provided that both the copyright notice and this
 * permission notice appear in all copies of the software, derivative
 * works, or modified versions, and any portions thereof.
 *
 * THIS SOFTWARE IS EXPERIMENTAL AND IS KNOWN TO HAVE BUGS, SOME OF
 * WHICH MAY HAVE SERIOUS CONSEQUENCES.  CARNEGIE MELLON PROVIDES THIS
 * SOFTWARE IN ITS ``AS IS'' CONDITION, 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 CARNEGIE MELLON UNIVERSITY 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.
 *
 * Carnegie Mellon encourages (but does not require) users of this
 * software to return any improvements or extensions that they make,
 * and to grant Carnegie Mellon the rights to redistribute these
 * changes without encumbrance.
 */
#ifndef _ALTQ_ALTQ_HFSC_H_
#define	_ALTQ_ALTQ_HFSC_H_

#include <altq/altq.h>
#include <altq/altq_classq.h>
#include <altq/altq_red.h>
#include <altq/altq_rio.h>

#ifdef __cplusplus
extern "C" {
#endif

struct service_curve {
	u_int	m1;	/* slope of the first segment in bits/sec */
	u_int	d;	/* the x-projection of the first segment in msec */
	u_int	m2;	/* slope of the second segment in bits/sec */
};

/* special class handles */
#define	HFSC_NULLCLASS_HANDLE	0
#define	HFSC_MAX_CLASSES	64

/* hfsc class flags */
#define	HFCF_RED		0x0001	/* use RED */
#define	HFCF_ECN		0x0002  /* use RED/ECN */
#define	HFCF_RIO		0x0004  /* use RIO */
#define	HFCF_CLEARDSCP		0x0010  /* clear diffserv codepoint */
#define	HFCF_DEFAULTCLASS	0x1000	/* default class */

/* service curve types */
#define	HFSC_REALTIMESC		1
#define	HFSC_LINKSHARINGSC	2
#define	HFSC_UPPERLIMITSC	4
#define	HFSC_DEFAULTSC		(HFSC_REALTIMESC|HFSC_LINKSHARINGSC)

struct hfsc_classstats {
	u_int			class_id;
	u_int32_t		class_handle;
	struct service_curve	rsc;
	struct service_curve	fsc;
	struct service_curve	usc;	/* upper limit service curve */

	u_int64_t		total;	/* total work in bytes */
	u_int64_t		cumul;	/* cumulative work in bytes
					   done by real-time criteria */
	u_int64_t		d;		/* deadline */
	u_int64_t		e;		/* eligible time */
	u_int64_t		vt;		/* virtual time */
	u_int64_t		f;		/* fit time for upper-limit */

	/* info helpful for debugging */
	u_int64_t		initvt;		/* init virtual time */
	u_int64_t		vtoff;		/* cl_vt_ipoff */
	u_int64_t		cvtmax;		/* cl_maxvt */
	u_int64_t		myf;		/* cl_myf */
	u_int64_t		cfmin;		/* cl_mincf */
	u_int64_t		cvtmin;		/* cl_mincvt */
	u_int64_t		myfadj;		/* cl_myfadj */
	u_int64_t		vtadj;		/* cl_vtadj */
	u_int64_t		cur_time;
	u_int32_t		machclk_freq;

	u_int			qlength;
	u_int			qlimit;
	struct pktcntr		xmit_cnt;
	struct pktcntr		drop_cnt;
	u_int			period;

	u_int			vtperiod;	/* vt period sequence no */
	u_int			parentperiod;	/* parent's vt period seqno */
	int			nactive;	/* number of active children */

	/* red and rio related info */
	int			qtype;
	struct redstats		red[3];
};

#ifdef ALTQ3_COMPAT
struct hfsc_interface {
	char	hfsc_ifname[IFNAMSIZ];  /* interface name (e.g., fxp0) */
};

struct hfsc_attach {
	struct hfsc_interface	iface;
	u_int			bandwidth;  /* link bandwidth in bits/sec */
};

struct hfsc_add_class {
	struct hfsc_interface	iface;
	u_int32_t		parent_handle;
	struct service_curve	service_curve;
	int			qlimit;
	int			flags;

	u_int32_t		class_handle;  /* return value */
};

struct hfsc_delete_class {
	struct hfsc_interface	iface;
	u_int32_t		class_handle;
};

struct hfsc_modify_class {
	struct hfsc_interface	iface;
	u_int32_t		class_handle;
	struct service_curve	service_curve;
	int			sctype;
};

struct hfsc_add_filter {
	struct hfsc_interface	iface;
	u_int32_t		class_handle;
	struct flow_filter	filter;

	u_long			filter_handle;  /* return value */
};

struct hfsc_delete_filter {
	struct hfsc_interface	iface;
	u_long			filter_handle;
};

struct hfsc_class_stats {
	struct hfsc_interface	iface;
	int			nskip;		/* skip # of classes */
	int			nclasses;	/* # of class stats (WR) */
	u_int64_t		cur_time;	/* current time */
	u_int32_t		machclk_freq;	/* machine clock frequency */
	u_int			hif_classes;	/* # of classes in the tree */
	u_int			hif_packets;	/* # of packets in the tree */
	struct hfsc_classstats	*stats;		/* pointer to stats array */
};

#define	HFSC_IF_ATTACH		_IOW('Q', 1, struct hfsc_attach)
#define	HFSC_IF_DETACH		_IOW('Q', 2, struct hfsc_interface)
#define	HFSC_ENABLE		_IOW('Q', 3, struct hfsc_interface)
#define	HFSC_DISABLE		_IOW('Q', 4, struct hfsc_interface)
#define	HFSC_CLEAR_HIERARCHY	_IOW('Q', 5, struct hfsc_interface)
#define	HFSC_ADD_CLASS		_IOWR('Q', 7, struct hfsc_add_class)
#define	HFSC_DEL_CLASS		_IOW('Q', 8, struct hfsc_delete_class)
#define	HFSC_MOD_CLASS		_IOW('Q', 9, struct hfsc_modify_class)
#define	HFSC_ADD_FILTER		_IOWR('Q', 10, struct hfsc_add_filter)
#define	HFSC_DEL_FILTER		_IOW('Q', 11, struct hfsc_delete_filter)
#define	HFSC_GETSTATS		_IOWR('Q', 12, struct hfsc_class_stats)
#endif /* ALTQ3_COMPAT */

#ifdef _KERNEL
/*
 * kernel internal service curve representation
 *	coordinates are given by 64 bit unsigned integers.
 *	x-axis: unit is clock count.  for the intel x86 architecture,
 *		the raw Pentium TSC (Timestamp Counter) value is used.
 *		virtual time is also calculated in this time scale.
 *	y-axis: unit is byte.
 *
 *	the service curve parameters are converted to the internal
 *	representation.
 *	the slope values are scaled to avoid overflow.
 *	the inverse slope values as well as the y-projection of the 1st
 *	segment are kept in order to to avoid 64-bit divide operations
 *	that are expensive on 32-bit architectures.
 *
 *  note: Intel Pentium TSC never wraps around in several thousands of years.
 *	x-axis doesn't wrap around for 1089 years with 1GHz clock.
 *      y-axis doesn't wrap around for 4358 years with 1Gbps bandwidth.
 */

/* kernel internal representation of a service curve */
struct internal_sc {
	u_int64_t	sm1;	/* scaled slope of the 1st segment */
	u_int64_t	ism1;	/* scaled inverse-slope of the 1st segment */
	u_int64_t	dx;	/* the x-projection of the 1st segment */
	u_int64_t	dy;	/* the y-projection of the 1st segment */
	u_int64_t	sm2;	/* scaled slope of the 2nd segment */
	u_int64_t	ism2;	/* scaled inverse-slope of the 2nd segment */
};

/* runtime service curve */
struct runtime_sc {
	u_int64_t	x;	/* current starting position on x-axis */
	u_int64_t	y;	/* current starting position on x-axis */
	u_int64_t	sm1;	/* scaled slope of the 1st segment */
	u_int64_t	ism1;	/* scaled inverse-slope of the 1st segment */
	u_int64_t	dx;	/* the x-projection of the 1st segment */
	u_int64_t	dy;	/* the y-projection of the 1st segment */
	u_int64_t	sm2;	/* scaled slope of the 2nd segment */
	u_int64_t	ism2;	/* scaled inverse-slope of the 2nd segment */
};

/* for TAILQ based ellist and actlist implementation */
struct hfsc_class;
typedef TAILQ_HEAD(_eligible, hfsc_class) ellist_t;
typedef TAILQ_ENTRY(hfsc_class) elentry_t;
typedef TAILQ_HEAD(_active, hfsc_class) actlist_t;
typedef TAILQ_ENTRY(hfsc_class) actentry_t;
#define	ellist_first(s)		TAILQ_FIRST(s)
#define	actlist_first(s)	TAILQ_FIRST(s)
#define	actlist_last(s)		TAILQ_LAST(s, _active)

struct hfsc_class {
	u_int		cl_id;		/* class id (just for debug) */
	u_int32_t	cl_handle;	/* class handle */
	struct hfsc_if	*cl_hif;	/* back pointer to struct hfsc_if */
	int		cl_flags;	/* misc flags */

	struct hfsc_class *cl_parent;	/* parent class */
	struct hfsc_class *cl_siblings;	/* sibling classes */
	struct hfsc_class *cl_children;	/* child classes */

	class_queue_t	*cl_q;		/* class queue structure */
	struct red	*cl_red;	/* RED state */
	struct altq_pktattr *cl_pktattr; /* saved header used by ECN */

	u_int64_t	cl_total;	/* total work in bytes */
	u_int64_t	cl_cumul;	/* cumulative work in bytes
					   done by real-time criteria */
	u_int64_t	cl_d;		/* deadline */
	u_int64_t	cl_e;		/* eligible time */
	u_int64_t	cl_vt;		/* virtual time */
	u_int64_t	cl_f;		/* time when this class will fit for
					   link-sharing, max(myf, cfmin) */
	u_int64_t	cl_myf;		/* my fit-time (as calculated from this
					   class's own upperlimit curve) */
	u_int64_t	cl_myfadj;	/* my fit-time adjustment
					   (to cancel history dependence) */
	u_int64_t	cl_cfmin;	/* earliest children's fit-time (used
					   with cl_myf to obtain cl_f) */
	u_int64_t	cl_cvtmin;	/* minimal virtual time among the
					   children fit for link-sharing
					   (monotonic within a period) */
	u_int64_t	cl_vtadj;	/* intra-period cumulative vt
					   adjustment */
	u_int64_t	cl_vtoff;	/* inter-period cumulative vt offset */
	u_int64_t	cl_cvtmax;	/* max child's vt in the last period */

	u_int64_t	cl_initvt;	/* init virtual time (for debugging) */

	struct internal_sc *cl_rsc;	/* internal real-time service curve */
	struct internal_sc *cl_fsc;	/* internal fair service curve */
	struct internal_sc *cl_usc;	/* internal upperlimit service curve */
	struct runtime_sc  cl_deadline;	/* deadline curve */
	struct runtime_sc  cl_eligible;	/* eligible curve */
	struct runtime_sc  cl_virtual;	/* virtual curve */
	struct runtime_sc  cl_ulimit;	/* upperlimit curve */

	u_int		cl_vtperiod;	/* vt period sequence no */
	u_int		cl_parentperiod;  /* parent's vt period seqno */
	int		cl_nactive;	/* number of active children */
	actlist_t	*cl_actc;	/* active children list */

	actentry_t	cl_actlist;	/* active children list entry */
	elentry_t	cl_ellist;	/* eligible list entry */

	struct {
		struct pktcntr	xmit_cnt;
		struct pktcntr	drop_cnt;
		u_int period;
	} cl_stats;
};

/*
 * hfsc interface state
 */
struct hfsc_if {
	struct hfsc_if		*hif_next;	/* interface state list */
	struct ifaltq		*hif_ifq;	/* backpointer to ifaltq */
	struct hfsc_class	*hif_rootclass;		/* root class */
	struct hfsc_class	*hif_defaultclass;	/* default class */
	struct hfsc_class	*hif_class_tbl[HFSC_MAX_CLASSES];
	struct hfsc_class	*hif_pollcache;	/* cache for poll operation */

	u_int	hif_classes;			/* # of classes in the tree */
	u_int	hif_packets;			/* # of packets in the tree */
	u_int	hif_classid;			/* class id sequence number */

	ellist_t *hif_eligible;			/* eligible list */

#ifdef ALTQ3_CLFIER_COMPAT
	struct acc_classifier	hif_classifier;
#endif
};

#endif /* _KERNEL */

#ifdef __cplusplus
}
#endif

#endif /* _ALTQ_ALTQ_HFSC_H_ */

repo_name: veiledmerc/mira

license: mit


code:
/*	$KAME: altq_priq.h,v 1.7 2003/10/03 05:05:15 kjc Exp $	*/
/*
 * Copyright (C) 2000-2003
 *	Sony Computer Science Laboratories Inc.  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 SONY CSL 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 SONY CSL 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.
 */

#ifndef _ALTQ_ALTQ_PRIQ_H_
#define	_ALTQ_ALTQ_PRIQ_H_

#include <altq/altq.h>
#include <altq/altq_classq.h>
#include <altq/altq_red.h>
#include <altq/altq_rio.h>

#ifdef __cplusplus
extern "C" {
#endif

#define	PRIQ_MAXPRI	16	/* upper limit of the number of priorities */

#ifdef ALTQ3_COMPAT
struct priq_interface {
	char	ifname[IFNAMSIZ];	/* interface name (e.g., fxp0) */
	u_long	arg;			/* request-specific argument */
};

struct priq_add_class {
	struct priq_interface	iface;
	int			pri;	/* priority (0 is the lowest) */
	int			qlimit;	/* queue size limit */
	int			flags;	/* misc flags (see below) */

	u_int32_t		class_handle;  /* return value */
};
#endif /* ALTQ3_COMPAT */

/* priq class flags */
#define	PRCF_RED		0x0001	/* use RED */
#define	PRCF_ECN		0x0002  /* use RED/ECN */
#define	PRCF_RIO		0x0004  /* use RIO */
#define	PRCF_CLEARDSCP		0x0010  /* clear diffserv codepoint */
#define	PRCF_DEFAULTCLASS	0x1000	/* default class */

/* special class handles */
#define	PRIQ_NULLCLASS_HANDLE	0

#ifdef ALTQ3_COMPAT
struct priq_delete_class {
	struct priq_interface	iface;
	u_int32_t		class_handle;
};

struct priq_modify_class {
	struct priq_interface	iface;
	u_int32_t		class_handle;
	int			pri;
	int			qlimit;
	int			flags;
};

struct priq_add_filter {
	struct priq_interface	iface;
	u_int32_t		class_handle;
	struct flow_filter	filter;

	u_long			filter_handle;  /* return value */
};

struct priq_delete_filter {
	struct priq_interface	iface;
	u_long			filter_handle;
};
#endif /* ALTQ3_COMPAT */

struct priq_classstats {
	u_int32_t		class_handle;

	u_int			qlength;
	u_int			qlimit;
	u_int			period;
	struct pktcntr		xmitcnt;  /* transmitted packet counter */
	struct pktcntr		dropcnt;  /* dropped packet counter */

	/* red and rio related info */
	int			qtype;
	struct redstats		red[3];	/* rio has 3 red stats */
};

#ifdef ALTQ3_COMPAT
struct priq_class_stats {
	struct priq_interface	iface;
	int			maxpri;	  /* in/out */

	struct priq_classstats	*stats;   /* pointer to stats array */
};

#define	PRIQ_IF_ATTACH		_IOW('Q', 1, struct priq_interface)
#define	PRIQ_IF_DETACH		_IOW('Q', 2, struct priq_interface)
#define	PRIQ_ENABLE		_IOW('Q', 3, struct priq_interface)
#define	PRIQ_DISABLE		_IOW('Q', 4, struct priq_interface)
#define	PRIQ_CLEAR		_IOW('Q', 5, struct priq_interface)
#define	PRIQ_ADD_CLASS		_IOWR('Q', 7, struct priq_add_class)
#define	PRIQ_DEL_CLASS		_IOW('Q', 8, struct priq_delete_class)
#define	PRIQ_MOD_CLASS		_IOW('Q', 9, struct priq_modify_class)
#define	PRIQ_ADD_FILTER		_IOWR('Q', 10, struct priq_add_filter)
#define	PRIQ_DEL_FILTER		_IOW('Q', 11, struct priq_delete_filter)
#define	PRIQ_GETSTATS		_IOWR('Q', 12, struct priq_class_stats)

#endif /* ALTQ3_COMPAT */

#ifdef _KERNEL

struct priq_class {
	u_int32_t	cl_handle;	/* class handle */
	class_queue_t	*cl_q;		/* class queue structure */
	struct red	*cl_red;	/* RED state */
	int		cl_pri;		/* priority */
	int		cl_flags;	/* class flags */
	struct priq_if	*cl_pif;	/* back pointer to pif */
	struct altq_pktattr *cl_pktattr; /* saved header used by ECN */

	/* statistics */
	u_int		cl_period;	/* backlog period */
	struct pktcntr  cl_xmitcnt;	/* transmitted packet counter */
	struct pktcntr  cl_dropcnt;	/* dropped packet counter */
};

/*
 * priq interface state
 */
struct priq_if {
	struct priq_if		*pif_next;	/* interface state list */
	struct ifaltq		*pif_ifq;	/* backpointer to ifaltq */
	u_int			pif_bandwidth;	/* link bandwidth in bps */
	int			pif_maxpri;	/* max priority in use */
	struct priq_class	*pif_default;	/* default class */
	struct priq_class	*pif_classes[PRIQ_MAXPRI]; /* classes */
#ifdef ALTQ3_CLFIER_COMPAT
	struct acc_classifier	pif_classifier;	/* classifier */
#endif
};

#endif /* _KERNEL */

#ifdef __cplusplus
}
#endif

#endif /* _ALTQ_ALTQ_PRIQ_H_ */


code:
/*	$KAME: altq_red.h,v 1.8 2003/07/10 12:07:49 kjc Exp $	*/

/*
 * Copyright (C) 1997-2003
 *	Sony Computer Science Laboratories Inc.  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 SONY CSL 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 SONY CSL 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.
 */

#ifndef _ALTQ_ALTQ_RED_H_
#define	_ALTQ_ALTQ_RED_H_

#include <altq/altq_classq.h>

#ifdef ALTQ3_COMPAT
struct red_interface {
	char	red_ifname[IFNAMSIZ];
};

struct red_stats {
	struct red_interface iface;
	int q_len;
	int q_avg;

	struct pktcntr	xmit_cnt;
	struct pktcntr	drop_cnt;
	u_int		drop_forced;
	u_int		drop_unforced;
	u_int		marked_packets;

	/* static red parameters */
	int q_limit;
	int weight;
	int inv_pmax;
	int th_min;
	int th_max;

	/* flowvalve related stuff */
	u_int fv_flows;
	u_int fv_pass;
	u_int fv_predrop;
	u_int fv_alloc;
	u_int fv_escape;
};

struct red_conf {
	struct red_interface iface;
	int red_weight;		/* weight for EWMA */
	int red_inv_pmax;	/* inverse of max drop probability */
	int red_thmin;		/* red min threshold */
	int red_thmax;		/* red max threshold */
	int red_limit;		/* max queue length */
	int red_pkttime;	/* average packet time in usec */
	int red_flags;		/* see below */
};
#endif /* ALTQ3_COMPAT */

/* red flags */
#define	REDF_ECN4	0x01	/* use packet marking for IPv4 packets */
#define	REDF_ECN6	0x02	/* use packet marking for IPv6 packets */
#define	REDF_ECN	(REDF_ECN4 | REDF_ECN6)
#define	REDF_FLOWVALVE	0x04	/* use flowvalve (aka penalty-box) */

/*
 * simpler versions of red parameters and statistics used by other
 * disciplines (e.g., CBQ)
 */
struct redparams {
	int th_min;		/* red min threshold */
	int th_max;		/* red max threshold */
	int inv_pmax;		/* inverse of max drop probability */
};

struct redstats {
	int		q_avg;
	struct pktcntr	xmit_cnt;
	struct pktcntr	drop_cnt;
	u_int		drop_forced;
	u_int		drop_unforced;
	u_int		marked_packets;
};

#ifdef ALTQ3_COMPAT
/*
 * IOCTLs for RED
 */
#define	RED_IF_ATTACH		_IOW('Q', 1, struct red_interface)
#define	RED_IF_DETACH		_IOW('Q', 2, struct red_interface)
#define	RED_ENABLE		_IOW('Q', 3, struct red_interface)
#define	RED_DISABLE		_IOW('Q', 4, struct red_interface)
#define	RED_CONFIG		_IOWR('Q', 6, struct red_conf)
#define	RED_GETSTATS		_IOWR('Q', 12, struct red_stats)
#define	RED_SETDEFAULTS		_IOW('Q', 30, struct redparams)
#endif /* ALTQ3_COMPAT */

#ifdef _KERNEL

#ifdef ALTQ3_COMPAT
struct flowvalve;
#endif

/* weight table structure for idle time calibration */
struct wtab {
	struct wtab	*w_next;
	int		 w_weight;
	int		 w_param_max;
	int		 w_refcount;
	int32_t		 w_tab[32];
};

typedef struct red {
	int		red_pkttime;	/* average packet time in micro sec
					   used for idle calibration */
	int		red_flags;	/* red flags */

	/* red parameters */
	int		red_weight;	/* weight for EWMA */
	int		red_inv_pmax;	/* inverse of max drop probability */
	int		red_thmin;	/* red min threshold */
	int		red_thmax;	/* red max threshold */

	/* variables for internal use */
	int		red_wshift;	/* log(red_weight) */
	int		red_thmin_s;	/* th_min scaled by avgshift */
	int		red_thmax_s;	/* th_max scaled by avgshift */
	int		red_probd;	/* drop probability denominator */

	int		red_avg;	/* queue len avg scaled by avgshift */
	int		red_count;	/* packet count since last dropped/
					   marked packet */
	int		red_idle;	/* queue was empty */
	int		red_old;	/* avg is above th_min */
	struct wtab	*red_wtab;	/* weight table */
	struct timeval	 red_last;	/* time when the queue becomes idle */

#ifdef ALTQ3_COMPAT
	struct flowvalve *red_flowvalve;	/* flowvalve state */
#endif

	struct {
		struct pktcntr	xmit_cnt;
		struct pktcntr	drop_cnt;
		u_int		drop_forced;
		u_int		drop_unforced;
		u_int		marked_packets;
	} red_stats;
} red_t;

#ifdef ALTQ3_COMPAT
typedef struct red_queue {
	struct red_queue *rq_next;	/* next red_state in the list */
	struct ifaltq *rq_ifq;		/* backpointer to ifaltq */

	class_queue_t *rq_q;

	red_t *rq_red;
} red_queue_t;
#endif /* ALTQ3_COMPAT */

/* red drop types */
#define	DTYPE_NODROP	0	/* no drop */
#define	DTYPE_FORCED	1	/* a "forced" drop */
#define	DTYPE_EARLY	2	/* an "unforced" (early) drop */

extern red_t		*red_alloc(int, int, int, int, int, int);
extern void		 red_destroy(red_t *);
extern void		 red_getstats(red_t *, struct redstats *);
extern int		 red_addq(red_t *, class_queue_t *, struct mbuf *,
			     struct altq_pktattr *);
extern struct mbuf	*red_getq(red_t *, class_queue_t *);
extern int		 drop_early(int, int, int);
extern int		 mark_ecn(struct mbuf *, struct altq_pktattr *, int);
extern struct wtab	*wtab_alloc(int);
extern int		 wtab_destroy(struct wtab *);
extern int32_t		 pow_w(struct wtab *, int);

#endif /* _KERNEL */

#endif /* _ALTQ_ALTQ_RED_H_ */


code:
/*	$KAME: altq_rio.h,v 1.9 2003/07/10 12:07:49 kjc Exp $	*/

/*
 * Copyright (C) 1998-2003
 *	Sony Computer Science Laboratories Inc.  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 SONY CSL 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 SONY CSL 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.
 */

#ifndef _ALTQ_ALTQ_RIO_H_
#define	_ALTQ_ALTQ_RIO_H_

#include <altq/altq_classq.h>

/*
 * RIO: RED with IN/OUT bit
 * (extended to support more than 2 drop precedence values)
 */
#define	RIO_NDROPPREC	3	/* number of drop precedence values */

#ifdef ALTQ3_COMPAT
struct rio_interface {
	char	rio_ifname[IFNAMSIZ];
};

struct rio_stats {
	struct rio_interface iface;
	int q_len[RIO_NDROPPREC];
	struct redstats q_stats[RIO_NDROPPREC];

	/* static red parameters */
	int q_limit;
	int weight;
	int flags;
	struct redparams q_params[RIO_NDROPPREC];
};

struct rio_conf {
	struct rio_interface iface;
	struct redparams q_params[RIO_NDROPPREC];
	int rio_weight;		/* weight for EWMA */
	int rio_limit;		/* max queue length */
	int rio_pkttime;	/* average packet time in usec */
	int rio_flags;		/* see below */
};
#endif /* ALTQ3_COMPAT */

/* rio flags */
#define	RIOF_ECN4	0x01	/* use packet marking for IPv4 packets */
#define	RIOF_ECN6	0x02	/* use packet marking for IPv6 packets */
#define	RIOF_ECN	(RIOF_ECN4 | RIOF_ECN6)
#define	RIOF_CLEARDSCP	0x200	/* clear diffserv codepoint */

#ifdef ALTQ3_COMPAT
/*
 * IOCTLs for RIO
 */
#define	RIO_IF_ATTACH		_IOW('Q', 1, struct rio_interface)
#define	RIO_IF_DETACH		_IOW('Q', 2, struct rio_interface)
#define	RIO_ENABLE		_IOW('Q', 3, struct rio_interface)
#define	RIO_DISABLE		_IOW('Q', 4, struct rio_interface)
#define	RIO_CONFIG		_IOWR('Q', 6, struct rio_conf)
#define	RIO_GETSTATS		_IOWR('Q', 12, struct rio_stats)
#define	RIO_SETDEFAULTS		_IOW('Q', 30, struct redparams[RIO_NDROPPREC])
#endif /* ALTQ3_COMPAT */

#ifdef _KERNEL

typedef struct rio {
	/* per drop precedence structure */
	struct dropprec_state {
		/* red parameters */
		int	inv_pmax;	/* inverse of max drop probability */
		int	th_min;		/* red min threshold */
		int	th_max;		/* red max threshold */

		/* variables for internal use */
		int	th_min_s;	/* th_min scaled by avgshift */
		int	th_max_s;	/* th_max scaled by avgshift */
		int	probd;		/* drop probability denominator */

		int	qlen;		/* queue length */
		int	avg;		/* (scaled) queue length average */
		int	count;		/* packet count since the last dropped/
					   marked packet */
		int	idle;		/* queue was empty */
		int	old;		/* avg is above th_min */
		struct timeval	last;	/* timestamp when queue becomes idle */
	} rio_precstate[RIO_NDROPPREC];

	int		 rio_wshift;	/* log(red_weight) */
	int		 rio_weight;	/* weight for EWMA */
	struct wtab	*rio_wtab;	/* weight table */

	int		 rio_pkttime;	/* average packet time in micro sec
					   used for idle calibration */
	int		 rio_flags;	/* rio flags */

	u_int8_t	 rio_codepoint;	/* codepoint value to tag packets */
	u_int8_t	 rio_codepointmask;	/* codepoint mask bits */

	struct redstats q_stats[RIO_NDROPPREC];	/* statistics */
} rio_t;

#ifdef ALTQ3_COMPAT
typedef struct rio_queue {
	struct rio_queue	*rq_next;	/* next red_state in the list */
	struct ifaltq		*rq_ifq;	/* backpointer to ifaltq */

	class_queue_t		*rq_q;

	rio_t			*rq_rio;
} rio_queue_t;
#endif /* ALTQ3_COMPAT */

extern rio_t		*rio_alloc(int, struct redparams *, int, int);
extern void		 rio_destroy(rio_t *);
extern void		 rio_getstats(rio_t *, struct redstats *);
extern int		 rio_addq(rio_t *, class_queue_t *, struct mbuf *,
			     struct altq_pktattr *);
extern struct mbuf	*rio_getq(rio_t *, class_queue_t *);

#endif /* _KERNEL */

#endif /* _ALTQ_ALTQ_RIO_H_ */


code:
/*	$KAME: altq_rmclass.h,v 1.10 2003/08/20 23:30:23 itojun Exp $	*/

/*
 * Copyright (c) 1991-1997 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Network Research
 *	Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory 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.
 */

#ifndef _ALTQ_ALTQ_RMCLASS_H_
#define	_ALTQ_ALTQ_RMCLASS_H_

#include <altq/altq_classq.h>

/* #pragma ident "@(#)rm_class.h  1.20     97/10/23 SMI" */

#ifdef __cplusplus
extern "C" {
#endif

#define	RM_MAXPRIO	8	/* Max priority */

#ifdef _KERNEL

typedef struct mbuf		mbuf_t;
typedef struct rm_ifdat		rm_ifdat_t;
typedef struct rm_class		rm_class_t;

struct red;

/*
 * Macros for dealing with time values.  We assume all times are
 * 'timevals'.  `microtime' is used to get the best available clock
 * resolution.  If `microtime' *doesn't* return a value that's about
 * ten times smaller than the average packet time on the fastest
 * link that will use these routines, a slightly different clock
 * scheme than this one should be used.
 * (Bias due to truncation error in this scheme will overestimate utilization
 * and discriminate against high bandwidth classes.  To remove this bias an
 * integrator needs to be added.  The simplest integrator uses a history of
 * 10 * avg.packet.time / min.tick.time packet completion entries.  This is
 * straight forward to add but we don't want to pay the extra memory
 * traffic to maintain it if it's not necessary (occasionally a vendor
 * accidentally builds a workstation with a decent clock - e.g., Sun & HP).)
 */

#define	RM_GETTIME(now) microtime(&now)

#define	TV_LT(a, b) (((a)->tv_sec < (b)->tv_sec) ||  \
	(((a)->tv_usec < (b)->tv_usec) && ((a)->tv_sec <= (b)->tv_sec)))

#define	TV_DELTA(a, b, delta) { \
	register int	xxs;	\
							\
	delta = (a)->tv_usec - (b)->tv_usec; \
	if ((xxs = (a)->tv_sec - (b)->tv_sec)) { \
		switch (xxs) { \
		default: \
			/* if (xxs < 0) \
				printf("rm_class: bogus time values\n"); */ \
			delta = 0; \
			/* fall through */ \
		case 2: \
			delta += 1000000; \
			/* fall through */ \
		case 1: \
			delta += 1000000; \
			break; \
		} \
	} \
}

#define	TV_ADD_DELTA(a, delta, res) { \
	register int xxus = (a)->tv_usec + (delta); \
	\
	(res)->tv_sec = (a)->tv_sec; \
	while (xxus >= 1000000) { \
		++((res)->tv_sec); \
		xxus -= 1000000; \
	} \
	(res)->tv_usec = xxus; \
}

#define	RM_TIMEOUT	2	/* 1 Clock tick. */

#if 1
#define	RM_MAXQUEUED	1	/* this isn't used in ALTQ/CBQ */
#else
#define	RM_MAXQUEUED	16	/* Max number of packets downstream of CBQ */
#endif
#define	RM_MAXQUEUE	64	/* Max queue length */
#define	RM_FILTER_GAIN	5	/* log2 of gain, e.g., 5 => 31/32 */
#define	RM_POWER	(1 << RM_FILTER_GAIN)
#define	RM_MAXDEPTH	32
#define	RM_NS_PER_SEC	(1000000000)

typedef struct _rm_class_stats_ {
	u_int		handle;
	u_int		depth;

	struct pktcntr	xmit_cnt;	/* packets sent in this class */
	struct pktcntr	drop_cnt;	/* dropped packets */
	u_int		over;		/* # times went over limit */
	u_int		borrows;	/* # times tried to borrow */
	u_int		overactions;	/* # times invoked overlimit action */
	u_int		delays;		/* # times invoked delay actions */
} rm_class_stats_t;

/*
 * CBQ Class state structure
 */
struct rm_class {
	class_queue_t	*q_;		/* Queue of packets */
	rm_ifdat_t	*ifdat_;
	int		pri_;		/* Class priority. */
	int		depth_;		/* Class depth */
	u_int		ns_per_byte_;	/* NanoSeconds per byte. */
	u_int		maxrate_;	/* Bytes per second for this class. */
	u_int		allotment_;	/* Fraction of link bandwidth. */
	u_int		w_allotment_;	/* Weighted allotment for WRR */
	int		bytes_alloc_;	/* Allocation for round of WRR */

	int		avgidle_;
	int		maxidle_;
	int		minidle_;
	int		offtime_;
	int		sleeping_;	/* != 0 if delaying */
	int		qthresh_;	/* Queue threshold for formal link sharing */
	int		leaf_;		/* Note whether leaf class or not.*/

	rm_class_t	*children_;	/* Children of this class */
	rm_class_t	*next_;		/* Next pointer, used if child */

	rm_class_t	*peer_;		/* Peer class */
	rm_class_t	*borrow_;	/* Borrow class */
	rm_class_t	*parent_;	/* Parent class */

	void	(*overlimit)(struct rm_class *, struct rm_class *);
	void	(*drop)(struct rm_class *);       /* Class drop action. */

	struct red	*red_;		/* RED state pointer */
	struct altq_pktattr *pktattr_;	/* saved hdr used by RED/ECN */
	int		flags_;

	int		last_pkttime_;	/* saved pkt_time */
	struct timeval	undertime_;	/* time can next send */
	struct timeval	last_;		/* time last packet sent */
	struct timeval	overtime_;
	struct callout	callout_; 	/* for timeout() calls */

	rm_class_stats_t stats_;	/* Class Statistics */
};

/*
 * CBQ Interface state
 */
struct rm_ifdat {
	int		queued_;	/* # pkts queued downstream */
	int		efficient_;	/* Link Efficency bit */
	int		wrr_;		/* Enable Weighted Round-Robin */
	u_long		ns_per_byte_;	/* Link byte speed. */
	int		maxqueued_;	/* Max packets to queue */
	int		maxpkt_;	/* Max packet size. */
	int		qi_;		/* In/out pointers for downstream */
	int		qo_;		/* packets */

	/*
	 * Active class state and WRR state.
	 */
	rm_class_t	*active_[RM_MAXPRIO];	/* Active cl's in each pri */
	int		na_[RM_MAXPRIO];	/* # of active cl's in a pri */
	int		num_[RM_MAXPRIO];	/* # of cl's per pri */
	int		alloc_[RM_MAXPRIO];	/* Byte Allocation */
	u_long		M_[RM_MAXPRIO];		/* WRR weights. */

	/*
	 * Network Interface/Solaris Queue state pointer.
	 */
	struct ifaltq	*ifq_;
	rm_class_t	*default_;	/* Default Pkt class, BE */
	rm_class_t	*root_;		/* Root Link class. */
	rm_class_t	*ctl_;		/* Control Traffic class. */
	void		(*restart)(struct ifaltq *);	/* Restart routine. */

	/*
	 * Current packet downstream packet state and dynamic state.
	 */
	rm_class_t	*borrowed_[RM_MAXQUEUED]; /* Class borrowed last */
	rm_class_t	*class_[RM_MAXQUEUED];	/* class sending */
	int		curlen_[RM_MAXQUEUED];	/* Current pktlen */
	struct timeval	now_[RM_MAXQUEUED];	/* Current packet time. */
	int		is_overlimit_[RM_MAXQUEUED];/* Current packet time. */

	int		cutoff_;	/* Cut-off depth for borrowing */

	struct timeval	ifnow_;		/* expected xmit completion time */
#if 1 /* ALTQ4PPP */
	int		maxiftime_;	/* max delay inside interface */
#endif
        rm_class_t	*pollcache_;	/* cached rm_class by poll operation */
};

/* flags for rmc_init and rmc_newclass */
/* class flags */
#define	RMCF_RED		0x0001
#define	RMCF_ECN		0x0002
#define	RMCF_RIO		0x0004
#define	RMCF_FLOWVALVE		0x0008	/* use flowvalve (aka penalty-box) */
#define	RMCF_CLEARDSCP		0x0010  /* clear diffserv codepoint */

/* flags for rmc_init */
#define	RMCF_WRR		0x0100
#define	RMCF_EFFICIENT		0x0200

#define	is_a_parent_class(cl)	((cl)->children_ != NULL)

extern rm_class_t *rmc_newclass(int, struct rm_ifdat *, u_int,
				void (*)(struct rm_class *, struct rm_class *),
				int, struct rm_class *, struct rm_class *,
				u_int, int, u_int, int, int);
extern void	rmc_delete_class(struct rm_ifdat *, struct rm_class *);
extern int 	rmc_modclass(struct rm_class *, u_int, int,
			     u_int, int, u_int, int);
extern void	rmc_init(struct ifaltq *, struct rm_ifdat *, u_int,
			 void (*)(struct ifaltq *),
			 int, int, u_int, int, u_int, int);
extern int	rmc_queue_packet(struct rm_class *, mbuf_t *);
extern mbuf_t	*rmc_dequeue_next(struct rm_ifdat *, int);
extern void	rmc_update_class_util(struct rm_ifdat *);
extern void	rmc_delay_action(struct rm_class *, struct rm_class *);
extern void	rmc_dropall(struct rm_class *);
extern int	rmc_get_weight(struct rm_ifdat *, int);

#endif /* _KERNEL */

#ifdef __cplusplus
}
#endif

#endif /* _ALTQ_ALTQ_RMCLASS_H_ */


code:
/*	$KAME: altq_rmclass_debug.h,v 1.3 2002/11/29 04:36:24 kjc Exp $	*/

/*
 * Copyright (c) Sun Microsystems, Inc. 1998 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 the SMCC Technology
 *      Development Group at Sun Microsystems, Inc.
 *
 * 4. The name of the Sun Microsystems, Inc nor may not be used to endorse or
 *      promote products derived from this software without specific prior
 *      written permission.
 *
 * SUN MICROSYSTEMS DOES NOT CLAIM MERCHANTABILITY OF THIS SOFTWARE OR THE
 * SUITABILITY OF THIS SOFTWARE FOR ANY PARTICULAR PURPOSE.  The software is
 * provided "as is" without express or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this software.
 */

#ifndef _ALTQ_ALTQ_RMCLASS_DEBUG_H_
#define	_ALTQ_ALTQ_RMCLASS_DEBUG_H_

/* #pragma ident	"@(#)rm_class_debug.h	1.7	98/05/04 SMI" */

/*
 * Cbq debugging macros
 */

#ifdef __cplusplus
extern "C" {
#endif

#ifdef	CBQ_TRACE
#ifndef NCBQTRACE
#define	NCBQTRACE (16 * 1024)
#endif

/*
 * To view the trace output, using adb, type:
 *	adb -k /dev/ksyms /dev/mem <cr>, then type
 *	cbqtrace_count/D to get the count, then type
 *	cbqtrace_buffer,0tcount/Dp4C" "Xn
 *	This will dump the trace buffer from 0 to count.
 */
/*
 * in ALTQ, "call cbqtrace_dump(N)" from DDB to display 20 events
 * from Nth event in the circular buffer.
 */

struct cbqtrace {
	int count;
	int function;		/* address of function */
	int trace_action;	/* descriptive 4 characters */
	int object;		/* object operated on */
};

extern struct cbqtrace cbqtrace_buffer[];
extern struct cbqtrace *cbqtrace_ptr;
extern int cbqtrace_count;

#define	CBQTRACEINIT() {				\
	if (cbqtrace_ptr == NULL)		\
		cbqtrace_ptr = cbqtrace_buffer; \
	else { \
		cbqtrace_ptr = cbqtrace_buffer; \
		bzero((void *)cbqtrace_ptr, sizeof(cbqtrace_buffer)); \
		cbqtrace_count = 0; \
	} \
}

#define	LOCK_TRACE()	splimp()
#define	UNLOCK_TRACE(x)	splx(x)

#define	CBQTRACE(func, act, obj) {		\
	int __s = LOCK_TRACE();			\
	int *_p = &cbqtrace_ptr->count;	\
	*_p++ = ++cbqtrace_count;		\
	*_p++ = (int)(func);			\
	*_p++ = (int)(act);			\
	*_p++ = (int)(obj);			\
	if ((struct cbqtrace *)(void *)_p >= &cbqtrace_buffer[NCBQTRACE])\
		cbqtrace_ptr = cbqtrace_buffer; \
	else					\
		cbqtrace_ptr = (struct cbqtrace *)(void *)_p; \
	UNLOCK_TRACE(__s);			\
	}
#else

/* If no tracing, define no-ops */
#define	CBQTRACEINIT()
#define	CBQTRACE(a, b, c)

#endif	/* !CBQ_TRACE */

#ifdef __cplusplus
}
#endif

#endif	/* _ALTQ_ALTQ_RMCLASS_DEBUG_H_ */


code:
/*	$FreeBSD: release/9.0.0/sys/contrib/altq/altq/altq_var.h 219457 2011-03-10 18:49:15Z jkim $	*/
/*	$KAME: altq_var.h,v 1.16 2003/10/03 05:05:15 kjc Exp $	*/

/*
 * Copyright (C) 1998-2003
 *	Sony Computer Science Laboratories Inc.  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 SONY CSL 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 SONY CSL 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.
 */
#ifndef _ALTQ_ALTQ_VAR_H_
#define	_ALTQ_ALTQ_VAR_H_

#ifdef _KERNEL

#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/queue.h>

#ifdef ALTQ3_CLFIER_COMPAT
/*
 * filter structure for altq common classifier
 */
struct acc_filter {
	LIST_ENTRY(acc_filter)	f_chain;
	void			*f_class;	/* pointer to the class */
	u_long			f_handle;	/* filter id */
	u_int32_t		f_fbmask;	/* filter bitmask */
	struct flow_filter	f_filter;	/* filter value */
};

/*
 * XXX ACC_FILTER_TABLESIZE can't be larger than 2048 unless we fix
 * the handle assignment.
 */
#define	ACC_FILTER_TABLESIZE	(256+1)
#define	ACC_FILTER_MASK		(ACC_FILTER_TABLESIZE - 2)
#define	ACC_WILDCARD_INDEX	(ACC_FILTER_TABLESIZE - 1)
#ifdef __GNUC__
#define	ACC_GET_HASH_INDEX(addr) \
	({int x = (addr) + ((addr) >> 16); (x + (x >> 8)) & ACC_FILTER_MASK;})
#else
#define	ACC_GET_HASH_INDEX(addr) \
	(((addr) + ((addr) >> 8) + ((addr) >> 16) + ((addr) >> 24)) \
	& ACC_FILTER_MASK)
#endif
#define	ACC_GET_HINDEX(handle) ((handle) >> 20)

#if (__FreeBSD_version > 500000)
#define ACC_LOCK_INIT(ac)	mtx_init(&(ac)->acc_mtx, "classifier", MTX_DEF)
#define ACC_LOCK_DESTROY(ac)	mtx_destroy(&(ac)->acc_mtx)
#define ACC_LOCK(ac)		mtx_lock(&(ac)->acc_mtx)
#define ACC_UNLOCK(ac)		mtx_unlock(&(ac)->acc_mtx)
#else
#define ACC_LOCK_INIT(ac)
#define ACC_LOCK_DESTROY(ac)
#define ACC_LOCK(ac)
#define ACC_UNLOCK(ac)
#endif

struct acc_classifier {
	u_int32_t			acc_fbmask;
	LIST_HEAD(filt, acc_filter)	acc_filters[ACC_FILTER_TABLESIZE];

#if (__FreeBSD_version > 500000)
	struct	mtx acc_mtx;
#endif
};

/*
 * flowinfo mask bits used by classifier
 */
/* for ipv4 */
#define	FIMB4_PROTO	0x0001
#define	FIMB4_TOS	0x0002
#define	FIMB4_DADDR	0x0004
#define	FIMB4_SADDR	0x0008
#define	FIMB4_DPORT	0x0010
#define	FIMB4_SPORT	0x0020
#define	FIMB4_GPI	0x0040
#define	FIMB4_ALL	0x007f
/* for ipv6 */
#define	FIMB6_PROTO	0x0100
#define	FIMB6_TCLASS	0x0200
#define	FIMB6_DADDR	0x0400
#define	FIMB6_SADDR	0x0800
#define	FIMB6_DPORT	0x1000
#define	FIMB6_SPORT	0x2000
#define	FIMB6_GPI	0x4000
#define	FIMB6_FLABEL	0x8000
#define	FIMB6_ALL	0xff00

#define	FIMB_ALL	(FIMB4_ALL|FIMB6_ALL)

#define	FIMB4_PORTS	(FIMB4_DPORT|FIMB4_SPORT|FIMB4_GPI)
#define	FIMB6_PORTS	(FIMB6_DPORT|FIMB6_SPORT|FIMB6_GPI)
#endif /* ALTQ3_CLFIER_COMPAT */

/*
 * machine dependent clock
 * a 64bit high resolution time counter.
 */
extern int machclk_usepcc;
extern u_int32_t machclk_freq;
extern u_int32_t machclk_per_tick;
extern void init_machclk(void);
extern u_int64_t read_machclk(void);

/*
 * debug support
 */
#ifdef ALTQ_DEBUG
#ifdef __STDC__
#define	ASSERT(e)	((e) ? (void)0 : altq_assert(__FILE__, __LINE__, #e))
#else	/* PCC */
#define	ASSERT(e)	((e) ? (void)0 : altq_assert(__FILE__, __LINE__, "e"))
#endif
#else
#define	ASSERT(e)	((void)0)
#endif

/*
 * misc stuff for compatibility
 */
/* ioctl cmd type */
typedef u_long ioctlcmd_t;

/*
 * queue macros:
 * the interface of TAILQ_LAST macro changed after the introduction
 * of softupdate. redefine it here to make it work with pre-2.2.7.
 */
#undef TAILQ_LAST
#define	TAILQ_LAST(head, headname) \
	(*(((struct headname *)((head)->tqh_last))->tqh_last))

#ifndef TAILQ_EMPTY
#define	TAILQ_EMPTY(head) ((head)->tqh_first == NULL)
#endif
#ifndef TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)					\
	for (var = TAILQ_FIRST(head); var; var = TAILQ_NEXT(var, field))
#endif

/* macro for timeout/untimeout */
#if (__FreeBSD_version > 300000) || defined(__NetBSD__)
/* use callout */
#include <sys/callout.h>

#if (__FreeBSD_version > 500000)
#define	CALLOUT_INIT(c)		callout_init((c), 0)
#else
#define	CALLOUT_INIT(c)		callout_init((c))
#endif
#define	CALLOUT_RESET(c,t,f,a)	callout_reset((c),(t),(f),(a))
#define	CALLOUT_STOP(c)		callout_stop((c))
#if !defined(CALLOUT_INITIALIZER) && (__FreeBSD_version < 600000)
#define	CALLOUT_INITIALIZER	{ { { NULL } }, 0, NULL, NULL, 0 }
#endif
#elif defined(__OpenBSD__)
#include <sys/timeout.h>
/* callout structure as a wrapper of struct timeout */
struct callout {
	struct timeout	c_to;
};
#define	CALLOUT_INIT(c)		do { bzero((c), sizeof(*(c))); } while (/*CONSTCOND*/ 0)
#define	CALLOUT_RESET(c,t,f,a)	do { if (!timeout_initialized(&(c)->c_to))  \
					 timeout_set(&(c)->c_to, (f), (a)); \
				     timeout_add(&(c)->c_to, (t)); } while (/*CONSTCOND*/ 0)
#define	CALLOUT_STOP(c)		timeout_del(&(c)->c_to)
#define	CALLOUT_INITIALIZER	{ { { NULL }, NULL, NULL, 0, 0 } }
#else
/* use old-style timeout/untimeout */
/* dummy callout structure */
struct callout {
	void		*c_arg;			/* function argument */
	void		(*c_func)(void *);	/* functiuon to call */
};
#define	CALLOUT_INIT(c)		do { bzero((c), sizeof(*(c))); } while (/*CONSTCOND*/ 0)
#define	CALLOUT_RESET(c,t,f,a)	do {	(c)->c_arg = (a);	\
					(c)->c_func = (f);	\
					timeout((f),(a),(t)); } while (/*CONSTCOND*/ 0)
#define	CALLOUT_STOP(c)		untimeout((c)->c_func,(c)->c_arg)
#define	CALLOUT_INITIALIZER	{ NULL, NULL }
#endif
#if !defined(__FreeBSD__)
typedef void (timeout_t)(void *);
#endif

#define	m_pktlen(m)		((m)->m_pkthdr.len)

struct ifnet; struct mbuf;
struct pf_altq;
#ifdef ALTQ3_CLFIER_COMPAT
struct flowinfo;
#endif

void	*altq_lookup(char *, int);
#ifdef ALTQ3_CLFIER_COMPAT
int	altq_extractflow(struct mbuf *, int, struct flowinfo *, u_int32_t);
int	acc_add_filter(struct acc_classifier *, struct flow_filter *,
	    void *, u_long *);
int	acc_delete_filter(struct acc_classifier *, u_long);
int	acc_discard_filters(struct acc_classifier *, void *, int);
void	*acc_classify(void *, struct mbuf *, int);
#endif
u_int8_t read_dsfield(struct mbuf *, struct altq_pktattr *);
void	write_dsfield(struct mbuf *, struct altq_pktattr *, u_int8_t);
void	altq_assert(const char *, int, const char *);
int	tbr_set(struct ifaltq *, struct tb_profile *);
int	tbr_get(struct ifaltq *, struct tb_profile *);

int	altq_pfattach(struct pf_altq *);
int	altq_pfdetach(struct pf_altq *);
int	altq_add(struct pf_altq *);
int	altq_remove(struct pf_altq *);
int	altq_add_queue(struct pf_altq *);
int	altq_remove_queue(struct pf_altq *);
int	altq_getqstats(struct pf_altq *, void *, int *);

int	cbq_pfattach(struct pf_altq *);
int	cbq_add_altq(struct pf_altq *);
int	cbq_remove_altq(struct pf_altq *);
int	cbq_add_queue(struct pf_altq *);
int	cbq_remove_queue(struct pf_altq *);
int	cbq_getqstats(struct pf_altq *, void *, int *);

int	priq_pfattach(struct pf_altq *);
int	priq_add_altq(struct pf_altq *);
int	priq_remove_altq(struct pf_altq *);
int	priq_add_queue(struct pf_altq *);
int	priq_remove_queue(struct pf_altq *);
int	priq_getqstats(struct pf_altq *, void *, int *);

int	hfsc_pfattach(struct pf_altq *);
int	hfsc_add_altq(struct pf_altq *);
int	hfsc_remove_altq(struct pf_altq *);
int	hfsc_add_queue(struct pf_altq *);
int	hfsc_remove_queue(struct pf_altq *);
int	hfsc_getqstats(struct pf_altq *, void *, int *);

#endif /* _KERNEL */
#endif /* _ALTQ_ALTQ_VAR_H_ */


code:
/*	$OpenBSD: altqconf.h,v 1.1 2001/06/27 05:28:36 kjc Exp $	*/
/*	$NetBSD: altqconf.h,v 1.2 2001/05/30 11:57:16 mrg Exp $	*/

#if defined(_KERNEL_OPT) || defined(__OpenBSD__)

#if defined(_KERNEL_OPT)
#include "opt_altq_enabled.h"
#endif

#include <sys/conf.h>

#ifdef ALTQ
#define	NALTQ	1
#else
#define	NALTQ	0
#endif

cdev_decl(altq);

#ifdef __OpenBSD__
#define cdev_altq_init(c,n) { \
	dev_init(c,n,open), dev_init(c,n,close), (dev_type_read((*))) enodev, \
	(dev_type_write((*))) enodev, dev_init(c,n,ioctl), \
	(dev_type_stop((*))) enodev, 0, (dev_type_select((*))) enodev, \
	(dev_type_mmap((*))) enodev }
#else
#define	cdev_altq_init(x,y)	cdev__oci_init(x,y)
#endif
#endif /* defined(_KERNEL_OPT) || defined(__OpenBSD__) */


code:
/*	$FreeBSD: release/9.0.0/sys/contrib/altq/altq/if_altq.h 219457 2011-03-10 18:49:15Z jkim $	*/
/*	$KAME: if_altq.h,v 1.12 2005/04/13 03:44:25 suz Exp $	*/

/*
 * Copyright (C) 1997-2003
 *	Sony Computer Science Laboratories Inc.  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 SONY CSL 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 SONY CSL 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.
 */
#ifndef _ALTQ_IF_ALTQ_H_
#define	_ALTQ_IF_ALTQ_H_

#ifdef __FreeBSD__
#include <sys/lock.h>		/* XXX */
#include <sys/mutex.h>		/* XXX */
#include <sys/event.h>		/* XXX */
#endif

#ifdef _KERNEL_OPT
#include <altq/altqconf.h>
#endif

struct altq_pktattr; struct tb_regulator; struct top_cdnr;

/*
 * Structure defining a queue for a network interface.
 */
struct	ifaltq {
	/* fields compatible with struct ifqueue */
	struct	mbuf *ifq_head;
	struct	mbuf *ifq_tail;
	int	ifq_len;
	int	ifq_maxlen;
	int	ifq_drops;
#ifdef __FreeBSD__
	struct	mtx ifq_mtx;
#endif

	/* driver owned queue (used for bulk dequeue and prepend) UNLOCKED */
	struct	mbuf *ifq_drv_head;
	struct	mbuf *ifq_drv_tail;
	int	ifq_drv_len;
	int	ifq_drv_maxlen;

	/* alternate queueing related fields */
	int	altq_type;		/* discipline type */
	int	altq_flags;		/* flags (e.g. ready, in-use) */
	void	*altq_disc;		/* for discipline-specific use */
	struct	ifnet *altq_ifp;	/* back pointer to interface */

	int	(*altq_enqueue)(struct ifaltq *, struct mbuf *,
				struct altq_pktattr *);
	struct	mbuf *(*altq_dequeue)(struct ifaltq *, int);
	int	(*altq_request)(struct ifaltq *, int, void *);

	/* classifier fields */
	void	*altq_clfier;		/* classifier-specific use */
	void	*(*altq_classify)(void *, struct mbuf *, int);

	/* token bucket regulator */
	struct	tb_regulator *altq_tbr;

	/* input traffic conditioner (doesn't belong to the output queue...) */
	struct top_cdnr *altq_cdnr;
};

#ifdef _KERNEL

/*
 * packet attributes used by queueing disciplines.
 * pattr_class is a discipline-dependent scheduling class that is
 * set by a classifier.
 * pattr_hdr and pattr_af may be used by a discipline to access
 * the header within a mbuf.  (e.g. ECN needs to update the CE bit)
 * note that pattr_hdr could be stale after m_pullup, though link
 * layer output routines usually don't use m_pullup.  link-level
 * compression also invalidates these fields.  thus, pattr_hdr needs
 * to be verified when a discipline touches the header.
 */
struct altq_pktattr {
	void	*pattr_class;		/* sched class set by classifier */
	int	pattr_af;		/* address family */
	caddr_t	pattr_hdr;		/* saved header position in mbuf */
};

/*
 * mbuf tag to carry a queue id (and hints for ECN).
 */
struct altq_tag {
	u_int32_t	qid;		/* queue id */
	/* hints for ecn */
	int		af;		/* address family */
	void		*hdr;		/* saved header position in mbuf */
};

/*
 * a token-bucket regulator limits the rate that a network driver can
 * dequeue packets from the output queue.
 * modern cards are able to buffer a large amount of packets and dequeue
 * too many packets at a time.  this bursty dequeue behavior makes it
 * impossible to schedule packets by queueing disciplines.
 * a token-bucket is used to control the burst size in a device
 * independent manner.
 */
struct tb_regulator {
	int64_t		tbr_rate;	/* (scaled) token bucket rate */
	int64_t		tbr_depth;	/* (scaled) token bucket depth */

	int64_t		tbr_token;	/* (scaled) current token */
	int64_t		tbr_filluptime;	/* (scaled) time to fill up bucket */
	u_int64_t	tbr_last;	/* last time token was updated */

	int		tbr_lastop;	/* last dequeue operation type
					   needed for poll-and-dequeue */
};

/* if_altqflags */
#define	ALTQF_READY	 0x01	/* driver supports alternate queueing */
#define	ALTQF_ENABLED	 0x02	/* altq is in use */
#define	ALTQF_CLASSIFY	 0x04	/* classify packets */
#define	ALTQF_CNDTNING	 0x08	/* altq traffic conditioning is enabled */
#define	ALTQF_DRIVER1	 0x40	/* driver specific */

/* if_altqflags set internally only: */
#define	ALTQF_CANTCHANGE 	(ALTQF_READY)

/* altq_dequeue 2nd arg */
#define	ALTDQ_REMOVE		1	/* dequeue mbuf from the queue */
#define	ALTDQ_POLL		2	/* don't dequeue mbuf from the queue */

/* altq request types (currently only purge is defined) */
#define	ALTRQ_PURGE		1	/* purge all packets */

#define	ALTQ_IS_READY(ifq)		((ifq)->altq_flags & ALTQF_READY)
#define	ALTQ_IS_ENABLED(ifq)		((ifq)->altq_flags & ALTQF_ENABLED)
#define	ALTQ_NEEDS_CLASSIFY(ifq)	((ifq)->altq_flags & ALTQF_CLASSIFY)
#define	ALTQ_IS_CNDTNING(ifq)		((ifq)->altq_flags & ALTQF_CNDTNING)

#define	ALTQ_SET_CNDTNING(ifq)		((ifq)->altq_flags |= ALTQF_CNDTNING)
#define	ALTQ_CLEAR_CNDTNING(ifq)	((ifq)->altq_flags &= ~ALTQF_CNDTNING)
#define	ALTQ_IS_ATTACHED(ifq)		((ifq)->altq_disc != NULL)

#define	ALTQ_ENQUEUE(ifq, m, pa, err)					\
	(err) = (*(ifq)->altq_enqueue)((ifq),(m),(pa))
#define	ALTQ_DEQUEUE(ifq, m)						\
	(m) = (*(ifq)->altq_dequeue)((ifq), ALTDQ_REMOVE)
#define	ALTQ_POLL(ifq, m)						\
	(m) = (*(ifq)->altq_dequeue)((ifq), ALTDQ_POLL)
#define	ALTQ_PURGE(ifq)							\
	(void)(*(ifq)->altq_request)((ifq), ALTRQ_PURGE, (void *)0)
#define	ALTQ_IS_EMPTY(ifq)		((ifq)->ifq_len == 0)
#define	TBR_IS_ENABLED(ifq)		((ifq)->altq_tbr != NULL)

extern int altq_attach(struct ifaltq *, int, void *,
		       int (*)(struct ifaltq *, struct mbuf *,
			       struct altq_pktattr *),
		       struct mbuf *(*)(struct ifaltq *, int),
		       int (*)(struct ifaltq *, int, void *),
		       void *,
		       void *(*)(void *, struct mbuf *, int));
extern int altq_detach(struct ifaltq *);
extern int altq_enable(struct ifaltq *);
extern int altq_disable(struct ifaltq *);
extern struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int);
extern int (*altq_input)(struct mbuf *, int);
#if 0 /* ALTQ3_CLFIER_COMPAT */
void altq_etherclassify(struct ifaltq *, struct mbuf *, struct altq_pktattr *);
#endif
#endif /* _KERNEL */

#endif /* _ALTQ_IF_ALTQ_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.
 *
 * This code is derived from software contributed to Berkeley by
 * Hugh Smith at The University of Guelph.
 *
 * 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. 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.
 *
 *	@(#)ar.h	8.2 (Berkeley) 1/21/94
 *
 * $FreeBSD: release/9.0.0/include/ar.h 203964 2010-02-16 19:39:50Z imp $
 */

#ifndef _AR_H_
#define	_AR_H_

#include <sys/cdefs.h>

/* Pre-4BSD archives had these magic numbers in them. */
#define	OARMAG1	0177555
#define	OARMAG2	0177545

#define	ARMAG		"!<arch>\n"	/* ar "magic number" */
#define	SARMAG		8		/* strlen(ARMAG); */

#define	AR_EFMT1	"#1/"		/* extended format #1 */

struct ar_hdr {
	char ar_name[16];		/* name */
	char ar_date[12];		/* modification time */
	char ar_uid[6];			/* user id */
	char ar_gid[6];			/* group id */
	char ar_mode[8];		/* octal file permissions */
	char ar_size[10];		/* size in bytes */
#define	ARFMAG	"`\n"
	char ar_fmag[2];		/* consistency check */
} __packed;

#endif /* !_AR_H_ */


code:
/*-
 * Copyright (c) 2003-2007 Tim Kientzle
 * 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(S) ``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(S) 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/lib/libarchive/archive.h 224152 2011-07-17 21:27:38Z mm $
 */

#ifndef ARCHIVE_H_INCLUDED
#define	ARCHIVE_H_INCLUDED

/*
 * Note: archive.h is for use outside of libarchive; the configuration
 * headers (config.h, archive_platform.h, etc.) are purely internal.
 * Do NOT use HAVE_XXX configuration macros to control the behavior of
 * this header!  If you must conditionalize, use predefined compiler and/or
 * platform macros.
 */
#if defined(__BORLANDC__) && __BORLANDC__ >= 0x560
# define __LA_STDINT_H <stdint.h>
#elif !defined(__WATCOMC__) && !defined(_MSC_VER) && !defined(__INTERIX) && !defined(__BORLANDC__)
# define __LA_STDINT_H <inttypes.h>
#endif

#include <sys/stat.h>
#include <sys/types.h>  /* Linux requires this for off_t */
#ifdef __LA_STDINT_H
# include __LA_STDINT_H /* int64_t, etc. */
#endif
#include <stdio.h> /* For FILE * */

/* Get appropriate definitions of standard POSIX-style types. */
/* These should match the types used in 'struct stat' */
#if defined(_WIN32) && !defined(__CYGWIN__)
#define	__LA_INT64_T	__int64
# if defined(_SSIZE_T_DEFINED)
#  define	__LA_SSIZE_T	ssize_t
# elif defined(_WIN64)
#  define	__LA_SSIZE_T	__int64
# else
#  define	__LA_SSIZE_T	long
# endif
# if defined(__BORLANDC__)
#  define	__LA_UID_T	uid_t
#  define	__LA_GID_T	gid_t
# else
#  define	__LA_UID_T	short
#  define	__LA_GID_T	short
# endif
#else
#include <unistd.h>  /* ssize_t, uid_t, and gid_t */
#define	__LA_INT64_T	int64_t
#define	__LA_SSIZE_T	ssize_t
#define	__LA_UID_T	uid_t
#define	__LA_GID_T	gid_t
#endif

/*
 * On Windows, define LIBARCHIVE_STATIC if you're building or using a
 * .lib.  The default here assumes you're building a DLL.  Only
 * libarchive source should ever define __LIBARCHIVE_BUILD.
 */
#if ((defined __WIN32__) || (defined _WIN32) || defined(__CYGWIN__)) && (!defined LIBARCHIVE_STATIC)
# ifdef __LIBARCHIVE_BUILD
#  ifdef __GNUC__
#   define __LA_DECL	__attribute__((dllexport)) extern
#  else
#   define __LA_DECL	__declspec(dllexport)
#  endif
# else
#  ifdef __GNUC__
#   define __LA_DECL	__attribute__((dllimport)) extern
#  else
#   define __LA_DECL	__declspec(dllimport)
#  endif
# endif
#else
/* Static libraries or non-Windows needs no special declaration. */
# define __LA_DECL
#endif

#ifdef __cplusplus
extern "C" {
#endif

/*
 * The version number is provided as both a macro and a function.
 * The macro identifies the installed header; the function identifies
 * the library version (which may not be the same if you're using a
 * dynamically-linked version of the library).  Of course, if the
 * header and library are very different, you should expect some
 * strangeness.  Don't do that.
 */

/*
 * The version number is expressed as a single integer that makes it
 * easy to compare versions at build time: for version a.b.c, the
 * version number is printf("%d%03d%03d",a,b,c).  For example, if you
 * know your application requires version 2.12.108 or later, you can
 * assert that ARCHIVE_VERSION >= 2012108.
 *
 * This single-number format was introduced with libarchive 1.9.0 in
 * the libarchive 1.x family and libarchive 2.2.4 in the libarchive
 * 2.x family.  The following may be useful if you really want to do
 * feature detection for earlier libarchive versions (which defined
 * ARCHIVE_API_VERSION and ARCHIVE_API_FEATURE instead):
 *
 * #ifndef ARCHIVE_VERSION_NUMBER
 * #define ARCHIVE_VERSION_NUMBER	\
 *             (ARCHIVE_API_VERSION * 1000000 + ARCHIVE_API_FEATURE * 1000)
 * #endif
 */
#define	ARCHIVE_VERSION_NUMBER 2008004
__LA_DECL int		archive_version_number(void);

/*
 * Textual name/version of the library, useful for version displays.
 */
#define	ARCHIVE_VERSION_STRING "libarchive 2.8.4"
__LA_DECL const char *	archive_version_string(void);

#if ARCHIVE_VERSION_NUMBER < 3000000
/*
 * Deprecated; these are older names that will be removed in favor of
 * the simpler definitions above.
 */
#define	ARCHIVE_VERSION_STAMP	ARCHIVE_VERSION_NUMBER
__LA_DECL int		archive_version_stamp(void);
#define	ARCHIVE_LIBRARY_VERSION	ARCHIVE_VERSION_STRING
__LA_DECL const char *	archive_version(void);
#define	ARCHIVE_API_VERSION	(ARCHIVE_VERSION_NUMBER / 1000000)
__LA_DECL int		archive_api_version(void);
#define	ARCHIVE_API_FEATURE	((ARCHIVE_VERSION_NUMBER / 1000) % 1000)
__LA_DECL int		archive_api_feature(void);
#endif

#if ARCHIVE_VERSION_NUMBER < 3000000
/* This should never have been here in the first place. */
/* Legacy of old tar assumptions, will be removed in libarchive 3.0. */
#define	ARCHIVE_BYTES_PER_RECORD	  512
#define	ARCHIVE_DEFAULT_BYTES_PER_BLOCK	10240
#endif

/* Declare our basic types. */
struct archive;
struct archive_entry;

/*
 * Error codes: Use archive_errno() and archive_error_string()
 * to retrieve details.  Unless specified otherwise, all functions
 * that return 'int' use these codes.
 */
#define	ARCHIVE_EOF	  1	/* Found end of archive. */
#define	ARCHIVE_OK	  0	/* Operation was successful. */
#define	ARCHIVE_RETRY	(-10)	/* Retry might succeed. */
#define	ARCHIVE_WARN	(-20)	/* Partial success. */
/* For example, if write_header "fails", then you can't push data. */
#define	ARCHIVE_FAILED	(-25)	/* Current operation cannot complete. */
/* But if write_header is "fatal," then this archive is dead and useless. */
#define	ARCHIVE_FATAL	(-30)	/* No more operations are possible. */

/*
 * As far as possible, archive_errno returns standard platform errno codes.
 * Of course, the details vary by platform, so the actual definitions
 * here are stored in "archive_platform.h".  The symbols are listed here
 * for reference; as a rule, clients should not need to know the exact
 * platform-dependent error code.
 */
/* Unrecognized or invalid file format. */
/* #define	ARCHIVE_ERRNO_FILE_FORMAT */
/* Illegal usage of the library. */
/* #define	ARCHIVE_ERRNO_PROGRAMMER_ERROR */
/* Unknown or unclassified error. */
/* #define	ARCHIVE_ERRNO_MISC */

/*
 * Callbacks are invoked to automatically read/skip/write/open/close the
 * archive. You can provide your own for complex tasks (like breaking
 * archives across multiple tapes) or use standard ones built into the
 * library.
 */

/* Returns pointer and size of next block of data from archive. */
typedef __LA_SSIZE_T	archive_read_callback(struct archive *,
			    void *_client_data, const void **_buffer);

/* Skips at most request bytes from archive and returns the skipped amount */
#if ARCHIVE_VERSION_NUMBER < 2000000
/* Libarchive 1.0 used ssize_t for the return, which is only 32 bits
 * on most 32-bit platforms; not large enough. */
typedef __LA_SSIZE_T	archive_skip_callback(struct archive *,
			    void *_client_data, size_t request);
#elif ARCHIVE_VERSION_NUMBER < 3000000
/* Libarchive 2.0 used off_t here, but that is a bad idea on Linux and a
 * few other platforms where off_t varies with build settings. */
typedef off_t		archive_skip_callback(struct archive *,
			    void *_client_data, off_t request);
#else
/* Libarchive 3.0 uses int64_t here, which is actually guaranteed to be
 * 64 bits on every platform. */
typedef __LA_INT64_T	archive_skip_callback(struct archive *,
			    void *_client_data, __LA_INT64_T request);
#endif

/* Returns size actually written, zero on EOF, -1 on error. */
typedef __LA_SSIZE_T	archive_write_callback(struct archive *,
			    void *_client_data,
			    const void *_buffer, size_t _length);

#if ARCHIVE_VERSION_NUMBER < 3000000
/* Open callback is actually never needed; remove it in libarchive 3.0. */
typedef int	archive_open_callback(struct archive *, void *_client_data);
#endif

typedef int	archive_close_callback(struct archive *, void *_client_data);

/*
 * Codes for archive_compression.
 */
#define	ARCHIVE_COMPRESSION_NONE	0
#define	ARCHIVE_COMPRESSION_GZIP	1
#define	ARCHIVE_COMPRESSION_BZIP2	2
#define	ARCHIVE_COMPRESSION_COMPRESS	3
#define	ARCHIVE_COMPRESSION_PROGRAM	4
#define	ARCHIVE_COMPRESSION_LZMA	5
#define	ARCHIVE_COMPRESSION_XZ		6
#define	ARCHIVE_COMPRESSION_UU		7
#define	ARCHIVE_COMPRESSION_RPM		8

/*
 * Codes returned by archive_format.
 *
 * Top 16 bits identifies the format family (e.g., "tar"); lower
 * 16 bits indicate the variant.  This is updated by read_next_header.
 * Note that the lower 16 bits will often vary from entry to entry.
 * In some cases, this variation occurs as libarchive learns more about
 * the archive (for example, later entries might utilize extensions that
 * weren't necessary earlier in the archive; in this case, libarchive
 * will change the format code to indicate the extended format that
 * was used).  In other cases, it's because different tools have
 * modified the archive and so different parts of the archive
 * actually have slightly different formts.  (Both tar and cpio store
 * format codes in each entry, so it is quite possible for each
 * entry to be in a different format.)
 */
#define	ARCHIVE_FORMAT_BASE_MASK		0xff0000
#define	ARCHIVE_FORMAT_CPIO			0x10000
#define	ARCHIVE_FORMAT_CPIO_POSIX		(ARCHIVE_FORMAT_CPIO | 1)
#define	ARCHIVE_FORMAT_CPIO_BIN_LE		(ARCHIVE_FORMAT_CPIO | 2)
#define	ARCHIVE_FORMAT_CPIO_BIN_BE		(ARCHIVE_FORMAT_CPIO | 3)
#define	ARCHIVE_FORMAT_CPIO_SVR4_NOCRC		(ARCHIVE_FORMAT_CPIO | 4)
#define	ARCHIVE_FORMAT_CPIO_SVR4_CRC		(ARCHIVE_FORMAT_CPIO | 5)
#define	ARCHIVE_FORMAT_SHAR			0x20000
#define	ARCHIVE_FORMAT_SHAR_BASE		(ARCHIVE_FORMAT_SHAR | 1)
#define	ARCHIVE_FORMAT_SHAR_DUMP		(ARCHIVE_FORMAT_SHAR | 2)
#define	ARCHIVE_FORMAT_TAR			0x30000
#define	ARCHIVE_FORMAT_TAR_USTAR		(ARCHIVE_FORMAT_TAR | 1)
#define	ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE	(ARCHIVE_FORMAT_TAR | 2)
#define	ARCHIVE_FORMAT_TAR_PAX_RESTRICTED	(ARCHIVE_FORMAT_TAR | 3)
#define	ARCHIVE_FORMAT_TAR_GNUTAR		(ARCHIVE_FORMAT_TAR | 4)
#define	ARCHIVE_FORMAT_ISO9660			0x40000
#define	ARCHIVE_FORMAT_ISO9660_ROCKRIDGE	(ARCHIVE_FORMAT_ISO9660 | 1)
#define	ARCHIVE_FORMAT_ZIP			0x50000
#define	ARCHIVE_FORMAT_EMPTY			0x60000
#define	ARCHIVE_FORMAT_AR			0x70000
#define	ARCHIVE_FORMAT_AR_GNU			(ARCHIVE_FORMAT_AR | 1)
#define	ARCHIVE_FORMAT_AR_BSD			(ARCHIVE_FORMAT_AR | 2)
#define	ARCHIVE_FORMAT_MTREE			0x80000
#define	ARCHIVE_FORMAT_RAW			0x90000
#define	ARCHIVE_FORMAT_XAR			0xA0000

/*-
 * Basic outline for reading an archive:
 *   1) Ask archive_read_new for an archive reader object.
 *   2) Update any global properties as appropriate.
 *      In particular, you'll certainly want to call appropriate
 *      archive_read_support_XXX functions.
 *   3) Call archive_read_open_XXX to open the archive
 *   4) Repeatedly call archive_read_next_header to get information about
 *      successive archive entries.  Call archive_read_data to extract
 *      data for entries of interest.
 *   5) Call archive_read_finish to end processing.
 */
__LA_DECL struct archive	*archive_read_new(void);

/*
 * The archive_read_support_XXX calls enable auto-detect for this
 * archive handle.  They also link in the necessary support code.
 * For example, if you don't want bzlib linked in, don't invoke
 * support_compression_bzip2().  The "all" functions provide the
 * obvious shorthand.
 */
__LA_DECL int		 archive_read_support_compression_all(struct archive *);
__LA_DECL int		 archive_read_support_compression_bzip2(struct archive *);
__LA_DECL int		 archive_read_support_compression_compress(struct archive *);
__LA_DECL int		 archive_read_support_compression_gzip(struct archive *);
__LA_DECL int		 archive_read_support_compression_lzma(struct archive *);
__LA_DECL int		 archive_read_support_compression_none(struct archive *);
__LA_DECL int		 archive_read_support_compression_program(struct archive *,
		     const char *command);
__LA_DECL int		 archive_read_support_compression_program_signature
				(struct archive *, const char *,
				    const void * /* match */, size_t);

__LA_DECL int		 archive_read_support_compression_rpm(struct archive *);
__LA_DECL int		 archive_read_support_compression_uu(struct archive *);
__LA_DECL int		 archive_read_support_compression_xz(struct archive *);

__LA_DECL int		 archive_read_support_format_all(struct archive *);
__LA_DECL int		 archive_read_support_format_ar(struct archive *);
__LA_DECL int		 archive_read_support_format_cpio(struct archive *);
__LA_DECL int		 archive_read_support_format_empty(struct archive *);
__LA_DECL int		 archive_read_support_format_gnutar(struct archive *);
__LA_DECL int		 archive_read_support_format_iso9660(struct archive *);
__LA_DECL int		 archive_read_support_format_mtree(struct archive *);
__LA_DECL int		 archive_read_support_format_raw(struct archive *);
__LA_DECL int		 archive_read_support_format_tar(struct archive *);
__LA_DECL int		 archive_read_support_format_xar(struct archive *);
__LA_DECL int		 archive_read_support_format_zip(struct archive *);

/* Open the archive using callbacks for archive I/O. */
__LA_DECL int		 archive_read_open(struct archive *, void *_client_data,
		     archive_open_callback *, archive_read_callback *,
		     archive_close_callback *);
__LA_DECL int		 archive_read_open2(struct archive *, void *_client_data,
		     archive_open_callback *, archive_read_callback *,
		     archive_skip_callback *, archive_close_callback *);

/*
 * A variety of shortcuts that invoke archive_read_open() with
 * canned callbacks suitable for common situations.  The ones that
 * accept a block size handle tape blocking correctly.
 */
/* Use this if you know the filename.  Note: NULL indicates stdin. */
__LA_DECL int		 archive_read_open_filename(struct archive *,
		     const char *_filename, size_t _block_size);
/* archive_read_open_file() is a deprecated synonym for ..._open_filename(). */
__LA_DECL int		 archive_read_open_file(struct archive *,
		     const char *_filename, size_t _block_size);
/* Read an archive that's stored in memory. */
__LA_DECL int		 archive_read_open_memory(struct archive *,
		     void * buff, size_t size);
/* A more involved version that is only used for internal testing. */
__LA_DECL int		archive_read_open_memory2(struct archive *a, void *buff,
		     size_t size, size_t read_size);
/* Read an archive that's already open, using the file descriptor. */
__LA_DECL int		 archive_read_open_fd(struct archive *, int _fd,
		     size_t _block_size);
/* Read an archive that's already open, using a FILE *. */
/* Note: DO NOT use this with tape drives. */
__LA_DECL int		 archive_read_open_FILE(struct archive *, FILE *_file);

/* Parses and returns next entry header. */
__LA_DECL int		 archive_read_next_header(struct archive *,
		     struct archive_entry **);

/* Parses and returns next entry header using the archive_entry passed in */
__LA_DECL int		 archive_read_next_header2(struct archive *,
		     struct archive_entry *);

/*
 * Retrieve the byte offset in UNCOMPRESSED data where last-read
 * header started.
 */
__LA_DECL __LA_INT64_T		 archive_read_header_position(struct archive *);

/* Read data from the body of an entry.  Similar to read(2). */
__LA_DECL __LA_SSIZE_T		 archive_read_data(struct archive *,
				    void *, size_t);

/*
 * A zero-copy version of archive_read_data that also exposes the file offset
 * of each returned block.  Note that the client has no way to specify
 * the desired size of the block.  The API does guarantee that offsets will
 * be strictly increasing and that returned blocks will not overlap.
 */
#if ARCHIVE_VERSION_NUMBER < 3000000
__LA_DECL int		 archive_read_data_block(struct archive *a,
			    const void **buff, size_t *size, off_t *offset);
#else
__LA_DECL int		 archive_read_data_block(struct archive *a,
			    const void **buff, size_t *size,
			    __LA_INT64_T *offset);
#endif

/*-
 * Some convenience functions that are built on archive_read_data:
 *  'skip': skips entire entry
 *  'into_buffer': writes data into memory buffer that you provide
 *  'into_fd': writes data to specified filedes
 */
__LA_DECL int		 archive_read_data_skip(struct archive *);
__LA_DECL int		 archive_read_data_into_buffer(struct archive *,
			    void *buffer, __LA_SSIZE_T len);
__LA_DECL int		 archive_read_data_into_fd(struct archive *, int fd);

/*
 * Set read options.
 */
/* Apply option string to the format only. */
__LA_DECL int		archive_read_set_format_options(struct archive *_a,
			    const char *s);
/* Apply option string to the filter only. */
__LA_DECL int		archive_read_set_filter_options(struct archive *_a,
			    const char *s);
/* Apply option string to both the format and the filter. */
__LA_DECL int		archive_read_set_options(struct archive *_a,
			    const char *s);

/*-
 * Convenience function to recreate the current entry (whose header
 * has just been read) on disk.
 *
 * This does quite a bit more than just copy data to disk. It also:
 *  - Creates intermediate directories as required.
 *  - Manages directory permissions:  non-writable directories will
 *    be initially created with write permission enabled; when the
 *    archive is closed, dir permissions are edited to the values specified
 *    in the archive.
 *  - Checks hardlinks:  hardlinks will not be extracted unless the
 *    linked-to file was also extracted within the same session. (TODO)
 */

/* The "flags" argument selects optional behavior, 'OR' the flags you want. */

/* Default: Do not try to set owner/group. */
#define	ARCHIVE_EXTRACT_OWNER			(0x0001)
/* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */
#define	ARCHIVE_EXTRACT_PERM			(0x0002)
/* Default: Do not restore mtime/atime. */
#define	ARCHIVE_EXTRACT_TIME			(0x0004)
/* Default: Replace existing files. */
#define	ARCHIVE_EXTRACT_NO_OVERWRITE 		(0x0008)
/* Default: Try create first, unlink only if create fails with EEXIST. */
#define	ARCHIVE_EXTRACT_UNLINK			(0x0010)
/* Default: Do not restore ACLs. */
#define	ARCHIVE_EXTRACT_ACL			(0x0020)
/* Default: Do not restore fflags. */
#define	ARCHIVE_EXTRACT_FFLAGS			(0x0040)
/* Default: Do not restore xattrs. */
#define	ARCHIVE_EXTRACT_XATTR 			(0x0080)
/* Default: Do not try to guard against extracts redirected by symlinks. */
/* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */
#define	ARCHIVE_EXTRACT_SECURE_SYMLINKS		(0x0100)
/* Default: Do not reject entries with '..' as path elements. */
#define	ARCHIVE_EXTRACT_SECURE_NODOTDOT		(0x0200)
/* Default: Create parent directories as needed. */
#define	ARCHIVE_EXTRACT_NO_AUTODIR		(0x0400)
/* Default: Overwrite files, even if one on disk is newer. */
#define	ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER	(0x0800)
/* Detect blocks of 0 and write holes instead. */
#define	ARCHIVE_EXTRACT_SPARSE			(0x1000)

__LA_DECL int	 archive_read_extract(struct archive *, struct archive_entry *,
		     int flags);
__LA_DECL int	 archive_read_extract2(struct archive *, struct archive_entry *,
		     struct archive * /* dest */);
__LA_DECL void	 archive_read_extract_set_progress_callback(struct archive *,
		     void (*_progress_func)(void *), void *_user_data);

/* Record the dev/ino of a file that will not be written.  This is
 * generally set to the dev/ino of the archive being read. */
__LA_DECL void		archive_read_extract_set_skip_file(struct archive *,
		     dev_t, ino_t);

/* Close the file and release most resources. */
__LA_DECL int		 archive_read_close(struct archive *);
/* Release all resources and destroy the object. */
/* Note that archive_read_free will call archive_read_close for you. */
__LA_DECL int		 archive_read_free(struct archive *);
#if ARCHIVE_VERSION_NUMBER < 4000000
/* Synonym for archive_read_free() for backwards compatibility. */
__LA_DECL int		 archive_read_finish(struct archive *);
#endif

/*-
 * To create an archive:
 *   1) Ask archive_write_new for a archive writer object.
 *   2) Set any global properties.  In particular, you should set
 *      the compression and format to use.
 *   3) Call archive_write_open to open the file (most people
 *       will use archive_write_open_file or archive_write_open_fd,
 *       which provide convenient canned I/O callbacks for you).
 *   4) For each entry:
 *      - construct an appropriate struct archive_entry structure
 *      - archive_write_header to write the header
 *      - archive_write_data to write the entry data
 *   5) archive_write_close to close the output
 *   6) archive_write_free to cleanup the writer and release resources
 */
__LA_DECL struct archive	*archive_write_new(void);
__LA_DECL int		 archive_write_set_bytes_per_block(struct archive *,
		     int bytes_per_block);
__LA_DECL int		 archive_write_get_bytes_per_block(struct archive *);
/* XXX This is badly misnamed; suggestions appreciated. XXX */
__LA_DECL int		 archive_write_set_bytes_in_last_block(struct archive *,
		     int bytes_in_last_block);
__LA_DECL int		 archive_write_get_bytes_in_last_block(struct archive *);

/* The dev/ino of a file that won't be archived.  This is used
 * to avoid recursively adding an archive to itself. */
__LA_DECL int		 archive_write_set_skip_file(struct archive *, dev_t, ino_t);

__LA_DECL int		 archive_write_set_compression_bzip2(struct archive *);
__LA_DECL int		 archive_write_set_compression_compress(struct archive *);
__LA_DECL int		 archive_write_set_compression_gzip(struct archive *);
__LA_DECL int		 archive_write_set_compression_lzma(struct archive *);
__LA_DECL int		 archive_write_set_compression_none(struct archive *);
__LA_DECL int		 archive_write_set_compression_program(struct archive *,
		     const char *cmd);
__LA_DECL int		 archive_write_set_compression_xz(struct archive *);
/* A convenience function to set the format based on the code or name. */
__LA_DECL int		 archive_write_set_format(struct archive *, int format_code);
__LA_DECL int		 archive_write_set_format_by_name(struct archive *,
		     const char *name);
/* To minimize link pollution, use one or more of the following. */
__LA_DECL int		 archive_write_set_format_ar_bsd(struct archive *);
__LA_DECL int		 archive_write_set_format_ar_svr4(struct archive *);
__LA_DECL int		 archive_write_set_format_cpio(struct archive *);
__LA_DECL int		 archive_write_set_format_cpio_newc(struct archive *);
__LA_DECL int		 archive_write_set_format_mtree(struct archive *);
/* TODO: int archive_write_set_format_old_tar(struct archive *); */
__LA_DECL int		 archive_write_set_format_pax(struct archive *);
__LA_DECL int		 archive_write_set_format_pax_restricted(struct archive *);
__LA_DECL int		 archive_write_set_format_shar(struct archive *);
__LA_DECL int		 archive_write_set_format_shar_dump(struct archive *);
__LA_DECL int		 archive_write_set_format_ustar(struct archive *);
__LA_DECL int		 archive_write_set_format_zip(struct archive *);
__LA_DECL int		 archive_write_open(struct archive *, void *,
		     archive_open_callback *, archive_write_callback *,
		     archive_close_callback *);
__LA_DECL int		 archive_write_open_fd(struct archive *, int _fd);
__LA_DECL int		 archive_write_open_filename(struct archive *, const char *_file);
/* A deprecated synonym for archive_write_open_filename() */
__LA_DECL int		 archive_write_open_file(struct archive *, const char *_file);
__LA_DECL int		 archive_write_open_FILE(struct archive *, FILE *);
/* _buffSize is the size of the buffer, _used refers to a variable that
 * will be updated after each write into the buffer. */
__LA_DECL int		 archive_write_open_memory(struct archive *,
			void *_buffer, size_t _buffSize, size_t *_used);

/*
 * Note that the library will truncate writes beyond the size provided
 * to archive_write_header or pad if the provided data is short.
 */
__LA_DECL int		 archive_write_header(struct archive *,
		     struct archive_entry *);
#if ARCHIVE_VERSION_NUMBER < 2000000
/* This was erroneously declared to return "int" in libarchive 1.x. */
__LA_DECL int		 archive_write_data(struct archive *,
			    const void *, size_t);
#else
/* Libarchive 2.0 and later return ssize_t here. */
__LA_DECL __LA_SSIZE_T	 archive_write_data(struct archive *,
			    const void *, size_t);
#endif

#if ARCHIVE_VERSION_NUMBER < 3000000
/* Libarchive 1.x and 2.x use off_t for the argument, but that's not
 * stable on Linux. */
__LA_DECL __LA_SSIZE_T	 archive_write_data_block(struct archive *,
				    const void *, size_t, off_t);
#else
/* Libarchive 3.0 uses explicit int64_t to ensure consistent 64-bit support. */
__LA_DECL __LA_SSIZE_T	 archive_write_data_block(struct archive *,
				    const void *, size_t, __LA_INT64_T);
#endif
__LA_DECL int		 archive_write_finish_entry(struct archive *);
__LA_DECL int		 archive_write_close(struct archive *);

/* This can fail if the archive wasn't already closed, in which case
 * archive_write_free() will implicitly call archive_write_close(). */
__LA_DECL int		 archive_write_free(struct archive *);
#if ARCHIVE_VERSION_NUMBER < 4000000
/* Synonym for archive_write_free() for backwards compatibility. */
__LA_DECL int		 archive_write_finish(struct archive *);
#endif

/*
 * Set write options.
 */
/* Apply option string to the format only. */
__LA_DECL int		archive_write_set_format_options(struct archive *_a,
			    const char *s);
/* Apply option string to the compressor only. */
__LA_DECL int		archive_write_set_compressor_options(struct archive *_a,
			    const char *s);
/* Apply option string to both the format and the compressor. */
__LA_DECL int		archive_write_set_options(struct archive *_a,
			    const char *s);

/*-
 * ARCHIVE_WRITE_DISK API
 *
 * To create objects on disk:
 *   1) Ask archive_write_disk_new for a new archive_write_disk object.
 *   2) Set any global properties.  In particular, you probably
 *      want to set the options.
 *   3) For each entry:
 *      - construct an appropriate struct archive_entry structure
 *      - archive_write_header to create the file/dir/etc on disk
 *      - archive_write_data to write the entry data
 *   4) archive_write_free to cleanup the writer and release resources
 *
 * In particular, you can use this in conjunction with archive_read()
 * to pull entries out of an archive and create them on disk.
 */
__LA_DECL struct archive	*archive_write_disk_new(void);
/* This file will not be overwritten. */
__LA_DECL int		 archive_write_disk_set_skip_file(struct archive *,
		     dev_t, ino_t);
/* Set flags to control how the next item gets created.
 * This accepts a bitmask of ARCHIVE_EXTRACT_XXX flags defined above. */
__LA_DECL int		 archive_write_disk_set_options(struct archive *,
		     int flags);
/*
 * The lookup functions are given uname/uid (or gname/gid) pairs and
 * return a uid (gid) suitable for this system.  These are used for
 * restoring ownership and for setting ACLs.  The default functions
 * are naive, they just return the uid/gid.  These are small, so reasonable
 * for applications that don't need to preserve ownership; they
 * are probably also appropriate for applications that are doing
 * same-system backup and restore.
 */
/*
 * The "standard" lookup functions use common system calls to lookup
 * the uname/gname, falling back to the uid/gid if the names can't be
 * found.  They cache lookups and are reasonably fast, but can be very
 * large, so they are not used unless you ask for them.  In
 * particular, these match the specifications of POSIX "pax" and old
 * POSIX "tar".
 */
__LA_DECL int	 archive_write_disk_set_standard_lookup(struct archive *);
/*
 * If neither the default (naive) nor the standard (big) functions suit
 * your needs, you can write your own and register them.  Be sure to
 * include a cleanup function if you have allocated private data.
 */
__LA_DECL int	 archive_write_disk_set_group_lookup(struct archive *,
			    void * /* private_data */,
			    __LA_GID_T (*)(void *, const char *, __LA_GID_T),
			    void (* /* cleanup */)(void *));
__LA_DECL int	 archive_write_disk_set_user_lookup(struct archive *,
			    void * /* private_data */,
			    __LA_UID_T (*)(void *, const char *, __LA_UID_T),
			    void (* /* cleanup */)(void *));

/*
 * ARCHIVE_READ_DISK API
 *
 * This is still evolving and somewhat experimental.
 */
__LA_DECL struct archive *archive_read_disk_new(void);
/* The names for symlink modes here correspond to an old BSD
 * command-line argument convention: -L, -P, -H */
/* Follow all symlinks. */
__LA_DECL int archive_read_disk_set_symlink_logical(struct archive *);
/* Follow no symlinks. */
__LA_DECL int archive_read_disk_set_symlink_physical(struct archive *);
/* Follow symlink initially, then not. */
__LA_DECL int archive_read_disk_set_symlink_hybrid(struct archive *);
/* TODO: Handle Linux stat32/stat64 ugliness. <sigh> */
__LA_DECL int archive_read_disk_entry_from_file(struct archive *,
    struct archive_entry *, int /* fd */, const struct stat *);
/* Look up gname for gid or uname for uid. */
/* Default implementations are very, very stupid. */
__LA_DECL const char *archive_read_disk_gname(struct archive *, __LA_GID_T);
__LA_DECL const char *archive_read_disk_uname(struct archive *, __LA_UID_T);
/* "Standard" implementation uses getpwuid_r, getgrgid_r and caches the
 * results for performance. */
__LA_DECL int	archive_read_disk_set_standard_lookup(struct archive *);
/* You can install your own lookups if you like. */
__LA_DECL int	archive_read_disk_set_gname_lookup(struct archive *,
    void * /* private_data */,
    const char *(* /* lookup_fn */)(void *, __LA_GID_T),
    void (* /* cleanup_fn */)(void *));
__LA_DECL int	archive_read_disk_set_uname_lookup(struct archive *,
    void * /* private_data */,
    const char *(* /* lookup_fn */)(void *, __LA_UID_T),
    void (* /* cleanup_fn */)(void *));

/*
 * Accessor functions to read/set various information in
 * the struct archive object:
 */
/* Bytes written after compression or read before decompression. */
__LA_DECL __LA_INT64_T	 archive_position_compressed(struct archive *);
/* Bytes written to compressor or read from decompressor. */
__LA_DECL __LA_INT64_T	 archive_position_uncompressed(struct archive *);

__LA_DECL const char	*archive_compression_name(struct archive *);
__LA_DECL int		 archive_compression(struct archive *);
__LA_DECL int		 archive_errno(struct archive *);
__LA_DECL const char	*archive_error_string(struct archive *);
__LA_DECL const char	*archive_format_name(struct archive *);
__LA_DECL int		 archive_format(struct archive *);
__LA_DECL void		 archive_clear_error(struct archive *);
__LA_DECL void		 archive_set_error(struct archive *, int _err,
			    const char *fmt, ...);
__LA_DECL void		 archive_copy_error(struct archive *dest,
			    struct archive *src);
__LA_DECL int		 archive_file_count(struct archive *);

#ifdef __cplusplus
}
#endif

/* These are meaningless outside of this header. */
#undef __LA_DECL
#undef __LA_GID_T
#undef __LA_UID_T

/* These need to remain defined because they're used in the
 * callback type definitions.  XXX Fix this.  This is ugly. XXX */
/* #undef __LA_INT64_T */
/* #undef __LA_SSIZE_T */

#endif /* !ARCHIVE_H_INCLUDED */