Deleted Added
full compact
ng_ppp.c (129823) ng_ppp.c (131155)
1
2/*
3 * ng_ppp.c
4 *
5 * Copyright (c) 1996-2000 Whistle Communications, Inc.
6 * All rights reserved.
7 *
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 * copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 * Communications, Inc. trademarks, including the mark "WHISTLE
16 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 * such appears in the above copyright notice or in the software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35 * OF SUCH DAMAGE.
36 *
37 * Author: Archie Cobbs <archie@freebsd.org>
38 *
1
2/*
3 * ng_ppp.c
4 *
5 * Copyright (c) 1996-2000 Whistle Communications, Inc.
6 * All rights reserved.
7 *
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 * copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 * Communications, Inc. trademarks, including the mark "WHISTLE
16 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 * such appears in the above copyright notice or in the software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35 * OF SUCH DAMAGE.
36 *
37 * Author: Archie Cobbs <archie@freebsd.org>
38 *
39 * $FreeBSD: head/sys/netgraph/ng_ppp.c 129823 2004-05-29 00:51:19Z julian $
39 * $FreeBSD: head/sys/netgraph/ng_ppp.c 131155 2004-06-26 22:24:16Z julian $
40 * $Whistle: ng_ppp.c,v 1.24 1999/11/01 09:24:52 julian Exp $
41 */
42
43/*
44 * PPP node type.
45 */
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/limits.h>
51#include <sys/time.h>
52#include <sys/mbuf.h>
53#include <sys/malloc.h>
54#include <sys/errno.h>
55#include <sys/ctype.h>
56
57#include <netgraph/ng_message.h>
58#include <netgraph/netgraph.h>
59#include <netgraph/ng_parse.h>
60#include <netgraph/ng_ppp.h>
61#include <netgraph/ng_vjc.h>
62
63#ifdef NG_SEPARATE_MALLOC
64MALLOC_DEFINE(M_NETGRAPH_PPP, "netgraph_ppp", "netgraph ppp node");
65#else
66#define M_NETGRAPH_PPP M_NETGRAPH
67#endif
68
69#define PROT_VALID(p) (((p) & 0x0101) == 0x0001)
70#define PROT_COMPRESSABLE(p) (((p) & 0xff00) == 0x0000)
71
72/* Some PPP protocol numbers we're interested in */
73#define PROT_APPLETALK 0x0029
74#define PROT_COMPD 0x00fd
75#define PROT_CRYPTD 0x0053
76#define PROT_IP 0x0021
77#define PROT_IPV6 0x0057
78#define PROT_IPX 0x002b
79#define PROT_LCP 0xc021
80#define PROT_MP 0x003d
81#define PROT_VJCOMP 0x002d
82#define PROT_VJUNCOMP 0x002f
83
84/* Multilink PPP definitions */
85#define MP_MIN_MRRU 1500 /* per RFC 1990 */
86#define MP_INITIAL_SEQ 0 /* per RFC 1990 */
87#define MP_MIN_LINK_MRU 32
88
89#define MP_SHORT_SEQ_MASK 0x00000fff /* short seq # mask */
90#define MP_SHORT_SEQ_HIBIT 0x00000800 /* short seq # high bit */
91#define MP_SHORT_FIRST_FLAG 0x00008000 /* first fragment in frame */
92#define MP_SHORT_LAST_FLAG 0x00004000 /* last fragment in frame */
93
94#define MP_LONG_SEQ_MASK 0x00ffffff /* long seq # mask */
95#define MP_LONG_SEQ_HIBIT 0x00800000 /* long seq # high bit */
96#define MP_LONG_FIRST_FLAG 0x80000000 /* first fragment in frame */
97#define MP_LONG_LAST_FLAG 0x40000000 /* last fragment in frame */
98
99#define MP_NOSEQ 0x7fffffff /* impossible sequence number */
100
101/* Sign extension of MP sequence numbers */
102#define MP_SHORT_EXTEND(s) (((s) & MP_SHORT_SEQ_HIBIT) ? \
103 ((s) | ~MP_SHORT_SEQ_MASK) \
104 : ((s) & MP_SHORT_SEQ_MASK))
105#define MP_LONG_EXTEND(s) (((s) & MP_LONG_SEQ_HIBIT) ? \
106 ((s) | ~MP_LONG_SEQ_MASK) \
107 : ((s) & MP_LONG_SEQ_MASK))
108
109/* Comparision of MP sequence numbers. Note: all sequence numbers
110 except priv->xseq are stored with the sign bit extended. */
111#define MP_SHORT_SEQ_DIFF(x,y) MP_SHORT_EXTEND((x) - (y))
112#define MP_LONG_SEQ_DIFF(x,y) MP_LONG_EXTEND((x) - (y))
113
114#define MP_RECV_SEQ_DIFF(priv,x,y) \
115 ((priv)->conf.recvShortSeq ? \
116 MP_SHORT_SEQ_DIFF((x), (y)) : \
117 MP_LONG_SEQ_DIFF((x), (y)))
118
119/* Increment receive sequence number */
120#define MP_NEXT_RECV_SEQ(priv,seq) \
121 ((priv)->conf.recvShortSeq ? \
122 MP_SHORT_EXTEND((seq) + 1) : \
123 MP_LONG_EXTEND((seq) + 1))
124
125/* Don't fragment transmitted packets smaller than this */
126#define MP_MIN_FRAG_LEN 6
127
128/* Maximum fragment reasssembly queue length */
129#define MP_MAX_QUEUE_LEN 128
130
131/* Fragment queue scanner period */
132#define MP_FRAGTIMER_INTERVAL (hz/2)
133
134/* We store incoming fragments this way */
135struct ng_ppp_frag {
136 int seq; /* fragment seq# */
137 u_char first; /* First in packet? */
138 u_char last; /* Last in packet? */
139 struct timeval timestamp; /* time of reception */
140 struct mbuf *data; /* Fragment data */
40 * $Whistle: ng_ppp.c,v 1.24 1999/11/01 09:24:52 julian Exp $
41 */
42
43/*
44 * PPP node type.
45 */
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/limits.h>
51#include <sys/time.h>
52#include <sys/mbuf.h>
53#include <sys/malloc.h>
54#include <sys/errno.h>
55#include <sys/ctype.h>
56
57#include <netgraph/ng_message.h>
58#include <netgraph/netgraph.h>
59#include <netgraph/ng_parse.h>
60#include <netgraph/ng_ppp.h>
61#include <netgraph/ng_vjc.h>
62
63#ifdef NG_SEPARATE_MALLOC
64MALLOC_DEFINE(M_NETGRAPH_PPP, "netgraph_ppp", "netgraph ppp node");
65#else
66#define M_NETGRAPH_PPP M_NETGRAPH
67#endif
68
69#define PROT_VALID(p) (((p) & 0x0101) == 0x0001)
70#define PROT_COMPRESSABLE(p) (((p) & 0xff00) == 0x0000)
71
72/* Some PPP protocol numbers we're interested in */
73#define PROT_APPLETALK 0x0029
74#define PROT_COMPD 0x00fd
75#define PROT_CRYPTD 0x0053
76#define PROT_IP 0x0021
77#define PROT_IPV6 0x0057
78#define PROT_IPX 0x002b
79#define PROT_LCP 0xc021
80#define PROT_MP 0x003d
81#define PROT_VJCOMP 0x002d
82#define PROT_VJUNCOMP 0x002f
83
84/* Multilink PPP definitions */
85#define MP_MIN_MRRU 1500 /* per RFC 1990 */
86#define MP_INITIAL_SEQ 0 /* per RFC 1990 */
87#define MP_MIN_LINK_MRU 32
88
89#define MP_SHORT_SEQ_MASK 0x00000fff /* short seq # mask */
90#define MP_SHORT_SEQ_HIBIT 0x00000800 /* short seq # high bit */
91#define MP_SHORT_FIRST_FLAG 0x00008000 /* first fragment in frame */
92#define MP_SHORT_LAST_FLAG 0x00004000 /* last fragment in frame */
93
94#define MP_LONG_SEQ_MASK 0x00ffffff /* long seq # mask */
95#define MP_LONG_SEQ_HIBIT 0x00800000 /* long seq # high bit */
96#define MP_LONG_FIRST_FLAG 0x80000000 /* first fragment in frame */
97#define MP_LONG_LAST_FLAG 0x40000000 /* last fragment in frame */
98
99#define MP_NOSEQ 0x7fffffff /* impossible sequence number */
100
101/* Sign extension of MP sequence numbers */
102#define MP_SHORT_EXTEND(s) (((s) & MP_SHORT_SEQ_HIBIT) ? \
103 ((s) | ~MP_SHORT_SEQ_MASK) \
104 : ((s) & MP_SHORT_SEQ_MASK))
105#define MP_LONG_EXTEND(s) (((s) & MP_LONG_SEQ_HIBIT) ? \
106 ((s) | ~MP_LONG_SEQ_MASK) \
107 : ((s) & MP_LONG_SEQ_MASK))
108
109/* Comparision of MP sequence numbers. Note: all sequence numbers
110 except priv->xseq are stored with the sign bit extended. */
111#define MP_SHORT_SEQ_DIFF(x,y) MP_SHORT_EXTEND((x) - (y))
112#define MP_LONG_SEQ_DIFF(x,y) MP_LONG_EXTEND((x) - (y))
113
114#define MP_RECV_SEQ_DIFF(priv,x,y) \
115 ((priv)->conf.recvShortSeq ? \
116 MP_SHORT_SEQ_DIFF((x), (y)) : \
117 MP_LONG_SEQ_DIFF((x), (y)))
118
119/* Increment receive sequence number */
120#define MP_NEXT_RECV_SEQ(priv,seq) \
121 ((priv)->conf.recvShortSeq ? \
122 MP_SHORT_EXTEND((seq) + 1) : \
123 MP_LONG_EXTEND((seq) + 1))
124
125/* Don't fragment transmitted packets smaller than this */
126#define MP_MIN_FRAG_LEN 6
127
128/* Maximum fragment reasssembly queue length */
129#define MP_MAX_QUEUE_LEN 128
130
131/* Fragment queue scanner period */
132#define MP_FRAGTIMER_INTERVAL (hz/2)
133
134/* We store incoming fragments this way */
135struct ng_ppp_frag {
136 int seq; /* fragment seq# */
137 u_char first; /* First in packet? */
138 u_char last; /* Last in packet? */
139 struct timeval timestamp; /* time of reception */
140 struct mbuf *data; /* Fragment data */
141 meta_p meta; /* Fragment meta */
142 TAILQ_ENTRY(ng_ppp_frag) f_qent; /* Fragment queue */
143};
144
145/* We use integer indicies to refer to the non-link hooks */
146static const char *const ng_ppp_hook_names[] = {
147 NG_PPP_HOOK_ATALK,
148#define HOOK_INDEX_ATALK 0
149 NG_PPP_HOOK_BYPASS,
150#define HOOK_INDEX_BYPASS 1
151 NG_PPP_HOOK_COMPRESS,
152#define HOOK_INDEX_COMPRESS 2
153 NG_PPP_HOOK_ENCRYPT,
154#define HOOK_INDEX_ENCRYPT 3
155 NG_PPP_HOOK_DECOMPRESS,
156#define HOOK_INDEX_DECOMPRESS 4
157 NG_PPP_HOOK_DECRYPT,
158#define HOOK_INDEX_DECRYPT 5
159 NG_PPP_HOOK_INET,
160#define HOOK_INDEX_INET 6
161 NG_PPP_HOOK_IPX,
162#define HOOK_INDEX_IPX 7
163 NG_PPP_HOOK_VJC_COMP,
164#define HOOK_INDEX_VJC_COMP 8
165 NG_PPP_HOOK_VJC_IP,
166#define HOOK_INDEX_VJC_IP 9
167 NG_PPP_HOOK_VJC_UNCOMP,
168#define HOOK_INDEX_VJC_UNCOMP 10
169 NG_PPP_HOOK_VJC_VJIP,
170#define HOOK_INDEX_VJC_VJIP 11
171 NG_PPP_HOOK_IPV6,
172#define HOOK_INDEX_IPV6 12
173 NULL
174#define HOOK_INDEX_MAX 13
175};
176
177/* We store index numbers in the hook private pointer. The HOOK_INDEX()
178 for a hook is either the index (above) for normal hooks, or the ones
179 complement of the link number for link hooks.
180XXX Not any more.. (what a hack)
181#define HOOK_INDEX(hook) (*((int16_t *) &(hook)->private))
182*/
183
184/* Per-link private information */
185struct ng_ppp_link {
186 struct ng_ppp_link_conf conf; /* link configuration */
187 hook_p hook; /* connection to link data */
188 int32_t seq; /* highest rec'd seq# - MSEQ */
189 struct timeval lastWrite; /* time of last write */
190 int bytesInQueue; /* bytes in the output queue */
191 struct ng_ppp_link_stat stats; /* Link stats */
192};
193
194/* Total per-node private information */
195struct ng_ppp_private {
196 struct ng_ppp_bund_conf conf; /* bundle config */
197 struct ng_ppp_link_stat bundleStats; /* bundle stats */
198 struct ng_ppp_link links[NG_PPP_MAX_LINKS];/* per-link info */
199 int32_t xseq; /* next out MP seq # */
200 int32_t mseq; /* min links[i].seq */
201 u_char vjCompHooked; /* VJ comp hooked up? */
202 u_char allLinksEqual; /* all xmit the same? */
203 u_char timerActive; /* frag timer active? */
204 u_int numActiveLinks; /* how many links up */
205 int activeLinks[NG_PPP_MAX_LINKS]; /* indicies */
206 u_int lastLink; /* for round robin */
207 hook_p hooks[HOOK_INDEX_MAX]; /* non-link hooks */
208 TAILQ_HEAD(ng_ppp_fraglist, ng_ppp_frag) /* fragment queue */
209 frags;
210 int qlen; /* fraq queue length */
211 struct callout_handle fragTimer; /* fraq queue check */
212};
213typedef struct ng_ppp_private *priv_p;
214
215/* Netgraph node methods */
216static ng_constructor_t ng_ppp_constructor;
217static ng_rcvmsg_t ng_ppp_rcvmsg;
218static ng_shutdown_t ng_ppp_shutdown;
219static ng_newhook_t ng_ppp_newhook;
220static ng_rcvdata_t ng_ppp_rcvdata;
221static ng_disconnect_t ng_ppp_disconnect;
222
223/* Helper functions */
224static int ng_ppp_input(node_p node, int bypass,
225 int linkNum, item_p item);
226static int ng_ppp_output(node_p node, int bypass, int proto,
227 int linkNum, item_p item);
228static int ng_ppp_mp_input(node_p node, int linkNum, item_p item);
229static int ng_ppp_check_packet(node_p node);
141 TAILQ_ENTRY(ng_ppp_frag) f_qent; /* Fragment queue */
142};
143
144/* We use integer indicies to refer to the non-link hooks */
145static const char *const ng_ppp_hook_names[] = {
146 NG_PPP_HOOK_ATALK,
147#define HOOK_INDEX_ATALK 0
148 NG_PPP_HOOK_BYPASS,
149#define HOOK_INDEX_BYPASS 1
150 NG_PPP_HOOK_COMPRESS,
151#define HOOK_INDEX_COMPRESS 2
152 NG_PPP_HOOK_ENCRYPT,
153#define HOOK_INDEX_ENCRYPT 3
154 NG_PPP_HOOK_DECOMPRESS,
155#define HOOK_INDEX_DECOMPRESS 4
156 NG_PPP_HOOK_DECRYPT,
157#define HOOK_INDEX_DECRYPT 5
158 NG_PPP_HOOK_INET,
159#define HOOK_INDEX_INET 6
160 NG_PPP_HOOK_IPX,
161#define HOOK_INDEX_IPX 7
162 NG_PPP_HOOK_VJC_COMP,
163#define HOOK_INDEX_VJC_COMP 8
164 NG_PPP_HOOK_VJC_IP,
165#define HOOK_INDEX_VJC_IP 9
166 NG_PPP_HOOK_VJC_UNCOMP,
167#define HOOK_INDEX_VJC_UNCOMP 10
168 NG_PPP_HOOK_VJC_VJIP,
169#define HOOK_INDEX_VJC_VJIP 11
170 NG_PPP_HOOK_IPV6,
171#define HOOK_INDEX_IPV6 12
172 NULL
173#define HOOK_INDEX_MAX 13
174};
175
176/* We store index numbers in the hook private pointer. The HOOK_INDEX()
177 for a hook is either the index (above) for normal hooks, or the ones
178 complement of the link number for link hooks.
179XXX Not any more.. (what a hack)
180#define HOOK_INDEX(hook) (*((int16_t *) &(hook)->private))
181*/
182
183/* Per-link private information */
184struct ng_ppp_link {
185 struct ng_ppp_link_conf conf; /* link configuration */
186 hook_p hook; /* connection to link data */
187 int32_t seq; /* highest rec'd seq# - MSEQ */
188 struct timeval lastWrite; /* time of last write */
189 int bytesInQueue; /* bytes in the output queue */
190 struct ng_ppp_link_stat stats; /* Link stats */
191};
192
193/* Total per-node private information */
194struct ng_ppp_private {
195 struct ng_ppp_bund_conf conf; /* bundle config */
196 struct ng_ppp_link_stat bundleStats; /* bundle stats */
197 struct ng_ppp_link links[NG_PPP_MAX_LINKS];/* per-link info */
198 int32_t xseq; /* next out MP seq # */
199 int32_t mseq; /* min links[i].seq */
200 u_char vjCompHooked; /* VJ comp hooked up? */
201 u_char allLinksEqual; /* all xmit the same? */
202 u_char timerActive; /* frag timer active? */
203 u_int numActiveLinks; /* how many links up */
204 int activeLinks[NG_PPP_MAX_LINKS]; /* indicies */
205 u_int lastLink; /* for round robin */
206 hook_p hooks[HOOK_INDEX_MAX]; /* non-link hooks */
207 TAILQ_HEAD(ng_ppp_fraglist, ng_ppp_frag) /* fragment queue */
208 frags;
209 int qlen; /* fraq queue length */
210 struct callout_handle fragTimer; /* fraq queue check */
211};
212typedef struct ng_ppp_private *priv_p;
213
214/* Netgraph node methods */
215static ng_constructor_t ng_ppp_constructor;
216static ng_rcvmsg_t ng_ppp_rcvmsg;
217static ng_shutdown_t ng_ppp_shutdown;
218static ng_newhook_t ng_ppp_newhook;
219static ng_rcvdata_t ng_ppp_rcvdata;
220static ng_disconnect_t ng_ppp_disconnect;
221
222/* Helper functions */
223static int ng_ppp_input(node_p node, int bypass,
224 int linkNum, item_p item);
225static int ng_ppp_output(node_p node, int bypass, int proto,
226 int linkNum, item_p item);
227static int ng_ppp_mp_input(node_p node, int linkNum, item_p item);
228static int ng_ppp_check_packet(node_p node);
230static void ng_ppp_get_packet(node_p node, struct mbuf **mp, meta_p *metap);
229static void ng_ppp_get_packet(node_p node, struct mbuf **mp);
231static int ng_ppp_frag_process(node_p node);
232static int ng_ppp_frag_trim(node_p node);
233static void ng_ppp_frag_timeout(void *arg);
234static void ng_ppp_frag_checkstale(node_p node);
235static void ng_ppp_frag_reset(node_p node);
230static int ng_ppp_frag_process(node_p node);
231static int ng_ppp_frag_trim(node_p node);
232static void ng_ppp_frag_timeout(void *arg);
233static void ng_ppp_frag_checkstale(node_p node);
234static void ng_ppp_frag_reset(node_p node);
236static int ng_ppp_mp_output(node_p node, struct mbuf *m, meta_p meta);
235static int ng_ppp_mp_output(node_p node, struct mbuf *m);
237static void ng_ppp_mp_strategy(node_p node, int len, int *distrib);
238static int ng_ppp_intcmp(const void *v1, const void *v2);
239static struct mbuf *ng_ppp_addproto(struct mbuf *m, int proto, int compOK);
240static struct mbuf *ng_ppp_prepend(struct mbuf *m, const void *buf, int len);
241static int ng_ppp_config_valid(node_p node,
242 const struct ng_ppp_node_conf *newConf);
243static void ng_ppp_update(node_p node, int newConf);
244static void ng_ppp_start_frag_timer(node_p node);
245static void ng_ppp_stop_frag_timer(node_p node);
246
247/* Parse type for struct ng_ppp_mp_state_type */
248static const struct ng_parse_fixedarray_info ng_ppp_rseq_array_info = {
249 &ng_parse_hint32_type,
250 NG_PPP_MAX_LINKS
251};
252static const struct ng_parse_type ng_ppp_rseq_array_type = {
253 &ng_parse_fixedarray_type,
254 &ng_ppp_rseq_array_info,
255};
256static const struct ng_parse_struct_field ng_ppp_mp_state_type_fields[]
257 = NG_PPP_MP_STATE_TYPE_INFO(&ng_ppp_rseq_array_type);
258static const struct ng_parse_type ng_ppp_mp_state_type = {
259 &ng_parse_struct_type,
260 &ng_ppp_mp_state_type_fields
261};
262
263/* Parse type for struct ng_ppp_link_conf */
264static const struct ng_parse_struct_field ng_ppp_link_type_fields[]
265 = NG_PPP_LINK_TYPE_INFO;
266static const struct ng_parse_type ng_ppp_link_type = {
267 &ng_parse_struct_type,
268 &ng_ppp_link_type_fields
269};
270
271/* Parse type for struct ng_ppp_bund_conf */
272static const struct ng_parse_struct_field ng_ppp_bund_type_fields[]
273 = NG_PPP_BUND_TYPE_INFO;
274static const struct ng_parse_type ng_ppp_bund_type = {
275 &ng_parse_struct_type,
276 &ng_ppp_bund_type_fields
277};
278
279/* Parse type for struct ng_ppp_node_conf */
280static const struct ng_parse_fixedarray_info ng_ppp_array_info = {
281 &ng_ppp_link_type,
282 NG_PPP_MAX_LINKS
283};
284static const struct ng_parse_type ng_ppp_link_array_type = {
285 &ng_parse_fixedarray_type,
286 &ng_ppp_array_info,
287};
288static const struct ng_parse_struct_field ng_ppp_conf_type_fields[]
289 = NG_PPP_CONFIG_TYPE_INFO(&ng_ppp_bund_type, &ng_ppp_link_array_type);
290static const struct ng_parse_type ng_ppp_conf_type = {
291 &ng_parse_struct_type,
292 &ng_ppp_conf_type_fields
293};
294
295/* Parse type for struct ng_ppp_link_stat */
296static const struct ng_parse_struct_field ng_ppp_stats_type_fields[]
297 = NG_PPP_STATS_TYPE_INFO;
298static const struct ng_parse_type ng_ppp_stats_type = {
299 &ng_parse_struct_type,
300 &ng_ppp_stats_type_fields
301};
302
303/* List of commands and how to convert arguments to/from ASCII */
304static const struct ng_cmdlist ng_ppp_cmds[] = {
305 {
306 NGM_PPP_COOKIE,
307 NGM_PPP_SET_CONFIG,
308 "setconfig",
309 &ng_ppp_conf_type,
310 NULL
311 },
312 {
313 NGM_PPP_COOKIE,
314 NGM_PPP_GET_CONFIG,
315 "getconfig",
316 NULL,
317 &ng_ppp_conf_type
318 },
319 {
320 NGM_PPP_COOKIE,
321 NGM_PPP_GET_MP_STATE,
322 "getmpstate",
323 NULL,
324 &ng_ppp_mp_state_type
325 },
326 {
327 NGM_PPP_COOKIE,
328 NGM_PPP_GET_LINK_STATS,
329 "getstats",
330 &ng_parse_int16_type,
331 &ng_ppp_stats_type
332 },
333 {
334 NGM_PPP_COOKIE,
335 NGM_PPP_CLR_LINK_STATS,
336 "clrstats",
337 &ng_parse_int16_type,
338 NULL
339 },
340 {
341 NGM_PPP_COOKIE,
342 NGM_PPP_GETCLR_LINK_STATS,
343 "getclrstats",
344 &ng_parse_int16_type,
345 &ng_ppp_stats_type
346 },
347 { 0 }
348};
349
350/* Node type descriptor */
351static struct ng_type ng_ppp_typestruct = {
352 .version = NG_ABI_VERSION,
353 .name = NG_PPP_NODE_TYPE,
354 .constructor = ng_ppp_constructor,
355 .rcvmsg = ng_ppp_rcvmsg,
356 .shutdown = ng_ppp_shutdown,
357 .newhook = ng_ppp_newhook,
358 .rcvdata = ng_ppp_rcvdata,
359 .disconnect = ng_ppp_disconnect,
360 .cmdlist = ng_ppp_cmds,
361};
362NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
363
364static int *compareLatencies; /* hack for ng_ppp_intcmp() */
365
366/* Address and control field header */
367static const u_char ng_ppp_acf[2] = { 0xff, 0x03 };
368
369/* Maximum time we'll let a complete incoming packet sit in the queue */
370static const struct timeval ng_ppp_max_staleness = { 2, 0 }; /* 2 seconds */
371
372#define ERROUT(x) do { error = (x); goto done; } while (0)
373
374/************************************************************************
375 NETGRAPH NODE STUFF
376 ************************************************************************/
377
378/*
379 * Node type constructor
380 */
381static int
382ng_ppp_constructor(node_p node)
383{
384 priv_p priv;
385 int i;
386
387 /* Allocate private structure */
388 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_PPP, M_NOWAIT | M_ZERO);
389 if (priv == NULL)
390 return (ENOMEM);
391
392 NG_NODE_SET_PRIVATE(node, priv);
393
394 /* Initialize state */
395 TAILQ_INIT(&priv->frags);
396 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
397 priv->links[i].seq = MP_NOSEQ;
398 callout_handle_init(&priv->fragTimer);
399
400 /* Done */
401 return (0);
402}
403
404/*
405 * Give our OK for a hook to be added
406 */
407static int
408ng_ppp_newhook(node_p node, hook_p hook, const char *name)
409{
410 const priv_p priv = NG_NODE_PRIVATE(node);
411 int linkNum = -1;
412 hook_p *hookPtr = NULL;
413 int hookIndex = -1;
414
415 /* Figure out which hook it is */
416 if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX, /* a link hook? */
417 strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
418 const char *cp;
419 char *eptr;
420
421 cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
422 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
423 return (EINVAL);
424 linkNum = (int)strtoul(cp, &eptr, 10);
425 if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
426 return (EINVAL);
427 hookPtr = &priv->links[linkNum].hook;
428 hookIndex = ~linkNum;
429 } else { /* must be a non-link hook */
430 int i;
431
432 for (i = 0; ng_ppp_hook_names[i] != NULL; i++) {
433 if (strcmp(name, ng_ppp_hook_names[i]) == 0) {
434 hookPtr = &priv->hooks[i];
435 hookIndex = i;
436 break;
437 }
438 }
439 if (ng_ppp_hook_names[i] == NULL)
440 return (EINVAL); /* no such hook */
441 }
442
443 /* See if hook is already connected */
444 if (*hookPtr != NULL)
445 return (EISCONN);
446
447 /* Disallow more than one link unless multilink is enabled */
448 if (linkNum != -1 && priv->links[linkNum].conf.enableLink
449 && !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
450 return (ENODEV);
451
452 /* OK */
453 *hookPtr = hook;
454 NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)hookIndex);
455 ng_ppp_update(node, 0);
456 return (0);
457}
458
459/*
460 * Receive a control message
461 */
462static int
463ng_ppp_rcvmsg(node_p node, item_p item, hook_p lasthook)
464{
465 const priv_p priv = NG_NODE_PRIVATE(node);
466 struct ng_mesg *resp = NULL;
467 int error = 0;
468 struct ng_mesg *msg;
469
470 NGI_GET_MSG(item, msg);
471 switch (msg->header.typecookie) {
472 case NGM_PPP_COOKIE:
473 switch (msg->header.cmd) {
474 case NGM_PPP_SET_CONFIG:
475 {
476 struct ng_ppp_node_conf *const conf =
477 (struct ng_ppp_node_conf *)msg->data;
478 int i;
479
480 /* Check for invalid or illegal config */
481 if (msg->header.arglen != sizeof(*conf))
482 ERROUT(EINVAL);
483 if (!ng_ppp_config_valid(node, conf))
484 ERROUT(EINVAL);
485
486 /* Copy config */
487 priv->conf = conf->bund;
488 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
489 priv->links[i].conf = conf->links[i];
490 ng_ppp_update(node, 1);
491 break;
492 }
493 case NGM_PPP_GET_CONFIG:
494 {
495 struct ng_ppp_node_conf *conf;
496 int i;
497
498 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
499 if (resp == NULL)
500 ERROUT(ENOMEM);
501 conf = (struct ng_ppp_node_conf *)resp->data;
502 conf->bund = priv->conf;
503 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
504 conf->links[i] = priv->links[i].conf;
505 break;
506 }
507 case NGM_PPP_GET_MP_STATE:
508 {
509 struct ng_ppp_mp_state *info;
510 int i;
511
512 NG_MKRESPONSE(resp, msg, sizeof(*info), M_NOWAIT);
513 if (resp == NULL)
514 ERROUT(ENOMEM);
515 info = (struct ng_ppp_mp_state *)resp->data;
516 bzero(info, sizeof(*info));
517 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
518 if (priv->links[i].seq != MP_NOSEQ)
519 info->rseq[i] = priv->links[i].seq;
520 }
521 info->mseq = priv->mseq;
522 info->xseq = priv->xseq;
523 break;
524 }
525 case NGM_PPP_GET_LINK_STATS:
526 case NGM_PPP_CLR_LINK_STATS:
527 case NGM_PPP_GETCLR_LINK_STATS:
528 {
529 struct ng_ppp_link_stat *stats;
530 u_int16_t linkNum;
531
532 if (msg->header.arglen != sizeof(u_int16_t))
533 ERROUT(EINVAL);
534 linkNum = *((u_int16_t *) msg->data);
535 if (linkNum >= NG_PPP_MAX_LINKS
536 && linkNum != NG_PPP_BUNDLE_LINKNUM)
537 ERROUT(EINVAL);
538 stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
539 &priv->bundleStats : &priv->links[linkNum].stats;
540 if (msg->header.cmd != NGM_PPP_CLR_LINK_STATS) {
541 NG_MKRESPONSE(resp, msg,
542 sizeof(struct ng_ppp_link_stat), M_NOWAIT);
543 if (resp == NULL)
544 ERROUT(ENOMEM);
545 bcopy(stats, resp->data, sizeof(*stats));
546 }
547 if (msg->header.cmd != NGM_PPP_GET_LINK_STATS)
548 bzero(stats, sizeof(*stats));
549 break;
550 }
551 default:
552 error = EINVAL;
553 break;
554 }
555 break;
556 case NGM_VJC_COOKIE:
557 {
558 /*
559 * Forward it to the vjc node. leave the
560 * old return address alone.
561 * If we have no hook, let NG_RESPOND_MSG
562 * clean up any remaining resources.
563 * Because we have no resp, the item will be freed
564 * along with anything it references. Don't
565 * let msg be freed twice.
566 */
567 NGI_MSG(item) = msg; /* put it back in the item */
568 msg = NULL;
569 if ((lasthook = priv->links[HOOK_INDEX_VJC_IP].hook)) {
570 NG_FWD_ITEM_HOOK(error, item, lasthook);
571 }
572 return (error);
573 }
574 default:
575 error = EINVAL;
576 break;
577 }
578done:
579 NG_RESPOND_MSG(error, node, item, resp);
580 NG_FREE_MSG(msg);
581 return (error);
582}
583
584/*
585 * Receive data on a hook
586 */
587static int
588ng_ppp_rcvdata(hook_p hook, item_p item)
589{
590 const node_p node = NG_HOOK_NODE(hook);
591 const priv_p priv = NG_NODE_PRIVATE(node);
592 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
593 u_int16_t linkNum = NG_PPP_BUNDLE_LINKNUM;
594 hook_p outHook = NULL;
595 int proto = 0, error;
596 struct mbuf *m;
597
598 NGI_GET_M(item, m);
599 /* Did it come from a link hook? */
600 if (index < 0) {
601 struct ng_ppp_link *link;
602
603 /* Convert index into a link number */
604 linkNum = (u_int16_t)~index;
605 KASSERT(linkNum < NG_PPP_MAX_LINKS,
606 ("%s: bogus index 0x%x", __func__, index));
607 link = &priv->links[linkNum];
608
609 /* Stats */
610 link->stats.recvFrames++;
611 link->stats.recvOctets += m->m_pkthdr.len;
612
613 /* Strip address and control fields, if present */
614 if (m->m_pkthdr.len >= 2) {
615 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
616 NG_FREE_ITEM(item);
617 return (ENOBUFS);
618 }
619 if (bcmp(mtod(m, u_char *), &ng_ppp_acf, 2) == 0)
620 m_adj(m, 2);
621 }
622
623 /* Dispatch incoming frame (if not enabled, to bypass) */
624 NGI_M(item) = m; /* put changed m back in item */
625 return ng_ppp_input(node,
626 !link->conf.enableLink, linkNum, item);
627 }
628
629 /* Get protocol & check if data allowed from this hook */
630 NGI_M(item) = m; /* put possibly changed m back in item */
631 switch (index) {
632
633 /* Outgoing data */
634 case HOOK_INDEX_ATALK:
635 if (!priv->conf.enableAtalk) {
636 NG_FREE_ITEM(item);
637 return (ENXIO);
638 }
639 proto = PROT_APPLETALK;
640 break;
641 case HOOK_INDEX_IPX:
642 if (!priv->conf.enableIPX) {
643 NG_FREE_ITEM(item);
644 return (ENXIO);
645 }
646 proto = PROT_IPX;
647 break;
648 case HOOK_INDEX_IPV6:
649 if (!priv->conf.enableIPv6) {
650 NG_FREE_ITEM(item);
651 return (ENXIO);
652 }
653 proto = PROT_IPV6;
654 break;
655 case HOOK_INDEX_INET:
656 case HOOK_INDEX_VJC_VJIP:
657 if (!priv->conf.enableIP) {
658 NG_FREE_ITEM(item);
659 return (ENXIO);
660 }
661 proto = PROT_IP;
662 break;
663 case HOOK_INDEX_VJC_COMP:
664 if (!priv->conf.enableVJCompression) {
665 NG_FREE_ITEM(item);
666 return (ENXIO);
667 }
668 proto = PROT_VJCOMP;
669 break;
670 case HOOK_INDEX_VJC_UNCOMP:
671 if (!priv->conf.enableVJCompression) {
672 NG_FREE_ITEM(item);
673 return (ENXIO);
674 }
675 proto = PROT_VJUNCOMP;
676 break;
677 case HOOK_INDEX_COMPRESS:
678 if (!priv->conf.enableCompression) {
679 NG_FREE_ITEM(item);
680 return (ENXIO);
681 }
682 proto = PROT_COMPD;
683 break;
684 case HOOK_INDEX_ENCRYPT:
685 if (!priv->conf.enableEncryption) {
686 NG_FREE_ITEM(item);
687 return (ENXIO);
688 }
689 proto = PROT_CRYPTD;
690 break;
691 case HOOK_INDEX_BYPASS:
692 if (m->m_pkthdr.len < 4) {
693 NG_FREE_ITEM(item);
694 return (EINVAL);
695 }
696 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
697 NGI_M(item) = NULL; /* don't free twice */
698 NG_FREE_ITEM(item);
699 return (ENOBUFS);
700 }
701 NGI_M(item) = m; /* m may have changed */
702 linkNum = ntohs(mtod(m, u_int16_t *)[0]);
703 proto = ntohs(mtod(m, u_int16_t *)[1]);
704 m_adj(m, 4);
705 if (linkNum >= NG_PPP_MAX_LINKS
706 && linkNum != NG_PPP_BUNDLE_LINKNUM) {
707 NG_FREE_ITEM(item);
708 return (EINVAL);
709 }
710 break;
711
712 /* Incoming data */
713 case HOOK_INDEX_VJC_IP:
714 if (!priv->conf.enableIP || !priv->conf.enableVJDecompression) {
715 NG_FREE_ITEM(item);
716 return (ENXIO);
717 }
718 break;
719 case HOOK_INDEX_DECOMPRESS:
720 if (!priv->conf.enableDecompression) {
721 NG_FREE_ITEM(item);
722 return (ENXIO);
723 }
724 break;
725 case HOOK_INDEX_DECRYPT:
726 if (!priv->conf.enableDecryption) {
727 NG_FREE_ITEM(item);
728 return (ENXIO);
729 }
730 break;
731 default:
732 panic("%s: bogus index 0x%x", __func__, index);
733 }
734
735 /* Now figure out what to do with the frame */
736 switch (index) {
737
738 /* Outgoing data */
739 case HOOK_INDEX_INET:
740 if (priv->conf.enableVJCompression && priv->vjCompHooked) {
741 outHook = priv->hooks[HOOK_INDEX_VJC_IP];
742 break;
743 }
744 /* FALLTHROUGH */
745 case HOOK_INDEX_ATALK:
746 case HOOK_INDEX_IPV6:
747 case HOOK_INDEX_IPX:
748 case HOOK_INDEX_VJC_COMP:
749 case HOOK_INDEX_VJC_UNCOMP:
750 case HOOK_INDEX_VJC_VJIP:
751 if (priv->conf.enableCompression
752 && priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
753 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
754 NGI_M(item) = NULL;
755 NG_FREE_ITEM(item);
756 return (ENOBUFS);
757 }
758 NGI_M(item) = m; /* m may have changed */
759 outHook = priv->hooks[HOOK_INDEX_COMPRESS];
760 break;
761 }
762 /* FALLTHROUGH */
763 case HOOK_INDEX_COMPRESS:
764 if (priv->conf.enableEncryption
765 && priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
766 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
767 NGI_M(item) = NULL;
768 NG_FREE_ITEM(item);
769 return (ENOBUFS);
770 }
771 NGI_M(item) = m; /* m may have changed */
772 outHook = priv->hooks[HOOK_INDEX_ENCRYPT];
773 break;
774 }
775 /* FALLTHROUGH */
776 case HOOK_INDEX_ENCRYPT:
777 return ng_ppp_output(node, 0, proto, NG_PPP_BUNDLE_LINKNUM, item);
778
779 case HOOK_INDEX_BYPASS:
780 return ng_ppp_output(node, 1, proto, linkNum, item);
781
782 /* Incoming data */
783 case HOOK_INDEX_DECRYPT:
784 case HOOK_INDEX_DECOMPRESS:
785 return ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
786
787 case HOOK_INDEX_VJC_IP:
788 outHook = priv->hooks[HOOK_INDEX_INET];
789 break;
790 }
791
792 /* Send packet out hook */
793 NG_FWD_ITEM_HOOK(error, item, outHook);
794 return (error);
795}
796
797/*
798 * Destroy node
799 */
800static int
801ng_ppp_shutdown(node_p node)
802{
803 const priv_p priv = NG_NODE_PRIVATE(node);
804
805 /* Stop fragment queue timer */
806 ng_ppp_stop_frag_timer(node);
807
808 /* Take down netgraph node */
809 ng_ppp_frag_reset(node);
810 bzero(priv, sizeof(*priv));
811 FREE(priv, M_NETGRAPH_PPP);
812 NG_NODE_SET_PRIVATE(node, NULL);
813 NG_NODE_UNREF(node); /* let the node escape */
814 return (0);
815}
816
817/*
818 * Hook disconnection
819 */
820static int
821ng_ppp_disconnect(hook_p hook)
822{
823 const node_p node = NG_HOOK_NODE(hook);
824 const priv_p priv = NG_NODE_PRIVATE(node);
825 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
826
827 /* Zero out hook pointer */
828 if (index < 0)
829 priv->links[~index].hook = NULL;
830 else
831 priv->hooks[index] = NULL;
832
833 /* Update derived info (or go away if no hooks left) */
834 if (NG_NODE_NUMHOOKS(node) > 0) {
835 ng_ppp_update(node, 0);
836 } else {
837 if (NG_NODE_IS_VALID(node)) {
838 ng_rmnode_self(node);
839 }
840 }
841 return (0);
842}
843
844/************************************************************************
845 HELPER STUFF
846 ************************************************************************/
847
848/*
849 * Handle an incoming frame. Extract the PPP protocol number
850 * and dispatch accordingly.
851 */
852static int
853ng_ppp_input(node_p node, int bypass, int linkNum, item_p item)
854{
855 const priv_p priv = NG_NODE_PRIVATE(node);
856 hook_p outHook = NULL;
857 int proto, error;
858 struct mbuf *m;
859
860
861 NGI_GET_M(item, m);
862 /* Extract protocol number */
863 for (proto = 0; !PROT_VALID(proto) && m->m_pkthdr.len > 0; ) {
864 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL) {
865 NG_FREE_ITEM(item);
866 return (ENOBUFS);
867 }
868 proto = (proto << 8) + *mtod(m, u_char *);
869 m_adj(m, 1);
870 }
871 if (!PROT_VALID(proto)) {
872 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
873 priv->bundleStats.badProtos++;
874 else
875 priv->links[linkNum].stats.badProtos++;
876 NG_FREE_ITEM(item);
877 NG_FREE_M(m);
878 return (EINVAL);
879 }
880
881 /* Bypass frame? */
882 if (bypass)
883 goto bypass;
884
885 /* Check protocol */
886 switch (proto) {
887 case PROT_COMPD:
888 if (priv->conf.enableDecompression)
889 outHook = priv->hooks[HOOK_INDEX_DECOMPRESS];
890 break;
891 case PROT_CRYPTD:
892 if (priv->conf.enableDecryption)
893 outHook = priv->hooks[HOOK_INDEX_DECRYPT];
894 break;
895 case PROT_VJCOMP:
896 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
897 outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
898 break;
899 case PROT_VJUNCOMP:
900 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
901 outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
902 break;
903 case PROT_MP:
904 if (priv->conf.enableMultilink
905 && linkNum != NG_PPP_BUNDLE_LINKNUM) {
906 NGI_M(item) = m;
907 return ng_ppp_mp_input(node, linkNum, item);
908 }
909 break;
910 case PROT_APPLETALK:
911 if (priv->conf.enableAtalk)
912 outHook = priv->hooks[HOOK_INDEX_ATALK];
913 break;
914 case PROT_IPX:
915 if (priv->conf.enableIPX)
916 outHook = priv->hooks[HOOK_INDEX_IPX];
917 break;
918 case PROT_IP:
919 if (priv->conf.enableIP)
920 outHook = priv->hooks[HOOK_INDEX_INET];
921 break;
922 case PROT_IPV6:
923 if (priv->conf.enableIPv6)
924 outHook = priv->hooks[HOOK_INDEX_IPV6];
925 break;
926 }
927
928bypass:
929 /* For unknown/inactive protocols, forward out the bypass hook */
930 if (outHook == NULL) {
931 u_int16_t hdr[2];
932
933 hdr[0] = htons(linkNum);
934 hdr[1] = htons((u_int16_t)proto);
935 if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
936 NG_FREE_ITEM(item);
937 return (ENOBUFS);
938 }
939 outHook = priv->hooks[HOOK_INDEX_BYPASS];
940 }
941
942 /* Forward frame */
943 NG_FWD_NEW_DATA(error, item, outHook, m);
944 return (error);
945}
946
947/*
948 * Deliver a frame out a link, either a real one or NG_PPP_BUNDLE_LINKNUM.
949 * If the link is not enabled then ENXIO is returned, unless "bypass" is != 0.
950 *
951 * If the frame is too big for the particular link, return EMSGSIZE.
952 */
953static int
954ng_ppp_output(node_p node, int bypass,
955 int proto, int linkNum, item_p item)
956{
957 const priv_p priv = NG_NODE_PRIVATE(node);
958 struct ng_ppp_link *link;
959 int len, error;
960 struct mbuf *m;
961 u_int16_t mru;
962
963 /* Extract mbuf */
964 NGI_GET_M(item, m);
965
966 /* If not doing MP, map bundle virtual link to (the only) link */
967 if (linkNum == NG_PPP_BUNDLE_LINKNUM && !priv->conf.enableMultilink)
968 linkNum = priv->activeLinks[0];
969
970 /* Get link pointer (optimization) */
971 link = (linkNum != NG_PPP_BUNDLE_LINKNUM) ?
972 &priv->links[linkNum] : NULL;
973
974 /* Check link status (if real) */
975 if (linkNum != NG_PPP_BUNDLE_LINKNUM) {
976 if (!bypass && !link->conf.enableLink) {
977 NG_FREE_M(m);
978 NG_FREE_ITEM(item);
979 return (ENXIO);
980 }
981 if (link->hook == NULL) {
982 NG_FREE_M(m);
983 NG_FREE_ITEM(item);
984 return (ENETDOWN);
985 }
986 }
987
988 /* Check peer's MRU for this link */
989 mru = (link != NULL) ? link->conf.mru : priv->conf.mrru;
990 if (mru != 0 && m->m_pkthdr.len > mru) {
991 NG_FREE_M(m);
992 NG_FREE_ITEM(item);
993 return (EMSGSIZE);
994 }
995
996 /* Prepend protocol number, possibly compressed */
997 if ((m = ng_ppp_addproto(m, proto,
998 linkNum == NG_PPP_BUNDLE_LINKNUM
999 || link->conf.enableProtoComp)) == NULL) {
1000 NG_FREE_ITEM(item);
1001 return (ENOBUFS);
1002 }
1003
1004 /* Special handling for the MP virtual link */
1005 if (linkNum == NG_PPP_BUNDLE_LINKNUM) {
236static void ng_ppp_mp_strategy(node_p node, int len, int *distrib);
237static int ng_ppp_intcmp(const void *v1, const void *v2);
238static struct mbuf *ng_ppp_addproto(struct mbuf *m, int proto, int compOK);
239static struct mbuf *ng_ppp_prepend(struct mbuf *m, const void *buf, int len);
240static int ng_ppp_config_valid(node_p node,
241 const struct ng_ppp_node_conf *newConf);
242static void ng_ppp_update(node_p node, int newConf);
243static void ng_ppp_start_frag_timer(node_p node);
244static void ng_ppp_stop_frag_timer(node_p node);
245
246/* Parse type for struct ng_ppp_mp_state_type */
247static const struct ng_parse_fixedarray_info ng_ppp_rseq_array_info = {
248 &ng_parse_hint32_type,
249 NG_PPP_MAX_LINKS
250};
251static const struct ng_parse_type ng_ppp_rseq_array_type = {
252 &ng_parse_fixedarray_type,
253 &ng_ppp_rseq_array_info,
254};
255static const struct ng_parse_struct_field ng_ppp_mp_state_type_fields[]
256 = NG_PPP_MP_STATE_TYPE_INFO(&ng_ppp_rseq_array_type);
257static const struct ng_parse_type ng_ppp_mp_state_type = {
258 &ng_parse_struct_type,
259 &ng_ppp_mp_state_type_fields
260};
261
262/* Parse type for struct ng_ppp_link_conf */
263static const struct ng_parse_struct_field ng_ppp_link_type_fields[]
264 = NG_PPP_LINK_TYPE_INFO;
265static const struct ng_parse_type ng_ppp_link_type = {
266 &ng_parse_struct_type,
267 &ng_ppp_link_type_fields
268};
269
270/* Parse type for struct ng_ppp_bund_conf */
271static const struct ng_parse_struct_field ng_ppp_bund_type_fields[]
272 = NG_PPP_BUND_TYPE_INFO;
273static const struct ng_parse_type ng_ppp_bund_type = {
274 &ng_parse_struct_type,
275 &ng_ppp_bund_type_fields
276};
277
278/* Parse type for struct ng_ppp_node_conf */
279static const struct ng_parse_fixedarray_info ng_ppp_array_info = {
280 &ng_ppp_link_type,
281 NG_PPP_MAX_LINKS
282};
283static const struct ng_parse_type ng_ppp_link_array_type = {
284 &ng_parse_fixedarray_type,
285 &ng_ppp_array_info,
286};
287static const struct ng_parse_struct_field ng_ppp_conf_type_fields[]
288 = NG_PPP_CONFIG_TYPE_INFO(&ng_ppp_bund_type, &ng_ppp_link_array_type);
289static const struct ng_parse_type ng_ppp_conf_type = {
290 &ng_parse_struct_type,
291 &ng_ppp_conf_type_fields
292};
293
294/* Parse type for struct ng_ppp_link_stat */
295static const struct ng_parse_struct_field ng_ppp_stats_type_fields[]
296 = NG_PPP_STATS_TYPE_INFO;
297static const struct ng_parse_type ng_ppp_stats_type = {
298 &ng_parse_struct_type,
299 &ng_ppp_stats_type_fields
300};
301
302/* List of commands and how to convert arguments to/from ASCII */
303static const struct ng_cmdlist ng_ppp_cmds[] = {
304 {
305 NGM_PPP_COOKIE,
306 NGM_PPP_SET_CONFIG,
307 "setconfig",
308 &ng_ppp_conf_type,
309 NULL
310 },
311 {
312 NGM_PPP_COOKIE,
313 NGM_PPP_GET_CONFIG,
314 "getconfig",
315 NULL,
316 &ng_ppp_conf_type
317 },
318 {
319 NGM_PPP_COOKIE,
320 NGM_PPP_GET_MP_STATE,
321 "getmpstate",
322 NULL,
323 &ng_ppp_mp_state_type
324 },
325 {
326 NGM_PPP_COOKIE,
327 NGM_PPP_GET_LINK_STATS,
328 "getstats",
329 &ng_parse_int16_type,
330 &ng_ppp_stats_type
331 },
332 {
333 NGM_PPP_COOKIE,
334 NGM_PPP_CLR_LINK_STATS,
335 "clrstats",
336 &ng_parse_int16_type,
337 NULL
338 },
339 {
340 NGM_PPP_COOKIE,
341 NGM_PPP_GETCLR_LINK_STATS,
342 "getclrstats",
343 &ng_parse_int16_type,
344 &ng_ppp_stats_type
345 },
346 { 0 }
347};
348
349/* Node type descriptor */
350static struct ng_type ng_ppp_typestruct = {
351 .version = NG_ABI_VERSION,
352 .name = NG_PPP_NODE_TYPE,
353 .constructor = ng_ppp_constructor,
354 .rcvmsg = ng_ppp_rcvmsg,
355 .shutdown = ng_ppp_shutdown,
356 .newhook = ng_ppp_newhook,
357 .rcvdata = ng_ppp_rcvdata,
358 .disconnect = ng_ppp_disconnect,
359 .cmdlist = ng_ppp_cmds,
360};
361NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
362
363static int *compareLatencies; /* hack for ng_ppp_intcmp() */
364
365/* Address and control field header */
366static const u_char ng_ppp_acf[2] = { 0xff, 0x03 };
367
368/* Maximum time we'll let a complete incoming packet sit in the queue */
369static const struct timeval ng_ppp_max_staleness = { 2, 0 }; /* 2 seconds */
370
371#define ERROUT(x) do { error = (x); goto done; } while (0)
372
373/************************************************************************
374 NETGRAPH NODE STUFF
375 ************************************************************************/
376
377/*
378 * Node type constructor
379 */
380static int
381ng_ppp_constructor(node_p node)
382{
383 priv_p priv;
384 int i;
385
386 /* Allocate private structure */
387 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_PPP, M_NOWAIT | M_ZERO);
388 if (priv == NULL)
389 return (ENOMEM);
390
391 NG_NODE_SET_PRIVATE(node, priv);
392
393 /* Initialize state */
394 TAILQ_INIT(&priv->frags);
395 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
396 priv->links[i].seq = MP_NOSEQ;
397 callout_handle_init(&priv->fragTimer);
398
399 /* Done */
400 return (0);
401}
402
403/*
404 * Give our OK for a hook to be added
405 */
406static int
407ng_ppp_newhook(node_p node, hook_p hook, const char *name)
408{
409 const priv_p priv = NG_NODE_PRIVATE(node);
410 int linkNum = -1;
411 hook_p *hookPtr = NULL;
412 int hookIndex = -1;
413
414 /* Figure out which hook it is */
415 if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX, /* a link hook? */
416 strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
417 const char *cp;
418 char *eptr;
419
420 cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
421 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
422 return (EINVAL);
423 linkNum = (int)strtoul(cp, &eptr, 10);
424 if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
425 return (EINVAL);
426 hookPtr = &priv->links[linkNum].hook;
427 hookIndex = ~linkNum;
428 } else { /* must be a non-link hook */
429 int i;
430
431 for (i = 0; ng_ppp_hook_names[i] != NULL; i++) {
432 if (strcmp(name, ng_ppp_hook_names[i]) == 0) {
433 hookPtr = &priv->hooks[i];
434 hookIndex = i;
435 break;
436 }
437 }
438 if (ng_ppp_hook_names[i] == NULL)
439 return (EINVAL); /* no such hook */
440 }
441
442 /* See if hook is already connected */
443 if (*hookPtr != NULL)
444 return (EISCONN);
445
446 /* Disallow more than one link unless multilink is enabled */
447 if (linkNum != -1 && priv->links[linkNum].conf.enableLink
448 && !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
449 return (ENODEV);
450
451 /* OK */
452 *hookPtr = hook;
453 NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)hookIndex);
454 ng_ppp_update(node, 0);
455 return (0);
456}
457
458/*
459 * Receive a control message
460 */
461static int
462ng_ppp_rcvmsg(node_p node, item_p item, hook_p lasthook)
463{
464 const priv_p priv = NG_NODE_PRIVATE(node);
465 struct ng_mesg *resp = NULL;
466 int error = 0;
467 struct ng_mesg *msg;
468
469 NGI_GET_MSG(item, msg);
470 switch (msg->header.typecookie) {
471 case NGM_PPP_COOKIE:
472 switch (msg->header.cmd) {
473 case NGM_PPP_SET_CONFIG:
474 {
475 struct ng_ppp_node_conf *const conf =
476 (struct ng_ppp_node_conf *)msg->data;
477 int i;
478
479 /* Check for invalid or illegal config */
480 if (msg->header.arglen != sizeof(*conf))
481 ERROUT(EINVAL);
482 if (!ng_ppp_config_valid(node, conf))
483 ERROUT(EINVAL);
484
485 /* Copy config */
486 priv->conf = conf->bund;
487 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
488 priv->links[i].conf = conf->links[i];
489 ng_ppp_update(node, 1);
490 break;
491 }
492 case NGM_PPP_GET_CONFIG:
493 {
494 struct ng_ppp_node_conf *conf;
495 int i;
496
497 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
498 if (resp == NULL)
499 ERROUT(ENOMEM);
500 conf = (struct ng_ppp_node_conf *)resp->data;
501 conf->bund = priv->conf;
502 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
503 conf->links[i] = priv->links[i].conf;
504 break;
505 }
506 case NGM_PPP_GET_MP_STATE:
507 {
508 struct ng_ppp_mp_state *info;
509 int i;
510
511 NG_MKRESPONSE(resp, msg, sizeof(*info), M_NOWAIT);
512 if (resp == NULL)
513 ERROUT(ENOMEM);
514 info = (struct ng_ppp_mp_state *)resp->data;
515 bzero(info, sizeof(*info));
516 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
517 if (priv->links[i].seq != MP_NOSEQ)
518 info->rseq[i] = priv->links[i].seq;
519 }
520 info->mseq = priv->mseq;
521 info->xseq = priv->xseq;
522 break;
523 }
524 case NGM_PPP_GET_LINK_STATS:
525 case NGM_PPP_CLR_LINK_STATS:
526 case NGM_PPP_GETCLR_LINK_STATS:
527 {
528 struct ng_ppp_link_stat *stats;
529 u_int16_t linkNum;
530
531 if (msg->header.arglen != sizeof(u_int16_t))
532 ERROUT(EINVAL);
533 linkNum = *((u_int16_t *) msg->data);
534 if (linkNum >= NG_PPP_MAX_LINKS
535 && linkNum != NG_PPP_BUNDLE_LINKNUM)
536 ERROUT(EINVAL);
537 stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
538 &priv->bundleStats : &priv->links[linkNum].stats;
539 if (msg->header.cmd != NGM_PPP_CLR_LINK_STATS) {
540 NG_MKRESPONSE(resp, msg,
541 sizeof(struct ng_ppp_link_stat), M_NOWAIT);
542 if (resp == NULL)
543 ERROUT(ENOMEM);
544 bcopy(stats, resp->data, sizeof(*stats));
545 }
546 if (msg->header.cmd != NGM_PPP_GET_LINK_STATS)
547 bzero(stats, sizeof(*stats));
548 break;
549 }
550 default:
551 error = EINVAL;
552 break;
553 }
554 break;
555 case NGM_VJC_COOKIE:
556 {
557 /*
558 * Forward it to the vjc node. leave the
559 * old return address alone.
560 * If we have no hook, let NG_RESPOND_MSG
561 * clean up any remaining resources.
562 * Because we have no resp, the item will be freed
563 * along with anything it references. Don't
564 * let msg be freed twice.
565 */
566 NGI_MSG(item) = msg; /* put it back in the item */
567 msg = NULL;
568 if ((lasthook = priv->links[HOOK_INDEX_VJC_IP].hook)) {
569 NG_FWD_ITEM_HOOK(error, item, lasthook);
570 }
571 return (error);
572 }
573 default:
574 error = EINVAL;
575 break;
576 }
577done:
578 NG_RESPOND_MSG(error, node, item, resp);
579 NG_FREE_MSG(msg);
580 return (error);
581}
582
583/*
584 * Receive data on a hook
585 */
586static int
587ng_ppp_rcvdata(hook_p hook, item_p item)
588{
589 const node_p node = NG_HOOK_NODE(hook);
590 const priv_p priv = NG_NODE_PRIVATE(node);
591 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
592 u_int16_t linkNum = NG_PPP_BUNDLE_LINKNUM;
593 hook_p outHook = NULL;
594 int proto = 0, error;
595 struct mbuf *m;
596
597 NGI_GET_M(item, m);
598 /* Did it come from a link hook? */
599 if (index < 0) {
600 struct ng_ppp_link *link;
601
602 /* Convert index into a link number */
603 linkNum = (u_int16_t)~index;
604 KASSERT(linkNum < NG_PPP_MAX_LINKS,
605 ("%s: bogus index 0x%x", __func__, index));
606 link = &priv->links[linkNum];
607
608 /* Stats */
609 link->stats.recvFrames++;
610 link->stats.recvOctets += m->m_pkthdr.len;
611
612 /* Strip address and control fields, if present */
613 if (m->m_pkthdr.len >= 2) {
614 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
615 NG_FREE_ITEM(item);
616 return (ENOBUFS);
617 }
618 if (bcmp(mtod(m, u_char *), &ng_ppp_acf, 2) == 0)
619 m_adj(m, 2);
620 }
621
622 /* Dispatch incoming frame (if not enabled, to bypass) */
623 NGI_M(item) = m; /* put changed m back in item */
624 return ng_ppp_input(node,
625 !link->conf.enableLink, linkNum, item);
626 }
627
628 /* Get protocol & check if data allowed from this hook */
629 NGI_M(item) = m; /* put possibly changed m back in item */
630 switch (index) {
631
632 /* Outgoing data */
633 case HOOK_INDEX_ATALK:
634 if (!priv->conf.enableAtalk) {
635 NG_FREE_ITEM(item);
636 return (ENXIO);
637 }
638 proto = PROT_APPLETALK;
639 break;
640 case HOOK_INDEX_IPX:
641 if (!priv->conf.enableIPX) {
642 NG_FREE_ITEM(item);
643 return (ENXIO);
644 }
645 proto = PROT_IPX;
646 break;
647 case HOOK_INDEX_IPV6:
648 if (!priv->conf.enableIPv6) {
649 NG_FREE_ITEM(item);
650 return (ENXIO);
651 }
652 proto = PROT_IPV6;
653 break;
654 case HOOK_INDEX_INET:
655 case HOOK_INDEX_VJC_VJIP:
656 if (!priv->conf.enableIP) {
657 NG_FREE_ITEM(item);
658 return (ENXIO);
659 }
660 proto = PROT_IP;
661 break;
662 case HOOK_INDEX_VJC_COMP:
663 if (!priv->conf.enableVJCompression) {
664 NG_FREE_ITEM(item);
665 return (ENXIO);
666 }
667 proto = PROT_VJCOMP;
668 break;
669 case HOOK_INDEX_VJC_UNCOMP:
670 if (!priv->conf.enableVJCompression) {
671 NG_FREE_ITEM(item);
672 return (ENXIO);
673 }
674 proto = PROT_VJUNCOMP;
675 break;
676 case HOOK_INDEX_COMPRESS:
677 if (!priv->conf.enableCompression) {
678 NG_FREE_ITEM(item);
679 return (ENXIO);
680 }
681 proto = PROT_COMPD;
682 break;
683 case HOOK_INDEX_ENCRYPT:
684 if (!priv->conf.enableEncryption) {
685 NG_FREE_ITEM(item);
686 return (ENXIO);
687 }
688 proto = PROT_CRYPTD;
689 break;
690 case HOOK_INDEX_BYPASS:
691 if (m->m_pkthdr.len < 4) {
692 NG_FREE_ITEM(item);
693 return (EINVAL);
694 }
695 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
696 NGI_M(item) = NULL; /* don't free twice */
697 NG_FREE_ITEM(item);
698 return (ENOBUFS);
699 }
700 NGI_M(item) = m; /* m may have changed */
701 linkNum = ntohs(mtod(m, u_int16_t *)[0]);
702 proto = ntohs(mtod(m, u_int16_t *)[1]);
703 m_adj(m, 4);
704 if (linkNum >= NG_PPP_MAX_LINKS
705 && linkNum != NG_PPP_BUNDLE_LINKNUM) {
706 NG_FREE_ITEM(item);
707 return (EINVAL);
708 }
709 break;
710
711 /* Incoming data */
712 case HOOK_INDEX_VJC_IP:
713 if (!priv->conf.enableIP || !priv->conf.enableVJDecompression) {
714 NG_FREE_ITEM(item);
715 return (ENXIO);
716 }
717 break;
718 case HOOK_INDEX_DECOMPRESS:
719 if (!priv->conf.enableDecompression) {
720 NG_FREE_ITEM(item);
721 return (ENXIO);
722 }
723 break;
724 case HOOK_INDEX_DECRYPT:
725 if (!priv->conf.enableDecryption) {
726 NG_FREE_ITEM(item);
727 return (ENXIO);
728 }
729 break;
730 default:
731 panic("%s: bogus index 0x%x", __func__, index);
732 }
733
734 /* Now figure out what to do with the frame */
735 switch (index) {
736
737 /* Outgoing data */
738 case HOOK_INDEX_INET:
739 if (priv->conf.enableVJCompression && priv->vjCompHooked) {
740 outHook = priv->hooks[HOOK_INDEX_VJC_IP];
741 break;
742 }
743 /* FALLTHROUGH */
744 case HOOK_INDEX_ATALK:
745 case HOOK_INDEX_IPV6:
746 case HOOK_INDEX_IPX:
747 case HOOK_INDEX_VJC_COMP:
748 case HOOK_INDEX_VJC_UNCOMP:
749 case HOOK_INDEX_VJC_VJIP:
750 if (priv->conf.enableCompression
751 && priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
752 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
753 NGI_M(item) = NULL;
754 NG_FREE_ITEM(item);
755 return (ENOBUFS);
756 }
757 NGI_M(item) = m; /* m may have changed */
758 outHook = priv->hooks[HOOK_INDEX_COMPRESS];
759 break;
760 }
761 /* FALLTHROUGH */
762 case HOOK_INDEX_COMPRESS:
763 if (priv->conf.enableEncryption
764 && priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
765 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
766 NGI_M(item) = NULL;
767 NG_FREE_ITEM(item);
768 return (ENOBUFS);
769 }
770 NGI_M(item) = m; /* m may have changed */
771 outHook = priv->hooks[HOOK_INDEX_ENCRYPT];
772 break;
773 }
774 /* FALLTHROUGH */
775 case HOOK_INDEX_ENCRYPT:
776 return ng_ppp_output(node, 0, proto, NG_PPP_BUNDLE_LINKNUM, item);
777
778 case HOOK_INDEX_BYPASS:
779 return ng_ppp_output(node, 1, proto, linkNum, item);
780
781 /* Incoming data */
782 case HOOK_INDEX_DECRYPT:
783 case HOOK_INDEX_DECOMPRESS:
784 return ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
785
786 case HOOK_INDEX_VJC_IP:
787 outHook = priv->hooks[HOOK_INDEX_INET];
788 break;
789 }
790
791 /* Send packet out hook */
792 NG_FWD_ITEM_HOOK(error, item, outHook);
793 return (error);
794}
795
796/*
797 * Destroy node
798 */
799static int
800ng_ppp_shutdown(node_p node)
801{
802 const priv_p priv = NG_NODE_PRIVATE(node);
803
804 /* Stop fragment queue timer */
805 ng_ppp_stop_frag_timer(node);
806
807 /* Take down netgraph node */
808 ng_ppp_frag_reset(node);
809 bzero(priv, sizeof(*priv));
810 FREE(priv, M_NETGRAPH_PPP);
811 NG_NODE_SET_PRIVATE(node, NULL);
812 NG_NODE_UNREF(node); /* let the node escape */
813 return (0);
814}
815
816/*
817 * Hook disconnection
818 */
819static int
820ng_ppp_disconnect(hook_p hook)
821{
822 const node_p node = NG_HOOK_NODE(hook);
823 const priv_p priv = NG_NODE_PRIVATE(node);
824 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
825
826 /* Zero out hook pointer */
827 if (index < 0)
828 priv->links[~index].hook = NULL;
829 else
830 priv->hooks[index] = NULL;
831
832 /* Update derived info (or go away if no hooks left) */
833 if (NG_NODE_NUMHOOKS(node) > 0) {
834 ng_ppp_update(node, 0);
835 } else {
836 if (NG_NODE_IS_VALID(node)) {
837 ng_rmnode_self(node);
838 }
839 }
840 return (0);
841}
842
843/************************************************************************
844 HELPER STUFF
845 ************************************************************************/
846
847/*
848 * Handle an incoming frame. Extract the PPP protocol number
849 * and dispatch accordingly.
850 */
851static int
852ng_ppp_input(node_p node, int bypass, int linkNum, item_p item)
853{
854 const priv_p priv = NG_NODE_PRIVATE(node);
855 hook_p outHook = NULL;
856 int proto, error;
857 struct mbuf *m;
858
859
860 NGI_GET_M(item, m);
861 /* Extract protocol number */
862 for (proto = 0; !PROT_VALID(proto) && m->m_pkthdr.len > 0; ) {
863 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL) {
864 NG_FREE_ITEM(item);
865 return (ENOBUFS);
866 }
867 proto = (proto << 8) + *mtod(m, u_char *);
868 m_adj(m, 1);
869 }
870 if (!PROT_VALID(proto)) {
871 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
872 priv->bundleStats.badProtos++;
873 else
874 priv->links[linkNum].stats.badProtos++;
875 NG_FREE_ITEM(item);
876 NG_FREE_M(m);
877 return (EINVAL);
878 }
879
880 /* Bypass frame? */
881 if (bypass)
882 goto bypass;
883
884 /* Check protocol */
885 switch (proto) {
886 case PROT_COMPD:
887 if (priv->conf.enableDecompression)
888 outHook = priv->hooks[HOOK_INDEX_DECOMPRESS];
889 break;
890 case PROT_CRYPTD:
891 if (priv->conf.enableDecryption)
892 outHook = priv->hooks[HOOK_INDEX_DECRYPT];
893 break;
894 case PROT_VJCOMP:
895 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
896 outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
897 break;
898 case PROT_VJUNCOMP:
899 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
900 outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
901 break;
902 case PROT_MP:
903 if (priv->conf.enableMultilink
904 && linkNum != NG_PPP_BUNDLE_LINKNUM) {
905 NGI_M(item) = m;
906 return ng_ppp_mp_input(node, linkNum, item);
907 }
908 break;
909 case PROT_APPLETALK:
910 if (priv->conf.enableAtalk)
911 outHook = priv->hooks[HOOK_INDEX_ATALK];
912 break;
913 case PROT_IPX:
914 if (priv->conf.enableIPX)
915 outHook = priv->hooks[HOOK_INDEX_IPX];
916 break;
917 case PROT_IP:
918 if (priv->conf.enableIP)
919 outHook = priv->hooks[HOOK_INDEX_INET];
920 break;
921 case PROT_IPV6:
922 if (priv->conf.enableIPv6)
923 outHook = priv->hooks[HOOK_INDEX_IPV6];
924 break;
925 }
926
927bypass:
928 /* For unknown/inactive protocols, forward out the bypass hook */
929 if (outHook == NULL) {
930 u_int16_t hdr[2];
931
932 hdr[0] = htons(linkNum);
933 hdr[1] = htons((u_int16_t)proto);
934 if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
935 NG_FREE_ITEM(item);
936 return (ENOBUFS);
937 }
938 outHook = priv->hooks[HOOK_INDEX_BYPASS];
939 }
940
941 /* Forward frame */
942 NG_FWD_NEW_DATA(error, item, outHook, m);
943 return (error);
944}
945
946/*
947 * Deliver a frame out a link, either a real one or NG_PPP_BUNDLE_LINKNUM.
948 * If the link is not enabled then ENXIO is returned, unless "bypass" is != 0.
949 *
950 * If the frame is too big for the particular link, return EMSGSIZE.
951 */
952static int
953ng_ppp_output(node_p node, int bypass,
954 int proto, int linkNum, item_p item)
955{
956 const priv_p priv = NG_NODE_PRIVATE(node);
957 struct ng_ppp_link *link;
958 int len, error;
959 struct mbuf *m;
960 u_int16_t mru;
961
962 /* Extract mbuf */
963 NGI_GET_M(item, m);
964
965 /* If not doing MP, map bundle virtual link to (the only) link */
966 if (linkNum == NG_PPP_BUNDLE_LINKNUM && !priv->conf.enableMultilink)
967 linkNum = priv->activeLinks[0];
968
969 /* Get link pointer (optimization) */
970 link = (linkNum != NG_PPP_BUNDLE_LINKNUM) ?
971 &priv->links[linkNum] : NULL;
972
973 /* Check link status (if real) */
974 if (linkNum != NG_PPP_BUNDLE_LINKNUM) {
975 if (!bypass && !link->conf.enableLink) {
976 NG_FREE_M(m);
977 NG_FREE_ITEM(item);
978 return (ENXIO);
979 }
980 if (link->hook == NULL) {
981 NG_FREE_M(m);
982 NG_FREE_ITEM(item);
983 return (ENETDOWN);
984 }
985 }
986
987 /* Check peer's MRU for this link */
988 mru = (link != NULL) ? link->conf.mru : priv->conf.mrru;
989 if (mru != 0 && m->m_pkthdr.len > mru) {
990 NG_FREE_M(m);
991 NG_FREE_ITEM(item);
992 return (EMSGSIZE);
993 }
994
995 /* Prepend protocol number, possibly compressed */
996 if ((m = ng_ppp_addproto(m, proto,
997 linkNum == NG_PPP_BUNDLE_LINKNUM
998 || link->conf.enableProtoComp)) == NULL) {
999 NG_FREE_ITEM(item);
1000 return (ENOBUFS);
1001 }
1002
1003 /* Special handling for the MP virtual link */
1004 if (linkNum == NG_PPP_BUNDLE_LINKNUM) {
1006 meta_p meta;
1007
1008 /* strip off and discard the queue item */
1009 NGI_GET_META(item, meta);
1005 /* discard the queue item */
1010 NG_FREE_ITEM(item);
1006 NG_FREE_ITEM(item);
1011 return ng_ppp_mp_output(node, m, meta);
1007 return ng_ppp_mp_output(node, m);
1012 }
1013
1014 /* Prepend address and control field (unless compressed) */
1015 if (proto == PROT_LCP || !link->conf.enableACFComp) {
1016 if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL) {
1017 NG_FREE_ITEM(item);
1018 return (ENOBUFS);
1019 }
1020 }
1021
1022 /* Deliver frame */
1023 len = m->m_pkthdr.len;
1024 NG_FWD_NEW_DATA(error, item, link->hook, m);
1025
1026 /* Update stats and 'bytes in queue' counter */
1027 if (error == 0) {
1028 link->stats.xmitFrames++;
1029 link->stats.xmitOctets += len;
1030 link->bytesInQueue += len;
1031 getmicrouptime(&link->lastWrite);
1032 }
1033 return error;
1034}
1035
1036/*
1037 * Handle an incoming multi-link fragment
1038 *
1039 * The fragment reassembly algorithm is somewhat complex. This is mainly
1040 * because we are required not to reorder the reconstructed packets, yet
1041 * fragments are only guaranteed to arrive in order on a per-link basis.
1042 * In other words, when we have a complete packet ready, but the previous
1043 * packet is still incomplete, we have to decide between delivering the
1044 * complete packet and throwing away the incomplete one, or waiting to
1045 * see if the remainder of the incomplete one arrives, at which time we
1046 * can deliver both packets, in order.
1047 *
1048 * This problem is exacerbated by "sequence number slew", which is when
1049 * the sequence numbers coming in from different links are far apart from
1050 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1051 * has been seen to generate sequence number slew of up to 10 on an ISDN
1052 * 2B-channel MP link. There is nothing invalid about sequence number slew
1053 * but it makes the reasssembly process have to work harder.
1054 *
1055 * However, the peer is required to transmit fragments in order on each
1056 * link. That means if we define MSEQ as the minimum over all links of
1057 * the highest sequence number received on that link, then we can always
1058 * give up any hope of receiving a fragment with sequence number < MSEQ in
1059 * the future (all of this using 'wraparound' sequence number space).
1060 * Therefore we can always immediately throw away incomplete packets
1061 * missing fragments with sequence numbers < MSEQ.
1062 *
1063 * Here is an overview of our algorithm:
1064 *
1065 * o Received fragments are inserted into a queue, for which we
1066 * maintain these invariants between calls to this function:
1067 *
1068 * - Fragments are ordered in the queue by sequence number
1069 * - If a complete packet is at the head of the queue, then
1070 * the first fragment in the packet has seq# > MSEQ + 1
1071 * (otherwise, we could deliver it immediately)
1072 * - If any fragments have seq# < MSEQ, then they are necessarily
1073 * part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1074 * we can throw them away because they'll never be completed)
1075 * - The queue contains at most MP_MAX_QUEUE_LEN fragments
1076 *
1077 * o We have a periodic timer that checks the queue for the first
1078 * complete packet that has been sitting in the queue "too long".
1079 * When one is detected, all previous (incomplete) fragments are
1080 * discarded, their missing fragments are declared lost and MSEQ
1081 * is increased.
1082 *
1083 * o If we recieve a fragment with seq# < MSEQ, we throw it away
1084 * because we've already delcared it lost.
1085 *
1086 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1087 */
1088static int
1089ng_ppp_mp_input(node_p node, int linkNum, item_p item)
1090{
1091 const priv_p priv = NG_NODE_PRIVATE(node);
1092 struct ng_ppp_link *const link = &priv->links[linkNum];
1093 struct ng_ppp_frag frag0, *frag = &frag0;
1094 struct ng_ppp_frag *qent;
1095 int i, diff, inserted;
1096 struct mbuf *m;
1008 }
1009
1010 /* Prepend address and control field (unless compressed) */
1011 if (proto == PROT_LCP || !link->conf.enableACFComp) {
1012 if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL) {
1013 NG_FREE_ITEM(item);
1014 return (ENOBUFS);
1015 }
1016 }
1017
1018 /* Deliver frame */
1019 len = m->m_pkthdr.len;
1020 NG_FWD_NEW_DATA(error, item, link->hook, m);
1021
1022 /* Update stats and 'bytes in queue' counter */
1023 if (error == 0) {
1024 link->stats.xmitFrames++;
1025 link->stats.xmitOctets += len;
1026 link->bytesInQueue += len;
1027 getmicrouptime(&link->lastWrite);
1028 }
1029 return error;
1030}
1031
1032/*
1033 * Handle an incoming multi-link fragment
1034 *
1035 * The fragment reassembly algorithm is somewhat complex. This is mainly
1036 * because we are required not to reorder the reconstructed packets, yet
1037 * fragments are only guaranteed to arrive in order on a per-link basis.
1038 * In other words, when we have a complete packet ready, but the previous
1039 * packet is still incomplete, we have to decide between delivering the
1040 * complete packet and throwing away the incomplete one, or waiting to
1041 * see if the remainder of the incomplete one arrives, at which time we
1042 * can deliver both packets, in order.
1043 *
1044 * This problem is exacerbated by "sequence number slew", which is when
1045 * the sequence numbers coming in from different links are far apart from
1046 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1047 * has been seen to generate sequence number slew of up to 10 on an ISDN
1048 * 2B-channel MP link. There is nothing invalid about sequence number slew
1049 * but it makes the reasssembly process have to work harder.
1050 *
1051 * However, the peer is required to transmit fragments in order on each
1052 * link. That means if we define MSEQ as the minimum over all links of
1053 * the highest sequence number received on that link, then we can always
1054 * give up any hope of receiving a fragment with sequence number < MSEQ in
1055 * the future (all of this using 'wraparound' sequence number space).
1056 * Therefore we can always immediately throw away incomplete packets
1057 * missing fragments with sequence numbers < MSEQ.
1058 *
1059 * Here is an overview of our algorithm:
1060 *
1061 * o Received fragments are inserted into a queue, for which we
1062 * maintain these invariants between calls to this function:
1063 *
1064 * - Fragments are ordered in the queue by sequence number
1065 * - If a complete packet is at the head of the queue, then
1066 * the first fragment in the packet has seq# > MSEQ + 1
1067 * (otherwise, we could deliver it immediately)
1068 * - If any fragments have seq# < MSEQ, then they are necessarily
1069 * part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1070 * we can throw them away because they'll never be completed)
1071 * - The queue contains at most MP_MAX_QUEUE_LEN fragments
1072 *
1073 * o We have a periodic timer that checks the queue for the first
1074 * complete packet that has been sitting in the queue "too long".
1075 * When one is detected, all previous (incomplete) fragments are
1076 * discarded, their missing fragments are declared lost and MSEQ
1077 * is increased.
1078 *
1079 * o If we recieve a fragment with seq# < MSEQ, we throw it away
1080 * because we've already delcared it lost.
1081 *
1082 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1083 */
1084static int
1085ng_ppp_mp_input(node_p node, int linkNum, item_p item)
1086{
1087 const priv_p priv = NG_NODE_PRIVATE(node);
1088 struct ng_ppp_link *const link = &priv->links[linkNum];
1089 struct ng_ppp_frag frag0, *frag = &frag0;
1090 struct ng_ppp_frag *qent;
1091 int i, diff, inserted;
1092 struct mbuf *m;
1097 meta_p meta;
1098
1099 NGI_GET_M(item, m);
1093
1094 NGI_GET_M(item, m);
1100 NGI_GET_META(item, meta);
1101 NG_FREE_ITEM(item);
1102 /* Stats */
1103 priv->bundleStats.recvFrames++;
1104 priv->bundleStats.recvOctets += m->m_pkthdr.len;
1105
1106 /* Extract fragment information from MP header */
1107 if (priv->conf.recvShortSeq) {
1108 u_int16_t shdr;
1109
1110 if (m->m_pkthdr.len < 2) {
1111 link->stats.runts++;
1112 NG_FREE_M(m);
1095 NG_FREE_ITEM(item);
1096 /* Stats */
1097 priv->bundleStats.recvFrames++;
1098 priv->bundleStats.recvOctets += m->m_pkthdr.len;
1099
1100 /* Extract fragment information from MP header */
1101 if (priv->conf.recvShortSeq) {
1102 u_int16_t shdr;
1103
1104 if (m->m_pkthdr.len < 2) {
1105 link->stats.runts++;
1106 NG_FREE_M(m);
1113 NG_FREE_META(meta);
1114 return (EINVAL);
1115 }
1107 return (EINVAL);
1108 }
1116 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
1117 NG_FREE_META(meta);
1109 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1118 return (ENOBUFS);
1110 return (ENOBUFS);
1119 }
1111
1120 shdr = ntohs(*mtod(m, u_int16_t *));
1121 frag->seq = MP_SHORT_EXTEND(shdr);
1122 frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1123 frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1124 diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1125 m_adj(m, 2);
1126 } else {
1127 u_int32_t lhdr;
1128
1129 if (m->m_pkthdr.len < 4) {
1130 link->stats.runts++;
1131 NG_FREE_M(m);
1112 shdr = ntohs(*mtod(m, u_int16_t *));
1113 frag->seq = MP_SHORT_EXTEND(shdr);
1114 frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1115 frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1116 diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1117 m_adj(m, 2);
1118 } else {
1119 u_int32_t lhdr;
1120
1121 if (m->m_pkthdr.len < 4) {
1122 link->stats.runts++;
1123 NG_FREE_M(m);
1132 NG_FREE_META(meta);
1133 return (EINVAL);
1134 }
1124 return (EINVAL);
1125 }
1135 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
1136 NG_FREE_META(meta);
1126 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL)
1137 return (ENOBUFS);
1127 return (ENOBUFS);
1138 }
1128
1139 lhdr = ntohl(*mtod(m, u_int32_t *));
1140 frag->seq = MP_LONG_EXTEND(lhdr);
1141 frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1142 frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1143 diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1144 m_adj(m, 4);
1145 }
1146 frag->data = m;
1129 lhdr = ntohl(*mtod(m, u_int32_t *));
1130 frag->seq = MP_LONG_EXTEND(lhdr);
1131 frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1132 frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1133 diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1134 m_adj(m, 4);
1135 }
1136 frag->data = m;
1147 frag->meta = meta;
1148 getmicrouptime(&frag->timestamp);
1149
1150 /* If sequence number is < MSEQ, we've already declared this
1151 fragment as lost, so we have no choice now but to drop it */
1152 if (diff < 0) {
1153 link->stats.dropFragments++;
1154 NG_FREE_M(m);
1137 getmicrouptime(&frag->timestamp);
1138
1139 /* If sequence number is < MSEQ, we've already declared this
1140 fragment as lost, so we have no choice now but to drop it */
1141 if (diff < 0) {
1142 link->stats.dropFragments++;
1143 NG_FREE_M(m);
1155 NG_FREE_META(meta);
1156 return (0);
1157 }
1158
1159 /* Update highest received sequence number on this link and MSEQ */
1160 priv->mseq = link->seq = frag->seq;
1161 for (i = 0; i < priv->numActiveLinks; i++) {
1162 struct ng_ppp_link *const alink =
1163 &priv->links[priv->activeLinks[i]];
1164
1165 if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1166 priv->mseq = alink->seq;
1167 }
1168
1169 /* Allocate a new frag struct for the queue */
1170 MALLOC(frag, struct ng_ppp_frag *, sizeof(*frag), M_NETGRAPH_PPP, M_NOWAIT);
1171 if (frag == NULL) {
1172 NG_FREE_M(m);
1144 return (0);
1145 }
1146
1147 /* Update highest received sequence number on this link and MSEQ */
1148 priv->mseq = link->seq = frag->seq;
1149 for (i = 0; i < priv->numActiveLinks; i++) {
1150 struct ng_ppp_link *const alink =
1151 &priv->links[priv->activeLinks[i]];
1152
1153 if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1154 priv->mseq = alink->seq;
1155 }
1156
1157 /* Allocate a new frag struct for the queue */
1158 MALLOC(frag, struct ng_ppp_frag *, sizeof(*frag), M_NETGRAPH_PPP, M_NOWAIT);
1159 if (frag == NULL) {
1160 NG_FREE_M(m);
1173 NG_FREE_META(meta);
1174 ng_ppp_frag_process(node);
1175 return (ENOMEM);
1176 }
1177 *frag = frag0;
1178
1179 /* Add fragment to queue, which is sorted by sequence number */
1180 inserted = 0;
1181 TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1182 diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1183 if (diff > 0) {
1184 TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1185 inserted = 1;
1186 break;
1187 } else if (diff == 0) { /* should never happen! */
1188 link->stats.dupFragments++;
1189 NG_FREE_M(frag->data);
1161 ng_ppp_frag_process(node);
1162 return (ENOMEM);
1163 }
1164 *frag = frag0;
1165
1166 /* Add fragment to queue, which is sorted by sequence number */
1167 inserted = 0;
1168 TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1169 diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1170 if (diff > 0) {
1171 TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1172 inserted = 1;
1173 break;
1174 } else if (diff == 0) { /* should never happen! */
1175 link->stats.dupFragments++;
1176 NG_FREE_M(frag->data);
1190 NG_FREE_META(frag->meta);
1191 FREE(frag, M_NETGRAPH_PPP);
1192 return (EINVAL);
1193 }
1194 }
1195 if (!inserted)
1196 TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1197 priv->qlen++;
1198
1199 /* Process the queue */
1200 return ng_ppp_frag_process(node);
1201}
1202
1203/*
1204 * Examine our list of fragments, and determine if there is a
1205 * complete and deliverable packet at the head of the list.
1206 * Return 1 if so, zero otherwise.
1207 */
1208static int
1209ng_ppp_check_packet(node_p node)
1210{
1211 const priv_p priv = NG_NODE_PRIVATE(node);
1212 struct ng_ppp_frag *qent, *qnext;
1213
1214 /* Check for empty queue */
1215 if (TAILQ_EMPTY(&priv->frags))
1216 return (0);
1217
1218 /* Check first fragment is the start of a deliverable packet */
1219 qent = TAILQ_FIRST(&priv->frags);
1220 if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1221 return (0);
1222
1223 /* Check that all the fragments are there */
1224 while (!qent->last) {
1225 qnext = TAILQ_NEXT(qent, f_qent);
1226 if (qnext == NULL) /* end of queue */
1227 return (0);
1228 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1229 return (0);
1230 qent = qnext;
1231 }
1232
1233 /* Got one */
1234 return (1);
1235}
1236
1237/*
1238 * Pull a completed packet off the head of the incoming fragment queue.
1239 * This assumes there is a completed packet there to pull off.
1240 */
1241static void
1177 FREE(frag, M_NETGRAPH_PPP);
1178 return (EINVAL);
1179 }
1180 }
1181 if (!inserted)
1182 TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1183 priv->qlen++;
1184
1185 /* Process the queue */
1186 return ng_ppp_frag_process(node);
1187}
1188
1189/*
1190 * Examine our list of fragments, and determine if there is a
1191 * complete and deliverable packet at the head of the list.
1192 * Return 1 if so, zero otherwise.
1193 */
1194static int
1195ng_ppp_check_packet(node_p node)
1196{
1197 const priv_p priv = NG_NODE_PRIVATE(node);
1198 struct ng_ppp_frag *qent, *qnext;
1199
1200 /* Check for empty queue */
1201 if (TAILQ_EMPTY(&priv->frags))
1202 return (0);
1203
1204 /* Check first fragment is the start of a deliverable packet */
1205 qent = TAILQ_FIRST(&priv->frags);
1206 if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1207 return (0);
1208
1209 /* Check that all the fragments are there */
1210 while (!qent->last) {
1211 qnext = TAILQ_NEXT(qent, f_qent);
1212 if (qnext == NULL) /* end of queue */
1213 return (0);
1214 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1215 return (0);
1216 qent = qnext;
1217 }
1218
1219 /* Got one */
1220 return (1);
1221}
1222
1223/*
1224 * Pull a completed packet off the head of the incoming fragment queue.
1225 * This assumes there is a completed packet there to pull off.
1226 */
1227static void
1242ng_ppp_get_packet(node_p node, struct mbuf **mp, meta_p *metap)
1228ng_ppp_get_packet(node_p node, struct mbuf **mp)
1243{
1244 const priv_p priv = NG_NODE_PRIVATE(node);
1245 struct ng_ppp_frag *qent, *qnext;
1246 struct mbuf *m = NULL, *tail;
1247
1248 qent = TAILQ_FIRST(&priv->frags);
1249 KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1250 ("%s: no packet", __func__));
1251 for (tail = NULL; qent != NULL; qent = qnext) {
1252 qnext = TAILQ_NEXT(qent, f_qent);
1253 KASSERT(!TAILQ_EMPTY(&priv->frags),
1254 ("%s: empty q", __func__));
1255 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1229{
1230 const priv_p priv = NG_NODE_PRIVATE(node);
1231 struct ng_ppp_frag *qent, *qnext;
1232 struct mbuf *m = NULL, *tail;
1233
1234 qent = TAILQ_FIRST(&priv->frags);
1235 KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1236 ("%s: no packet", __func__));
1237 for (tail = NULL; qent != NULL; qent = qnext) {
1238 qnext = TAILQ_NEXT(qent, f_qent);
1239 KASSERT(!TAILQ_EMPTY(&priv->frags),
1240 ("%s: empty q", __func__));
1241 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1256 if (tail == NULL) {
1242 if (tail == NULL)
1257 tail = m = qent->data;
1243 tail = m = qent->data;
1258 *metap = qent->meta; /* inherit first frag's meta */
1259 } else {
1244 else {
1260 m->m_pkthdr.len += qent->data->m_pkthdr.len;
1261 tail->m_next = qent->data;
1245 m->m_pkthdr.len += qent->data->m_pkthdr.len;
1246 tail->m_next = qent->data;
1262 NG_FREE_META(qent->meta); /* drop other frags' metas */
1263 }
1264 while (tail->m_next != NULL)
1265 tail = tail->m_next;
1266 if (qent->last)
1267 qnext = NULL;
1268 FREE(qent, M_NETGRAPH_PPP);
1269 priv->qlen--;
1270 }
1271 *mp = m;
1272}
1273
1274/*
1275 * Trim fragments from the queue whose packets can never be completed.
1276 * This assumes a complete packet is NOT at the beginning of the queue.
1277 * Returns 1 if fragments were removed, zero otherwise.
1278 */
1279static int
1280ng_ppp_frag_trim(node_p node)
1281{
1282 const priv_p priv = NG_NODE_PRIVATE(node);
1283 struct ng_ppp_frag *qent, *qnext = NULL;
1284 int removed = 0;
1285
1286 /* Scan for "dead" fragments and remove them */
1287 while (1) {
1288 int dead = 0;
1289
1290 /* If queue is empty, we're done */
1291 if (TAILQ_EMPTY(&priv->frags))
1292 break;
1293
1294 /* Determine whether first fragment can ever be completed */
1295 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1296 if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1297 break;
1298 qnext = TAILQ_NEXT(qent, f_qent);
1299 KASSERT(qnext != NULL,
1300 ("%s: last frag < MSEQ?", __func__));
1301 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1302 || qent->last || qnext->first) {
1303 dead = 1;
1304 break;
1305 }
1306 }
1307 if (!dead)
1308 break;
1309
1310 /* Remove fragment and all others in the same packet */
1311 while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1312 KASSERT(!TAILQ_EMPTY(&priv->frags),
1313 ("%s: empty q", __func__));
1314 priv->bundleStats.dropFragments++;
1315 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1316 NG_FREE_M(qent->data);
1247 }
1248 while (tail->m_next != NULL)
1249 tail = tail->m_next;
1250 if (qent->last)
1251 qnext = NULL;
1252 FREE(qent, M_NETGRAPH_PPP);
1253 priv->qlen--;
1254 }
1255 *mp = m;
1256}
1257
1258/*
1259 * Trim fragments from the queue whose packets can never be completed.
1260 * This assumes a complete packet is NOT at the beginning of the queue.
1261 * Returns 1 if fragments were removed, zero otherwise.
1262 */
1263static int
1264ng_ppp_frag_trim(node_p node)
1265{
1266 const priv_p priv = NG_NODE_PRIVATE(node);
1267 struct ng_ppp_frag *qent, *qnext = NULL;
1268 int removed = 0;
1269
1270 /* Scan for "dead" fragments and remove them */
1271 while (1) {
1272 int dead = 0;
1273
1274 /* If queue is empty, we're done */
1275 if (TAILQ_EMPTY(&priv->frags))
1276 break;
1277
1278 /* Determine whether first fragment can ever be completed */
1279 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1280 if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1281 break;
1282 qnext = TAILQ_NEXT(qent, f_qent);
1283 KASSERT(qnext != NULL,
1284 ("%s: last frag < MSEQ?", __func__));
1285 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1286 || qent->last || qnext->first) {
1287 dead = 1;
1288 break;
1289 }
1290 }
1291 if (!dead)
1292 break;
1293
1294 /* Remove fragment and all others in the same packet */
1295 while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1296 KASSERT(!TAILQ_EMPTY(&priv->frags),
1297 ("%s: empty q", __func__));
1298 priv->bundleStats.dropFragments++;
1299 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1300 NG_FREE_M(qent->data);
1317 NG_FREE_META(qent->meta);
1318 FREE(qent, M_NETGRAPH_PPP);
1319 priv->qlen--;
1320 removed = 1;
1321 }
1322 }
1323 return (removed);
1324}
1325
1326/*
1327 * Run the queue, restoring the queue invariants
1328 */
1329static int
1330ng_ppp_frag_process(node_p node)
1331{
1332 const priv_p priv = NG_NODE_PRIVATE(node);
1333 struct mbuf *m;
1301 FREE(qent, M_NETGRAPH_PPP);
1302 priv->qlen--;
1303 removed = 1;
1304 }
1305 }
1306 return (removed);
1307}
1308
1309/*
1310 * Run the queue, restoring the queue invariants
1311 */
1312static int
1313ng_ppp_frag_process(node_p node)
1314{
1315 const priv_p priv = NG_NODE_PRIVATE(node);
1316 struct mbuf *m;
1334 meta_p meta;
1335 item_p item;
1336
1337 /* Deliver any deliverable packets */
1338 while (ng_ppp_check_packet(node)) {
1317 item_p item;
1318
1319 /* Deliver any deliverable packets */
1320 while (ng_ppp_check_packet(node)) {
1339 ng_ppp_get_packet(node, &m, &meta);
1340 item = ng_package_data(m, meta);
1321 ng_ppp_get_packet(node, &m);
1322 item = ng_package_data(m, NULL);
1341 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1342 }
1343
1344 /* Delete dead fragments and try again */
1345 if (ng_ppp_frag_trim(node)) {
1346 while (ng_ppp_check_packet(node)) {
1323 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1324 }
1325
1326 /* Delete dead fragments and try again */
1327 if (ng_ppp_frag_trim(node)) {
1328 while (ng_ppp_check_packet(node)) {
1347 ng_ppp_get_packet(node, &m, &meta);
1348 item = ng_package_data(m, meta);
1329 ng_ppp_get_packet(node, &m);
1330 item = ng_package_data(m, NULL);
1349 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1350 }
1351 }
1352
1353 /* Check for stale fragments while we're here */
1354 ng_ppp_frag_checkstale(node);
1355
1356 /* Check queue length */
1357 if (priv->qlen > MP_MAX_QUEUE_LEN) {
1358 struct ng_ppp_frag *qent;
1359 int i;
1360
1361 /* Get oldest fragment */
1362 KASSERT(!TAILQ_EMPTY(&priv->frags),
1363 ("%s: empty q", __func__));
1364 qent = TAILQ_FIRST(&priv->frags);
1365
1366 /* Bump MSEQ if necessary */
1367 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, qent->seq) < 0) {
1368 priv->mseq = qent->seq;
1369 for (i = 0; i < priv->numActiveLinks; i++) {
1370 struct ng_ppp_link *const alink =
1371 &priv->links[priv->activeLinks[i]];
1372
1373 if (MP_RECV_SEQ_DIFF(priv,
1374 alink->seq, priv->mseq) < 0)
1375 alink->seq = priv->mseq;
1376 }
1377 }
1378
1379 /* Drop it */
1380 priv->bundleStats.dropFragments++;
1381 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1382 NG_FREE_M(qent->data);
1331 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1332 }
1333 }
1334
1335 /* Check for stale fragments while we're here */
1336 ng_ppp_frag_checkstale(node);
1337
1338 /* Check queue length */
1339 if (priv->qlen > MP_MAX_QUEUE_LEN) {
1340 struct ng_ppp_frag *qent;
1341 int i;
1342
1343 /* Get oldest fragment */
1344 KASSERT(!TAILQ_EMPTY(&priv->frags),
1345 ("%s: empty q", __func__));
1346 qent = TAILQ_FIRST(&priv->frags);
1347
1348 /* Bump MSEQ if necessary */
1349 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, qent->seq) < 0) {
1350 priv->mseq = qent->seq;
1351 for (i = 0; i < priv->numActiveLinks; i++) {
1352 struct ng_ppp_link *const alink =
1353 &priv->links[priv->activeLinks[i]];
1354
1355 if (MP_RECV_SEQ_DIFF(priv,
1356 alink->seq, priv->mseq) < 0)
1357 alink->seq = priv->mseq;
1358 }
1359 }
1360
1361 /* Drop it */
1362 priv->bundleStats.dropFragments++;
1363 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1364 NG_FREE_M(qent->data);
1383 NG_FREE_META(qent->meta);
1384 FREE(qent, M_NETGRAPH_PPP);
1385 priv->qlen--;
1386
1387 /* Process queue again */
1388 return ng_ppp_frag_process(node);
1389 }
1390
1391 /* Done */
1392 return (0);
1393}
1394
1395/*
1396 * Check for 'stale' completed packets that need to be delivered
1397 *
1398 * If a link goes down or has a temporary failure, MSEQ can get
1399 * "stuck", because no new incoming fragments appear on that link.
1400 * This can cause completed packets to never get delivered if
1401 * their sequence numbers are all > MSEQ + 1.
1402 *
1403 * This routine checks how long all of the completed packets have
1404 * been sitting in the queue, and if too long, removes fragments
1405 * from the queue and increments MSEQ to allow them to be delivered.
1406 */
1407static void
1408ng_ppp_frag_checkstale(node_p node)
1409{
1410 const priv_p priv = NG_NODE_PRIVATE(node);
1411 struct ng_ppp_frag *qent, *beg, *end;
1412 struct timeval now, age;
1413 struct mbuf *m;
1365 FREE(qent, M_NETGRAPH_PPP);
1366 priv->qlen--;
1367
1368 /* Process queue again */
1369 return ng_ppp_frag_process(node);
1370 }
1371
1372 /* Done */
1373 return (0);
1374}
1375
1376/*
1377 * Check for 'stale' completed packets that need to be delivered
1378 *
1379 * If a link goes down or has a temporary failure, MSEQ can get
1380 * "stuck", because no new incoming fragments appear on that link.
1381 * This can cause completed packets to never get delivered if
1382 * their sequence numbers are all > MSEQ + 1.
1383 *
1384 * This routine checks how long all of the completed packets have
1385 * been sitting in the queue, and if too long, removes fragments
1386 * from the queue and increments MSEQ to allow them to be delivered.
1387 */
1388static void
1389ng_ppp_frag_checkstale(node_p node)
1390{
1391 const priv_p priv = NG_NODE_PRIVATE(node);
1392 struct ng_ppp_frag *qent, *beg, *end;
1393 struct timeval now, age;
1394 struct mbuf *m;
1414 meta_p meta;
1415 int i, seq;
1416 item_p item;
1417 int endseq;
1418
1419 now.tv_sec = 0; /* uninitialized state */
1420 while (1) {
1421
1422 /* If queue is empty, we're done */
1423 if (TAILQ_EMPTY(&priv->frags))
1424 break;
1425
1426 /* Find the first complete packet in the queue */
1427 beg = end = NULL;
1428 seq = TAILQ_FIRST(&priv->frags)->seq;
1429 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1430 if (qent->first)
1431 beg = qent;
1432 else if (qent->seq != seq)
1433 beg = NULL;
1434 if (beg != NULL && qent->last) {
1435 end = qent;
1436 break;
1437 }
1438 seq = MP_NEXT_RECV_SEQ(priv, seq);
1439 }
1440
1441 /* If none found, exit */
1442 if (end == NULL)
1443 break;
1444
1445 /* Get current time (we assume we've been up for >= 1 second) */
1446 if (now.tv_sec == 0)
1447 getmicrouptime(&now);
1448
1449 /* Check if packet has been queued too long */
1450 age = now;
1451 timevalsub(&age, &beg->timestamp);
1452 if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1453 break;
1454
1455 /* Throw away junk fragments in front of the completed packet */
1456 while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1457 KASSERT(!TAILQ_EMPTY(&priv->frags),
1458 ("%s: empty q", __func__));
1459 priv->bundleStats.dropFragments++;
1460 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1461 NG_FREE_M(qent->data);
1395 int i, seq;
1396 item_p item;
1397 int endseq;
1398
1399 now.tv_sec = 0; /* uninitialized state */
1400 while (1) {
1401
1402 /* If queue is empty, we're done */
1403 if (TAILQ_EMPTY(&priv->frags))
1404 break;
1405
1406 /* Find the first complete packet in the queue */
1407 beg = end = NULL;
1408 seq = TAILQ_FIRST(&priv->frags)->seq;
1409 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1410 if (qent->first)
1411 beg = qent;
1412 else if (qent->seq != seq)
1413 beg = NULL;
1414 if (beg != NULL && qent->last) {
1415 end = qent;
1416 break;
1417 }
1418 seq = MP_NEXT_RECV_SEQ(priv, seq);
1419 }
1420
1421 /* If none found, exit */
1422 if (end == NULL)
1423 break;
1424
1425 /* Get current time (we assume we've been up for >= 1 second) */
1426 if (now.tv_sec == 0)
1427 getmicrouptime(&now);
1428
1429 /* Check if packet has been queued too long */
1430 age = now;
1431 timevalsub(&age, &beg->timestamp);
1432 if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1433 break;
1434
1435 /* Throw away junk fragments in front of the completed packet */
1436 while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1437 KASSERT(!TAILQ_EMPTY(&priv->frags),
1438 ("%s: empty q", __func__));
1439 priv->bundleStats.dropFragments++;
1440 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1441 NG_FREE_M(qent->data);
1462 NG_FREE_META(qent->meta);
1463 FREE(qent, M_NETGRAPH_PPP);
1464 priv->qlen--;
1465 }
1466
1467 /* Extract completed packet */
1468 endseq = end->seq;
1442 FREE(qent, M_NETGRAPH_PPP);
1443 priv->qlen--;
1444 }
1445
1446 /* Extract completed packet */
1447 endseq = end->seq;
1469 ng_ppp_get_packet(node, &m, &meta);
1448 ng_ppp_get_packet(node, &m);
1470
1471 /* Bump MSEQ if necessary */
1472 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, endseq) < 0) {
1473 priv->mseq = endseq;
1474 for (i = 0; i < priv->numActiveLinks; i++) {
1475 struct ng_ppp_link *const alink =
1476 &priv->links[priv->activeLinks[i]];
1477
1478 if (MP_RECV_SEQ_DIFF(priv,
1479 alink->seq, priv->mseq) < 0)
1480 alink->seq = priv->mseq;
1481 }
1482 }
1483
1484 /* Deliver packet */
1449
1450 /* Bump MSEQ if necessary */
1451 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, endseq) < 0) {
1452 priv->mseq = endseq;
1453 for (i = 0; i < priv->numActiveLinks; i++) {
1454 struct ng_ppp_link *const alink =
1455 &priv->links[priv->activeLinks[i]];
1456
1457 if (MP_RECV_SEQ_DIFF(priv,
1458 alink->seq, priv->mseq) < 0)
1459 alink->seq = priv->mseq;
1460 }
1461 }
1462
1463 /* Deliver packet */
1485 item = ng_package_data(m, meta);
1464 item = ng_package_data(m, NULL);
1486 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1487 }
1488}
1489
1490/*
1491 * Periodically call ng_ppp_frag_checkstale()
1492 */
1493static void
1494ng_ppp_frag_timeout(void *arg)
1495{
1496 const node_p node = arg;
1497 const priv_p priv = NG_NODE_PRIVATE(node);
1498 int s = splnet();
1499
1500 /* Handle the race where shutdown happens just before splnet() above */
1501 if (NG_NODE_NOT_VALID(node)) {
1502 NG_NODE_UNREF(node);
1503 splx(s);
1504 return;
1505 }
1506
1507 /* Reset timer state after timeout */
1508 KASSERT(priv->timerActive, ("%s: !timerActive", __func__));
1509 priv->timerActive = 0;
1510 KASSERT(node->nd_refs > 1, ("%s: nd_refs=%d", __func__, node->nd_refs));
1511 NG_NODE_UNREF(node);
1512
1513 /* Start timer again */
1514 ng_ppp_start_frag_timer(node);
1515
1516 /* Scan the fragment queue */
1517 ng_ppp_frag_checkstale(node);
1518 splx(s);
1519}
1520
1521/*
1522 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1523 * the frame across the individual PPP links and do so.
1524 */
1525static int
1465 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, item);
1466 }
1467}
1468
1469/*
1470 * Periodically call ng_ppp_frag_checkstale()
1471 */
1472static void
1473ng_ppp_frag_timeout(void *arg)
1474{
1475 const node_p node = arg;
1476 const priv_p priv = NG_NODE_PRIVATE(node);
1477 int s = splnet();
1478
1479 /* Handle the race where shutdown happens just before splnet() above */
1480 if (NG_NODE_NOT_VALID(node)) {
1481 NG_NODE_UNREF(node);
1482 splx(s);
1483 return;
1484 }
1485
1486 /* Reset timer state after timeout */
1487 KASSERT(priv->timerActive, ("%s: !timerActive", __func__));
1488 priv->timerActive = 0;
1489 KASSERT(node->nd_refs > 1, ("%s: nd_refs=%d", __func__, node->nd_refs));
1490 NG_NODE_UNREF(node);
1491
1492 /* Start timer again */
1493 ng_ppp_start_frag_timer(node);
1494
1495 /* Scan the fragment queue */
1496 ng_ppp_frag_checkstale(node);
1497 splx(s);
1498}
1499
1500/*
1501 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1502 * the frame across the individual PPP links and do so.
1503 */
1504static int
1526ng_ppp_mp_output(node_p node, struct mbuf *m, meta_p meta)
1505ng_ppp_mp_output(node_p node, struct mbuf *m)
1527{
1528 const priv_p priv = NG_NODE_PRIVATE(node);
1529 const int hdr_len = priv->conf.xmitShortSeq ? 2 : 4;
1530 int distrib[NG_PPP_MAX_LINKS];
1531 int firstFragment;
1532 int activeLinkNum;
1533 item_p item;
1534
1535 /* At least one link must be active */
1536 if (priv->numActiveLinks == 0) {
1537 NG_FREE_M(m);
1506{
1507 const priv_p priv = NG_NODE_PRIVATE(node);
1508 const int hdr_len = priv->conf.xmitShortSeq ? 2 : 4;
1509 int distrib[NG_PPP_MAX_LINKS];
1510 int firstFragment;
1511 int activeLinkNum;
1512 item_p item;
1513
1514 /* At least one link must be active */
1515 if (priv->numActiveLinks == 0) {
1516 NG_FREE_M(m);
1538 NG_FREE_META(meta);
1539 return (ENETDOWN);
1540 }
1541
1542 /* Round-robin strategy */
1543 if (priv->conf.enableRoundRobin || m->m_pkthdr.len < MP_MIN_FRAG_LEN) {
1544 activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
1545 bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
1546 distrib[activeLinkNum] = m->m_pkthdr.len;
1547 goto deliver;
1548 }
1549
1550 /* Strategy when all links are equivalent (optimize the common case) */
1551 if (priv->allLinksEqual) {
1552 const int fraction = m->m_pkthdr.len / priv->numActiveLinks;
1553 int i, remain;
1554
1555 for (i = 0; i < priv->numActiveLinks; i++)
1556 distrib[priv->lastLink++ % priv->numActiveLinks]
1557 = fraction;
1558 remain = m->m_pkthdr.len - (fraction * priv->numActiveLinks);
1559 while (remain > 0) {
1560 distrib[priv->lastLink++ % priv->numActiveLinks]++;
1561 remain--;
1562 }
1563 goto deliver;
1564 }
1565
1566 /* Strategy when all links are not equivalent */
1567 ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
1568
1569deliver:
1570 /* Update stats */
1571 priv->bundleStats.xmitFrames++;
1572 priv->bundleStats.xmitOctets += m->m_pkthdr.len;
1573
1574 /* Send alloted portions of frame out on the link(s) */
1575 for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
1576 activeLinkNum >= 0; activeLinkNum--) {
1577 const int linkNum = priv->activeLinks[activeLinkNum];
1578 struct ng_ppp_link *const link = &priv->links[linkNum];
1579
1580 /* Deliver fragment(s) out the next link */
1581 for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
1582 int len, lastFragment, error;
1583 struct mbuf *m2;
1517 return (ENETDOWN);
1518 }
1519
1520 /* Round-robin strategy */
1521 if (priv->conf.enableRoundRobin || m->m_pkthdr.len < MP_MIN_FRAG_LEN) {
1522 activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
1523 bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
1524 distrib[activeLinkNum] = m->m_pkthdr.len;
1525 goto deliver;
1526 }
1527
1528 /* Strategy when all links are equivalent (optimize the common case) */
1529 if (priv->allLinksEqual) {
1530 const int fraction = m->m_pkthdr.len / priv->numActiveLinks;
1531 int i, remain;
1532
1533 for (i = 0; i < priv->numActiveLinks; i++)
1534 distrib[priv->lastLink++ % priv->numActiveLinks]
1535 = fraction;
1536 remain = m->m_pkthdr.len - (fraction * priv->numActiveLinks);
1537 while (remain > 0) {
1538 distrib[priv->lastLink++ % priv->numActiveLinks]++;
1539 remain--;
1540 }
1541 goto deliver;
1542 }
1543
1544 /* Strategy when all links are not equivalent */
1545 ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
1546
1547deliver:
1548 /* Update stats */
1549 priv->bundleStats.xmitFrames++;
1550 priv->bundleStats.xmitOctets += m->m_pkthdr.len;
1551
1552 /* Send alloted portions of frame out on the link(s) */
1553 for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
1554 activeLinkNum >= 0; activeLinkNum--) {
1555 const int linkNum = priv->activeLinks[activeLinkNum];
1556 struct ng_ppp_link *const link = &priv->links[linkNum];
1557
1558 /* Deliver fragment(s) out the next link */
1559 for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
1560 int len, lastFragment, error;
1561 struct mbuf *m2;
1584 meta_p meta2;
1585
1586 /* Calculate fragment length; don't exceed link MTU */
1587 len = distrib[activeLinkNum];
1588 if (len > link->conf.mru - hdr_len)
1589 len = link->conf.mru - hdr_len;
1590 distrib[activeLinkNum] -= len;
1591 lastFragment = (len == m->m_pkthdr.len);
1592
1593 /* Split off next fragment as "m2" */
1594 m2 = m;
1595 if (!lastFragment) {
1596 struct mbuf *n = m_split(m, len, M_DONTWAIT);
1597
1598 if (n == NULL) {
1599 NG_FREE_M(m);
1562
1563 /* Calculate fragment length; don't exceed link MTU */
1564 len = distrib[activeLinkNum];
1565 if (len > link->conf.mru - hdr_len)
1566 len = link->conf.mru - hdr_len;
1567 distrib[activeLinkNum] -= len;
1568 lastFragment = (len == m->m_pkthdr.len);
1569
1570 /* Split off next fragment as "m2" */
1571 m2 = m;
1572 if (!lastFragment) {
1573 struct mbuf *n = m_split(m, len, M_DONTWAIT);
1574
1575 if (n == NULL) {
1576 NG_FREE_M(m);
1600 NG_FREE_META(meta);
1601 return (ENOMEM);
1602 }
1603 m = n;
1604 }
1605
1606 /* Prepend MP header */
1607 if (priv->conf.xmitShortSeq) {
1608 u_int16_t shdr;
1609
1610 shdr = priv->xseq;
1611 priv->xseq =
1612 (priv->xseq + 1) & MP_SHORT_SEQ_MASK;
1613 if (firstFragment)
1614 shdr |= MP_SHORT_FIRST_FLAG;
1615 if (lastFragment)
1616 shdr |= MP_SHORT_LAST_FLAG;
1617 shdr = htons(shdr);
1618 m2 = ng_ppp_prepend(m2, &shdr, 2);
1619 } else {
1620 u_int32_t lhdr;
1621
1622 lhdr = priv->xseq;
1623 priv->xseq =
1624 (priv->xseq + 1) & MP_LONG_SEQ_MASK;
1625 if (firstFragment)
1626 lhdr |= MP_LONG_FIRST_FLAG;
1627 if (lastFragment)
1628 lhdr |= MP_LONG_LAST_FLAG;
1629 lhdr = htonl(lhdr);
1630 m2 = ng_ppp_prepend(m2, &lhdr, 4);
1631 }
1632 if (m2 == NULL) {
1633 if (!lastFragment)
1634 m_freem(m);
1577 return (ENOMEM);
1578 }
1579 m = n;
1580 }
1581
1582 /* Prepend MP header */
1583 if (priv->conf.xmitShortSeq) {
1584 u_int16_t shdr;
1585
1586 shdr = priv->xseq;
1587 priv->xseq =
1588 (priv->xseq + 1) & MP_SHORT_SEQ_MASK;
1589 if (firstFragment)
1590 shdr |= MP_SHORT_FIRST_FLAG;
1591 if (lastFragment)
1592 shdr |= MP_SHORT_LAST_FLAG;
1593 shdr = htons(shdr);
1594 m2 = ng_ppp_prepend(m2, &shdr, 2);
1595 } else {
1596 u_int32_t lhdr;
1597
1598 lhdr = priv->xseq;
1599 priv->xseq =
1600 (priv->xseq + 1) & MP_LONG_SEQ_MASK;
1601 if (firstFragment)
1602 lhdr |= MP_LONG_FIRST_FLAG;
1603 if (lastFragment)
1604 lhdr |= MP_LONG_LAST_FLAG;
1605 lhdr = htonl(lhdr);
1606 m2 = ng_ppp_prepend(m2, &lhdr, 4);
1607 }
1608 if (m2 == NULL) {
1609 if (!lastFragment)
1610 m_freem(m);
1635 NG_FREE_META(meta);
1636 return (ENOBUFS);
1637 }
1638
1611 return (ENOBUFS);
1612 }
1613
1639 /* Copy the meta information, if any */
1640 meta2 = lastFragment ? meta : ng_copy_meta(meta);
1641
1642 /* Send fragment */
1614 /* Send fragment */
1643 item = ng_package_data(m2, meta2);
1615 item = ng_package_data(m2, NULL);
1644 error = ng_ppp_output(node, 0, PROT_MP, linkNum, item);
1645 if (error != 0) {
1616 error = ng_ppp_output(node, 0, PROT_MP, linkNum, item);
1617 if (error != 0) {
1646 if (!lastFragment) {
1618 if (!lastFragment)
1647 NG_FREE_M(m);
1619 NG_FREE_M(m);
1648 NG_FREE_META(meta);
1649 }
1650 return (error);
1651 }
1652 }
1653 }
1654
1655 /* Done */
1656 return (0);
1657}
1658
1659/*
1660 * Computing the optimal fragmentation
1661 * -----------------------------------
1662 *
1663 * This routine tries to compute the optimal fragmentation pattern based
1664 * on each link's latency, bandwidth, and calculated additional latency.
1665 * The latter quantity is the additional latency caused by previously
1666 * written data that has not been transmitted yet.
1667 *
1668 * This algorithm is only useful when not all of the links have the
1669 * same latency and bandwidth values.
1670 *
1671 * The essential idea is to make the last bit of each fragment of the
1672 * frame arrive at the opposite end at the exact same time. This greedy
1673 * algorithm is optimal, in that no other scheduling could result in any
1674 * packet arriving any sooner unless packets are delivered out of order.
1675 *
1676 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
1677 * latency l_i (in miliseconds). Consider the function function f_i(t)
1678 * which is equal to the number of bytes that will have arrived at
1679 * the peer after t miliseconds if we start writing continuously at
1680 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
1681 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
1682 * Note that the y-intersect is always <= zero because latency can't be
1683 * negative. Note also that really the function is f_i(t) except when
1684 * f_i(t) is negative, in which case the function is zero. To take
1685 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
1686 * So the actual number of bytes that will have arrived at the peer after
1687 * t miliseconds is f_i(t) * Q_i(t).
1688 *
1689 * At any given time, each link has some additional latency a_i >= 0
1690 * due to previously written fragment(s) which are still in the queue.
1691 * This value is easily computed from the time since last transmission,
1692 * the previous latency value, the number of bytes written, and the
1693 * link's bandwidth.
1694 *
1695 * Assume that l_i includes any a_i already, and that the links are
1696 * sorted by latency, so that l_i <= l_{i+1}.
1697 *
1698 * Let N be the total number of bytes in the current frame we are sending.
1699 *
1700 * Suppose we were to start writing bytes at time t = 0 on all links
1701 * simultaneously, which is the most we can possibly do. Then let
1702 * F(t) be equal to the total number of bytes received by the peer
1703 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
1704 *
1705 * Our goal is simply this: fragment the frame across the links such
1706 * that the peer is able to reconstruct the completed frame as soon as
1707 * possible, i.e., at the least possible value of t. Call this value t_0.
1708 *
1709 * Then it follows that F(t_0) = N. Our strategy is first to find the value
1710 * of t_0, and then deduce how many bytes to write to each link.
1711 *
1712 * Rewriting F(t_0):
1713 *
1714 * t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
1715 *
1716 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
1717 * lie in one of these ranges. To find it, we just need to find the i such
1718 * that F(l_i) <= N <= F(l_{i+1}). Then we compute all the constant values
1719 * for Q_i() in this range, plug in the remaining values, solving for t_0.
1720 *
1721 * Once t_0 is known, then the number of bytes to send on link i is
1722 * just f_i(t_0) * Q_i(t_0).
1723 *
1724 * In other words, we start allocating bytes to the links one at a time.
1725 * We keep adding links until the frame is completely sent. Some links
1726 * may not get any bytes because their latency is too high.
1727 *
1728 * Is all this work really worth the trouble? Depends on the situation.
1729 * The bigger the ratio of computer speed to link speed, and the more
1730 * important total bundle latency is (e.g., for interactive response time),
1731 * the more it's worth it. There is however the cost of calling this
1732 * function for every frame. The running time is O(n^2) where n is the
1733 * number of links that receive a non-zero number of bytes.
1734 *
1735 * Since latency is measured in miliseconds, the "resolution" of this
1736 * algorithm is one milisecond.
1737 *
1738 * To avoid this algorithm altogether, configure all links to have the
1739 * same latency and bandwidth.
1740 */
1741static void
1742ng_ppp_mp_strategy(node_p node, int len, int *distrib)
1743{
1744 const priv_p priv = NG_NODE_PRIVATE(node);
1745 int latency[NG_PPP_MAX_LINKS];
1746 int sortByLatency[NG_PPP_MAX_LINKS];
1747 int activeLinkNum;
1748 int t0, total, topSum, botSum;
1749 struct timeval now;
1750 int i, numFragments;
1751
1752 /* If only one link, this gets real easy */
1753 if (priv->numActiveLinks == 1) {
1754 distrib[0] = len;
1755 return;
1756 }
1757
1758 /* Get current time */
1759 getmicrouptime(&now);
1760
1761 /* Compute latencies for each link at this point in time */
1762 for (activeLinkNum = 0;
1763 activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
1764 struct ng_ppp_link *alink;
1765 struct timeval diff;
1766 int xmitBytes;
1767
1768 /* Start with base latency value */
1769 alink = &priv->links[priv->activeLinks[activeLinkNum]];
1770 latency[activeLinkNum] = alink->conf.latency;
1771 sortByLatency[activeLinkNum] = activeLinkNum; /* see below */
1772
1773 /* Any additional latency? */
1774 if (alink->bytesInQueue == 0)
1775 continue;
1776
1777 /* Compute time delta since last write */
1778 diff = now;
1779 timevalsub(&diff, &alink->lastWrite);
1780 if (now.tv_sec < 0 || diff.tv_sec >= 10) { /* sanity */
1781 alink->bytesInQueue = 0;
1782 continue;
1783 }
1784
1785 /* How many bytes could have transmitted since last write? */
1786 xmitBytes = (alink->conf.bandwidth * diff.tv_sec)
1787 + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
1788 alink->bytesInQueue -= xmitBytes;
1789 if (alink->bytesInQueue < 0)
1790 alink->bytesInQueue = 0;
1791 else
1792 latency[activeLinkNum] +=
1793 (100 * alink->bytesInQueue) / alink->conf.bandwidth;
1794 }
1795
1796 /* Sort active links by latency */
1797 compareLatencies = latency;
1798 qsort(sortByLatency,
1799 priv->numActiveLinks, sizeof(*sortByLatency), ng_ppp_intcmp);
1800 compareLatencies = NULL;
1801
1802 /* Find the interval we need (add links in sortByLatency[] order) */
1803 for (numFragments = 1;
1804 numFragments < priv->numActiveLinks; numFragments++) {
1805 for (total = i = 0; i < numFragments; i++) {
1806 int flowTime;
1807
1808 flowTime = latency[sortByLatency[numFragments]]
1809 - latency[sortByLatency[i]];
1810 total += ((flowTime * priv->links[
1811 priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
1812 + 99) / 100;
1813 }
1814 if (total >= len)
1815 break;
1816 }
1817
1818 /* Solve for t_0 in that interval */
1819 for (topSum = botSum = i = 0; i < numFragments; i++) {
1820 int bw = priv->links[
1821 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1822
1823 topSum += latency[sortByLatency[i]] * bw; /* / 100 */
1824 botSum += bw; /* / 100 */
1825 }
1826 t0 = ((len * 100) + topSum + botSum / 2) / botSum;
1827
1828 /* Compute f_i(t_0) all i */
1829 bzero(distrib, priv->numActiveLinks * sizeof(*distrib));
1830 for (total = i = 0; i < numFragments; i++) {
1831 int bw = priv->links[
1832 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1833
1834 distrib[sortByLatency[i]] =
1835 (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
1836 total += distrib[sortByLatency[i]];
1837 }
1838
1839 /* Deal with any rounding error */
1840 if (total < len) {
1841 struct ng_ppp_link *fastLink =
1842 &priv->links[priv->activeLinks[sortByLatency[0]]];
1843 int fast = 0;
1844
1845 /* Find the fastest link */
1846 for (i = 1; i < numFragments; i++) {
1847 struct ng_ppp_link *const link =
1848 &priv->links[priv->activeLinks[sortByLatency[i]]];
1849
1850 if (link->conf.bandwidth > fastLink->conf.bandwidth) {
1851 fast = i;
1852 fastLink = link;
1853 }
1854 }
1855 distrib[sortByLatency[fast]] += len - total;
1856 } else while (total > len) {
1857 struct ng_ppp_link *slowLink =
1858 &priv->links[priv->activeLinks[sortByLatency[0]]];
1859 int delta, slow = 0;
1860
1861 /* Find the slowest link that still has bytes to remove */
1862 for (i = 1; i < numFragments; i++) {
1863 struct ng_ppp_link *const link =
1864 &priv->links[priv->activeLinks[sortByLatency[i]]];
1865
1866 if (distrib[sortByLatency[slow]] == 0
1867 || (distrib[sortByLatency[i]] > 0
1868 && link->conf.bandwidth <
1869 slowLink->conf.bandwidth)) {
1870 slow = i;
1871 slowLink = link;
1872 }
1873 }
1874 delta = total - len;
1875 if (delta > distrib[sortByLatency[slow]])
1876 delta = distrib[sortByLatency[slow]];
1877 distrib[sortByLatency[slow]] -= delta;
1878 total -= delta;
1879 }
1880}
1881
1882/*
1883 * Compare two integers
1884 */
1885static int
1886ng_ppp_intcmp(const void *v1, const void *v2)
1887{
1888 const int index1 = *((const int *) v1);
1889 const int index2 = *((const int *) v2);
1890
1891 return compareLatencies[index1] - compareLatencies[index2];
1892}
1893
1894/*
1895 * Prepend a possibly compressed PPP protocol number in front of a frame
1896 */
1897static struct mbuf *
1898ng_ppp_addproto(struct mbuf *m, int proto, int compOK)
1899{
1900 if (compOK && PROT_COMPRESSABLE(proto)) {
1901 u_char pbyte = (u_char)proto;
1902
1903 return ng_ppp_prepend(m, &pbyte, 1);
1904 } else {
1905 u_int16_t pword = htons((u_int16_t)proto);
1906
1907 return ng_ppp_prepend(m, &pword, 2);
1908 }
1909}
1910
1911/*
1912 * Prepend some bytes to an mbuf
1913 */
1914static struct mbuf *
1915ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
1916{
1917 M_PREPEND(m, len, M_DONTWAIT);
1918 if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
1919 return (NULL);
1920 bcopy(buf, mtod(m, u_char *), len);
1921 return (m);
1922}
1923
1924/*
1925 * Update private information that is derived from other private information
1926 */
1927static void
1928ng_ppp_update(node_p node, int newConf)
1929{
1930 const priv_p priv = NG_NODE_PRIVATE(node);
1931 int i;
1932
1933 /* Update active status for VJ Compression */
1934 priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
1935 && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
1936 && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
1937 && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
1938
1939 /* Increase latency for each link an amount equal to one MP header */
1940 if (newConf) {
1941 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1942 int hdrBytes;
1943
1944 hdrBytes = (priv->links[i].conf.enableACFComp ? 0 : 2)
1945 + (priv->links[i].conf.enableProtoComp ? 1 : 2)
1946 + (priv->conf.xmitShortSeq ? 2 : 4);
1947 priv->links[i].conf.latency +=
1948 ((hdrBytes * priv->links[i].conf.bandwidth) + 50)
1949 / 100;
1950 }
1951 }
1952
1953 /* Update list of active links */
1954 bzero(&priv->activeLinks, sizeof(priv->activeLinks));
1955 priv->numActiveLinks = 0;
1956 priv->allLinksEqual = 1;
1957 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1958 struct ng_ppp_link *const link = &priv->links[i];
1959
1960 /* Is link active? */
1961 if (link->conf.enableLink && link->hook != NULL) {
1962 struct ng_ppp_link *link0;
1963
1964 /* Add link to list of active links */
1965 priv->activeLinks[priv->numActiveLinks++] = i;
1966 link0 = &priv->links[priv->activeLinks[0]];
1967
1968 /* Determine if all links are still equal */
1969 if (link->conf.latency != link0->conf.latency
1970 || link->conf.bandwidth != link0->conf.bandwidth)
1971 priv->allLinksEqual = 0;
1972
1973 /* Initialize rec'd sequence number */
1974 if (link->seq == MP_NOSEQ) {
1975 link->seq = (link == link0) ?
1976 MP_INITIAL_SEQ : link0->seq;
1977 }
1978 } else
1979 link->seq = MP_NOSEQ;
1980 }
1981
1982 /* Update MP state as multi-link is active or not */
1983 if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
1984 ng_ppp_start_frag_timer(node);
1985 else {
1986 ng_ppp_stop_frag_timer(node);
1987 ng_ppp_frag_reset(node);
1988 priv->xseq = MP_INITIAL_SEQ;
1989 priv->mseq = MP_INITIAL_SEQ;
1990 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1991 struct ng_ppp_link *const link = &priv->links[i];
1992
1993 bzero(&link->lastWrite, sizeof(link->lastWrite));
1994 link->bytesInQueue = 0;
1995 link->seq = MP_NOSEQ;
1996 }
1997 }
1998}
1999
2000/*
2001 * Determine if a new configuration would represent a valid change
2002 * from the current configuration and link activity status.
2003 */
2004static int
2005ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
2006{
2007 const priv_p priv = NG_NODE_PRIVATE(node);
2008 int i, newNumLinksActive;
2009
2010 /* Check per-link config and count how many links would be active */
2011 for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
2012 if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
2013 newNumLinksActive++;
2014 if (!newConf->links[i].enableLink)
2015 continue;
2016 if (newConf->links[i].mru < MP_MIN_LINK_MRU)
2017 return (0);
2018 if (newConf->links[i].bandwidth == 0)
2019 return (0);
2020 if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
2021 return (0);
2022 if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
2023 return (0);
2024 }
2025
2026 /* Check bundle parameters */
2027 if (newConf->bund.enableMultilink && newConf->bund.mrru < MP_MIN_MRRU)
2028 return (0);
2029
2030 /* Disallow changes to multi-link configuration while MP is active */
2031 if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
2032 if (!priv->conf.enableMultilink
2033 != !newConf->bund.enableMultilink
2034 || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
2035 || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
2036 return (0);
2037 }
2038
2039 /* At most one link can be active unless multi-link is enabled */
2040 if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
2041 return (0);
2042
2043 /* Configuration change would be valid */
2044 return (1);
2045}
2046
2047/*
2048 * Free all entries in the fragment queue
2049 */
2050static void
2051ng_ppp_frag_reset(node_p node)
2052{
2053 const priv_p priv = NG_NODE_PRIVATE(node);
2054 struct ng_ppp_frag *qent, *qnext;
2055
2056 for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
2057 qnext = TAILQ_NEXT(qent, f_qent);
2058 NG_FREE_M(qent->data);
1620 return (error);
1621 }
1622 }
1623 }
1624
1625 /* Done */
1626 return (0);
1627}
1628
1629/*
1630 * Computing the optimal fragmentation
1631 * -----------------------------------
1632 *
1633 * This routine tries to compute the optimal fragmentation pattern based
1634 * on each link's latency, bandwidth, and calculated additional latency.
1635 * The latter quantity is the additional latency caused by previously
1636 * written data that has not been transmitted yet.
1637 *
1638 * This algorithm is only useful when not all of the links have the
1639 * same latency and bandwidth values.
1640 *
1641 * The essential idea is to make the last bit of each fragment of the
1642 * frame arrive at the opposite end at the exact same time. This greedy
1643 * algorithm is optimal, in that no other scheduling could result in any
1644 * packet arriving any sooner unless packets are delivered out of order.
1645 *
1646 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
1647 * latency l_i (in miliseconds). Consider the function function f_i(t)
1648 * which is equal to the number of bytes that will have arrived at
1649 * the peer after t miliseconds if we start writing continuously at
1650 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
1651 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
1652 * Note that the y-intersect is always <= zero because latency can't be
1653 * negative. Note also that really the function is f_i(t) except when
1654 * f_i(t) is negative, in which case the function is zero. To take
1655 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
1656 * So the actual number of bytes that will have arrived at the peer after
1657 * t miliseconds is f_i(t) * Q_i(t).
1658 *
1659 * At any given time, each link has some additional latency a_i >= 0
1660 * due to previously written fragment(s) which are still in the queue.
1661 * This value is easily computed from the time since last transmission,
1662 * the previous latency value, the number of bytes written, and the
1663 * link's bandwidth.
1664 *
1665 * Assume that l_i includes any a_i already, and that the links are
1666 * sorted by latency, so that l_i <= l_{i+1}.
1667 *
1668 * Let N be the total number of bytes in the current frame we are sending.
1669 *
1670 * Suppose we were to start writing bytes at time t = 0 on all links
1671 * simultaneously, which is the most we can possibly do. Then let
1672 * F(t) be equal to the total number of bytes received by the peer
1673 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
1674 *
1675 * Our goal is simply this: fragment the frame across the links such
1676 * that the peer is able to reconstruct the completed frame as soon as
1677 * possible, i.e., at the least possible value of t. Call this value t_0.
1678 *
1679 * Then it follows that F(t_0) = N. Our strategy is first to find the value
1680 * of t_0, and then deduce how many bytes to write to each link.
1681 *
1682 * Rewriting F(t_0):
1683 *
1684 * t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
1685 *
1686 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
1687 * lie in one of these ranges. To find it, we just need to find the i such
1688 * that F(l_i) <= N <= F(l_{i+1}). Then we compute all the constant values
1689 * for Q_i() in this range, plug in the remaining values, solving for t_0.
1690 *
1691 * Once t_0 is known, then the number of bytes to send on link i is
1692 * just f_i(t_0) * Q_i(t_0).
1693 *
1694 * In other words, we start allocating bytes to the links one at a time.
1695 * We keep adding links until the frame is completely sent. Some links
1696 * may not get any bytes because their latency is too high.
1697 *
1698 * Is all this work really worth the trouble? Depends on the situation.
1699 * The bigger the ratio of computer speed to link speed, and the more
1700 * important total bundle latency is (e.g., for interactive response time),
1701 * the more it's worth it. There is however the cost of calling this
1702 * function for every frame. The running time is O(n^2) where n is the
1703 * number of links that receive a non-zero number of bytes.
1704 *
1705 * Since latency is measured in miliseconds, the "resolution" of this
1706 * algorithm is one milisecond.
1707 *
1708 * To avoid this algorithm altogether, configure all links to have the
1709 * same latency and bandwidth.
1710 */
1711static void
1712ng_ppp_mp_strategy(node_p node, int len, int *distrib)
1713{
1714 const priv_p priv = NG_NODE_PRIVATE(node);
1715 int latency[NG_PPP_MAX_LINKS];
1716 int sortByLatency[NG_PPP_MAX_LINKS];
1717 int activeLinkNum;
1718 int t0, total, topSum, botSum;
1719 struct timeval now;
1720 int i, numFragments;
1721
1722 /* If only one link, this gets real easy */
1723 if (priv->numActiveLinks == 1) {
1724 distrib[0] = len;
1725 return;
1726 }
1727
1728 /* Get current time */
1729 getmicrouptime(&now);
1730
1731 /* Compute latencies for each link at this point in time */
1732 for (activeLinkNum = 0;
1733 activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
1734 struct ng_ppp_link *alink;
1735 struct timeval diff;
1736 int xmitBytes;
1737
1738 /* Start with base latency value */
1739 alink = &priv->links[priv->activeLinks[activeLinkNum]];
1740 latency[activeLinkNum] = alink->conf.latency;
1741 sortByLatency[activeLinkNum] = activeLinkNum; /* see below */
1742
1743 /* Any additional latency? */
1744 if (alink->bytesInQueue == 0)
1745 continue;
1746
1747 /* Compute time delta since last write */
1748 diff = now;
1749 timevalsub(&diff, &alink->lastWrite);
1750 if (now.tv_sec < 0 || diff.tv_sec >= 10) { /* sanity */
1751 alink->bytesInQueue = 0;
1752 continue;
1753 }
1754
1755 /* How many bytes could have transmitted since last write? */
1756 xmitBytes = (alink->conf.bandwidth * diff.tv_sec)
1757 + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
1758 alink->bytesInQueue -= xmitBytes;
1759 if (alink->bytesInQueue < 0)
1760 alink->bytesInQueue = 0;
1761 else
1762 latency[activeLinkNum] +=
1763 (100 * alink->bytesInQueue) / alink->conf.bandwidth;
1764 }
1765
1766 /* Sort active links by latency */
1767 compareLatencies = latency;
1768 qsort(sortByLatency,
1769 priv->numActiveLinks, sizeof(*sortByLatency), ng_ppp_intcmp);
1770 compareLatencies = NULL;
1771
1772 /* Find the interval we need (add links in sortByLatency[] order) */
1773 for (numFragments = 1;
1774 numFragments < priv->numActiveLinks; numFragments++) {
1775 for (total = i = 0; i < numFragments; i++) {
1776 int flowTime;
1777
1778 flowTime = latency[sortByLatency[numFragments]]
1779 - latency[sortByLatency[i]];
1780 total += ((flowTime * priv->links[
1781 priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
1782 + 99) / 100;
1783 }
1784 if (total >= len)
1785 break;
1786 }
1787
1788 /* Solve for t_0 in that interval */
1789 for (topSum = botSum = i = 0; i < numFragments; i++) {
1790 int bw = priv->links[
1791 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1792
1793 topSum += latency[sortByLatency[i]] * bw; /* / 100 */
1794 botSum += bw; /* / 100 */
1795 }
1796 t0 = ((len * 100) + topSum + botSum / 2) / botSum;
1797
1798 /* Compute f_i(t_0) all i */
1799 bzero(distrib, priv->numActiveLinks * sizeof(*distrib));
1800 for (total = i = 0; i < numFragments; i++) {
1801 int bw = priv->links[
1802 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1803
1804 distrib[sortByLatency[i]] =
1805 (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
1806 total += distrib[sortByLatency[i]];
1807 }
1808
1809 /* Deal with any rounding error */
1810 if (total < len) {
1811 struct ng_ppp_link *fastLink =
1812 &priv->links[priv->activeLinks[sortByLatency[0]]];
1813 int fast = 0;
1814
1815 /* Find the fastest link */
1816 for (i = 1; i < numFragments; i++) {
1817 struct ng_ppp_link *const link =
1818 &priv->links[priv->activeLinks[sortByLatency[i]]];
1819
1820 if (link->conf.bandwidth > fastLink->conf.bandwidth) {
1821 fast = i;
1822 fastLink = link;
1823 }
1824 }
1825 distrib[sortByLatency[fast]] += len - total;
1826 } else while (total > len) {
1827 struct ng_ppp_link *slowLink =
1828 &priv->links[priv->activeLinks[sortByLatency[0]]];
1829 int delta, slow = 0;
1830
1831 /* Find the slowest link that still has bytes to remove */
1832 for (i = 1; i < numFragments; i++) {
1833 struct ng_ppp_link *const link =
1834 &priv->links[priv->activeLinks[sortByLatency[i]]];
1835
1836 if (distrib[sortByLatency[slow]] == 0
1837 || (distrib[sortByLatency[i]] > 0
1838 && link->conf.bandwidth <
1839 slowLink->conf.bandwidth)) {
1840 slow = i;
1841 slowLink = link;
1842 }
1843 }
1844 delta = total - len;
1845 if (delta > distrib[sortByLatency[slow]])
1846 delta = distrib[sortByLatency[slow]];
1847 distrib[sortByLatency[slow]] -= delta;
1848 total -= delta;
1849 }
1850}
1851
1852/*
1853 * Compare two integers
1854 */
1855static int
1856ng_ppp_intcmp(const void *v1, const void *v2)
1857{
1858 const int index1 = *((const int *) v1);
1859 const int index2 = *((const int *) v2);
1860
1861 return compareLatencies[index1] - compareLatencies[index2];
1862}
1863
1864/*
1865 * Prepend a possibly compressed PPP protocol number in front of a frame
1866 */
1867static struct mbuf *
1868ng_ppp_addproto(struct mbuf *m, int proto, int compOK)
1869{
1870 if (compOK && PROT_COMPRESSABLE(proto)) {
1871 u_char pbyte = (u_char)proto;
1872
1873 return ng_ppp_prepend(m, &pbyte, 1);
1874 } else {
1875 u_int16_t pword = htons((u_int16_t)proto);
1876
1877 return ng_ppp_prepend(m, &pword, 2);
1878 }
1879}
1880
1881/*
1882 * Prepend some bytes to an mbuf
1883 */
1884static struct mbuf *
1885ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
1886{
1887 M_PREPEND(m, len, M_DONTWAIT);
1888 if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
1889 return (NULL);
1890 bcopy(buf, mtod(m, u_char *), len);
1891 return (m);
1892}
1893
1894/*
1895 * Update private information that is derived from other private information
1896 */
1897static void
1898ng_ppp_update(node_p node, int newConf)
1899{
1900 const priv_p priv = NG_NODE_PRIVATE(node);
1901 int i;
1902
1903 /* Update active status for VJ Compression */
1904 priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
1905 && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
1906 && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
1907 && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
1908
1909 /* Increase latency for each link an amount equal to one MP header */
1910 if (newConf) {
1911 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1912 int hdrBytes;
1913
1914 hdrBytes = (priv->links[i].conf.enableACFComp ? 0 : 2)
1915 + (priv->links[i].conf.enableProtoComp ? 1 : 2)
1916 + (priv->conf.xmitShortSeq ? 2 : 4);
1917 priv->links[i].conf.latency +=
1918 ((hdrBytes * priv->links[i].conf.bandwidth) + 50)
1919 / 100;
1920 }
1921 }
1922
1923 /* Update list of active links */
1924 bzero(&priv->activeLinks, sizeof(priv->activeLinks));
1925 priv->numActiveLinks = 0;
1926 priv->allLinksEqual = 1;
1927 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1928 struct ng_ppp_link *const link = &priv->links[i];
1929
1930 /* Is link active? */
1931 if (link->conf.enableLink && link->hook != NULL) {
1932 struct ng_ppp_link *link0;
1933
1934 /* Add link to list of active links */
1935 priv->activeLinks[priv->numActiveLinks++] = i;
1936 link0 = &priv->links[priv->activeLinks[0]];
1937
1938 /* Determine if all links are still equal */
1939 if (link->conf.latency != link0->conf.latency
1940 || link->conf.bandwidth != link0->conf.bandwidth)
1941 priv->allLinksEqual = 0;
1942
1943 /* Initialize rec'd sequence number */
1944 if (link->seq == MP_NOSEQ) {
1945 link->seq = (link == link0) ?
1946 MP_INITIAL_SEQ : link0->seq;
1947 }
1948 } else
1949 link->seq = MP_NOSEQ;
1950 }
1951
1952 /* Update MP state as multi-link is active or not */
1953 if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
1954 ng_ppp_start_frag_timer(node);
1955 else {
1956 ng_ppp_stop_frag_timer(node);
1957 ng_ppp_frag_reset(node);
1958 priv->xseq = MP_INITIAL_SEQ;
1959 priv->mseq = MP_INITIAL_SEQ;
1960 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1961 struct ng_ppp_link *const link = &priv->links[i];
1962
1963 bzero(&link->lastWrite, sizeof(link->lastWrite));
1964 link->bytesInQueue = 0;
1965 link->seq = MP_NOSEQ;
1966 }
1967 }
1968}
1969
1970/*
1971 * Determine if a new configuration would represent a valid change
1972 * from the current configuration and link activity status.
1973 */
1974static int
1975ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
1976{
1977 const priv_p priv = NG_NODE_PRIVATE(node);
1978 int i, newNumLinksActive;
1979
1980 /* Check per-link config and count how many links would be active */
1981 for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
1982 if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
1983 newNumLinksActive++;
1984 if (!newConf->links[i].enableLink)
1985 continue;
1986 if (newConf->links[i].mru < MP_MIN_LINK_MRU)
1987 return (0);
1988 if (newConf->links[i].bandwidth == 0)
1989 return (0);
1990 if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
1991 return (0);
1992 if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
1993 return (0);
1994 }
1995
1996 /* Check bundle parameters */
1997 if (newConf->bund.enableMultilink && newConf->bund.mrru < MP_MIN_MRRU)
1998 return (0);
1999
2000 /* Disallow changes to multi-link configuration while MP is active */
2001 if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
2002 if (!priv->conf.enableMultilink
2003 != !newConf->bund.enableMultilink
2004 || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
2005 || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
2006 return (0);
2007 }
2008
2009 /* At most one link can be active unless multi-link is enabled */
2010 if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
2011 return (0);
2012
2013 /* Configuration change would be valid */
2014 return (1);
2015}
2016
2017/*
2018 * Free all entries in the fragment queue
2019 */
2020static void
2021ng_ppp_frag_reset(node_p node)
2022{
2023 const priv_p priv = NG_NODE_PRIVATE(node);
2024 struct ng_ppp_frag *qent, *qnext;
2025
2026 for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
2027 qnext = TAILQ_NEXT(qent, f_qent);
2028 NG_FREE_M(qent->data);
2059 NG_FREE_META(qent->meta);
2060 FREE(qent, M_NETGRAPH_PPP);
2061 }
2062 TAILQ_INIT(&priv->frags);
2063 priv->qlen = 0;
2064}
2065
2066/*
2067 * Start fragment queue timer
2068 */
2069static void
2070ng_ppp_start_frag_timer(node_p node)
2071{
2072 const priv_p priv = NG_NODE_PRIVATE(node);
2073
2074 if (!priv->timerActive) {
2075 priv->fragTimer = timeout(ng_ppp_frag_timeout,
2076 node, MP_FRAGTIMER_INTERVAL);
2077 priv->timerActive = 1;
2078 NG_NODE_REF(node);
2079 }
2080}
2081
2082/*
2083 * Stop fragment queue timer
2084 */
2085static void
2086ng_ppp_stop_frag_timer(node_p node)
2087{
2088 const priv_p priv = NG_NODE_PRIVATE(node);
2089
2090 if (priv->timerActive) {
2091 untimeout(ng_ppp_frag_timeout, node, priv->fragTimer);
2092 priv->timerActive = 0;
2093 KASSERT(node->nd_refs > 1,
2094 ("%s: nd_refs=%d", __func__, node->nd_refs));
2095 NG_NODE_UNREF(node);
2096 }
2097}
2098
2029 FREE(qent, M_NETGRAPH_PPP);
2030 }
2031 TAILQ_INIT(&priv->frags);
2032 priv->qlen = 0;
2033}
2034
2035/*
2036 * Start fragment queue timer
2037 */
2038static void
2039ng_ppp_start_frag_timer(node_p node)
2040{
2041 const priv_p priv = NG_NODE_PRIVATE(node);
2042
2043 if (!priv->timerActive) {
2044 priv->fragTimer = timeout(ng_ppp_frag_timeout,
2045 node, MP_FRAGTIMER_INTERVAL);
2046 priv->timerActive = 1;
2047 NG_NODE_REF(node);
2048 }
2049}
2050
2051/*
2052 * Stop fragment queue timer
2053 */
2054static void
2055ng_ppp_stop_frag_timer(node_p node)
2056{
2057 const priv_p priv = NG_NODE_PRIVATE(node);
2058
2059 if (priv->timerActive) {
2060 untimeout(ng_ppp_frag_timeout, node, priv->fragTimer);
2061 priv->timerActive = 0;
2062 KASSERT(node->nd_refs > 1,
2063 ("%s: nd_refs=%d", __func__, node->nd_refs));
2064 NG_NODE_UNREF(node);
2065 }
2066}
2067