code:
/*-
 * Copyright (c) 2010-2011 Alexander V. Chernikov <melifaro@ipfw.ru>
 * Copyright (c) 2004 Gleb Smirnoff <glebius@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	 $SourceForge: netflow.h,v 1.8 2004/09/16 17:05:11 glebius Exp $
 *	 $FreeBSD: release/9.0.0/sys/netgraph/netflow/netflow.h 219182 2011-03-02 16:15:11Z glebius $
 */

/* netflow timeouts in seconds */

#define	ACTIVE_TIMEOUT		(30*60)	/* maximum flow lifetime is 30 min */
#define	INACTIVE_TIMEOUT	15

/*
 * More info can be found in these Cisco documents:
 *
 * Cisco IOS NetFlow, White Papers.
 * http://www.cisco.com/en/US/products/ps6601/prod_white_papers_list.html
 *
 * Cisco CNS NetFlow Collection Engine User Guide, 5.0.2, NetFlow Export
 * Datagram Formats.
 * http://www.cisco.com/en/US/products/sw/netmgtsw/ps1964/products_user_guide_chapter09186a00803f3147.html#wp26453
 *
 * Cisco Systems NetFlow Services Export Version 9
 * http://www.ietf.org/rfc/rfc3954.txt
 *
 */

#define NETFLOW_V1 1
#define NETFLOW_V5 5
#define NETFLOW_V9 9

struct netflow_v1_header
{
  uint16_t version;	/* NetFlow version */
  uint16_t count;	/* Number of records in flow */
  uint32_t sys_uptime;	/* System uptime */
  uint32_t unix_secs;	/* Current seconds since 0000 UTC 1970 */
  uint32_t unix_nsecs;	/* Remaining nanoseconds since 0000 UTC 1970 */
} __attribute__((__packed__));

struct netflow_v5_header
{
  uint16_t version;	/* NetFlow version */
  uint16_t count;	/* Number of records in flow */
  uint32_t sys_uptime;	/* System uptime */
  uint32_t unix_secs;	/* Current seconds since 0000 UTC 1970 */
  uint32_t unix_nsecs;	/* Remaining nanoseconds since 0000 UTC 1970 */
  uint32_t flow_seq;	/* Sequence number of the first record */
  uint8_t engine_type;	/* Type of flow switching engine (RP,VIP,etc.) */
  uint8_t engine_id;	/* Slot number of the flow switching engine */
  uint16_t pad;		/* Pad to word boundary */
} __attribute__((__packed__));

struct netflow_v9_header
{
  uint16_t version;	/* NetFlow version */
  uint16_t count;	/* Total number of records in packet */
  uint32_t sys_uptime;	/* System uptime */
  uint32_t unix_secs;	/* Current seconds since 0000 UTC 1970 */
  uint32_t seq_num;	/* Sequence number */
  uint32_t source_id;	/* Observation Domain id */
} __attribute__((__packed__));

struct netflow_v1_record
{
  uint32_t src_addr;	/* Source IP address */
  uint32_t dst_addr;	/* Destination IP address */
  uint32_t next_hop;	/* Next hop IP address */
  uint16_t in_ifx;	/* Source interface index */
  uint16_t out_ifx;	/* Destination interface index */
  uint32_t packets;	/* Number of packets in a flow */
  uint32_t octets;	/* Number of octets in a flow */
  uint32_t first;	/* System uptime at start of a flow */
  uint32_t last;	/* System uptime at end of a flow */
  uint16_t s_port;	/* Source port */
  uint16_t d_port;	/* Destination port */
  uint16_t pad1;	/* Pad to word boundary */
  uint8_t prot;		/* IP protocol */
  uint8_t tos;		/* IP type of service */
  uint8_t flags;	/* Cumulative OR of tcp flags */
  uint8_t pad2;		/* Pad to word boundary */
  uint16_t pad3;	/* Pad to word boundary */
  uint8_t reserved[5];	/* Reserved for future use */
} __attribute__((__packed__));

struct netflow_v5_record
{
  uint32_t src_addr;	/* Source IP address */
  uint32_t dst_addr;	/* Destination IP address */
  uint32_t next_hop;	/* Next hop IP address */
  uint16_t i_ifx;	/* Source interface index */
  uint16_t o_ifx;	/* Destination interface index */
  uint32_t packets;	/* Number of packets in a flow */
  uint32_t octets;	/* Number of octets in a flow */
  uint32_t first;	/* System uptime at start of a flow */
  uint32_t last;	/* System uptime at end of a flow */
  uint16_t s_port;	/* Source port */
  uint16_t d_port;	/* Destination port */
  uint8_t pad1;		/* Pad to word boundary */
  uint8_t flags;	/* Cumulative OR of tcp flags */
  uint8_t prot;		/* IP protocol */
  uint8_t tos;		/* IP type of service */
  uint16_t src_as;	/* Src peer/origin Autonomous System */
  uint16_t dst_as;	/* Dst peer/origin Autonomous System */
  uint8_t src_mask;	/* Source route's mask bits */
  uint8_t dst_mask;	/* Destination route's mask bits */
  uint16_t pad2;	/* Pad to word boundary */
} __attribute__((__packed__));

#define NETFLOW_V1_MAX_RECORDS 24
#define NETFLOW_V5_MAX_RECORDS 30

#define NETFLOW_V1_MAX_SIZE (sizeof(netflow_v1_header)+ \
			     sizeof(netflow_v1_record)*NETFLOW_V1_MAX_RECORDS)
#define NETFLOW_V5_MAX_SIZE (sizeof(netflow_v5_header)+ \
			     sizeof(netflow_v5_record)*NETFLOW_V5_MAX_RECORDS)

struct netflow_v5_export_dgram {
	struct netflow_v5_header	header;
	struct netflow_v5_record	r[NETFLOW_V5_MAX_RECORDS];
} __attribute__((__packed__));

/* RFC3954 field definitions */
#define NETFLOW_V9_FIELD_IN_BYTES		1	/* Input bytes count for a flow. Default 4, can be 8 */
#define NETFLOW_V9_FIELD_IN_PKTS		2	/* Incoming counter with number of packets associated with an IP Flow. Default 4 */
#define NETFLOW_V9_FIELD_FLOWS			3	/* Number of Flows that were aggregated. Default 4 */
#define NETFLOW_V9_FIELD_PROTOCOL		4	/* IP protocol byte. 1 */
#define NETFLOW_V9_FIELD_TOS			5	/* Type of service byte setting when entering the incoming interface. 1 */
#define NETFLOW_V9_FIELD_TCP_FLAGS		6	/* TCP flags; cumulative of all the TCP flags seen in this Flow. 1 */
#define NETFLOW_V9_FIELD_L4_SRC_PORT		7	/* TCP/UDP source port number. 2 */
#define NETFLOW_V9_FIELD_IPV4_SRC_ADDR		8	/* IPv4 source address. 4 */
#define NETFLOW_V9_FIELD_SRC_MASK		9	/* The number of contiguous bits in the source subnet mask (i.e., the mask in slash notation). 1 */
#define NETFLOW_V9_FIELD_INPUT_SNMP		10	/* Input interface index. Default 2 */
#define NETFLOW_V9_FIELD_L4_DST_PORT		11	/* TCP/UDP destination port number. 2 */
#define NETFLOW_V9_FIELD_IPV4_DST_ADDR		12	/* IPv4 destination address. 4 */
#define NETFLOW_V9_FIELD_DST_MASK		13	/* The number of contiguous bits in the destination subnet mask (i.e., the mask in slash notation). 1 */
#define NETFLOW_V9_FIELD_OUTPUT_SNMP		14	/* Output interface index. Default 2 */
#define NETFLOW_V9_FIELD_IPV4_NEXT_HOP		15	/* IPv4 address of the next-hop router. 4 */
#define NETFLOW_V9_FIELD_SRC_AS			16	/* Source BGP autonomous system number. Default 2, can be 4 */
#define NETFLOW_V9_FIELD_DST_AS			17	/* Destination BGP autonomous system number. Default 2, can be 4 */
#define NETFLOW_V9_FIELD_BGP_IPV4_NEXT_HOP	18	/* Next-hop router's IP address in the BGP domain. 4 */
#define NETFLOW_V9_FIELD_MUL_DST_PKTS		19	/* IP multicast outgoing packet counter for packets associated with IP flow. Default 4 */
#define NETFLOW_V9_FIELD_MUL_DST_BYTES		20	/* IP multicast outgoing Octet (byte) counter for the number of bytes associated with IP flow. Default 4 */
#define NETFLOW_V9_FIELD_LAST_SWITCHED		21	/* sysUptime in msec at which the last packet of this Flow was switched. 4 */
#define NETFLOW_V9_FIELD_FIRST_SWITCHED		22	/* sysUptime in msec at which the first packet of this Flow was switched. 4 */
#define NETFLOW_V9_FIELD_OUT_BYTES		23	/* Outgoing counter for the number of bytes associated with an IP Flow. Default 4 */
#define NETFLOW_V9_FIELD_OUT_PKTS		24	/* Outgoing counter for the number of packets associated with an IP Flow. Default 4 */
#define NETFLOW_V9_FIELD_IPV6_SRC_ADDR		27	/* IPv6 source address. 16 */
#define NETFLOW_V9_FIELD_IPV6_DST_ADDR		28	/* IPv6 destination address. 16 */
#define NETFLOW_V9_FIELD_IPV6_SRC_MASK		29	/* Length of the IPv6 source mask in contiguous bits. 1 */
#define NETFLOW_V9_FIELD_IPV6_DST_MASK		30	/* Length of the IPv6 destination mask in contiguous bits. 1 */
#define NETFLOW_V9_FIELD_IPV6_FLOW_LABEL	31	/* IPv6 flow label as per RFC 2460 definition. 3 */
#define NETFLOW_V9_FIELD_ICMP_TYPE		32	/* Internet Control Message Protocol (ICMP) packet type; reported as ICMP Type * 256 + ICMP code. 2 */
#define NETFLOW_V9_FIELD_MUL_IGMP_TYPE		33	/* Internet Group Management Protocol (IGMP) packet type. 1 */
#define NETFLOW_V9_FIELD_SAMPLING_INTERVAL	34	/* When using sampled NetFlow, the rate at which packets are sampled; for example, a value of 100 indicates that one of every hundred packets is sampled. 4 */
#define NETFLOW_V9_FIELD_SAMPLING_ALGORITHM	35	/* For sampled NetFlow platform-wide: 0x01 deterministic sampling 0x02 random sampling. 1 */
#define NETFLOW_V9_FIELD_FLOW_ACTIVE_TIMEOUT	36	/* Timeout value (in seconds) for active flow entries in the NetFlow cache. 2 */
#define NETFLOW_V9_FIELD_FLOW_INACTIVE_TIMEOUT	37	/* Timeout value (in seconds) for inactive Flow entries in the NetFlow cache. 2 */
#define NETFLOW_V9_FIELD_ENGINE_TYPE		38	/* Type of Flow switching engine (route processor, linecard, etc...). 1 */
#define NETFLOW_V9_FIELD_ENGINE_ID		39	/* ID number of the Flow switching engine. 1 */
#define NETFLOW_V9_FIELD_TOTAL_BYTES_EXP	40	/* Counter with for the number of bytes exported by the Observation Domain. Default 4 */
#define NETFLOW_V9_FIELD_TOTAL_PKTS_EXP		41	/* Counter with for the number of packets exported by the Observation Domain. Default 4 */
#define NETFLOW_V9_FIELD_TOTAL_FLOWS_EXP	42	/* Counter with for the number of flows exported by the Observation Domain. Default 4 */
#define NETFLOW_V9_FIELD_MPLS_TOP_LABEL_TYPE	46	/* MPLS Top Label Type. 1 */
#define NETFLOW_V9_FIELD_MPLS_TOP_LABEL_IP_ADDR	47	/* Forwarding Equivalent Class corresponding to the MPLS Top Label. 4 */
#define NETFLOW_V9_FIELD_FLOW_SAMPLER_ID	48	/* Identifier shown in "show flow-sampler". 1 */
#define NETFLOW_V9_FIELD_FLOW_SAMPLER_MODE	49	/* The type of algorithm used for sampling data. 2 */
#define NETFLOW_V9_FIELD_FLOW_SAMPLER_RANDOM_INTERVAL		50	/* Packet interval at which to sample. 4. */
#define NETFLOW_V9_FIELD_DST_TOS		55	/* Type of Service byte setting when exiting outgoing interface. 1. */
#define NETFLOW_V9_FIELD_SRC_MAC		56	/* Source MAC Address. 6 */
#define NETFLOW_V9_FIELD_DST_MAC		57	/* Destination MAC Address. 6 */
#define NETFLOW_V9_FIELD_SRC_VLAN		58	/* Virtual LAN identifier associated with ingress interface. 2 */
#define NETFLOW_V9_FIELD_DST_VLAN		59	/* Virtual LAN identifier associated with egress interface. 2 */
#define NETFLOW_V9_FIELD_IP_PROTOCOL_VERSION	60	/* Internet Protocol Version. Set to 4 for IPv4, set to 6 for IPv6. If not present in the template, then version 4 is assumed. 1. */
#define NETFLOW_V9_FIELD_DIRECTION		61	/* Flow direction: 0 - ingress flow 1 - egress flow. 1 */
#define NETFLOW_V9_FIELD_IPV6_NEXT_HOP		62	/* IPv6 address of the next-hop router. 16 */
#define NETFLOW_V9_FIELD_BGP_IPV6_NEXT_HOP	63	/* Next-hop router in the BGP domain. 16 */
#define NETFLOW_V9_FIELD_IPV6_OPTION_HEADERS	64	/* Bit-encoded field identifying IPv6 option headers found in the flow */
#define NETFLOW_V9_FIELD_MPLS_LABEL_1		70	/* MPLS label at position 1 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_2		71	/* MPLS label at position 2 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_3		72	/* MPLS label at position 3 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_4		73	/* MPLS label at position 4 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_5		74	/* MPLS label at position 5 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_6		75	/* MPLS label at position 6 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_7		76	/* MPLS label at position 7 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_8		77	/* MPLS label at position 8 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_9		78	/* MPLS label at position 9 in the stack. 3 */
#define NETFLOW_V9_FIELD_MPLS_LABEL_10		79	/* MPLS label at position 10 in the stack. 3 */

#define NETFLOW_V9_MAX_RESERVED_FLOWSET		0xFF	/* Clause 5.2 */


code:
/*-
 * Copyright (c) 2010 Alexander V. Chernikov <melifaro@ipfw.ru>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	 $FreeBSD: release/9.0.0/sys/netgraph/netflow/netflow_v9.h 219182 2011-03-02 16:15:11Z glebius $
 */

#ifndef	_NETFLOW_V9_H_
#define	_NETFLOW_V9_H_

#ifdef COUNTERS_64
#define CNTR		uint64_t
#define CNTR_MAX	UINT64_MAX
#else
#define CNTR		uint32_t
#define CNTR_MAX	UINT_MAX
#endif

struct netflow_v9_template
{
	int	field_id;
	int	field_length;
};

/* Template ID for tcp/udp v4 streams ID:257 (0x100 + NETFLOW_V9_FLOW_V4_L4) */
struct netflow_v9_record_ipv4_tcp
{
	uint32_t	src_addr;	/* Source IPv4 address (IPV4_SRC_ADDR) */
	uint32_t	dst_addr;	/* Destination IPv4 address (IPV4_DST_ADDR) */
	uint32_t	next_hop;	/* Next hop IPv4 address (IPV4_NEXT_HOP) */
	uint16_t	i_ifx;	/* Source interface index (INPUT_SNMP) */
	uint16_t	o_ifx;	/* Destination interface index (OUTPUT_SNMP) */
	CNTR		i_packets;	/* Number of incoming packets in a flow (IN_PKTS) */
	CNTR		i_octets;	/* Number of incoming octets in a flow (IN_BYTES) */
	CNTR		o_packets;	/* Number of outgoing packets in a flow (OUT_PKTS) */
	CNTR		o_octets;	/* Number of outgoing octets in a flow (OUT_BYTES) */
	uint32_t	first;	/* System uptime at start of a flow (FIRST_SWITCHED) */
	uint32_t	last;	/* System uptime at end of a flow (LAST_SWITCHED) */
	uint16_t	s_port;	/* Source port (L4_SRC_PORT) */
	uint16_t	d_port;	/* Destination port (L4_DST_PORT) */
	uint8_t		flags;	/* Cumulative OR of tcp flags (TCP_FLAGS) */
	uint8_t		prot;		/* IP protocol */
	uint8_t		tos;		/* IP type of service IN (or OUT) (TOS) */
	uint32_t	src_as;	/* Src peer/origin Autonomous System (SRC_AS) */
	uint32_t	dst_as;	/* Dst peer/origin Autonomous System (DST_AS) */
	uint8_t		src_mask;	/* Source route's mask bits (SRC_MASK) */
	uint8_t		dst_mask; 	/* Destination route's mask bits (DST_MASK) */
} __attribute__((__packed__));

/* Template ID for tcp/udp v6 streams ID: 260 (0x100 + NETFLOW_V9_FLOW_V6_L4) */
struct netflow_v9_record_ipv6_tcp
{
	struct in6_addr	src_addr;	/* Source IPv6 address (IPV6_SRC_ADDR) */
	struct in6_addr	dst_addr;	/* Destination IPv6 address (IPV6_DST_ADDR) */
	struct in6_addr	next_hop;	/* Next hop IPv6 address (IPV6_NEXT_HOP) */
	uint16_t	i_ifx;	/* Source interface index (INPUT_SNMP) */
	uint16_t	o_ifx;	/* Destination interface index (OUTPUT_SNMP) */
	CNTR		i_packets;	/* Number of incoming packets in a flow (IN_PKTS) */
	CNTR		i_octets;	/* Number of incoming octets in a flow (IN_BYTES) */
	CNTR		o_packets;	/* Number of outgoing packets in a flow (OUT_PKTS) */
	CNTR		o_octets;	/* Number of outgoing octets in a flow (OUT_BYTES) */
	uint32_t	first;	/* System uptime at start of a flow (FIRST_SWITCHED) */
	uint32_t	last;	/* System uptime at end of a flow (LAST_SWITCHED) */
	uint16_t	s_port;	/* Source port (L4_SRC_PORT) */
	uint16_t	d_port;	/* Destination port (L4_DST_PORT) */
	uint8_t		flags;	/* Cumulative OR of tcp flags (TCP_FLAGS) */
	uint8_t		prot;		/* IP protocol */
	uint8_t		tos;		/* IP type of service IN (or OUT) (TOS) */
	uint32_t	src_as;	/* Src peer/origin Autonomous System (SRC_AS) */
	uint32_t	dst_as;	/* Dst peer/origin Autonomous System (DST_AS) */
	uint8_t		src_mask;	/* Source route's mask bits (SRC_MASK) */
	uint8_t		dst_mask; 	/* Destination route's mask bits (DST_MASK) */
} __attribute__((__packed__));

/* Used in export9_add to determine max record size */
struct netflow_v9_record_general
{
	union {
		struct netflow_v9_record_ipv4_tcp v4_tcp;
		struct netflow_v9_record_ipv6_tcp v6_tcp;
	} rec;
};

#define BASE_MTU	1500
#define MIN_MTU		sizeof(struct netflow_v5_header)
#define MAX_MTU		16384
#define NETFLOW_V9_MAX_SIZE	_NETFLOW_V9_MAX_SIZE(BASE_MTU)
/* Decrease MSS by 16 since there can be some IPv[46] header options */
#define _NETFLOW_V9_MAX_SIZE(x)	(x) - sizeof(struct ip6_hdr) - sizeof(struct udphdr) - 16

/* #define NETFLOW_V9_MAX_FLOWSETS	2 */

#define NETFLOW_V9_MAX_RECORD_SIZE	sizeof(struct netflow_v9_record_ipv6_tcp)
#define NETFLOW_V9_MAX_PACKETS_TEMPL	500	/* Send data templates every ... packets */
#define NETFLOW_V9_MAX_TIME_TEMPL	600	/* Send data templates every ... seconds */
#define NETFLOW_V9_MAX_TEMPLATES	16	/* Not a real value */
#define _NETFLOW_V9_TEMPLATE_SIZE(x)	(sizeof(x) / sizeof(struct netflow_v9_template)) * 4
//#define _NETFLOW_V9_TEMPLATE_SIZE(x)	((x) + 1) * 4

/* Flow Templates */
#define NETFLOW_V9_FLOW_V4_L4	1 /* IPv4 TCP/UDP packet */
#define NETFLOW_V9_FLOW_V4_ICMP	2 /* IPv4 ICMP packet, currently unused */
#define NETFLOW_V9_FLOW_V4_L3	3 /* IPv4 IP packet */
#define NETFLOW_V9_FLOW_V6_L4	4 /* IPv6 TCP/UDP packet */
#define NETFLOW_V9_FLOW_V6_ICMP	5 /* IPv6 ICMP packet, currently unused */
#define NETFLOW_V9_FLOW_V6_L3	6 /* IPv6 IP packet */

#define NETFLOW_V9_FLOW_FAKE	65535 /* Not uset used in real flowsets! */

struct netflow_v9_export_dgram {
	struct netflow_v9_header	header;
	char				*data; /* MTU can change, record length is dynamic */
};

struct netflow_v9_flowset_header {
	uint16_t	id; /* FlowSet id */
	uint16_t	length; /* FlowSet length */
} __attribute__((__packed__));

struct netflow_v9_packet_opt {
	uint16_t	length; /* current packet length */
	uint16_t	count; /* current records count */
	uint16_t	mtu; /* max MTU shapshot */
	uint16_t	flow_type; /* current flowset */
	uint16_t	flow_header; /* offset pointing to current flow header */
};
#endif

repo_name: veiledmerc/mira

license: mit


code:
/*-
 * Copyright (c) 2010-2011 Alexander V. Chernikov <melifaro@ipfw.ru>
 * Copyright (c) 2004-2005 Gleb Smirnoff <glebius@FreeBSD.org>
 * Copyright (c) 2001-2003 Roman V. Palagin <romanp@unshadow.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	 $SourceForge: ng_netflow.h,v 1.26 2004/09/04 15:44:55 glebius Exp $
 *	 $FreeBSD: release/9.0.0/sys/netgraph/netflow/ng_netflow.h 223787 2011-07-05 14:48:39Z glebius $
 */

#ifndef	_NG_NETFLOW_H_
#define	_NG_NETFLOW_H_

#define NG_NETFLOW_NODE_TYPE	"netflow"
#define NGM_NETFLOW_COOKIE	1309868867

#define	NG_NETFLOW_MAXIFACES	USHRT_MAX

/* Hook names */

#define	NG_NETFLOW_HOOK_DATA	"iface"
#define	NG_NETFLOW_HOOK_OUT	"out"
#define NG_NETFLOW_HOOK_EXPORT	"export"
#define NG_NETFLOW_HOOK_EXPORT9	"export9"

/* This define effectively disable (v5) netflow export hook! */
/* #define COUNTERS_64 */

/* Netgraph commands understood by netflow node */
enum {
    NGM_NETFLOW_INFO = 1|NGM_READONLY|NGM_HASREPLY,	/* get node info */
    NGM_NETFLOW_IFINFO = 2|NGM_READONLY|NGM_HASREPLY,	/* get iface info */
    NGM_NETFLOW_SHOW = 3|NGM_READONLY|NGM_HASREPLY,	/* show ip cache flow */
    NGM_NETFLOW_SETDLT		= 4,	/* set data-link type */
    NGM_NETFLOW_SETIFINDEX	= 5, 	/* set interface index */
    NGM_NETFLOW_SETTIMEOUTS	= 6, 	/* set active/inactive flow timeouts */
    NGM_NETFLOW_SETCONFIG	= 7, 	/* set flow generation options */
    NGM_NETFLOW_SETTEMPLATE	= 8, 	/* set v9 flow template periodic */
    NGM_NETFLOW_SETMTU		= 9, 	/* set outgoing interface MTU */
};

/* This structure is returned by the NGM_NETFLOW_INFO message */
struct ng_netflow_info {
	uint64_t	nfinfo_bytes;		/* accounted IPv4 bytes */
	uint32_t	nfinfo_packets;		/* accounted IPv4 packets */
	uint64_t	nfinfo_bytes6;		/* accounted IPv6 bytes */
	uint32_t	nfinfo_packets6;	/* accounted IPv6 packets */
	uint64_t	nfinfo_sbytes;		/* skipped IPv4 bytes */
	uint32_t	nfinfo_spackets;	/* skipped IPv4 packets */
	uint64_t	nfinfo_sbytes6;		/* skipped IPv6 bytes */
	uint32_t	nfinfo_spackets6;	/* skipped IPv6 packets */
	uint32_t	nfinfo_used;		/* used cache records */
	uint32_t	nfinfo_used6;		/* used IPv6 cache records */
	uint32_t	nfinfo_alloc_failed;	/* failed allocations */
	uint32_t	nfinfo_export_failed;	/* failed exports */
	uint32_t	nfinfo_export9_failed;	/* failed exports */
	uint32_t	nfinfo_realloc_mbuf;	/* reallocated mbufs */
	uint32_t	nfinfo_alloc_fibs;	/* fibs allocated */
	uint32_t	nfinfo_act_exp;		/* active expiries */
	uint32_t	nfinfo_inact_exp;	/* inactive expiries */
	uint32_t	nfinfo_inact_t;		/* flow inactive timeout */
	uint32_t	nfinfo_act_t;		/* flow active timeout */
};

/* This structure is returned by the NGM_NETFLOW_IFINFO message */
struct ng_netflow_ifinfo {
	uint32_t	ifinfo_packets;	/* number of packets for this iface */
	uint8_t		ifinfo_dlt;	/* Data Link Type, DLT_XXX */
#define	MAXDLTNAMELEN	20
	u_int16_t	ifinfo_index;	/* connected iface index */
	uint32_t	conf;
};

/* This structure is passed to NGM_NETFLOW_SETDLT message */
struct ng_netflow_setdlt {
	uint16_t iface;		/* which iface dlt change */
	uint8_t  dlt;			/* DLT_XXX from bpf.h */
};

/* This structure is passed to NGM_NETFLOW_SETIFINDEX */
struct ng_netflow_setifindex {
	u_int16_t iface;		/* which iface index change */
	u_int16_t index;		/* new index */
};

/* This structure is passed to NGM_NETFLOW_SETTIMEOUTS */
struct ng_netflow_settimeouts {
	uint32_t	inactive_timeout;	/* flow inactive timeout */
	uint32_t	active_timeout;		/* flow active timeout */
};

#define NG_NETFLOW_CONF_INGRESS		1
#define NG_NETFLOW_CONF_EGRESS		2
#define NG_NETFLOW_CONF_ONCE		4
#define NG_NETFLOW_CONF_THISONCE	8

/* This structure is passed to NGM_NETFLOW_SETCONFIG */
struct ng_netflow_setconfig {
	u_int16_t iface;		/* which iface config change */
	u_int32_t conf;			/* new config */
};

/* This structure is passed to NGM_NETFLOW_SETTEMPLATE */
struct ng_netflow_settemplate {
	uint16_t time;		/* max time between announce */
	uint16_t packets;	/* max packets between announce */
};

/* This structure is passed to NGM_NETFLOW_SETMTU */
struct ng_netflow_setmtu {
	uint16_t mtu;		/* MTU for packet */
};

/* This structure is used in NGM_NETFLOW_SHOW request/responce */
struct ngnf_show_header {
	u_char		version;	/* IPv4 or IPv6 */
	uint32_t	hash_id;	/* current hash index */
	uint32_t	list_id;	/* current record number in given hash */
	uint32_t	nentries;	/* number of records in response */
};

/* XXXGL
 * Somewhere flow_rec6 is casted to flow_rec, and flow6_entry_data is
 * casted to flow_entry_data. After casting, fle->r.fib is accessed.
 * So beginning of these structs up to fib should be kept common.
 */

/* This is unique data, which identifies flow */
struct flow_rec {
	uint16_t	flow_type; /* IPv4 L4/L3 flow, see NETFLOW_V9_FLOW* */
	uint16_t	fib;
	struct in_addr	r_src;
	struct in_addr	r_dst;
	union {
		struct {
			uint16_t	s_port;	/* source TCP/UDP port */
			uint16_t	d_port; /* destination TCP/UDP port */
		} dir;
		uint32_t both;
	} ports;
	union {
		struct {
			u_char		prot;	/* IP protocol */
			u_char		tos;	/* IP TOS */
			uint16_t	i_ifx;	/* input interface index */
		} i;
		uint32_t all;
	} misc;
};

/* This is unique data, which identifies flow */
struct flow6_rec {
	uint16_t	flow_type; /* IPv4 L4/L3 Ipv6 L4/L3 flow, see NETFLOW_V9_FLOW* */
	uint16_t	fib;
	union {
		struct in_addr	r_src;
		struct in6_addr	r_src6;
	} src;
	union {
		struct in_addr	r_dst;
		struct in6_addr	r_dst6;
	} dst;
	union {
		struct {
			uint16_t	s_port;	/* source TCP/UDP port */
			uint16_t	d_port; /* destination TCP/UDP port */
		} dir;
		uint32_t both;
	} ports;
	union {
		struct {
			u_char		prot;	/* IP protocol */
			u_char		tos;	/* IP TOS */
			uint16_t	i_ifx;	/* input interface index */
		} i;
		uint32_t all;
	} misc;
};

#define	r_ip_p	misc.i.prot
#define	r_tos	misc.i.tos
#define	r_i_ifx	misc.i.i_ifx
#define r_misc	misc.all
#define r_ports	ports.both
#define r_sport	ports.dir.s_port
#define r_dport	ports.dir.d_port

/* A flow entry which accumulates statistics */
struct flow_entry_data {
	uint16_t		version;	/* Protocol version */
	struct flow_rec		r;
	struct in_addr		next_hop;
	uint16_t		fle_o_ifx;	/* output interface index */
#define				fle_i_ifx	r.misc.i.i_ifx
	uint8_t		dst_mask;	/* destination route mask bits */
	uint8_t		src_mask;	/* source route mask bits */
	u_long			packets;
	u_long			bytes;
	long			first;	/* uptime on first packet */
	long			last;	/* uptime on last packet */
	u_char			tcp_flags;	/* cumulative OR */
};

struct flow6_entry_data {
	uint16_t		version;	/* Protocol version */
	struct flow6_rec	r;
	union {
		struct in_addr		next_hop;
		struct in6_addr		next_hop6;
	} n;
	uint16_t		fle_o_ifx;	/* output interface index */
#define				fle_i_ifx	r.misc.i.i_ifx
	uint8_t		dst_mask;	/* destination route mask bits */
	uint8_t		src_mask;	/* source route mask bits */
	u_long			packets;
	u_long			bytes;
	long			first;	/* uptime on first packet */
	long			last;	/* uptime on last packet */
	u_char			tcp_flags;	/* cumulative OR */
};

/*
 * How many flow records we will transfer at once
 * without overflowing socket receive buffer
 */
#define NREC_AT_ONCE		1000
#define NREC6_AT_ONCE		(NREC_AT_ONCE * sizeof(struct flow_entry_data) / \
				sizeof(struct flow6_entry_data))
#define NGRESP_SIZE		(sizeof(struct ngnf_show_header) + (NREC_AT_ONCE * \
				sizeof(struct flow_entry_data)))
#define SORCVBUF_SIZE		(NGRESP_SIZE + 2 * sizeof(struct ng_mesg))

/* Everything below is for kernel */

#ifdef _KERNEL

struct flow_entry {
	TAILQ_ENTRY(flow_entry)	fle_hash;	/* entries in hash slot */
	struct flow_entry_data	f;
};

struct flow6_entry {
	TAILQ_ENTRY(flow_entry)	fle_hash;	/* entries in hash slot */
	struct flow6_entry_data	f;
};
/* Parsing declarations */

/* Parse the info structure */
#define	NG_NETFLOW_INFO_TYPE	{			\
	{ "IPv4 bytes",		&ng_parse_uint64_type },	\
	{ "IPv4 packets",	&ng_parse_uint32_type },	\
	{ "IPv6 bytes",		&ng_parse_uint64_type },	\
	{ "IPv6 packets",	&ng_parse_uint32_type },	\
	{ "IPv4 skipped bytes",		&ng_parse_uint64_type },	\
	{ "IPv4 skipped packets",	&ng_parse_uint32_type },	\
	{ "IPv6 skipped bytes",		&ng_parse_uint64_type },	\
	{ "IPv6 skipped packets",	&ng_parse_uint32_type },	\
	{ "IPv4 records used",	&ng_parse_uint32_type },\
	{ "IPv6 records used",	&ng_parse_uint32_type },\
	{ "Failed allocations",	&ng_parse_uint32_type },\
	{ "V5 failed exports",	&ng_parse_uint32_type },\
	{ "V9 failed exports",	&ng_parse_uint32_type },\
	{ "mbuf reallocations",	&ng_parse_uint32_type },\
	{ "fibs allocated",	&ng_parse_uint32_type },\
	{ "Active expiries",	&ng_parse_uint32_type },\
	{ "Inactive expiries",	&ng_parse_uint32_type },\
	{ "Inactive timeout",	&ng_parse_uint32_type },\
	{ "Active timeout",	&ng_parse_uint32_type },\
	{ NULL }					\
}

/* Parse the ifinfo structure */
#define NG_NETFLOW_IFINFO_TYPE	{			\
	{ "packets",	&ng_parse_uint32_type },	\
	{ "data link type", &ng_parse_uint8_type },	\
	{ "index", &ng_parse_uint16_type },		\
	{ "conf", &ng_parse_uint32_type },		\
	{ NULL }					\
}

/* Parse the setdlt structure */
#define	NG_NETFLOW_SETDLT_TYPE {			\
	{ "iface",	&ng_parse_uint16_type },	\
	{ "dlt",	&ng_parse_uint8_type  },	\
	{ NULL }					\
}

/* Parse the setifindex structure */
#define	NG_NETFLOW_SETIFINDEX_TYPE {			\
	{ "iface",	&ng_parse_uint16_type },	\
	{ "index",	&ng_parse_uint16_type },	\
	{ NULL }					\
}

/* Parse the settimeouts structure */
#define NG_NETFLOW_SETTIMEOUTS_TYPE {			\
	{ "inactive",	&ng_parse_uint32_type },	\
	{ "active",	&ng_parse_uint32_type },	\
	{ NULL }					\
}

/* Parse the setifindex structure */
#define	NG_NETFLOW_SETCONFIG_TYPE {			\
	{ "iface",	&ng_parse_uint16_type },	\
	{ "conf",	&ng_parse_uint32_type },	\
	{ NULL }					\
}

/* Parse the settemplate structure */
#define	NG_NETFLOW_SETTEMPLATE_TYPE {		\
	{ "time",	&ng_parse_uint16_type },	\
	{ "packets",	&ng_parse_uint16_type },	\
	{ NULL }					\
}

/* Parse the setmtu structure */
#define	NG_NETFLOW_SETMTU_TYPE {			\
	{ "mtu",	&ng_parse_uint16_type },	\
	{ NULL }					\
}

/* Private hook data */
struct ng_netflow_iface {
	hook_p		hook;		/* NULL when disconnected */
	hook_p		out;		/* NULL when no bypass hook */
	struct ng_netflow_ifinfo	info;
};

typedef struct ng_netflow_iface *iface_p;
typedef struct ng_netflow_ifinfo *ifinfo_p;

struct netflow_export_item {
	item_p		item;
	item_p		item9;
	struct netflow_v9_packet_opt	*item9_opt;
};

/* Structure contatining fib-specific data */
struct fib_export {
	uint32_t			fib;		/* kernel fib id */
	struct netflow_export_item	exp;		/* Various data used for export */
	struct mtx			export_mtx;	/* exp.item mutex */
	struct mtx			export9_mtx;	/* exp.item9 mutex */
	uint32_t			flow_seq;	/* current V5 flow sequence */
	uint32_t			flow9_seq;	/* current V9 flow sequence */
	uint32_t			domain_id;	/* Observartion domain id */
	/* Netflow V9 counters */
	uint32_t			templ_last_ts;	/* unixtime of last template announce */
	uint32_t			templ_last_pkt;	/* packets count on last template announce */
	uint32_t			sent_packets;	/* packets sent by exporter; */
	struct netflow_v9_packet_opt	*export9_opt;	/* current packet specific options */
};

typedef struct fib_export *fib_export_p;

/* Structure describing our flow engine */
struct netflow {
	node_p			node;		/* link to the node itself */
	hook_p			export;		/* export data goes there */
	hook_p			export9;	/* Netflow V9 export data goes there */

	struct ng_netflow_info	info;
	struct callout		exp_callout;	/* expiry periodic job */

	/*
	 * Flow entries are allocated in uma(9) zone zone. They are
	 * indexed by hash hash. Each hash element consist of tailqueue
	 * head and mutex to protect this element.
	 */
#define	CACHESIZE			(65536*4)
#define	CACHELOWAT			(CACHESIZE * 3/4)
#define	CACHEHIGHWAT			(CACHESIZE * 9/10)
	uma_zone_t		zone;
	struct flow_hash_entry	*hash;

	/*
	 * NetFlow data export
	 *
	 * export_item is a data item, it has an mbuf with cluster
	 * attached to it. A thread detaches export_item from priv
	 * and works with it. If the export is full it is sent, and
	 * a new one is allocated. Before exiting thread re-attaches
	 * its current item back to priv. If there is item already,
	 * current incomplete datagram is sent.
	 * export_mtx is used for attaching/detaching.
	 */

	/* IPv6 support */
#ifdef INET6
	uma_zone_t		zone6;
	struct flow_hash_entry	*hash6;
#endif
	/* Multiple FIB support */
	fib_export_p		fib_data[RT_NUMFIBS]; /* array of pointers to fib-specific data */

	/*
	 * RFC 3954 clause 7.3
	 * "Both options MUST be configurable by the user on the Exporter."
	 */
	uint16_t		templ_time;	/* time between sending templates */
	uint16_t		templ_packets;	/* packets between sending templates */
#define NETFLOW_V9_MAX_FLOWSETS	2
	u_char			flowsets_count; /* current flowsets used */
	u_char			flowset_records[NETFLOW_V9_MAX_FLOWSETS - 1]; /* Count of records in each flowset */
	uint16_t		mtu;		/* export interface MTU */
	struct netflow_v9_flowset_header	*v9_flowsets[NETFLOW_V9_MAX_FLOWSETS - 1]; /* Pointers to pre-compiled flowsets */

	struct ng_netflow_iface	ifaces[NG_NETFLOW_MAXIFACES];
};

typedef struct netflow *priv_p;

/* Header of a small list in hash cell */
struct flow_hash_entry {
	struct mtx		mtx;
	TAILQ_HEAD(fhead, flow_entry) head;
};

#define	ERROUT(x)	{ error = (x); goto done; }

#define MTAG_NETFLOW		1221656444
#define MTAG_NETFLOW_CALLED	0

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

#define priv_to_fib(priv, fib)	(priv)->fib_data[(fib)]

/*
 * Cisco uses milliseconds for uptime. Bad idea, since it overflows
 * every 48+ days. But we will do same to keep compatibility. This macro
 * does overflowable multiplication to 1000.
 */
#define	MILLIUPTIME(t)	(((t) << 9) +	/* 512 */	\
			 ((t) << 8) +	/* 256 */	\
			 ((t) << 7) +	/* 128 */	\
			 ((t) << 6) +	/* 64  */	\
			 ((t) << 5) +	/* 32  */	\
			 ((t) << 3))	/* 8   */

/* Prototypes for netflow.c */
void	ng_netflow_cache_init(priv_p);
void	ng_netflow_cache_flush(priv_p);
int	ng_netflow_fib_init(priv_p priv, int fib);
void	ng_netflow_copyinfo(priv_p, struct ng_netflow_info *);
timeout_t ng_netflow_expire;
int 	ng_netflow_flow_add(priv_p, fib_export_p, struct ip *, caddr_t, uint8_t, uint8_t, unsigned int);
int	ng_netflow_flow6_add(priv_p, fib_export_p, struct ip6_hdr *, caddr_t , uint8_t, uint8_t, unsigned int);
int	ng_netflow_flow_show(priv_p, struct ngnf_show_header *req, struct ngnf_show_header *resp);

void	ng_netflow_v9_cache_init(priv_p);
void	ng_netflow_v9_cache_flush(priv_p);
item_p	get_export9_dgram(priv_p, fib_export_p, struct netflow_v9_packet_opt **);
void	return_export9_dgram(priv_p, fib_export_p, item_p,
	    struct netflow_v9_packet_opt *, int);
int	export9_add(item_p, struct netflow_v9_packet_opt *, struct flow_entry *);
int	export9_send(priv_p, fib_export_p, item_p, struct netflow_v9_packet_opt *,
	    int);

#endif	/* _KERNEL */
#endif	/* _NG_NETFLOW_H_ */


code:
/*
 * netgraph.h
 */

/*-
 * Copyright (c) 1996-1999 Whistle Communications, Inc.
 * All rights reserved.
 *
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 *
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Julian Elischer <julian@freebsd.org>
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/netgraph.h 223768 2011-07-04 20:50:09Z glebius $
 * $Whistle: netgraph.h,v 1.29 1999/11/01 07:56:13 julian Exp $
 */

#ifndef _NETGRAPH_NETGRAPH_H_
#define _NETGRAPH_NETGRAPH_H_

#ifndef _KERNEL
#error "This file should not be included in user level programs"
#endif

#include <sys/queue.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/refcount.h>

#ifdef HAVE_KERNEL_OPTION_HEADERS
#include "opt_netgraph.h"
#endif

/* debugging options */
#define NG_SEPARATE_MALLOC	/* make modules use their own malloc types */

/*
 * This defines the in-kernel binary interface version.
 * It is possible to change this but leave the external message
 * API the same. Each type also has it's own cookies for versioning as well.
 * Change it for NETGRAPH_DEBUG version so we cannot mix debug and non debug
 * modules.
 */
#define _NG_ABI_VERSION 12
#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
#define NG_ABI_VERSION	(_NG_ABI_VERSION + 0x10000)
#else	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/
#define NG_ABI_VERSION	_NG_ABI_VERSION
#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

/*
 * Forward references for the basic structures so we can
 * define the typedefs and use them in the structures themselves.
 */
struct ng_hook ;
struct ng_node ;
struct ng_item ;
typedef	struct ng_item *item_p;
typedef struct ng_node *node_p;
typedef struct ng_hook *hook_p;

/* node method definitions */
typedef	int	ng_constructor_t(node_p node);
typedef	int	ng_close_t(node_p node);
typedef	int	ng_shutdown_t(node_p node);
typedef	int	ng_newhook_t(node_p node, hook_p hook, const char *name);
typedef	hook_p	ng_findhook_t(node_p node, const char *name);
typedef	int	ng_connect_t(hook_p hook);
typedef	int	ng_rcvmsg_t(node_p node, item_p item, hook_p lasthook);
typedef	int	ng_rcvdata_t(hook_p hook, item_p item);
typedef	int	ng_disconnect_t(hook_p hook);
typedef	int	ng_rcvitem (node_p node, hook_p hook, item_p item);

/***********************************************************************
 ***************** Hook Structure and Methods **************************
 ***********************************************************************
 *
 * Structure of a hook
 */
struct ng_hook {
	char	hk_name[NG_HOOKSIZ];	/* what this node knows this link as */
	void   *hk_private;		/* node dependant ID for this hook */
	int	hk_flags;		/* info about this hook/link */
	int	hk_type;		/* tbd: hook data link type */
	struct	ng_hook *hk_peer;	/* the other end of this link */
	struct	ng_node *hk_node;	/* The node this hook is attached to */
	LIST_ENTRY(ng_hook) hk_hooks;	/* linked list of all hooks on node */
	ng_rcvmsg_t	*hk_rcvmsg;	/* control messages come here */
	ng_rcvdata_t	*hk_rcvdata;	/* data comes here */
	int	hk_refs;		/* dont actually free this till 0 */
#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
#define HK_MAGIC 0x78573011
	int	hk_magic;
	char	*lastfile;
	int	lastline;
	SLIST_ENTRY(ng_hook)	  hk_all;		/* all existing items */
#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/
};
/* Flags for a hook */
#define HK_INVALID		0x0001	/* don't trust it! */
#define HK_QUEUE		0x0002	/* queue for later delivery */
#define HK_FORCE_WRITER		0x0004	/* Incoming data queued as a writer */
#define HK_DEAD			0x0008	/* This is the dead hook.. don't free */
#define HK_HI_STACK		0x0010	/* Hook has hi stack usage */
#define HK_TO_INBOUND		0x0020	/* Hook on ntw. stack inbound path. */

/*
 * Public Methods for hook
 * If you can't do it with these you probably shouldn;t be doing it.
 */
void ng_unref_hook(hook_p hook); /* don't move this */
#define	_NG_HOOK_REF(hook)	refcount_acquire(&(hook)->hk_refs)
#define _NG_HOOK_NAME(hook)	((hook)->hk_name)
#define _NG_HOOK_UNREF(hook)	ng_unref_hook(hook)
#define	_NG_HOOK_SET_PRIVATE(hook, val)	do {(hook)->hk_private = val;} while (0)
#define	_NG_HOOK_SET_RCVMSG(hook, val)	do {(hook)->hk_rcvmsg = val;} while (0)
#define	_NG_HOOK_SET_RCVDATA(hook, val)	do {(hook)->hk_rcvdata = val;} while (0)
#define	_NG_HOOK_PRIVATE(hook)	((hook)->hk_private)
#define _NG_HOOK_NOT_VALID(hook)	((hook)->hk_flags & HK_INVALID)
#define _NG_HOOK_IS_VALID(hook)	(!((hook)->hk_flags & HK_INVALID))
#define _NG_HOOK_NODE(hook)	((hook)->hk_node) /* only rvalue! */
#define _NG_HOOK_PEER(hook)	((hook)->hk_peer) /* only rvalue! */
#define _NG_HOOK_FORCE_WRITER(hook)				\
		do { hook->hk_flags |= HK_FORCE_WRITER; } while (0)
#define _NG_HOOK_FORCE_QUEUE(hook) do { hook->hk_flags |= HK_QUEUE; } while (0)
#define _NG_HOOK_SET_TO_INBOUND(hook)				\
		do { hook->hk_flags |= HK_TO_INBOUND; } while (0)
#define _NG_HOOK_HI_STACK(hook) do { hook->hk_flags |= HK_HI_STACK; } while (0)

/* Some shortcuts */
#define NG_PEER_NODE(hook)	NG_HOOK_NODE(NG_HOOK_PEER(hook))
#define NG_PEER_HOOK_NAME(hook)	NG_HOOK_NAME(NG_HOOK_PEER(hook))
#define NG_PEER_NODE_NAME(hook)	NG_NODE_NAME(NG_PEER_NODE(hook))

#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
#define _NN_ __FILE__,__LINE__
void	dumphook (hook_p hook, char *file, int line);
static __inline void	_chkhook(hook_p hook, char *file, int line);
static __inline void	_ng_hook_ref(hook_p hook, char * file, int line);
static __inline char *	_ng_hook_name(hook_p hook, char * file, int line);
static __inline void	_ng_hook_unref(hook_p hook, char * file, int line);
static __inline void	_ng_hook_set_private(hook_p hook,
				void * val, char * file, int line);
static __inline void	_ng_hook_set_rcvmsg(hook_p hook,
				ng_rcvmsg_t *val, char * file, int line);
static __inline void	_ng_hook_set_rcvdata(hook_p hook,
				ng_rcvdata_t *val, char * file, int line);
static __inline void *	_ng_hook_private(hook_p hook, char * file, int line);
static __inline int	_ng_hook_not_valid(hook_p hook, char * file, int line);
static __inline int	_ng_hook_is_valid(hook_p hook, char * file, int line);
static __inline node_p	_ng_hook_node(hook_p hook, char * file, int line);
static __inline hook_p	_ng_hook_peer(hook_p hook, char * file, int line);
static __inline void	_ng_hook_force_writer(hook_p hook, char * file,
				int line);
static __inline void	_ng_hook_force_queue(hook_p hook, char * file,
				int line);
static __inline void	_ng_hook_set_to_inbound(hook_p hook, char * file,
				int line);

static __inline void
_chkhook(hook_p hook, char *file, int line)
{
	if (hook->hk_magic != HK_MAGIC) {
		printf("Accessing freed hook ");
		dumphook(hook, file, line);
	}
	hook->lastline = line;
	hook->lastfile = file;
}

static __inline void
_ng_hook_ref(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_REF(hook);
}

static __inline char *
_ng_hook_name(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_NAME(hook));
}

static __inline void
_ng_hook_unref(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_UNREF(hook);
}

static __inline void
_ng_hook_set_private(hook_p hook, void *val, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_SET_PRIVATE(hook, val);
}

static __inline void
_ng_hook_set_rcvmsg(hook_p hook, ng_rcvmsg_t *val, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_SET_RCVMSG(hook, val);
}

static __inline void
_ng_hook_set_rcvdata(hook_p hook, ng_rcvdata_t *val, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_SET_RCVDATA(hook, val);
}

static __inline void *
_ng_hook_private(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_PRIVATE(hook));
}

static __inline int
_ng_hook_not_valid(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_NOT_VALID(hook));
}

static __inline int
_ng_hook_is_valid(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_IS_VALID(hook));
}

static __inline node_p
_ng_hook_node(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_NODE(hook));
}

static __inline hook_p
_ng_hook_peer(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	return (_NG_HOOK_PEER(hook));
}

static __inline void
_ng_hook_force_writer(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_FORCE_WRITER(hook);
}

static __inline void
_ng_hook_force_queue(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_FORCE_QUEUE(hook);
}

static __inline void
_ng_hook_set_to_inbound(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_SET_TO_INBOUND(hook);
}

static __inline void
_ng_hook_hi_stack(hook_p hook, char * file, int line)
{
	_chkhook(hook, file, line);
	_NG_HOOK_HI_STACK(hook);
}

#define	NG_HOOK_REF(hook)		_ng_hook_ref(hook, _NN_)
#define NG_HOOK_NAME(hook)		_ng_hook_name(hook, _NN_)
#define NG_HOOK_UNREF(hook)		_ng_hook_unref(hook, _NN_)
#define	NG_HOOK_SET_PRIVATE(hook, val)	_ng_hook_set_private(hook, val, _NN_)
#define	NG_HOOK_SET_RCVMSG(hook, val)	_ng_hook_set_rcvmsg(hook, val, _NN_)
#define	NG_HOOK_SET_RCVDATA(hook, val)	_ng_hook_set_rcvdata(hook, val, _NN_)
#define	NG_HOOK_PRIVATE(hook)		_ng_hook_private(hook, _NN_)
#define NG_HOOK_NOT_VALID(hook)		_ng_hook_not_valid(hook, _NN_)
#define NG_HOOK_IS_VALID(hook)		_ng_hook_is_valid(hook, _NN_)
#define NG_HOOK_NODE(hook)		_ng_hook_node(hook, _NN_)
#define NG_HOOK_PEER(hook)		_ng_hook_peer(hook, _NN_)
#define NG_HOOK_FORCE_WRITER(hook)	_ng_hook_force_writer(hook, _NN_)
#define NG_HOOK_FORCE_QUEUE(hook)	_ng_hook_force_queue(hook, _NN_)
#define NG_HOOK_SET_TO_INBOUND(hook)	_ng_hook_set_to_inbound(hook, _NN_)
#define NG_HOOK_HI_STACK(hook)		_ng_hook_hi_stack(hook, _NN_)

#else	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

#define	NG_HOOK_REF(hook)		_NG_HOOK_REF(hook)
#define NG_HOOK_NAME(hook)		_NG_HOOK_NAME(hook)
#define NG_HOOK_UNREF(hook)		_NG_HOOK_UNREF(hook)
#define	NG_HOOK_SET_PRIVATE(hook, val)	_NG_HOOK_SET_PRIVATE(hook, val)
#define	NG_HOOK_SET_RCVMSG(hook, val)	_NG_HOOK_SET_RCVMSG(hook, val)
#define	NG_HOOK_SET_RCVDATA(hook, val)	_NG_HOOK_SET_RCVDATA(hook, val)
#define	NG_HOOK_PRIVATE(hook)		_NG_HOOK_PRIVATE(hook)
#define NG_HOOK_NOT_VALID(hook)		_NG_HOOK_NOT_VALID(hook)
#define NG_HOOK_IS_VALID(hook)		_NG_HOOK_IS_VALID(hook)
#define NG_HOOK_NODE(hook)		_NG_HOOK_NODE(hook)
#define NG_HOOK_PEER(hook)		_NG_HOOK_PEER(hook)
#define NG_HOOK_FORCE_WRITER(hook)	_NG_HOOK_FORCE_WRITER(hook)
#define NG_HOOK_FORCE_QUEUE(hook)	_NG_HOOK_FORCE_QUEUE(hook)
#define NG_HOOK_SET_TO_INBOUND(hook)	_NG_HOOK_SET_TO_INBOUND(hook)
#define NG_HOOK_HI_STACK(hook)		_NG_HOOK_HI_STACK(hook)

#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

/***********************************************************************
 ***************** Node Structure and Methods **************************
 ***********************************************************************
 * Structure of a node
 * including the eembedded queue structure.
 *
 * The structure for queueing Netgraph request items
 * embedded in the node structure
 */
struct ng_queue {
	u_int		q_flags;	/* Current r/w/q lock flags */
	u_int		q_flags2;	/* Other queue flags */
	struct mtx	q_mtx;
	STAILQ_ENTRY(ng_node)	q_work;	/* nodes with work to do */
	STAILQ_HEAD(, ng_item)	queue;	/* actually items queue */
};

struct ng_node {
	char	nd_name[NG_NODESIZ];	/* optional globally unique name */
	struct	ng_type *nd_type;	/* the installed 'type' */
	int	nd_flags;		/* see below for bit definitions */
	int	nd_numhooks;		/* number of hooks */
	void   *nd_private;		/* node type dependant node ID */
	ng_ID_t	nd_ID;			/* Unique per node */
	LIST_HEAD(hooks, ng_hook) nd_hooks;	/* linked list of node hooks */
	LIST_ENTRY(ng_node)	  nd_nodes;	/* linked list of all nodes */
	LIST_ENTRY(ng_node)	  nd_idnodes;	/* ID hash collision list */
	struct	ng_queue	  nd_input_queue; /* input queue for locking */
	int	nd_refs;		/* # of references to this node */
	struct	vnet		 *nd_vnet;	/* network stack instance */
#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
#define ND_MAGIC 0x59264837
	int	nd_magic;
	char	*lastfile;
	int	lastline;
	SLIST_ENTRY(ng_node)	  nd_all;	/* all existing nodes */
#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/
};

/* Flags for a node */
#define NGF_INVALID	0x00000001	/* free when refs go to 0 */
#define NG_INVALID	NGF_INVALID	/* compat for old code */
#define NGF_FORCE_WRITER	0x00000004	/* Never multithread this node */
#define NG_FORCE_WRITER	NGF_FORCE_WRITER /* compat for old code */
#define NGF_CLOSING	0x00000008	/* ng_rmnode() at work */
#define NG_CLOSING	NGF_CLOSING	/* compat for old code */
#define NGF_REALLY_DIE	0x00000010	/* "persistent" node is unloading */
#define NG_REALLY_DIE	NGF_REALLY_DIE	/* compat for old code */
#define NGF_HI_STACK	0x00000020	/* node has hi stack usage */
#define NGF_TYPE1	0x10000000	/* reserved for type specific storage */
#define NGF_TYPE2	0x20000000	/* reserved for type specific storage */
#define NGF_TYPE3	0x40000000	/* reserved for type specific storage */
#define NGF_TYPE4	0x80000000	/* reserved for type specific storage */

/*
 * Public methods for nodes.
 * If you can't do it with these you probably shouldn't be doing it.
 */
void	ng_unref_node(node_p node); /* don't move this */
#define _NG_NODE_NAME(node)	((node)->nd_name + 0)
#define _NG_NODE_HAS_NAME(node)	((node)->nd_name[0] + 0)
#define _NG_NODE_ID(node)	((node)->nd_ID + 0)
#define	_NG_NODE_REF(node)	refcount_acquire(&(node)->nd_refs)
#define	_NG_NODE_UNREF(node)	ng_unref_node(node)
#define	_NG_NODE_SET_PRIVATE(node, val)	do {(node)->nd_private = val;} while (0)
#define	_NG_NODE_PRIVATE(node)	((node)->nd_private)
#define _NG_NODE_IS_VALID(node)	(!((node)->nd_flags & NGF_INVALID))
#define _NG_NODE_NOT_VALID(node)	((node)->nd_flags & NGF_INVALID)
#define _NG_NODE_NUMHOOKS(node)	((node)->nd_numhooks + 0) /* rvalue */
#define _NG_NODE_FORCE_WRITER(node)					\
	do{ node->nd_flags |= NGF_FORCE_WRITER; }while (0)
#define _NG_NODE_HI_STACK(node)						\
	do{ node->nd_flags |= NGF_HI_STACK; }while (0)
#define _NG_NODE_REALLY_DIE(node)					\
	do{ node->nd_flags |= (NGF_REALLY_DIE|NGF_INVALID); }while (0)
#define _NG_NODE_REVIVE(node) \
	do { node->nd_flags &= ~NGF_INVALID; } while (0)
/*
 * The hook iterator.
 * This macro will call a function of type ng_fn_eachhook for each
 * hook attached to the node. If the function returns 0, then the
 * iterator will stop and return a pointer to the hook that returned 0.
 */
typedef	int	ng_fn_eachhook(hook_p hook, void* arg);
#define _NG_NODE_FOREACH_HOOK(node, fn, arg, rethook)			\
	do {								\
		hook_p _hook;						\
		(rethook) = NULL;					\
		LIST_FOREACH(_hook, &((node)->nd_hooks), hk_hooks) {	\
			if ((fn)(_hook, arg) == 0) {			\
				(rethook) = _hook;			\
				break;					\
			}						\
		}							\
	} while (0)

#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
void	dumpnode(node_p node, char *file, int line);
static __inline void _chknode(node_p node, char *file, int line);
static __inline char * _ng_node_name(node_p node, char *file, int line);
static __inline int _ng_node_has_name(node_p node, char *file, int line);
static __inline ng_ID_t _ng_node_id(node_p node, char *file, int line);
static __inline void _ng_node_ref(node_p node, char *file, int line);
static __inline void _ng_node_unref(node_p node, char *file, int line);
static __inline void _ng_node_set_private(node_p node, void * val,
							char *file, int line);
static __inline void * _ng_node_private(node_p node, char *file, int line);
static __inline int _ng_node_is_valid(node_p node, char *file, int line);
static __inline int _ng_node_not_valid(node_p node, char *file, int line);
static __inline int _ng_node_numhooks(node_p node, char *file, int line);
static __inline void _ng_node_force_writer(node_p node, char *file, int line);
static __inline hook_p _ng_node_foreach_hook(node_p node,
			ng_fn_eachhook *fn, void *arg, char *file, int line);
static __inline void _ng_node_revive(node_p node, char *file, int line);

static __inline void
_chknode(node_p node, char *file, int line)
{
	if (node->nd_magic != ND_MAGIC) {
		printf("Accessing freed node ");
		dumpnode(node, file, line);
	}
	node->lastline = line;
	node->lastfile = file;
}

static __inline char *
_ng_node_name(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_NAME(node));
}

static __inline int
_ng_node_has_name(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_HAS_NAME(node));
}

static __inline ng_ID_t
_ng_node_id(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_ID(node));
}

static __inline void
_ng_node_ref(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_REF(node);
}

static __inline void
_ng_node_unref(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_UNREF(node);
}

static __inline void
_ng_node_set_private(node_p node, void * val, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_SET_PRIVATE(node, val);
}

static __inline void *
_ng_node_private(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return (_NG_NODE_PRIVATE(node));
}

static __inline int
_ng_node_is_valid(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_IS_VALID(node));
}

static __inline int
_ng_node_not_valid(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_NOT_VALID(node));
}

static __inline int
_ng_node_numhooks(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	return(_NG_NODE_NUMHOOKS(node));
}

static __inline void
_ng_node_force_writer(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_FORCE_WRITER(node);
}

static __inline void
_ng_node_hi_stack(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_HI_STACK(node);
}

static __inline void
_ng_node_really_die(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_REALLY_DIE(node);
}

static __inline void
_ng_node_revive(node_p node, char *file, int line)
{
	_chknode(node, file, line);
	_NG_NODE_REVIVE(node);
}

static __inline hook_p
_ng_node_foreach_hook(node_p node, ng_fn_eachhook *fn, void *arg,
						char *file, int line)
{
	hook_p hook;
	_chknode(node, file, line);
	_NG_NODE_FOREACH_HOOK(node, fn, arg, hook);
	return (hook);
}

#define NG_NODE_NAME(node)		_ng_node_name(node, _NN_)
#define NG_NODE_HAS_NAME(node)		_ng_node_has_name(node, _NN_)
#define NG_NODE_ID(node)		_ng_node_id(node, _NN_)
#define NG_NODE_REF(node)		_ng_node_ref(node, _NN_)
#define	NG_NODE_UNREF(node)		_ng_node_unref(node, _NN_)
#define	NG_NODE_SET_PRIVATE(node, val)	_ng_node_set_private(node, val, _NN_)
#define	NG_NODE_PRIVATE(node)		_ng_node_private(node, _NN_)
#define NG_NODE_IS_VALID(node)		_ng_node_is_valid(node, _NN_)
#define NG_NODE_NOT_VALID(node)		_ng_node_not_valid(node, _NN_)
#define NG_NODE_FORCE_WRITER(node) 	_ng_node_force_writer(node, _NN_)
#define NG_NODE_HI_STACK(node) 		_ng_node_hi_stack(node, _NN_)
#define NG_NODE_REALLY_DIE(node) 	_ng_node_really_die(node, _NN_)
#define NG_NODE_NUMHOOKS(node)		_ng_node_numhooks(node, _NN_)
#define NG_NODE_REVIVE(node)		_ng_node_revive(node, _NN_)
#define NG_NODE_FOREACH_HOOK(node, fn, arg, rethook)			      \
	do {								      \
		rethook = _ng_node_foreach_hook(node, fn, (void *)arg, _NN_); \
	} while (0)

#else	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

#define NG_NODE_NAME(node)		_NG_NODE_NAME(node)
#define NG_NODE_HAS_NAME(node)		_NG_NODE_HAS_NAME(node)
#define NG_NODE_ID(node)		_NG_NODE_ID(node)
#define	NG_NODE_REF(node)		_NG_NODE_REF(node)
#define	NG_NODE_UNREF(node)		_NG_NODE_UNREF(node)
#define	NG_NODE_SET_PRIVATE(node, val)	_NG_NODE_SET_PRIVATE(node, val)
#define	NG_NODE_PRIVATE(node)		_NG_NODE_PRIVATE(node)
#define NG_NODE_IS_VALID(node)		_NG_NODE_IS_VALID(node)
#define NG_NODE_NOT_VALID(node)		_NG_NODE_NOT_VALID(node)
#define NG_NODE_FORCE_WRITER(node) 	_NG_NODE_FORCE_WRITER(node)
#define NG_NODE_HI_STACK(node) 		_NG_NODE_HI_STACK(node)
#define NG_NODE_REALLY_DIE(node) 	_NG_NODE_REALLY_DIE(node)
#define NG_NODE_NUMHOOKS(node)		_NG_NODE_NUMHOOKS(node)
#define NG_NODE_REVIVE(node)		_NG_NODE_REVIVE(node)
#define NG_NODE_FOREACH_HOOK(node, fn, arg, rethook)			\
		_NG_NODE_FOREACH_HOOK(node, fn, arg, rethook)
#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

/***********************************************************************
 ************* Node Queue and Item Structures and Methods **************
 ***********************************************************************
 *
 */
typedef	void	ng_item_fn(node_p node, hook_p hook, void *arg1, int arg2);
typedef	int	ng_item_fn2(node_p node, struct ng_item *item, hook_p hook);
typedef	void	ng_apply_t(void *context, int error);
struct ng_apply_info {
	ng_apply_t	*apply;
	void		*context;
	int		refs;
	int		error;
};
struct ng_item {
	u_long	el_flags;
	STAILQ_ENTRY(ng_item)	el_next;
	node_p	el_dest; /* The node it will be applied against (or NULL) */
	hook_p	el_hook; /* Entering hook. Optional in Control messages */
	union {
		struct mbuf	*da_m;
		struct {
			struct ng_mesg	*msg_msg;
			ng_ID_t		msg_retaddr;
		} msg;
		struct {
			union {
				ng_item_fn	*fn_fn;
				ng_item_fn2	*fn_fn2;
			} fn_fn;
			void 		*fn_arg1;
			int		fn_arg2;
		} fn;
	} body;
	/*
	 * Optional callback called when item is being applied,
	 * and its context.
	 */
	struct ng_apply_info	*apply;
	u_int	depth;
#ifdef	NETGRAPH_DEBUG /*----------------------------------------------*/
	char *lastfile;
	int  lastline;
	TAILQ_ENTRY(ng_item)	  all;		/* all existing items */
#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/
};

#define NGQF_TYPE	0x03		/* MASK of content definition */
#define NGQF_MESG	0x00		/* the queue element is a message */
#define NGQF_DATA	0x01		/* the queue element is data */
#define NGQF_FN		0x02		/* the queue element is a function */
#define NGQF_FN2	0x03		/* the queue element is a new function */

#define NGQF_RW		0x04		/* MASK for wanted queue mode */
#define NGQF_READER	0x04		/* wants to be a reader */
#define NGQF_WRITER	0x00		/* wants to be a writer */

#define NGQF_QMODE	0x08		/* MASK for how it was queued */
#define NGQF_QREADER	0x08		/* was queued as a reader */
#define NGQF_QWRITER	0x00		/* was queued as a writer */

/*
 * Get the mbuf (etc) out of an item.
 * Sets the value in the item to NULL in case we need to call NG_FREE_ITEM()
 * with it, (to avoid freeing the things twice).
 * If you don't want to zero out the item then realise that the
 * item still owns it.
 * Retaddr is different. There are no references on that. It's just a number.
 * The debug versions must be either all used everywhere or not at all.
 */

#define _NGI_M(i) ((i)->body.da_m)
#define _NGI_MSG(i) ((i)->body.msg.msg_msg)
#define _NGI_RETADDR(i) ((i)->body.msg.msg_retaddr)
#define	_NGI_FN(i) ((i)->body.fn.fn_fn.fn_fn)
#define	_NGI_FN2(i) ((i)->body.fn.fn_fn.fn_fn2)
#define	_NGI_ARG1(i) ((i)->body.fn.fn_arg1)
#define	_NGI_ARG2(i) ((i)->body.fn.fn_arg2)
#define	_NGI_NODE(i) ((i)->el_dest)
#define	_NGI_HOOK(i) ((i)->el_hook)
#define	_NGI_SET_HOOK(i,h) do { _NGI_HOOK(i) = h; h = NULL;} while (0)
#define	_NGI_CLR_HOOK(i)   do {						\
		hook_p _hook = _NGI_HOOK(i);				\
		if (_hook) {						\
			_NG_HOOK_UNREF(_hook);				\
			_NGI_HOOK(i) = NULL;				\
		}							\
	} while (0)
#define	_NGI_SET_NODE(i,n) do { _NGI_NODE(i) = n; n = NULL;} while (0)
#define	_NGI_CLR_NODE(i)   do {						\
		node_p _node = _NGI_NODE(i);				\
		if (_node) {						\
			_NG_NODE_UNREF(_node);				\
			_NGI_NODE(i) = NULL;				\
		}							\
	} while (0)

#ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
void				dumpitem(item_p item, char *file, int line);
static __inline void		_ngi_check(item_p item, char *file, int line) ;
static __inline struct mbuf **	_ngi_m(item_p item, char *file, int line) ;
static __inline ng_ID_t *	_ngi_retaddr(item_p item, char *file, int line);
static __inline struct ng_mesg ** _ngi_msg(item_p item, char *file, int line) ;
static __inline ng_item_fn **	_ngi_fn(item_p item, char *file, int line) ;
static __inline ng_item_fn2 **	_ngi_fn2(item_p item, char *file, int line) ;
static __inline void **		_ngi_arg1(item_p item, char *file, int line) ;
static __inline int *		_ngi_arg2(item_p item, char *file, int line) ;
static __inline node_p		_ngi_node(item_p item, char *file, int line);
static __inline hook_p		_ngi_hook(item_p item, char *file, int line);

static __inline void
_ngi_check(item_p item, char *file, int line)
{
	(item)->lastline = line;
	(item)->lastfile = file;
}

static __inline struct mbuf **
_ngi_m(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_M(item));
}

static __inline struct ng_mesg **
_ngi_msg(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_MSG(item));
}

static __inline ng_ID_t *
_ngi_retaddr(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_RETADDR(item));
}

static __inline ng_item_fn **
_ngi_fn(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_FN(item));
}

static __inline ng_item_fn2 **
_ngi_fn2(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_FN2(item));
}

static __inline void **
_ngi_arg1(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_ARG1(item));
}

static __inline int *
_ngi_arg2(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (&_NGI_ARG2(item));
}

static __inline node_p
_ngi_node(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (_NGI_NODE(item));
}

static __inline hook_p
_ngi_hook(item_p item, char *file, int line)
{
	_ngi_check(item, file, line);
	return (_NGI_HOOK(item));
}

#define NGI_M(i)	(*_ngi_m(i, _NN_))
#define NGI_MSG(i)	(*_ngi_msg(i, _NN_))
#define NGI_RETADDR(i)	(*_ngi_retaddr(i, _NN_))
#define NGI_FN(i)	(*_ngi_fn(i, _NN_))
#define NGI_FN2(i)	(*_ngi_fn2(i, _NN_))
#define NGI_ARG1(i)	(*_ngi_arg1(i, _NN_))
#define NGI_ARG2(i)	(*_ngi_arg2(i, _NN_))
#define NGI_HOOK(i)	_ngi_hook(i, _NN_)
#define NGI_NODE(i)	_ngi_node(i, _NN_)
#define	NGI_SET_HOOK(i,h)						\
	do { _ngi_check(i, _NN_); _NGI_SET_HOOK(i, h); } while (0)
#define	NGI_CLR_HOOK(i)							\
	do { _ngi_check(i, _NN_); _NGI_CLR_HOOK(i); } while (0)
#define	NGI_SET_NODE(i,n)						\
	do { _ngi_check(i, _NN_); _NGI_SET_NODE(i, n); } while (0)
#define	NGI_CLR_NODE(i)							\
	do { _ngi_check(i, _NN_); _NGI_CLR_NODE(i); } while (0)

#define NG_FREE_ITEM(item)						\
	do {								\
		_ngi_check(item, _NN_);					\
		ng_free_item((item));					\
	} while (0)

#define	SAVE_LINE(item)							\
	do {								\
		(item)->lastline = __LINE__;				\
		(item)->lastfile = __FILE__;				\
	} while (0)

#else	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

#define NGI_M(i)	_NGI_M(i)
#define NGI_MSG(i)	_NGI_MSG(i)
#define NGI_RETADDR(i)	_NGI_RETADDR(i)
#define NGI_FN(i)	_NGI_FN(i)
#define NGI_FN2(i)	_NGI_FN2(i)
#define NGI_ARG1(i)	_NGI_ARG1(i)
#define NGI_ARG2(i)	_NGI_ARG2(i)
#define	NGI_NODE(i)	_NGI_NODE(i)
#define	NGI_HOOK(i)	_NGI_HOOK(i)
#define	NGI_SET_HOOK(i,h) _NGI_SET_HOOK(i,h)
#define	NGI_CLR_HOOK(i)	  _NGI_CLR_HOOK(i)
#define	NGI_SET_NODE(i,n) _NGI_SET_NODE(i,n)
#define	NGI_CLR_NODE(i)	  _NGI_CLR_NODE(i)

#define	NG_FREE_ITEM(item)	ng_free_item((item))
#define	SAVE_LINE(item)		do {} while (0)

#endif	/* NETGRAPH_DEBUG */ /*----------------------------------------------*/

#define NGI_GET_M(i,m)							\
	do {								\
		(m) = NGI_M(i);						\
		_NGI_M(i) = NULL;					\
	} while (0)

#define NGI_GET_MSG(i,m)						\
	do {								\
		(m) = NGI_MSG(i);					\
		_NGI_MSG(i) = NULL;					\
	} while (0)

#define NGI_GET_NODE(i,n)	/* YOU NOW HAVE THE REFERENCE */	\
	do {								\
		(n) = NGI_NODE(i);					\
		_NGI_NODE(i) = NULL;					\
	} while (0)

#define NGI_GET_HOOK(i,h)						\
	do {								\
		(h) = NGI_HOOK(i);					\
		_NGI_HOOK(i) = NULL;					\
	} while (0)

#define NGI_SET_WRITER(i)	((i)->el_flags &= ~NGQF_QMODE)
#define NGI_SET_READER(i)	((i)->el_flags |= NGQF_QREADER)

#define NGI_QUEUED_READER(i)	((i)->el_flags & NGQF_QREADER)
#define NGI_QUEUED_WRITER(i)	(((i)->el_flags & NGQF_QMODE) == NGQF_QWRITER)

/**********************************************************************
* Data macros.  Send, manipulate and free.
**********************************************************************/
/*
 * Assuming the data is already ok, just set the new address and send
 */
#define NG_FWD_ITEM_HOOK_FLAGS(error, item, hook, flags)		\
	do {								\
		(error) =						\
		    ng_address_hook(NULL, (item), (hook), NG_NOFLAGS);	\
		if (error == 0) {					\
			SAVE_LINE(item);				\
			(error) = ng_snd_item((item), (flags));		\
		}							\
		(item) = NULL;						\
	} while (0)
#define	NG_FWD_ITEM_HOOK(error, item, hook)	\
		NG_FWD_ITEM_HOOK_FLAGS(error, item, hook, NG_NOFLAGS)

/*
 * Forward a data packet. Mbuf pointer is updated to new value. We
 * presume you dealt with the old one when you update it to the new one
 * (or it maybe the old one). We got a packet and possibly had to modify
 * the mbuf. You should probably use NGI_GET_M() if you are going to use
 * this too.
 */
#define NG_FWD_NEW_DATA_FLAGS(error, item, hook, m, flags)		\
	do {								\
		NGI_M(item) = (m);					\
		(m) = NULL;						\
		NG_FWD_ITEM_HOOK_FLAGS(error, item, hook, flags);	\
	} while (0)
#define	NG_FWD_NEW_DATA(error, item, hook, m)	\
		NG_FWD_NEW_DATA_FLAGS(error, item, hook, m, NG_NOFLAGS)

/* Send a previously unpackaged mbuf. XXX: This should be called
 * NG_SEND_DATA in future, but this name is kept for compatibility
 * reasons.
 */
#define NG_SEND_DATA_FLAGS(error, hook, m, flags)			\
	do {								\
		item_p _item;						\
		if ((_item = ng_package_data((m), flags))) {		\
			NG_FWD_ITEM_HOOK_FLAGS(error, _item, hook, flags);\
		} else {						\
			(error) = ENOMEM;				\
		}							\
		(m) = NULL;						\
	} while (0)

#define NG_SEND_DATA_ONLY(error, hook, m)	\
		NG_SEND_DATA_FLAGS(error, hook, m, NG_NOFLAGS)
/* NG_SEND_DATA() compat for meta-data times */
#define	NG_SEND_DATA(error, hook, m, x)	\
		NG_SEND_DATA_FLAGS(error, hook, m, NG_NOFLAGS)

#define NG_FREE_MSG(msg)						\
	do {								\
		if ((msg)) {						\
			free((msg), M_NETGRAPH_MSG);			\
			(msg) = NULL;					\
		}	 						\
	} while (0)

#define NG_FREE_M(m)							\
	do {								\
		if ((m)) {						\
			m_freem((m));					\
			(m) = NULL;					\
		}							\
	} while (0)

/*****************************************
* Message macros
*****************************************/

#define NG_SEND_MSG_HOOK(error, here, msg, hook, retaddr)		\
	do {								\
		item_p _item;						\
		if ((_item = ng_package_msg(msg, NG_NOFLAGS)) == NULL) {\
			(msg) = NULL;					\
			(error) = ENOMEM;				\
			break;						\
		}							\
		if (((error) = ng_address_hook((here), (_item),		\
					(hook), (retaddr))) == 0) {	\
			SAVE_LINE(_item);				\
			(error) = ng_snd_item((_item), 0);		\
		}							\
		(msg) = NULL;						\
	} while (0)

#define NG_SEND_MSG_PATH(error, here, msg, path, retaddr)		\
	do {								\
		item_p _item;						\
		if ((_item = ng_package_msg(msg, NG_NOFLAGS)) == NULL) {\
			(msg) = NULL;					\
			(error) = ENOMEM;				\
			break;						\
		}							\
		if (((error) = ng_address_path((here), (_item),		\
					(path), (retaddr))) == 0) {	\
			SAVE_LINE(_item);				\
			(error) = ng_snd_item((_item), 0);		\
		}							\
		(msg) = NULL;						\
	} while (0)

#define NG_SEND_MSG_ID(error, here, msg, ID, retaddr)			\
	do {								\
		item_p _item;						\
		if ((_item = ng_package_msg(msg, NG_NOFLAGS)) == NULL) {\
			(msg) = NULL;					\
			(error) = ENOMEM;				\
			break;						\
		}							\
		if (((error) = ng_address_ID((here), (_item),		\
					(ID), (retaddr))) == 0) {	\
			SAVE_LINE(_item);				\
			(error) = ng_snd_item((_item), 0);		\
		}							\
		(msg) = NULL;						\
	} while (0)

/*
 * Redirect the message to the next hop using the given hook.
 * ng_retarget_msg() frees the item if there is an error
 * and returns an error code.  It returns 0 on success.
 */
#define NG_FWD_MSG_HOOK(error, here, item, hook, retaddr)		\
	do {								\
		if (((error) = ng_address_hook((here), (item),		\
					(hook), (retaddr))) == 0) {	\
			SAVE_LINE(item);				\
			(error) = ng_snd_item((item), 0);		\
		}							\
		(item) = NULL;						\
	} while (0)

/*
 * Send a queue item back to it's originator with a response message.
 * Assume original message was removed and freed separatly.
 */
#define NG_RESPOND_MSG(error, here, item, resp)				\
	do {								\
		if (resp) {						\
			ng_ID_t _dest = NGI_RETADDR(item);		\
			NGI_RETADDR(item) = 0;				\
			NGI_MSG(item) = resp;				\
			if ((error = ng_address_ID((here), (item),	\
					_dest, 0)) == 0) {		\
				SAVE_LINE(item);			\
				(error) = ng_snd_item((item), NG_QUEUE);\
			}						\
		} else							\
			NG_FREE_ITEM(item);				\
		(item) = NULL;						\
	} while (0)

/***********************************************************************
 ******** Structures Definitions and Macros for defining a node  *******
 ***********************************************************************
 *
 * Here we define the structures needed to actually define a new node
 * type.
 */

/*
 * Command list -- each node type specifies the command that it knows
 * how to convert between ASCII and binary using an array of these.
 * The last element in the array must be a terminator with cookie=0.
 */

struct ng_cmdlist {
	u_int32_t			cookie;		/* command typecookie */
	int				cmd;		/* command number */
	const char			*name;		/* command name */
	const struct ng_parse_type	*mesgType;	/* args if !NGF_RESP */
	const struct ng_parse_type	*respType;	/* args if NGF_RESP */
};

/*
 * Structure of a node type
 * If data is sent to the "rcvdata()" entrypoint then the system
 * may decide to defer it until later by queing it with the normal netgraph
 * input queuing system.  This is decidde by the HK_QUEUE flag being set in
 * the flags word of the peer (receiving) hook. The dequeuing mechanism will
 * ensure it is not requeued again.
 * Note the input queueing system is to allow modules
 * to 'release the stack' or to pass data across spl layers.
 * The data will be redelivered as soon as the NETISR code runs
 * which may be almost immediatly.  A node may also do it's own queueing
 * for other reasons (e.g. device output queuing).
 */
struct ng_type {

	u_int32_t	version; 	/* must equal NG_API_VERSION */
	const char	*name;		/* Unique type name */
	modeventhand_t	mod_event;	/* Module event handler (optional) */
	ng_constructor_t *constructor;	/* Node constructor */
	ng_rcvmsg_t	*rcvmsg;	/* control messages come here */
	ng_close_t	*close;		/* warn about forthcoming shutdown */
	ng_shutdown_t	*shutdown;	/* reset, and free resources */
	ng_newhook_t	*newhook;	/* first notification of new hook */
	ng_findhook_t	*findhook;	/* only if you have lots of hooks */
	ng_connect_t	*connect;	/* final notification of new hook */
	ng_rcvdata_t	*rcvdata;	/* data comes here */
	ng_disconnect_t	*disconnect;	/* notify on disconnect */

	const struct	ng_cmdlist *cmdlist;	/* commands we can convert */

	/* R/W data private to the base netgraph code DON'T TOUCH! */
	LIST_ENTRY(ng_type) types;		/* linked list of all types */
	int		    refs;		/* number of instances */
};

/*
 * Use the NETGRAPH_INIT() macro to link a node type into the
 * netgraph system. This works for types compiled into the kernel
 * as well as KLD modules. The first argument should be the type
 * name (eg, echo) and the second a pointer to the type struct.
 *
 * If a different link time is desired, e.g., a device driver that
 * needs to install its netgraph type before probing, use the
 * NETGRAPH_INIT_ORDERED() macro instead.  Device drivers probably
 * want to use SI_SUB_DRIVERS/SI_ORDER_FIRST.
 */

#define NETGRAPH_INIT_ORDERED(typename, typestructp, sub, order)	\
static moduledata_t ng_##typename##_mod = {				\
	"ng_" #typename,						\
	ng_mod_event,							\
	(typestructp)							\
};									\
DECLARE_MODULE(ng_##typename, ng_##typename##_mod, sub, order);		\
MODULE_DEPEND(ng_##typename, netgraph,	NG_ABI_VERSION,			\
					NG_ABI_VERSION,			\
					NG_ABI_VERSION)

#define NETGRAPH_INIT(tn, tp)						\
	NETGRAPH_INIT_ORDERED(tn, tp, SI_SUB_PSEUDO, SI_ORDER_MIDDLE)

/* Special malloc() type for netgraph structs and ctrl messages */
/* Only these two types should be visible to nodes */
MALLOC_DECLARE(M_NETGRAPH);
MALLOC_DECLARE(M_NETGRAPH_MSG);

/* declare the base of the netgraph sysclt hierarchy */
/* but only if this file cares about sysctls */
#ifdef	SYSCTL_DECL
SYSCTL_DECL(_net_graph);
#endif

/*
 * Methods that the nodes can use.
 * Many of these methods should usually NOT be used directly but via
 * Macros above.
 */
int	ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr);
int	ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr);
int	ng_address_path(node_p here, item_p item, char *address, ng_ID_t raddr);
int	ng_bypass(hook_p hook1, hook_p hook2);
hook_p	ng_findhook(node_p node, const char *name);
struct	ng_type *ng_findtype(const char *type);
int	ng_make_node_common(struct ng_type *typep, node_p *nodep);
int	ng_name_node(node_p node, const char *name);
node_p	ng_name2noderef(node_p node, const char *name);
int	ng_newtype(struct ng_type *tp);
ng_ID_t ng_node2ID(node_p node);
item_p	ng_package_data(struct mbuf *m, int flags);
item_p	ng_package_msg(struct ng_mesg *msg, int flags);
item_p	ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg);
void	ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr);
int	ng_rmhook_self(hook_p hook);	/* if a node wants to kill a hook */
int	ng_rmnode_self(node_p here);	/* if a node wants to suicide */
int	ng_rmtype(struct ng_type *tp);
int	ng_snd_item(item_p item, int queue);
int 	ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void *arg1,
	int arg2);
int 	ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void *arg1,
	int arg2, int flags);
int 	ng_send_fn2(node_p node, hook_p hook, item_p pitem, ng_item_fn2 *fn,
	void *arg1, int arg2, int flags);
int	ng_uncallout(struct callout *c, node_p node);
int	ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
	    ng_item_fn *fn, void * arg1, int arg2);
#define	ng_callout_init(c)	callout_init(c, CALLOUT_MPSAFE)

/* Flags for netgraph functions. */
#define	NG_NOFLAGS	0x00000000	/* no special options */
#define	NG_QUEUE	0x00000001	/* enqueue item, don't dispatch */
#define	NG_WAITOK	0x00000002	/* use M_WAITOK, etc. */
/* XXXGL: NG_PROGRESS unused since ng_base.c rev. 1.136. Should be deleted? */
#define	NG_PROGRESS	0x00000004	/* return EINPROGRESS if queued */
#define	NG_REUSE_ITEM	0x00000008	/* supplied item should be reused */

/*
 * prototypes the user should DEFINITELY not use directly
 */
void	ng_free_item(item_p item); /* Use NG_FREE_ITEM instead */
int	ng_mod_event(module_t mod, int what, void *arg);

/*
 * Tag definitions and constants
 */

#define	NG_TAG_PRIO	1

struct ng_tag_prio {
	struct m_tag	tag;
	char	priority;
	char	discardability;
};

#define	NG_PRIO_CUTOFF		32
#define	NG_PRIO_LINKSTATE	64

/* Macros and declarations to keep compatibility with metadata, which
 * is obsoleted now. To be deleted.
 */
typedef void *meta_p;
#define _NGI_META(i)	NULL
#define NGI_META(i)	NULL
#define NG_FREE_META(meta)
#define NGI_GET_META(i,m)
#define	ng_copy_meta(meta) NULL

/* Hash related definitions */
#define	NG_ID_HASH_SIZE 128 /* most systems wont need even this many */
#define	NG_NAME_HASH_SIZE 128 /* most systems wont need even this many */

/*
 * Mark the current thread when called from the outbound path of the
 * network stack, in order to enforce queuing on ng nodes calling into
 * the inbound network stack path.
 */
#define NG_OUTBOUND_THREAD_REF()					\
	curthread->td_ng_outbound++
#define NG_OUTBOUND_THREAD_UNREF()					\
	do {								\
		curthread->td_ng_outbound--;				\
		KASSERT(curthread->td_ng_outbound >= 0,			\
		    ("%s: negative td_ng_outbound", __func__));		\
	} while (0)

#endif /* _NETGRAPH_NETGRAPH_H_ */


code:
/*
 * ng_UI.h
 */

/*-
 * Copyright (c) 1996-1999 Whistle Communications, Inc.
 * All rights reserved.
 *
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 *
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Julian Elischer <julian@freebsd.org>
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/ng_UI.h 139823 2005-01-07 01:45:51Z imp $
 * $Whistle: ng_UI.h,v 1.6 1999/01/20 00:54:15 archie Exp $
 */

#ifndef _NETGRAPH_NG_UI_H_
#define _NETGRAPH_NG_UI_H_

/* Node type name and cookie */
#define NG_UI_NODE_TYPE		"UI"
#define NGM_UI_COOKIE		884639499

/* Hook names */
#define NG_UI_HOOK_DOWNSTREAM	"downstream"
#define NG_UI_HOOK_UPSTREAM	"upstream"

#endif /* _NETGRAPH_NG_UI_H_ */


code:
/*
 * ng_async.h
 */

/*-
 * Copyright (c) 1996-1999 Whistle Communications, Inc.
 * All rights reserved.
 *
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 *
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Archie Cobbs <archie@freebsd.org>
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/ng_async.h 139823 2005-01-07 01:45:51Z imp $
 * $Whistle: ng_async.h,v 1.5 1999/01/25 01:17:14 archie Exp $
 */

#ifndef _NETGRAPH_NG_ASYNC_H_
#define _NETGRAPH_NG_ASYNC_H_

/* Type name and cookie */
#define NG_ASYNC_NODE_TYPE	"async"
#define NGM_ASYNC_COOKIE	886473717

/* Hook names */
#define NG_ASYNC_HOOK_SYNC	"sync"	/* Sync frames */
#define NG_ASYNC_HOOK_ASYNC	"async"	/* Async-encoded frames */

/* Maximum receive size bounds (for both sync and async sides) */
#define NG_ASYNC_MIN_MRU	1
#define NG_ASYNC_MAX_MRU	8192
#define NG_ASYNC_DEFAULT_MRU	1600

/* Frame statistics */
struct ng_async_stat {
	u_int32_t	syncOctets;
	u_int32_t	syncFrames;
	u_int32_t	syncOverflows;
	u_int32_t	asyncOctets;
	u_int32_t	asyncFrames;
	u_int32_t	asyncRunts;
	u_int32_t	asyncOverflows;
	u_int32_t	asyncBadCheckSums;
};

/* Keep this in sync with the above structure definition */
#define NG_ASYNC_STATS_TYPE_INFO	{			\
	  { "syncOctets",	&ng_parse_uint32_type	},	\
	  { "syncFrames",	&ng_parse_uint32_type	},	\
	  { "syncOverflows",	&ng_parse_uint32_type	},	\
	  { "asyncOctets",	&ng_parse_uint32_type	},	\
	  { "asyncFrames",	&ng_parse_uint32_type	},	\
	  { "asyncRunts",	&ng_parse_uint32_type	},	\
	  { "asyncOverflows",	&ng_parse_uint32_type	},	\
	  { "asyncBadCheckSums",&ng_parse_uint32_type	},	\
	  { NULL }						\
}

/* Configuration for this node */
struct ng_async_cfg {
	u_char		enabled;	/* Turn encoding on/off */
	u_int16_t	amru;		/* Max receive async frame length */
	u_int16_t	smru;		/* Max receive sync frame length */
	u_int32_t	accm;		/* ACCM encoding */
};

/* Keep this in sync with the above structure definition */
#define NG_ASYNC_CONFIG_TYPE_INFO	{			\
	  { "enabled",		&ng_parse_int8_type	},	\
	  { "amru",		&ng_parse_uint16_type	},	\
	  { "smru",		&ng_parse_uint16_type	},	\
	  { "accm",		&ng_parse_hint32_type	},	\
	  { NULL }						\
}

/* Commands */
enum {
	NGM_ASYNC_CMD_GET_STATS = 1,	/* returns struct ng_async_stat */
	NGM_ASYNC_CMD_CLR_STATS,
	NGM_ASYNC_CMD_SET_CONFIG,	/* takes struct ng_async_cfg */
	NGM_ASYNC_CMD_GET_CONFIG,	/* returns struct ng_async_cfg */
};

#endif /* _NETGRAPH_NG_ASYNC_H_ */


code:
/*-
 * Copyright (c) 2003-2004 Benno Rice <benno@FreeBSD.org>
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR  ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR  BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/ng_atmllc.h 139823 2005-01-07 01:45:51Z imp $
 */

#ifndef	_NETGRAPH_ATMLLC_H_
#define	_NETGRAPH_ATMLLC_H_

/* Node type name and magic cookie. */
#define	NG_ATMLLC_NODE_TYPE	"atmllc"
#define	NGM_ATMLLC_COOKIE	1065246274

/* Hook names. */
#define	NG_ATMLLC_HOOK_ATM	"atm"
#define	NG_ATMLLC_HOOK_ETHER	"ether"
#define	NG_ATMLLC_HOOK_802_4	"ieee8024"
#define	NG_ATMLLC_HOOK_802_5	"ieee8025"
#define	NG_ATMLLC_HOOK_802_6	"ieee8026"
#define	NG_ATMLLC_HOOK_FDDI	"fddi"
#define	NG_ATMLLC_HOOK_BPDU	"bpdu"

#endif /* _NETGRAPH_ATMLLC_H_ */


code:
/*
 * ng_bpf.h
 */

/*-
 * Copyright (c) 1996-1999 Whistle Communications, Inc.
 * All rights reserved.
 *
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 *
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Archie Cobbs <archie@freebsd.org>
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/ng_bpf.h 141751 2005-02-12 18:10:26Z ru $
 * $Whistle: ng_bpf.h,v 1.3 1999/12/03 20:30:23 archie Exp $
 */

#ifndef _NETGRAPH_NG_BPF_H_
#define _NETGRAPH_NG_BPF_H_

/* Node type name and magic cookie */
#define NG_BPF_NODE_TYPE	"bpf"
#define NGM_BPF_COOKIE		944100792

/* Program structure for one hook */
struct ng_bpf_hookprog {
	char		thisHook[NG_HOOKSIZ];		/* name of hook */
	char		ifMatch[NG_HOOKSIZ];		/* match dest hook */
	char		ifNotMatch[NG_HOOKSIZ];		/* !match dest hook */
	int32_t		bpf_prog_len;			/* #insns in program */
	struct bpf_insn	bpf_prog[];			/* bpf program */
};

#define NG_BPF_HOOKPROG_SIZE(numInsn)	\
	(sizeof(struct ng_bpf_hookprog) + (numInsn) * sizeof(struct bpf_insn))

/* Keep this in sync with the above structure definition */
#define NG_BPF_HOOKPROG_TYPE_INFO(bptype)	{		\
	  { "thisHook",		&ng_parse_hookbuf_type	},	\
	  { "ifMatch",		&ng_parse_hookbuf_type	},	\
	  { "ifNotMatch",	&ng_parse_hookbuf_type	},	\
	  { "bpf_prog_len",	&ng_parse_int32_type	},	\
	  { "bpf_prog",		(bptype)		},	\
	  { NULL }						\
}

/* Statistics structure for one hook */
struct ng_bpf_hookstat {
	u_int64_t	recvFrames;
	u_int64_t	recvOctets;
	u_int64_t	recvMatchFrames;
	u_int64_t	recvMatchOctets;
	u_int64_t	xmitFrames;
	u_int64_t	xmitOctets;
};

/* Keep this in sync with the above structure definition */
#define NG_BPF_HOOKSTAT_TYPE_INFO	{			\
	  { "recvFrames",	&ng_parse_uint64_type	},	\
	  { "recvOctets",	&ng_parse_uint64_type	},	\
	  { "recvMatchFrames",	&ng_parse_uint64_type	},	\
	  { "recvMatchOctets",	&ng_parse_uint64_type	},	\
	  { "xmitFrames",	&ng_parse_uint64_type	},	\
	  { "xmitOctets",	&ng_parse_uint64_type	},	\
	  { NULL }						\
}

/* Netgraph commands */
enum {
	NGM_BPF_SET_PROGRAM = 1,	/* supply a struct ng_bpf_hookprog */
	NGM_BPF_GET_PROGRAM,		/* returns a struct ng_bpf_hookprog */
	NGM_BPF_GET_STATS,		/* supply name as char[NG_HOOKSIZ] */
	NGM_BPF_CLR_STATS,		/* supply name as char[NG_HOOKSIZ] */
	NGM_BPF_GETCLR_STATS,		/* supply name as char[NG_HOOKSIZ] */
};

#endif /* _NETGRAPH_NG_BPF_H_ */


code:
/*
 * ng_bridge.h
 */

/*-
 * Copyright (c) 2000 Whistle Communications, Inc.
 * All rights reserved.
 *
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 *
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Author: Archie Cobbs <archie@freebsd.org>
 *
 * $FreeBSD: release/9.0.0/sys/netgraph/ng_bridge.h 207680 2010-05-05 22:06:05Z zec $
 */

#ifndef _NETGRAPH_NG_BRIDGE_H_
#define _NETGRAPH_NG_BRIDGE_H_

/* Node type name and magic cookie */
#define NG_BRIDGE_NODE_TYPE		"bridge"
#define NGM_BRIDGE_COOKIE		967239368

/* Hook names */
#define NG_BRIDGE_HOOK_LINK_PREFIX	"link"	 /* append decimal integer */
#define NG_BRIDGE_HOOK_LINK_FMT		"link%d" /* for use with printf(3) */

/* Maximum number of supported links */
#define NG_BRIDGE_MAX_LINKS		32

/* Node configuration structure */
struct ng_bridge_config {
	u_char		ipfw[NG_BRIDGE_MAX_LINKS]; 	/* enable ipfw */
	u_char		debugLevel;		/* debug level */
	u_int32_t	loopTimeout;		/* link loopback mute time */
	u_int32_t	maxStaleness;		/* max host age before nuking */
	u_int32_t	minStableAge;		/* min time for a stable host */
};

/* Keep this in sync with the above structure definition */
#define NG_BRIDGE_CONFIG_TYPE_INFO(ainfo)	{		\
	  { "ipfw",		(ainfo)			},	\
	  { "debugLevel",	&ng_parse_uint8_type	},	\
	  { "loopTimeout",	&ng_parse_uint32_type	},	\
	  { "maxStaleness",	&ng_parse_uint32_type	},	\
	  { "minStableAge",	&ng_parse_uint32_type	},	\
	  { NULL }						\
}

/* Statistics structure (one for each link) */
struct ng_bridge_link_stats {
	u_int64_t	recvOctets;	/* total octets rec'd on link */
	u_int64_t	recvPackets;	/* total pkts rec'd on link */
	u_int64_t	recvMulticasts;	/* multicast pkts rec'd on link */
	u_int64_t	recvBroadcasts;	/* broadcast pkts rec'd on link */
	u_int64_t	recvUnknown;	/* pkts rec'd with unknown dest addr */
	u_int64_t	recvRunts;	/* pkts rec'd less than 14 bytes */
	u_int64_t	recvInvalid;	/* pkts rec'd with bogus source addr */
	u_int64_t	xmitOctets;	/* total octets xmit'd on link */
	u_int64_t	xmitPackets;	/* total pkts xmit'd on link */
	u_int64_t	xmitMulticasts;	/* multicast pkts xmit'd on link */
	u_int64_t	xmitBroadcasts;	/* broadcast pkts xmit'd on link */
	u_int64_t	loopDrops;	/* pkts dropped due to loopback */
	u_int64_t	loopDetects;	/* number of loop detections */
	u_int64_t	memoryFailures;	/* times couldn't get mem or mbuf */
};

/* Keep this in sync with the above structure definition */
#define NG_BRIDGE_STATS_TYPE_INFO	{			\
	  { "recvOctets",	&ng_parse_uint64_type	},	\
	  { "recvPackets",	&ng_parse_uint64_type	},	\
	  { "recvMulticast",	&ng_parse_uint64_type	},	\
	  { "recvBroadcast",	&ng_parse_uint64_type	},	\
	  { "recvUnknown",	&ng_parse_uint64_type	},	\
	  { "recvRunts",	&ng_parse_uint64_type	},	\
	  { "recvInvalid",	&ng_parse_uint64_type	},	\
	  { "xmitOctets",	&ng_parse_uint64_type	},	\
	  { "xmitPackets",	&ng_parse_uint64_type	},	\
	  { "xmitMulticasts",	&ng_parse_uint64_type	},	\
	  { "xmitBroadcasts",	&ng_parse_uint64_type	},	\
	  { "loopDrops",	&ng_parse_uint64_type	},	\
	  { "loopDetects",	&ng_parse_uint64_type	},	\
	  { "memoryFailures",	&ng_parse_uint64_type	},	\
	  { NULL }						\
}

/* Structure describing a single host */
struct ng_bridge_host {
	u_char		addr[6];	/* ethernet address */
	u_int16_t	linkNum;	/* link where addr can be found */
	u_int16_t	age;		/* seconds ago entry was created */
	u_int16_t	staleness;	/* seconds ago host last heard from */
};

/* Keep this in sync with the above structure definition */
#define NG_BRIDGE_HOST_TYPE_INFO(entype)	{		\
	  { "addr",		(entype)		},	\
	  { "linkNum",		&ng_parse_uint16_type	},	\
	  { "age",		&ng_parse_uint16_type	},	\
	  { "staleness",	&ng_parse_uint16_type	},	\
	  { NULL }						\
}

/* Structure returned by NGM_BRIDGE_GET_TABLE */
struct ng_bridge_host_ary {
	u_int32_t		numHosts;
	struct ng_bridge_host	hosts[];
};

/* Keep this in sync with the above structure definition */
#define NG_BRIDGE_HOST_ARY_TYPE_INFO(harytype)	{		\
	  { "numHosts",		&ng_parse_uint32_type	},	\
	  { "hosts",		(harytype)		},	\
	  { NULL }						\
}

/* Netgraph control messages */
enum {
	NGM_BRIDGE_SET_CONFIG = 1,	/* set node configuration */
	NGM_BRIDGE_GET_CONFIG,		/* get node configuration */
	NGM_BRIDGE_RESET,		/* reset (forget) all information */
	NGM_BRIDGE_GET_STATS,		/* get link stats */
	NGM_BRIDGE_CLR_STATS,		/* clear link stats */
	NGM_BRIDGE_GETCLR_STATS,	/* atomically get & clear link stats */
	NGM_BRIDGE_GET_TABLE,		/* get link table */
	NGM_BRIDGE_SET_PERSISTENT,	/* set persistent mode */
};

#endif /* _NETGRAPH_NG_BRIDGE_H_ */