xref: /freebsd/share/man/man4/netgraph.4 (revision a14a0223ae1b172e96dd2a1d849e22026a98b692)
1.\" Copyright (c) 1996-1999 Whistle Communications, Inc.
2.\" All rights reserved.
3.\"
4.\" Subject to the following obligations and disclaimer of warranty, use and
5.\" redistribution of this software, in source or object code forms, with or
6.\" without modifications are expressly permitted by Whistle Communications;
7.\" provided, however, that:
8.\" 1. Any and all reproductions of the source or object code must include the
9.\"    copyright notice above and the following disclaimer of warranties; and
10.\" 2. No rights are granted, in any manner or form, to use Whistle
11.\"    Communications, Inc. trademarks, including the mark "WHISTLE
12.\"    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
13.\"    such appears in the above copyright notice or in the software.
14.\"
15.\" THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
16.\" TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
17.\" REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
18.\" INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
19.\" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
20.\" WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
21.\" REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
22.\" SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
23.\" IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
24.\" RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
25.\" WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
26.\" PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
27.\" SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
28.\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29.\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30.\" THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
31.\" OF SUCH DAMAGE.
32.\"
33.\" Authors: Julian Elischer <julian@whistle.com>
34.\"          Archie Cobbs <archie@whistle.com>
35.\"
36.\" $FreeBSD$
37.\" $Whistle: netgraph.4,v 1.7 1999/01/28 23:54:52 julian Exp $
38.\"
39.Dd January 19, 1999
40.Dt NETGRAPH 4
41.Os FreeBSD
42.Sh NAME
43.Nm netgraph
44.Nd graph based kernel networking subsystem
45.Sh DESCRIPTION
46The
47.Nm
48system provides a uniform and modular system for the implementation
49of kernel objects which perform various networking functions. The objects,
50known as
51.Em nodes ,
52can be arranged into arbitrarily complicated graphs. Nodes have
53.Em hooks
54which are used to connect two nodes together, forming the edges in the graph.
55Nodes communicate along the edges to process data, implement protocols, etc.
56.Pp
57The aim of
58.Nm
59is to supplement rather than replace the existing kernel networking
60infrastructure. It provides:
61.Pp
62.Bl -bullet -compact -offset 2n
63.It
64A flexible way of combining protocol and link level drivers
65.It
66A modular way to implement new protocols
67.It
68A common framework for kernel entities to inter-communicate
69.It
70A reasonably fast, kernel-based implementation
71.El
72.Sh Nodes and Types
73The most fundamental concept in
74.Nm
75is that of a
76.Em node .
77All nodes implement a number of predefined methods which allow them
78to interact with other nodes in a well defined manner.
79.Pp
80Each node has a
81.Em type ,
82which is a static property of the node determined at node creation time.
83A node's type is described by a unique ASCII type name.
84The type implies what the node does and how it may be connected
85to other nodes.
86.Pp
87In object-oriented language, types are classes and nodes are instances
88of their respective class. All node types are subclasses of the generic node
89type, and hence inherit certain common functionality and capabilities
90(e.g., the ability to have an ASCII name).
91.Pp
92Nodes may be assigned a globally unique ASCII name which can be
93used to refer to the node.
94The name must not contain the characters ``.'' or  ``:'' and is limited to
95.Dv "NG_NODELEN + 1"
96characters (including NUL byte).
97.Pp
98Each node instance has a unique
99.Em ID number
100which is expressed as a 32-bit hex value. This value may be used to
101refer to a node when there is no ASCII name assigned to it.
102.Sh Hooks
103Nodes are connected to other nodes by connecting a pair of
104.Em hooks ,
105one from each node. Data flows bidirectionally between nodes along
106connected pairs of hooks.  A node may have as many hooks as it
107needs, and may assign whatever meaning it wants to a hook.
108.Pp
109Hooks have these properties:
110.Pp
111.Bl -bullet -compact -offset 2n
112.It
113A hook has an ASCII name which is unique among all hooks
114on that node (other hooks on other nodes may have the same name).
115The name must not contain a ``.'' or a ``:''  and is
116limited to
117.Dv "NG_HOOKLEN + 1"
118characters (including NUL byte).
119.It
120A hook is always connected to another hook. That is, hooks are
121created at the time they are connected, and breaking an edge by
122removing either hook destroys both hooks.
123.El
124.Pp
125A node may decide to assign special meaning to some hooks.
126For example, connecting to the hook named ``debug'' might trigger
127the node to start sending debugging information to that hook.
128.Sh Data Flow
129Two types of information flow between nodes: data messages and
130control messages. Data messages are passed in mbuf chains along the edges
131in the graph, one edge at a time. The first mbuf in a chain must have the
132.Dv M_PKTHDR
133flag set. Each node decides how to handle data coming in on its hooks.
134.Pp
135Control messages are type-specific structures sent from one node directly
136to an arbitrary other node. There are two ways to address such a message. If
137there is a sequence of edges connecting the two nodes, the message
138may be ``source routed'' by specifying the corresponding sequence
139of hooks as the destination address for the message (relative
140addressing).  Otherwise, the recipient node global ASCII name
141(or equivalent ID based name) is used as the destination address
142for the message (absolute addressing).  The two types of addressing
143may be combined, by specifying an absolute start node and a sequence
144of hooks.
145.Pp
146Messages often represent commands that are followed by a reply message
147in the reverse direction. To facilitate this, the recipient of a
148control message is supplied with a ``return address'' that is suitable
149for addressing a reply.
150.Pp
151Each control message contains a 32 bit value called a
152.Em typecookie
153indicating the type of the message, i.e., how to interpret it.
154Typically each type defines a unique typecookie for the messages
155that it understands.  However, a node may choose to recognize and
156implement more than one type of message.
157.Sh Netgraph is Functional
158In order to minimize latency, most
159.Nm netgraph
160operations are functional.
161That is, data and control messages are delivered by making function
162calls rather than by using queues and mailboxes.  For example, if node
163A wishes to send a data mbuf to neighboring node B, it calls the
164generic
165.Nm
166data delivery function. This function in turn locates
167node B and calls B's ``receive data'' method. While this mode of operation
168results in good performance, it has a few implications for node
169developers:
170.Pp
171.Bl -bullet -compact -offset 2n
172.It
173Whenever a node delivers a data or control message, the node
174may need to allow for the possibility of receiving a returning message
175before the original delivery function call returns.
176.It
177Netgraph nodes and support routines generally run at
178.Dv "splnet()" .
179However, some nodes may want to send data and control messages
180from a different priority level. Netgraph supplies queueing routines which
181utilize the NETISR system to move message delivery to
182.Dv "splnet()" .
183Note that messages are always received at
184.Dv "splnet()" .
185.It
186It's possible for an infinite loop to occur if the graph contains cycles.
187.El
188.Pp
189So far, these issues have not proven problematical in practice.
190.Sh Interaction With Other Parts of the Kernel
191A node may have a hidden interaction with other components of the
192kernel outside of the
193.Nm
194subsystem, such as device hardware,
195kernel protocol stacks, etc.  In fact, one of the benefits of
196.Nm
197is the ability to join disparate kernel networking entities together in a
198consistent communication framework.
199.Pp
200An example is the node type
201.Em socket
202which is both a netgraph node and a
203.Xr socket 2
204BSD socket in the protocol family
205.Dv PF_NETGRAPH .
206Socket nodes allow user processes to participate in
207.Nm netgraph .
208Other nodes communicate with socket nodes using the usual methods, and the
209node hides the fact that it is also passing information to and from a
210cooperating user process.
211.Pp
212Another example is a device driver that presents
213a node interface to the hardware.
214.Sh Node Methods
215Nodes are notified of the following actions via function calls
216to the following node methods (all at
217.Dv "splnet()" )
218and may accept or reject that action (by returning the appropriate
219error code):
220.Bl -tag -width xxx
221.It Creation of a new node
222The constructor for the type is called. If creation of a new node is
223allowed, the constructor must call the generic node creation
224function (in object-oriented terms, the superclass constructor)
225and then allocate any special resources it needs. For nodes that
226correspond to hardware, this is typically done during the device
227attach routine. Often a global ASCII name corresponding to the
228device name is assigned here as well.
229.It Creation of a new hook
230The hook is created and tentatively
231linked to the node, and the node is told about the name that will be
232used to describe this hook. The node sets up any special data structures
233it needs, or may reject the connection, based on the name of the hook.
234.It Successful connection of two hooks
235After both ends have accepted their
236hooks, and the links have been made, the nodes get a chance to
237find out who their peer is across the link and can then decide to reject
238the connection. Tear-down is automatic.
239.It Destruction of a hook
240The node is notified of a broken connection. The node may consider some hooks
241to be critical to operation and others to be expendable: the disconnection
242of one hook may be an acceptable event while for another it
243may effect a total shutdown for the node.
244.It Shutdown of a node
245This method allows a node to clean up
246and to ensure that any actions that need to be performed
247at this time are taken. The method must call the generic (i.e., superclass)
248node destructor to get rid of the generic components of the node.
249Some nodes (usually associated with a piece of hardware) may be
250.Em persistent
251in that a shutdown breaks all edges and resets the node,
252but doesn't remove it, in which case the generic destructor is not called.
253.El
254.Sh Sending and Receiving Data
255Three other methods are also supported by all nodes:
256.Bl -tag -width xxx
257.It Receive data message
258An mbuf chain is passed to the node.
259The node is notified on which hook the data arrived,
260and can use this information in its processing decision.
261The node must must always
262.Dv m_freem()
263the mbuf chain on completion or error, or pass it on to another node
264(or kernel module) which will then be responsible for freeing it.
265.Pp
266In addition to the mbuf chain itself there is also a pointer to a
267structure describing meta-data about the message
268(e.g. priority information). This pointer may be
269.Dv NULL
270if there is no additional information. The format for this information is
271described in
272.Dv netgraph.h .
273The memory for meta-data must allocated via
274.Dv malloc()
275with type
276.Dv M_NETGRAPH .
277As with the data itself, it is the receiver's responsibility to
278.Dv free()
279the meta-data. If the mbuf chain is freed the meta-data must
280be freed at the same time. If the meta-data is freed but the
281real data on is passed on, then a
282.Dv NULL
283pointer must be substituted.
284.Pp
285The receiving node may decide to defer the data by queueing it in the
286.Nm
287NETISR system (see below).
288.Pp
289The structure and use of meta-data is still experimental, but is presently used in
290frame-relay to indicate that management packets should be queued for transmission
291at a higher priority than data packets. This is required for
292conformance with Frame Relay standards.
293.Pp
294.It Receive queued data message
295Usually this will be the same function as
296.Em Receive data message.
297This is the entry point called when a data message is being handed to
298the node after having been queued in the NETISR system.
299This allows a node to decide in the
300.Em Receive data message
301method that a message should be deferred and queued,
302and be sure that when it is processed from the queue,
303it will not be queued again.
304.It Receive control message
305This method is called when a control message is addressed to the node.
306A return address is always supplied, giving the address of the node
307that originated the message so a reply message can be sent anytime later.
308.Pp
309It is possible for a synchronous reply to be made, and in fact this
310is more common in practice.
311This is done by setting a pointer (supplied as an extra function parameter)
312to point to the reply.
313Then when the control message delivery function returns,
314the caller can check if this pointer has been made non-NULL,
315and if so then it points to the reply message allocated via
316.Dv malloc()
317and containing the synchronous response. In both directions,
318(request and response) it is up to the
319receiver of that message to
320.Dv free()
321the control message buffer. All control messages and replies are
322allocated with
323.Dv malloc()
324type
325.Dv M_NETGRAPH .
326.El
327.Pp
328Much use has been made of reference counts, so that nodes being
329free'd of all references are automatically freed, and this behaviour
330has been tested and debugged to present a consistent and trustworthy
331framework for the ``type module'' writer to use.
332.Sh Addressing
333The
334.Nm
335framework provides an unambiguous and simple to use method of specifically
336addressing any single node in the graph. The naming of a node is
337independent of its type, in that another node, or external component
338need not know anything about the node's type in order to address it so as
339to send it a generic message type. Node and hook names should be
340chosen so as to make addresses meaningful.
341.Pp
342Addresses are either absolute or relative. An absolute address begins
343with a node name, (or ID), followed by a colon, followed by a sequence of hook
344names separated by periods. This addresses the node reached by starting
345at the named node and following the specified sequence of hooks.
346A relative address includes only the sequence of hook names, implicitly
347starting hook traversal at the local node.
348.Pp
349There are a couple of special possibilities for the node name.
350The name ``.'' (referred to as ``.:'') always refers to the local node.
351Also, nodes that have no global name may be addressed by their ID numbers,
352by enclosing the hex representation of the ID number within square brackets.
353Here are some examples of valid netgraph addresses:
354.Bd -literal -offset 4n -compact
355
356  .:
357  foo:
358  .:hook1
359  foo:hook1.hook2
360  [f057cd80]:hook1
361.Ed
362.Pp
363Consider the following set of nodes might be created for a site with
364a single physical frame relay line having two active logical DLCI channels,
365with RFC-1490 frames on DLCI 16 and PPP frames over DLCI 20:
366.Pp
367.Bd -literal
368[type SYNC ]                  [type FRAME]                 [type RFC1490]
369[ "Frame1" ](uplink)<-->(data)[<un-named>](dlci16)<-->(mux)[<un-named>  ]
370[    A     ]                  [    B     ](dlci20)<---+    [     C      ]
371                                                      |
372                                                      |      [ type PPP ]
373                                                      +>(mux)[<un-named>]
374                                                             [    D     ]
375.Ed
376.Pp
377One could always send a control message to node C from anywhere
378by using the name
379.Em "Frame1:uplink.dlci16" .
380Similarly,
381.Em "Frame1:uplink.dlci20"
382could reliably be used to reach node D, and node A could refer
383to node B as
384.Em ".:uplink" ,
385or simply
386.Em "uplink" .
387Conversely, B can refer to A as
388.Em "data" .
389The address
390.Em "mux.data"
391could be used by both nodes C and D to address a message to node A.
392.Pp
393Note that this is only for
394.Em control messages .
395Data messages are routed one hop at a time, by specifying the departing
396hook, with each node making the next routing decision. So when B
397receives a frame on hook
398.Em data
399it decodes the frame relay header to determine the DLCI,
400and then forwards the unwrapped frame to either C or D.
401.Pp
402A similar graph might be used to represent multi-link PPP running
403over an ISDN line:
404.Pp
405.Bd -literal
406[ type BRI ](B1)<--->(link1)[ type MPP  ]
407[  "ISDN1" ](B2)<--->(link2)[ (no name) ]
408[          ](D) <-+
409                  |
410 +----------------+
411 |
412 +->(switch)[ type Q.921 ](term1)<---->(datalink)[ type Q.931 ]
413            [ (no name)  ]                       [ (no name)  ]
414.Ed
415.Sh Netgraph Structures
416Interesting members of the node and hook structures are shown below:
417.Bd -literal
418struct  ng_node {
419  char    *name;                /* Optional globally unique name */
420  void    *private;             /* Node implementation private info */
421  struct  ng_type *type;        /* The type of this node */
422  int     refs;                 /* Number of references to this struct */
423  int     numhooks;             /* Number of connected hooks */
424  hook_p  hooks;                /* Linked list of (connected) hooks */
425};
426typedef struct ng_node *node_p;
427
428struct  ng_hook {
429  char           *name;         /* This node's name for this hook */
430  void           *private;      /* Node implementation private info */
431  int            refs;          /* Number of references to this struct */
432  struct ng_node *node;         /* The node this hook is attached to */
433  struct ng_hook *peer;         /* The other hook in this connected pair */
434  struct ng_hook *next;         /* Next in list of hooks for this node */
435};
436typedef struct ng_hook *hook_p;
437.Ed
438.Pp
439The maintenance of the name pointers, reference counts, and linked list
440of hooks for each node is handled automatically by the
441.Nm
442subsystem.
443Typically a node's private info contains a back-pointer to the node or hook
444structure, which counts as a new reference that must be registered by
445incrementing
446.Dv "node->refs" .
447.Pp
448From a hook you can obtain the corresponding node, and from
449a node the list of all active hooks.
450.Pp
451Node types are described by this structure:
452.Bd -literal
453struct ng_type {
454  u_int32_t version;                    /* Must equal NG_VERSION */
455  const  char *name;                    /* Unique type name */
456
457  /* Module event handler */
458  modeventhand_t  mod_event;            /* Handle load/unload (optional) */
459
460  /* Constructor */
461  int    (*constructor)(node_p *node);  /* Create a new node */
462
463  /** Methods using the node **/
464  int    (*rcvmsg)(node_p node,         /* Receive control message */
465            struct ng_mesg *msg,                /* The message */
466            const char *retaddr,                /* Return address */
467            struct ng_mesg **resp);             /* Synchronous response */
468  int    (*shutdown)(node_p node);      /* Shutdown this node */
469  int    (*newhook)(node_p node,        /* create a new hook */
470            hook_p hook,                        /* Pre-allocated struct */
471            const char *name);                  /* Name for new hook */
472
473  /** Methods using the hook **/
474  int    (*connect)(hook_p hook);       /* Confirm new hook attachment */
475  int    (*rcvdata)(hook_p hook,        /* Receive data on a hook */
476            struct mbuf *m,                     /* The data in an mbuf */
477            meta_p meta);                       /* Meta-data, if any */
478  int    (*disconnect)(hook_p hook);    /* Notify disconnection of hook */
479};
480.Ed
481.Pp
482Control messages have the following structure:
483.Bd -literal
484#define NG_CMDSTRLEN    15      /* Max command string (16 with null) */
485
486struct ng_mesg {
487  struct ng_msghdr {
488    u_char      version;        /* Must equal NG_VERSION */
489    u_char      spare;          /* Pad to 2 bytes */
490    u_short     arglen;         /* Length of cmd/resp data */
491    u_long      flags;          /* Message status flags */
492    u_long      token;          /* Reply should have the same token */
493    u_long      typecookie;     /* Node type understanding this message */
494    u_long      cmd;            /* Command identifier */
495    u_char      cmdstr[NG_CMDSTRLEN+1]; /* Cmd string (for debug) */
496  } header;
497  char  data[0];                /* Start of cmd/resp data */
498};
499
500#define NG_VERSION      1               /* Netgraph version */
501#define NGF_ORIG        0x0000          /* Command */
502#define NGF_RESP        0x0001          /* Response */
503.Ed
504.Pp
505Control messages have the fixed header shown above, followed by a
506variable length data section which depends on the type cookie
507and the command. Each field is explained below:
508.Bl -tag -width xxx
509.It Dv version
510Indicates the version of netgraph itself. The current version is
511.Dv NG_VERSION .
512.It Dv arglen
513This is the length of any extra arguments, which begin at
514.Dv data .
515.It Dv flags
516Indicates whether this is a command or a response control message.
517.It Dv token
518The
519.Dv token
520is a means by which a sender can match a reply message to the
521corresponding command message; the reply always has the same token.
522.Pp
523.It Dv typecookie
524The corresponding node type's unique 32-bit value.
525If a node doesn't recognize the type cookie it must reject the message
526by returning
527.Er EINVAL .
528.Pp
529Each type should have an include file that defines the commands,
530argument format, and cookie for its own messages.
531The typecookie
532insures that the same header file was included by both sender and
533receiver; when an incompatible change in the header file is made,
534the typecookie
535.Em must
536be changed.
537The de facto method for generating unique type cookies is to take the
538seconds from the epoch at the time the header file is written
539(i.e., the output of
540.Dv "date -u +'%s'" ")."
541.Pp
542There is a predefined typecookie
543.Dv NGM_GENERIC_COOKIE
544for the ``generic'' node type, and
545a corresponding set of generic messages which all nodes understand.
546The handling of these messages is automatic.
547.It Dv command
548The identifier for the message command. This is type specific,
549and is defined in the same header file as the typecookie.
550.It Dv cmdstr
551Room for a short human readable version of ``command'' (for debugging
552purposes only).
553.El
554.Pp
555Some modules may choose to implement messages from more than one
556of the header files and thus recognize more than one type cookie.
557.Sh Generic Control Messages
558There are a number of standard predefined messages that will work
559for any node, as they are supported directly by the framework itself.
560These are defined in
561.Dv ng_message.h
562along with the basic layout of messages and other similar information.
563.Bl -tag -width xxx
564.It Dv NGM_CONNECT
565Connect to another node, using the supplied hook names on either end.
566.It Dv NGM_MKPEER
567Construct a node of the given type and then connect to it using the
568supplied hook names.
569.It Dv NGM_SHUTDOWN
570The target node should disconnect from all its neighbours and shut down.
571Persistent nodes such as those representing physical hardware
572might not disappear from the node namespace, but only reset themselves.
573The node must disconnect all of its hooks.
574This may result in neighbors shutting themselves down, and possibly a
575cascading shutdown of the entire connected graph.
576.It Dv NGM_NAME
577Assign a name to a node. Nodes can exist without having a name, and this
578is the default for nodes created using the
579.Dv NGM_MKPEER
580method. Such nodes can only be addressed relatively or by their ID number.
581.It Dv NGM_RMHOOK
582Ask the node to break a hook connection to one of its neighbours.
583Both nodes will have their ``disconnect'' method invoked.
584Either node may elect to totally shut down as a result.
585.It Dv NGM_NODEINFO
586Asks the target node to describe itself. The four returned fields
587are the node name (if named), the node type, the node ID and the
588number of hooks attached. The ID is an internal number unique to that node.
589.It Dv NGM_LISTHOOKS
590This returns the information given by
591.Dv NGM_NODEINFO ,
592but in addition
593includes an array of fields describing each link, and the description for
594the node at the far end of that link.
595.It Dv NGM_LISTNAMES
596This returns an array of node descriptions (as for
597.Dv NGM_NODEINFO ")"
598where each entry of the array describes a named node.
599All named nodes will be described.
600.It Dv NGM_LISTNODES
601This is the same as
602.Dv NGM_LISTNAMES
603except that all nodes are listed regardless of whether they have a name or not.
604.It Dv NGM_LISTTYPES
605This returns a list of all currently installed netgraph types.
606.It Dv NGM_TEXT_STATUS
607The node may return a text formatted status message.
608The status information is determined entirely by the node type.
609It is the only "generic" message
610that requires any support within the node itself and as such the node may
611elect to not support this message. The text response must be less than
612.Dv NG_TEXTRESPONSE
613bytes in length (presently 1024). This can be used to return general
614status information in human readable form.
615.El
616.Sh Metadata
617Data moving through the
618.Nm
619system can be accompanied by meta-data that describes some
620aspect of that data. The form of the meta-data is a fixed header,
621which contains enough information for most uses, and can optionally
622be supplemented by trailing
623.Em option
624structures, which contain a
625.Em cookie
626(see the section on control messages), an identifier, a length and optional
627data. If a node does not recognize the cookie associated with an option,
628it should ignore that option.
629.Pp
630Meta data might include such things as priority, discard eligibility,
631or special processing requirements. It might also mark a packet for
632debug status, etc. The use of meta-data is still experimental.
633.Sh INITIALIZATION
634The base
635.Nm
636code may either be statically compiled
637into the kernel or else loaded dynamically as a KLD via
638.Xr kldload 8 .
639In the former case, include
640.Bd -literal -offset 4n -compact
641
642   options NETGRAPH
643
644.Ed
645in your kernel configuration file. You may also include selected
646node types in the kernel compilation, for example:
647.Bd -literal -offset 4n -compact
648
649   options NETGRAPH
650   options NETGRAPH_SOCKET
651   options NETGRAPH_ECHO
652
653.Ed
654.Pp
655Once the
656.Nm
657subsystem is loaded, individual node types may be loaded at any time
658as KLD modules via
659.Xr kldload 8 .
660Moreover,
661.Nm
662knows how to automatically do this; when a request to create a new
663node of unknown type
664.Em type
665is made,
666.Nm
667will attempt to load the KLD module
668.Dv ng_type.ko .
669.Pp
670Types can also be installed at boot time, as certain device drivers
671may want to export each instance of the device as a netgraph node.
672.Pp
673In general, new types can be installed at any time from within the
674kernel by calling
675.Dv ng_newtype() ,
676supplying a pointer to the type's
677.Dv struct ng_type
678structure.
679.Pp
680The
681.Dv "NETGRAPH_INIT()"
682macro automates this process by using a linker set.
683.Sh EXISTING NODE TYPES
684Several node types currently exist. Each is fully documented
685in its own man page:
686.Bl -tag -width xxx
687.It SOCKET
688The socket type implements two new sockets in the new protocol domain
689.Dv PF_NETGRAPH .
690The new sockets protocols are
691.Dv NG_DATA
692and
693.Dv NG_CONTROL ,
694both of type
695.Dv SOCK_DGRAM .
696Typically one of each is associated with a socket node.
697When both sockets have closed, the node will shut down. The
698.Dv NG_DATA
699socket is used for sending and receiving data, while the
700.Dv NG_CONTROL
701socket is used for sending and receiving control messages.
702Data and control messages are passed using the
703.Xr sendto 2
704and
705.Xr recvfrom 2
706calls, using a
707.Dv struct sockaddr_ng
708socket address.
709.Pp
710.It HOLE
711Responds only to generic messages and is a ``black hole'' for data,
712Useful for testing. Always accepts new hooks.
713.Pp
714.It ECHO
715Responds only to generic messages and always echoes data back through the
716hook from which it arrived. Returns any non generic messages as their
717own response. Useful for testing.  Always accepts new hooks.
718.Pp
719.It TEE
720This node is useful for ``snooping.'' It has 4 hooks:
721.Dv left ,
722.Dv right ,
723.Dv left2right ,
724and
725.Dv right2left .
726Data entering from the right is passed to the left and duplicated on
727.Dv right2left,
728and data entering from the left is passed to the right and
729duplicated on
730.Dv left2right .
731Data entering from
732.Dv left2right
733is sent to the right and data from
734.Dv right2left
735to left.
736.Pp
737.It RFC1490 MUX
738Encapsulates/de-encapsulates frames encoded according to RFC 1490.
739Has a hook for the encapsulated packets (``downstream'') and one hook
740for each protocol (i.e., IP, PPP, etc.).
741.Pp
742.It FRAME RELAY MUX
743Encapsulates/de-encapsulates Frame Relay frames.
744Has a hook for the encapsulated packets (``downstream'') and one hook
745for each DLCI.
746.Pp
747.It FRAME RELAY LMI
748Automatically handles frame relay
749``LMI'' (link management interface) operations and packets.
750Automatically probes and detects which of several LMI standards
751is in use at the exchange.
752.Pp
753.It TTY
754This node is also a line discipline. It simply converts between mbuf
755frames and sequential serial data, allowing a tty to appear as a netgraph
756node. It has a programmable ``hotkey'' character.
757.Pp
758.It ASYNC
759This node encapsulates and de-encapsulates asynchronous frames
760according to RFC 1662. This is used in conjunction with the TTY node
761type for supporting PPP links over asynchronous serial lines.
762.Pp
763.It INTERFACE
764This node is also a system networking interface. It has hooks representing
765each protocol family (IP, AppleTalk, IPX, etc.) and appears in the output of
766.Xr ifconfig 8 .
767The interfaces are named
768.Em ng0 ,
769.Em ng1 ,
770etc.
771.El
772.Sh NOTES
773Whether a named node exists can be checked by trying to send a control message
774to it (e.g.,
775.Dv NGM_NODEINFO
776).
777If it does not exist,
778.Er ENOENT
779will be returned.
780.Pp
781All data messages are mbuf chains with the M_PKTHDR flag set.
782.Pp
783Nodes are responsible for freeing what they allocate.
784There are three exceptions:
785.Bl -tag -width xxxx
786.It 1
787Mbufs sent across a data link are never to be freed by the sender.
788.It 2
789Any meta-data information traveling with the data has the same restriction.
790It might be freed by any node the data passes through, and a
791.Dv NULL
792passed onwards, but the caller will never free it.
793Two macros
794.Dv "NG_FREE_META(meta)"
795and
796.Dv "NG_FREE_DATA(m, meta)"
797should be used if possible to free data and meta data (see
798.Dv netgraph.h ")."
799.It 3
800Messages sent using
801.Dv ng_send_message()
802are freed by the callee. As in the case above, the addresses
803associated with the message are freed by whatever allocated them so the
804recipient should copy them if it wants to keep that information.
805.El
806.Sh FILES
807.Bl -tag -width xxxxx -compact
808.It Pa /sys/netgraph/netgraph.h
809Definitions for use solely within the kernel by
810.Nm
811nodes.
812.It Pa /sys/netgraph/ng_message.h
813Definitions needed by any file that needs to deal with
814.Nm
815messages.
816.It Pa /sys/netgraph/ng_socket.h
817Definitions needed to use
818.Nm
819socket type nodes.
820.It Pa /sys/netgraph/ng_{type}.h
821Definitions needed to use
822.Nm
823{type}
824nodes, including the type cookie definition.
825.It Pa /modules/netgraph.ko
826Netgraph subsystem loadable KLD module.
827.It Pa /modules/ng_{type}.ko
828Loadable KLD module for node type {type}.
829.El
830.Sh USER MODE SUPPORT
831There is a library for supporting user-mode programs that wish
832to interact with the netgraph system. See
833.Xr netgraph 3
834for details.
835.Pp
836Two user-mode support programs,
837.Xr ngctl 8
838and
839.Xr nghook 8 ,
840are available to assist manual configuration and debugging.
841.Pp
842There are a few useful techniques for debugging new node types.
843First, implementing new node types in user-mode first
844makes debugging easier.
845The
846.Em tee
847node type is also useful for debugging, especially in conjunction with
848.Xr ngctl 8
849and
850.Xr nghook 8 .
851.Sh SEE ALSO
852.Xr socket 2 ,
853.Xr netgraph 3 ,
854.Xr ngctl 8 ,
855.Xr nghook 8 ,
856.Xr ng_async 8 .
857.Xr ng_cisco 8 .
858.Xr ng_echo 8 .
859.Xr ng_frame_relay 8 .
860.Xr ng_hole 8 .
861.Xr ng_iface 8 .
862.Xr ng_lmi 8 .
863.Xr ng_rfc1490 8 .
864.Xr ng_socket 8 .
865.Xr ng_tee 8 .
866.Xr ng_tty 8 .
867.Xr ng_UI 8 .
868.Xr ng_{type} 8 .
869.Sh HISTORY
870The
871.Nm
872system was designed and first implemented at Whistle Communications, Inc.
873in a version FreeBSD 2.2 customized for the Whistle InterJet.
874.Sh AUTHORS
875Julian Elischer <julian@whistle.com>, with contributions by
876Archie Cobbs <archie@whistle.com>.
877