Vendor import of netgraph from FreeBSD-current 20080626
[dragonfly.git] / sys / netgraph7 / ng_l2tp.c
1 /*-
2  * Copyright (c) 2001-2002 Packet Design, LLC.
3  * All rights reserved.
4  * 
5  * Subject to the following obligations and disclaimer of warranty,
6  * use and redistribution of this software, in source or object code
7  * forms, with or without modifications are expressly permitted by
8  * Packet Design; provided, however, that:
9  * 
10  *    (i)  Any and all reproductions of the source or object code
11  *         must include the copyright notice above and the following
12  *         disclaimer of warranties; and
13  *    (ii) No rights are granted, in any manner or form, to use
14  *         Packet Design trademarks, including the mark "PACKET DESIGN"
15  *         on advertising, endorsements, or otherwise except as such
16  *         appears in the above copyright notice or in the software.
17  * 
18  * THIS SOFTWARE IS BEING PROVIDED BY PACKET DESIGN "AS IS", AND
19  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, PACKET DESIGN MAKES NO
20  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING
21  * THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED
22  * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
23  * OR NON-INFRINGEMENT.  PACKET DESIGN DOES NOT WARRANT, GUARANTEE,
24  * OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS
25  * OF THE USE OF THIS SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY,
26  * RELIABILITY OR OTHERWISE.  IN NO EVENT SHALL PACKET DESIGN BE
27  * LIABLE FOR ANY DAMAGES RESULTING FROM OR ARISING OUT OF ANY USE
28  * OF THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY DIRECT,
29  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL
30  * DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF
31  * USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY THEORY OF
32  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
34  * THE USE OF THIS SOFTWARE, EVEN IF PACKET DESIGN IS ADVISED OF
35  * THE POSSIBILITY OF SUCH DAMAGE.
36  * 
37  * Author: Archie Cobbs <archie@freebsd.org>
38  *
39  * $FreeBSD: src/sys/netgraph/ng_l2tp.c,v 1.25 2008/03/16 21:33:12 mav Exp $
40  */
41
42 /*
43  * L2TP netgraph node type.
44  *
45  * This node type implements the lower layer of the
46  * L2TP protocol as specified in RFC 2661.
47  */
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/kernel.h>
52 #include <sys/time.h>
53 #include <sys/conf.h>
54 #include <sys/mbuf.h>
55 #include <sys/malloc.h>
56 #include <sys/errno.h>
57 #include <sys/libkern.h>
58
59 #include <netgraph/ng_message.h>
60 #include <netgraph/netgraph.h>
61 #include <netgraph/ng_parse.h>
62 #include <netgraph/ng_l2tp.h>
63
64 #ifdef NG_SEPARATE_MALLOC
65 MALLOC_DEFINE(M_NETGRAPH_L2TP, "netgraph_l2tp", "netgraph l2tp node");
66 #else
67 #define M_NETGRAPH_L2TP M_NETGRAPH
68 #endif
69
70 /* L2TP header format (first 2 bytes only) */
71 #define L2TP_HDR_CTRL           0x8000                  /* control packet */
72 #define L2TP_HDR_LEN            0x4000                  /* has length field */
73 #define L2TP_HDR_SEQ            0x0800                  /* has ns, nr fields */
74 #define L2TP_HDR_OFF            0x0200                  /* has offset field */
75 #define L2TP_HDR_PRIO           0x0100                  /* give priority */
76 #define L2TP_HDR_VERS_MASK      0x000f                  /* version field mask */
77 #define L2TP_HDR_VERSION        0x0002                  /* version field */
78
79 /* Bits that must be zero or one in first two bytes of header */
80 #define L2TP_CTRL_0BITS         0x030d                  /* ctrl: must be 0 */
81 #define L2TP_CTRL_1BITS         0xc802                  /* ctrl: must be 1 */
82 #define L2TP_DATA_0BITS         0x800d                  /* data: must be 0 */
83 #define L2TP_DATA_1BITS         0x0002                  /* data: must be 1 */
84
85 /* Standard xmit ctrl and data header bits */
86 #define L2TP_CTRL_HDR           (L2TP_HDR_CTRL | L2TP_HDR_LEN \
87                                     | L2TP_HDR_SEQ | L2TP_HDR_VERSION)
88 #define L2TP_DATA_HDR           (L2TP_HDR_VERSION)      /* optional: len, seq */
89
90 /* Some hard coded values */
91 #define L2TP_MAX_XWIN           128                     /* my max xmit window */
92 #define L2TP_MAX_REXMIT         5                       /* default max rexmit */
93 #define L2TP_MAX_REXMIT_TO      30                      /* default rexmit to */
94 #define L2TP_DELAYED_ACK        ((hz + 19) / 20)        /* delayed ack: 50 ms */
95
96 /* Default data sequence number configuration for new sessions */
97 #define L2TP_CONTROL_DSEQ       1                       /* we are the lns */
98 #define L2TP_ENABLE_DSEQ        1                       /* enable data seq # */
99
100 /* Compare sequence numbers using circular math */
101 #define L2TP_SEQ_DIFF(x, y)     ((int)((int16_t)(x) - (int16_t)(y)))
102
103 #define SESSHASHSIZE            0x0020
104 #define SESSHASH(x)             (((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
105
106 /* Hook private data (data session hooks only) */
107 struct ng_l2tp_hook_private {
108         struct ng_l2tp_sess_config      conf;   /* hook/session config */
109         struct ng_l2tp_session_stats    stats;  /* per sessions statistics */
110         hook_p                          hook;   /* hook reference */
111         u_int16_t                       ns;     /* data ns sequence number */
112         u_int16_t                       nr;     /* data nr sequence number */
113         LIST_ENTRY(ng_l2tp_hook_private) sessions;
114 };
115 typedef struct ng_l2tp_hook_private *hookpriv_p;
116
117 /*
118  * Sequence number state
119  *
120  * Invariants:
121  *    - If cwnd < ssth, we're doing slow start, otherwise congestion avoidance
122  *    - The number of unacknowledged xmit packets is (ns - rack) <= seq->wmax
123  *    - The first (ns - rack) mbuf's in xwin[] array are copies of these
124  *      unacknowledged packets; the remainder of xwin[] consists first of
125  *      zero or more further untransmitted packets in the transmit queue
126  *    - We try to keep the peer's receive window as full as possible.
127  *      Therefore, (i < cwnd && xwin[i] != NULL) implies (ns - rack) > i.
128  *    - rack_timer is running iff (ns - rack) > 0 (unack'd xmit'd pkts)
129  *    - If xack != nr, there are unacknowledged recv packet(s) (delayed ack)
130  *    - xack_timer is running iff xack != nr (unack'd rec'd pkts)
131  */
132 struct l2tp_seq {
133         u_int16_t               ns;             /* next xmit seq we send */
134         u_int16_t               nr;             /* next recv seq we expect */
135         u_int16_t               inproc;         /* packet is in processing */
136         u_int16_t               rack;           /* last 'nr' we rec'd */
137         u_int16_t               xack;           /* last 'nr' we sent */
138         u_int16_t               wmax;           /* peer's max recv window */
139         u_int16_t               cwnd;           /* current congestion window */
140         u_int16_t               ssth;           /* slow start threshold */
141         u_int16_t               acks;           /* # consecutive acks rec'd */
142         u_int16_t               rexmits;        /* # retransmits sent */
143         struct callout          rack_timer;     /* retransmit timer */
144         struct callout          xack_timer;     /* delayed ack timer */
145         struct mbuf             *xwin[L2TP_MAX_XWIN];   /* transmit window */
146         struct mtx              mtx;                    /* seq mutex */
147 };
148
149 /* Node private data */
150 struct ng_l2tp_private {
151         node_p                  node;           /* back pointer to node */
152         hook_p                  ctrl;           /* hook to upper layers */
153         hook_p                  lower;          /* hook to lower layers */
154         struct ng_l2tp_config   conf;           /* node configuration */
155         struct ng_l2tp_stats    stats;          /* node statistics */
156         struct l2tp_seq         seq;            /* ctrl sequence number state */
157         ng_ID_t                 ftarget;        /* failure message target */
158         LIST_HEAD(, ng_l2tp_hook_private) sesshash[SESSHASHSIZE];
159 };
160 typedef struct ng_l2tp_private *priv_p;
161
162 /* Netgraph node methods */
163 static ng_constructor_t ng_l2tp_constructor;
164 static ng_rcvmsg_t      ng_l2tp_rcvmsg;
165 static ng_shutdown_t    ng_l2tp_shutdown;
166 static ng_newhook_t     ng_l2tp_newhook;
167 static ng_rcvdata_t     ng_l2tp_rcvdata;
168 static ng_rcvdata_t     ng_l2tp_rcvdata_lower;
169 static ng_rcvdata_t     ng_l2tp_rcvdata_ctrl;
170 static ng_disconnect_t  ng_l2tp_disconnect;
171
172 /* Internal functions */
173 static int      ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns);
174
175 static void     ng_l2tp_seq_init(priv_p priv);
176 static int      ng_l2tp_seq_set(priv_p priv,
177                         const struct ng_l2tp_seq_config *conf);
178 static int      ng_l2tp_seq_adjust(priv_p priv,
179                         const struct ng_l2tp_config *conf);
180 static void     ng_l2tp_seq_reset(priv_p priv);
181 static void     ng_l2tp_seq_failure(priv_p priv);
182 static void     ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr);
183 static void     ng_l2tp_seq_xack_timeout(node_p node, hook_p hook,
184                     void *arg1, int arg2);
185 static void     ng_l2tp_seq_rack_timeout(node_p node, hook_p hook,
186                     void *arg1, int arg2);
187
188 static hookpriv_p       ng_l2tp_find_session(priv_p privp, u_int16_t sid);
189 static ng_fn_eachhook   ng_l2tp_reset_session;
190
191 #ifdef INVARIANTS
192 static void     ng_l2tp_seq_check(struct l2tp_seq *seq);
193 #endif
194
195 /* Parse type for struct ng_l2tp_seq_config. */
196 static const struct ng_parse_struct_field
197         ng_l2tp_seq_config_fields[] = NG_L2TP_SEQ_CONFIG_TYPE_INFO;
198 static const struct ng_parse_type ng_l2tp_seq_config_type = {
199         &ng_parse_struct_type,
200         &ng_l2tp_seq_config_fields
201 };
202
203 /* Parse type for struct ng_l2tp_config */
204 static const struct ng_parse_struct_field
205         ng_l2tp_config_type_fields[] = NG_L2TP_CONFIG_TYPE_INFO;
206 static const struct ng_parse_type ng_l2tp_config_type = {
207         &ng_parse_struct_type,
208         &ng_l2tp_config_type_fields,
209 };
210
211 /* Parse type for struct ng_l2tp_sess_config */
212 static const struct ng_parse_struct_field
213         ng_l2tp_sess_config_type_fields[] = NG_L2TP_SESS_CONFIG_TYPE_INFO;
214 static const struct ng_parse_type ng_l2tp_sess_config_type = {
215         &ng_parse_struct_type,
216         &ng_l2tp_sess_config_type_fields,
217 };
218
219 /* Parse type for struct ng_l2tp_stats */
220 static const struct ng_parse_struct_field
221         ng_l2tp_stats_type_fields[] = NG_L2TP_STATS_TYPE_INFO;
222 static const struct ng_parse_type ng_l2tp_stats_type = {
223         &ng_parse_struct_type,
224         &ng_l2tp_stats_type_fields
225 };
226
227 /* Parse type for struct ng_l2tp_session_stats. */
228 static const struct ng_parse_struct_field
229         ng_l2tp_session_stats_type_fields[] = NG_L2TP_SESSION_STATS_TYPE_INFO;
230 static const struct ng_parse_type ng_l2tp_session_stats_type = {
231         &ng_parse_struct_type,
232         &ng_l2tp_session_stats_type_fields
233 };
234
235 /* List of commands and how to convert arguments to/from ASCII */
236 static const struct ng_cmdlist ng_l2tp_cmdlist[] = {
237         {
238           NGM_L2TP_COOKIE,
239           NGM_L2TP_SET_CONFIG,
240           "setconfig",
241           &ng_l2tp_config_type,
242           NULL
243         },
244         {
245           NGM_L2TP_COOKIE,
246           NGM_L2TP_GET_CONFIG,
247           "getconfig",
248           NULL,
249           &ng_l2tp_config_type
250         },
251         {
252           NGM_L2TP_COOKIE,
253           NGM_L2TP_SET_SESS_CONFIG,
254           "setsessconfig",
255           &ng_l2tp_sess_config_type,
256           NULL
257         },
258         {
259           NGM_L2TP_COOKIE,
260           NGM_L2TP_GET_SESS_CONFIG,
261           "getsessconfig",
262           &ng_parse_hint16_type,
263           &ng_l2tp_sess_config_type
264         },
265         {
266           NGM_L2TP_COOKIE,
267           NGM_L2TP_GET_STATS,
268           "getstats",
269           NULL,
270           &ng_l2tp_stats_type
271         },
272         {
273           NGM_L2TP_COOKIE,
274           NGM_L2TP_CLR_STATS,
275           "clrstats",
276           NULL,
277           NULL
278         },
279         {
280           NGM_L2TP_COOKIE,
281           NGM_L2TP_GETCLR_STATS,
282           "getclrstats",
283           NULL,
284           &ng_l2tp_stats_type
285         },
286         {
287           NGM_L2TP_COOKIE,
288           NGM_L2TP_GET_SESSION_STATS,
289           "getsessstats",
290           &ng_parse_int16_type,
291           &ng_l2tp_session_stats_type
292         },
293         {
294           NGM_L2TP_COOKIE,
295           NGM_L2TP_CLR_SESSION_STATS,
296           "clrsessstats",
297           &ng_parse_int16_type,
298           NULL
299         },
300         {
301           NGM_L2TP_COOKIE,
302           NGM_L2TP_GETCLR_SESSION_STATS,
303           "getclrsessstats",
304           &ng_parse_int16_type,
305           &ng_l2tp_session_stats_type
306         },
307         {
308           NGM_L2TP_COOKIE,
309           NGM_L2TP_ACK_FAILURE,
310           "ackfailure",
311           NULL,
312           NULL
313         },
314         {
315           NGM_L2TP_COOKIE,
316           NGM_L2TP_SET_SEQ,
317           "setsequence",
318           &ng_l2tp_seq_config_type,
319           NULL
320         },
321         { 0 }
322 };
323
324 /* Node type descriptor */
325 static struct ng_type ng_l2tp_typestruct = {
326         .version =      NG_ABI_VERSION,
327         .name =         NG_L2TP_NODE_TYPE,
328         .constructor =  ng_l2tp_constructor,
329         .rcvmsg =       ng_l2tp_rcvmsg,
330         .shutdown =     ng_l2tp_shutdown,
331         .newhook =      ng_l2tp_newhook,
332         .rcvdata =      ng_l2tp_rcvdata,
333         .disconnect =   ng_l2tp_disconnect,
334         .cmdlist =      ng_l2tp_cmdlist,
335 };
336 NETGRAPH_INIT(l2tp, &ng_l2tp_typestruct);
337
338 /* Sequence number state sanity checking */
339 #ifdef INVARIANTS
340 #define L2TP_SEQ_CHECK(seq)     ng_l2tp_seq_check(seq)
341 #else
342 #define L2TP_SEQ_CHECK(x)       do { } while (0)
343 #endif
344
345 /* memmove macro */
346 #define memmove(d, s, l)        bcopy(s, d, l)
347
348 /* Whether to use m_copypacket() or m_dup() */
349 #define L2TP_COPY_MBUF          m_copypacket
350
351 #define ERROUT(x)       do { error = (x); goto done; } while (0)
352
353 /************************************************************************
354                         NETGRAPH NODE STUFF
355 ************************************************************************/
356
357 /*
358  * Node type constructor
359  */
360 static int
361 ng_l2tp_constructor(node_p node)
362 {
363         priv_p priv;
364         int     i;
365
366         /* Allocate private structure */
367         MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_L2TP, M_NOWAIT | M_ZERO);
368         if (priv == NULL)
369                 return (ENOMEM);
370         NG_NODE_SET_PRIVATE(node, priv);
371         priv->node = node;
372
373         /* Apply a semi-reasonable default configuration */
374         priv->conf.peer_win = 1;
375         priv->conf.rexmit_max = L2TP_MAX_REXMIT;
376         priv->conf.rexmit_max_to = L2TP_MAX_REXMIT_TO;
377
378         /* Initialize sequence number state */
379         ng_l2tp_seq_init(priv);
380
381         for (i = 0; i < SESSHASHSIZE; i++)
382             LIST_INIT(&priv->sesshash[i]);
383
384         /* Done */
385         return (0);
386 }
387
388 /*
389  * Give our OK for a hook to be added.
390  */
391 static int
392 ng_l2tp_newhook(node_p node, hook_p hook, const char *name)
393 {
394         const priv_p priv = NG_NODE_PRIVATE(node);
395
396         /* Check hook name */
397         if (strcmp(name, NG_L2TP_HOOK_CTRL) == 0) {
398                 if (priv->ctrl != NULL)
399                         return (EISCONN);
400                 priv->ctrl = hook;
401                 NG_HOOK_SET_RCVDATA(hook, ng_l2tp_rcvdata_ctrl);
402         } else if (strcmp(name, NG_L2TP_HOOK_LOWER) == 0) {
403                 if (priv->lower != NULL)
404                         return (EISCONN);
405                 priv->lower = hook;
406                 NG_HOOK_SET_RCVDATA(hook, ng_l2tp_rcvdata_lower);
407         } else {
408                 static const char hexdig[16] = "0123456789abcdef";
409                 u_int16_t session_id;
410                 hookpriv_p hpriv;
411                 uint16_t hash;
412                 const char *hex;
413                 int i;
414                 int j;
415
416                 /* Parse hook name to get session ID */
417                 if (strncmp(name, NG_L2TP_HOOK_SESSION_P,
418                     sizeof(NG_L2TP_HOOK_SESSION_P) - 1) != 0)
419                         return (EINVAL);
420                 hex = name + sizeof(NG_L2TP_HOOK_SESSION_P) - 1;
421                 for (session_id = i = 0; i < 4; i++) {
422                         for (j = 0; j < 16 && hex[i] != hexdig[j]; j++);
423                         if (j == 16)
424                                 return (EINVAL);
425                         session_id = (session_id << 4) | j;
426                 }
427                 if (hex[i] != '\0')
428                         return (EINVAL);
429
430                 /* Create hook private structure */
431                 MALLOC(hpriv, hookpriv_p,
432                     sizeof(*hpriv), M_NETGRAPH_L2TP, M_NOWAIT | M_ZERO);
433                 if (hpriv == NULL)
434                         return (ENOMEM);
435                 hpriv->conf.session_id = htons(session_id);
436                 hpriv->conf.control_dseq = L2TP_CONTROL_DSEQ;
437                 hpriv->conf.enable_dseq = L2TP_ENABLE_DSEQ;
438                 hpriv->hook = hook;
439                 NG_HOOK_SET_PRIVATE(hook, hpriv);
440                 hash = SESSHASH(hpriv->conf.session_id);
441                 LIST_INSERT_HEAD(&priv->sesshash[hash], hpriv, sessions);
442         }
443
444         /* Done */
445         return (0);
446 }
447
448 /*
449  * Receive a control message.
450  */
451 static int
452 ng_l2tp_rcvmsg(node_p node, item_p item, hook_p lasthook)
453 {
454         const priv_p priv = NG_NODE_PRIVATE(node);
455         struct ng_mesg *resp = NULL;
456         struct ng_mesg *msg;
457         int error = 0;
458
459         NGI_GET_MSG(item, msg);
460         switch (msg->header.typecookie) {
461         case NGM_L2TP_COOKIE:
462                 switch (msg->header.cmd) {
463                 case NGM_L2TP_SET_CONFIG:
464                     {
465                         struct ng_l2tp_config *const conf =
466                                 (struct ng_l2tp_config *)msg->data;
467
468                         /* Check for invalid or illegal config */
469                         if (msg->header.arglen != sizeof(*conf)) {
470                                 error = EINVAL;
471                                 break;
472                         }
473                         conf->enabled = !!conf->enabled;
474                         conf->match_id = !!conf->match_id;
475                         conf->tunnel_id = htons(conf->tunnel_id);
476                         conf->peer_id = htons(conf->peer_id);
477                         if (priv->conf.enabled
478                             && ((priv->conf.tunnel_id != 0
479                                && conf->tunnel_id != priv->conf.tunnel_id)
480                               || ((priv->conf.peer_id != 0
481                                && conf->peer_id != priv->conf.peer_id)))) {
482                                 error = EBUSY;
483                                 break;
484                         }
485
486                         /* Save calling node as failure target */
487                         priv->ftarget = NGI_RETADDR(item);
488
489                         /* Adjust sequence number state */
490                         if ((error = ng_l2tp_seq_adjust(priv, conf)) != 0)
491                                 break;
492
493                         /* Update node's config */
494                         priv->conf = *conf;
495                         break;
496                     }
497                 case NGM_L2TP_GET_CONFIG:
498                     {
499                         struct ng_l2tp_config *conf;
500
501                         NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
502                         if (resp == NULL) {
503                                 error = ENOMEM;
504                                 break;
505                         }
506                         conf = (struct ng_l2tp_config *)resp->data;
507                         *conf = priv->conf;
508
509                         /* Put ID's in host order */
510                         conf->tunnel_id = ntohs(conf->tunnel_id);
511                         conf->peer_id = ntohs(conf->peer_id);
512                         break;
513                     }
514                 case NGM_L2TP_SET_SESS_CONFIG:
515                     {
516                         struct ng_l2tp_sess_config *const conf =
517                             (struct ng_l2tp_sess_config *)msg->data;
518                         hookpriv_p hpriv;
519
520                         /* Check for invalid or illegal config. */
521                         if (msg->header.arglen != sizeof(*conf)) {
522                                 error = EINVAL;
523                                 break;
524                         }
525
526                         /* Put ID's in network order */
527                         conf->session_id = htons(conf->session_id);
528                         conf->peer_id = htons(conf->peer_id);
529
530                         /* Find matching hook */
531                         hpriv = ng_l2tp_find_session(priv, conf->session_id);
532                         if (hpriv == NULL) {
533                                 error = ENOENT;
534                                 break;
535                         }
536
537                         /* Update hook's config */
538                         hpriv->conf = *conf;
539                         break;
540                     }
541                 case NGM_L2TP_GET_SESS_CONFIG:
542                     {
543                         struct ng_l2tp_sess_config *conf;
544                         u_int16_t session_id;
545                         hookpriv_p hpriv;
546
547                         /* Get session ID */
548                         if (msg->header.arglen != sizeof(session_id)) {
549                                 error = EINVAL;
550                                 break;
551                         }
552                         memcpy(&session_id, msg->data, 2);
553                         session_id = htons(session_id);
554
555                         /* Find matching hook */
556                         hpriv = ng_l2tp_find_session(priv, session_id);
557                         if (hpriv == NULL) {
558                                 error = ENOENT;
559                                 break;
560                         }
561
562                         /* Send response */
563                         NG_MKRESPONSE(resp, msg, sizeof(hpriv->conf), M_NOWAIT);
564                         if (resp == NULL) {
565                                 error = ENOMEM;
566                                 break;
567                         }
568                         conf = (struct ng_l2tp_sess_config *)resp->data;
569                         *conf = hpriv->conf;
570
571                         /* Put ID's in host order */
572                         conf->session_id = ntohs(conf->session_id);
573                         conf->peer_id = ntohs(conf->peer_id);
574                         break;
575                     }
576                 case NGM_L2TP_GET_STATS:
577                 case NGM_L2TP_CLR_STATS:
578                 case NGM_L2TP_GETCLR_STATS:
579                     {
580                         if (msg->header.cmd != NGM_L2TP_CLR_STATS) {
581                                 NG_MKRESPONSE(resp, msg,
582                                     sizeof(priv->stats), M_NOWAIT);
583                                 if (resp == NULL) {
584                                         error = ENOMEM;
585                                         break;
586                                 }
587                                 memcpy(resp->data,
588                                     &priv->stats, sizeof(priv->stats));
589                         }
590                         if (msg->header.cmd != NGM_L2TP_GET_STATS)
591                                 memset(&priv->stats, 0, sizeof(priv->stats));
592                         break;
593                     }
594                 case NGM_L2TP_GET_SESSION_STATS:
595                 case NGM_L2TP_CLR_SESSION_STATS:
596                 case NGM_L2TP_GETCLR_SESSION_STATS:
597                     {
598                         uint16_t session_id;
599                         hookpriv_p hpriv;
600
601                         /* Get session ID. */
602                         if (msg->header.arglen != sizeof(session_id)) {
603                                 error = EINVAL;
604                                 break;
605                         }
606                         bcopy(msg->data, &session_id, sizeof(uint16_t));
607                         session_id = htons(session_id);
608
609                         /* Find matching hook. */
610                         hpriv = ng_l2tp_find_session(priv, session_id);
611                         if (hpriv == NULL) {
612                                 error = ENOENT;
613                                 break;
614                         }
615
616                         if (msg->header.cmd != NGM_L2TP_CLR_SESSION_STATS) {
617                                 NG_MKRESPONSE(resp, msg,
618                                     sizeof(hpriv->stats), M_NOWAIT);
619                                 if (resp == NULL) {
620                                         error = ENOMEM;
621                                         break;
622                                 }
623                                 bcopy(&hpriv->stats, resp->data,
624                                         sizeof(hpriv->stats));
625                         }
626                         if (msg->header.cmd != NGM_L2TP_GET_SESSION_STATS)
627                                 bzero(&hpriv->stats, sizeof(hpriv->stats));
628                         break;
629                     }
630                 case NGM_L2TP_SET_SEQ:
631                     {
632                         struct ng_l2tp_seq_config *const conf =
633                                 (struct ng_l2tp_seq_config *)msg->data;
634
635                         /* Check for invalid or illegal seq config. */
636                         if (msg->header.arglen != sizeof(*conf)) {
637                                 error = EINVAL;
638                                 break;
639                         }
640                         conf->ns = htons(conf->ns);
641                         conf->nr = htons(conf->nr);
642                         conf->rack = htons(conf->rack);
643                         conf->xack = htons(conf->xack);
644
645                         /* Set sequence numbers. */
646                         error = ng_l2tp_seq_set(priv, conf);
647                         break;
648                     }
649                 default:
650                         error = EINVAL;
651                         break;
652                 }
653                 break;
654         default:
655                 error = EINVAL;
656                 break;
657         }
658
659         /* Done */
660         NG_RESPOND_MSG(error, node, item, resp);
661         NG_FREE_MSG(msg);
662         return (error);
663 }
664
665 /*
666  * Destroy node
667  */
668 static int
669 ng_l2tp_shutdown(node_p node)
670 {
671         const priv_p priv = NG_NODE_PRIVATE(node);
672         struct l2tp_seq *const seq = &priv->seq;
673
674         /* Sanity check */
675         L2TP_SEQ_CHECK(seq);
676
677         /* Reset sequence number state */
678         ng_l2tp_seq_reset(priv);
679
680         /* Free private data if neither timer is running */
681         ng_uncallout(&seq->rack_timer, node);
682         ng_uncallout(&seq->xack_timer, node);
683
684         mtx_destroy(&seq->mtx);
685
686         FREE(priv, M_NETGRAPH_L2TP);
687
688         /* Unref node */
689         NG_NODE_UNREF(node);
690         return (0);
691 }
692
693 /*
694  * Hook disconnection
695  */
696 static int
697 ng_l2tp_disconnect(hook_p hook)
698 {
699         const node_p node = NG_HOOK_NODE(hook);
700         const priv_p priv = NG_NODE_PRIVATE(node);
701
702         /* Zero out hook pointer */
703         if (hook == priv->ctrl)
704                 priv->ctrl = NULL;
705         else if (hook == priv->lower)
706                 priv->lower = NULL;
707         else {
708                 const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
709                 LIST_REMOVE(hpriv, sessions);
710                 FREE(hpriv, M_NETGRAPH_L2TP);
711                 NG_HOOK_SET_PRIVATE(hook, NULL);
712         }
713
714         /* Go away if no longer connected to anything */
715         if (NG_NODE_NUMHOOKS(node) == 0 && NG_NODE_IS_VALID(node))
716                 ng_rmnode_self(node);
717         return (0);
718 }
719
720 /*************************************************************************
721                         INTERNAL FUNCTIONS
722 *************************************************************************/
723
724 /*
725  * Find the hook with a given session ID (in network order).
726  */
727 static hookpriv_p
728 ng_l2tp_find_session(priv_p privp, u_int16_t sid)
729 {
730         uint16_t        hash = SESSHASH(sid);
731         hookpriv_p      hpriv = NULL;
732
733         LIST_FOREACH(hpriv, &privp->sesshash[hash], sessions) {
734                 if (hpriv->conf.session_id == sid)
735                         break;
736         }
737
738         return (hpriv);
739 }
740
741 /*
742  * Reset a hook's session state.
743  */
744 static int
745 ng_l2tp_reset_session(hook_p hook, void *arg)
746 {
747         const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
748
749         if (hpriv != NULL) {
750                 hpriv->conf.control_dseq = 0;
751                 hpriv->conf.enable_dseq = 0;
752                 bzero(&hpriv->conf, sizeof(struct ng_l2tp_session_stats));
753                 hpriv->nr = 0;
754                 hpriv->ns = 0;
755         }
756         return (-1);
757 }
758
759 /*
760  * Handle an incoming frame from below.
761  */
762 static int
763 ng_l2tp_rcvdata_lower(hook_p h, item_p item)
764 {
765         static const u_int16_t req_bits[2][2] = {
766                 { L2TP_DATA_0BITS, L2TP_DATA_1BITS },
767                 { L2TP_CTRL_0BITS, L2TP_CTRL_1BITS },
768         };
769         const node_p node = NG_HOOK_NODE(h);
770         const priv_p priv = NG_NODE_PRIVATE(node);
771         hookpriv_p hpriv = NULL;
772         hook_p hook = NULL;
773         u_int16_t ids[2];
774         struct mbuf *m;
775         u_int16_t hdr;
776         u_int16_t ns;
777         u_int16_t nr;
778         int is_ctrl;
779         int error;
780         int len, plen;
781
782         /* Sanity check */
783         L2TP_SEQ_CHECK(&priv->seq);
784
785         /* If not configured, reject */
786         if (!priv->conf.enabled) {
787                 NG_FREE_ITEM(item);
788                 ERROUT(ENXIO);
789         }
790
791         /* Grab mbuf */
792         NGI_GET_M(item, m);
793
794         /* Remember full packet length; needed for per session accounting. */
795         plen = m->m_pkthdr.len;
796
797         /* Update stats */
798         priv->stats.recvPackets++;
799         priv->stats.recvOctets += plen;
800
801         /* Get initial header */
802         if (m->m_pkthdr.len < 6) {
803                 priv->stats.recvRunts++;
804                 NG_FREE_ITEM(item);
805                 NG_FREE_M(m);
806                 ERROUT(EINVAL);
807         }
808         if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
809                 priv->stats.memoryFailures++;
810                 NG_FREE_ITEM(item);
811                 ERROUT(EINVAL);
812         }
813         hdr = ntohs(*mtod(m, u_int16_t *));
814         m_adj(m, 2);
815
816         /* Check required header bits and minimum length */
817         is_ctrl = (hdr & L2TP_HDR_CTRL) != 0;
818         if ((hdr & req_bits[is_ctrl][0]) != 0
819             || (~hdr & req_bits[is_ctrl][1]) != 0) {
820                 priv->stats.recvInvalid++;
821                 NG_FREE_ITEM(item);
822                 NG_FREE_M(m);
823                 ERROUT(EINVAL);
824         }
825         if (m->m_pkthdr.len < 4                         /* tunnel, session id */
826             + (2 * ((hdr & L2TP_HDR_LEN) != 0))         /* length field */
827             + (4 * ((hdr & L2TP_HDR_SEQ) != 0))         /* seq # fields */
828             + (2 * ((hdr & L2TP_HDR_OFF) != 0))) {      /* offset field */
829                 priv->stats.recvRunts++;
830                 NG_FREE_ITEM(item);
831                 NG_FREE_M(m);
832                 ERROUT(EINVAL);
833         }
834
835         /* Get and validate length field if present */
836         if ((hdr & L2TP_HDR_LEN) != 0) {
837                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
838                         priv->stats.memoryFailures++;
839                         NG_FREE_ITEM(item);
840                         ERROUT(EINVAL);
841                 }
842                 len = (u_int16_t)ntohs(*mtod(m, u_int16_t *)) - 4;
843                 m_adj(m, 2);
844                 if (len < 0 || len > m->m_pkthdr.len) {
845                         priv->stats.recvInvalid++;
846                         NG_FREE_ITEM(item);
847                         NG_FREE_M(m);
848                         ERROUT(EINVAL);
849                 }
850                 if (len < m->m_pkthdr.len)              /* trim extra bytes */
851                         m_adj(m, -(m->m_pkthdr.len - len));
852         }
853
854         /* Get tunnel ID and session ID */
855         if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
856                 priv->stats.memoryFailures++;
857                 NG_FREE_ITEM(item);
858                 ERROUT(EINVAL);
859         }
860         memcpy(ids, mtod(m, u_int16_t *), 4);
861         m_adj(m, 4);
862
863         /* Check tunnel ID */
864         if (ids[0] != priv->conf.tunnel_id
865             && (priv->conf.match_id || ids[0] != 0)) {
866                 priv->stats.recvWrongTunnel++;
867                 NG_FREE_ITEM(item);
868                 NG_FREE_M(m);
869                 ERROUT(EADDRNOTAVAIL);
870         }
871
872         /* Check session ID (for data packets only) */
873         if ((hdr & L2TP_HDR_CTRL) == 0) {
874                 hpriv = ng_l2tp_find_session(priv, ids[1]);
875                 if (hpriv == NULL) {
876                         priv->stats.recvUnknownSID++;
877                         NG_FREE_ITEM(item);
878                         NG_FREE_M(m);
879                         ERROUT(ENOTCONN);
880                 }
881                 hook = hpriv->hook;
882         }
883
884         /* Get Ns, Nr fields if present */
885         if ((hdr & L2TP_HDR_SEQ) != 0) {
886                 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
887                         priv->stats.memoryFailures++;
888                         NG_FREE_ITEM(item);
889                         ERROUT(EINVAL);
890                 }
891                 memcpy(&ns, &mtod(m, u_int16_t *)[0], 2);
892                 ns = ntohs(ns);
893                 memcpy(&nr, &mtod(m, u_int16_t *)[1], 2);
894                 nr = ntohs(nr);
895                 m_adj(m, 4);
896         }
897
898         /* Strip offset padding if present */
899         if ((hdr & L2TP_HDR_OFF) != 0) {
900                 u_int16_t offset;
901
902                 /* Get length of offset padding */
903                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
904                         priv->stats.memoryFailures++;
905                         NG_FREE_ITEM(item);
906                         ERROUT(EINVAL);
907                 }
908                 memcpy(&offset, mtod(m, u_int16_t *), 2);
909                 offset = ntohs(offset);
910
911                 /* Trim offset padding */
912                 if ((2+offset) > m->m_pkthdr.len) {
913                         priv->stats.recvInvalid++;
914                         NG_FREE_ITEM(item);
915                         NG_FREE_M(m);
916                         ERROUT(EINVAL);
917                 }
918                 m_adj(m, 2+offset);
919         }
920
921         /* Handle control packets */
922         if ((hdr & L2TP_HDR_CTRL) != 0) {
923                 struct l2tp_seq *const seq = &priv->seq;
924
925                 /* Handle receive ack sequence number Nr */
926                 ng_l2tp_seq_recv_nr(priv, nr);
927
928                 /* Discard ZLB packets */
929                 if (m->m_pkthdr.len == 0) {
930                         priv->stats.recvZLBs++;
931                         NG_FREE_ITEM(item);
932                         NG_FREE_M(m);
933                         ERROUT(0);
934                 }
935
936                 mtx_lock(&seq->mtx);
937                 /*
938                  * If not what we expect or we are busy, drop packet and
939                  * send an immediate ZLB ack.
940                  */
941                 if (ns != seq->nr || seq->inproc) {
942                         if (L2TP_SEQ_DIFF(ns, seq->nr) <= 0)
943                                 priv->stats.recvDuplicates++;
944                         else
945                                 priv->stats.recvOutOfOrder++;
946                         mtx_unlock(&seq->mtx);
947                         ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
948                         NG_FREE_ITEM(item);
949                         NG_FREE_M(m);
950                         ERROUT(0);
951                 }
952                 /*
953                  * Until we deliver this packet we can't receive next one as
954                  * we have no information for sending ack.
955                  */
956                 seq->inproc = 1;
957                 mtx_unlock(&seq->mtx);
958
959                 /* Prepend session ID to packet. */
960                 M_PREPEND(m, 2, M_DONTWAIT);
961                 if (m == NULL) {
962                         seq->inproc = 0;
963                         priv->stats.memoryFailures++;
964                         NG_FREE_ITEM(item);
965                         ERROUT(ENOBUFS);
966                 }
967                 memcpy(mtod(m, u_int16_t *), &ids[1], 2);
968
969                 /* Deliver packet to upper layers */
970                 NG_FWD_NEW_DATA(error, item, priv->ctrl, m);
971                 
972                 mtx_lock(&seq->mtx);
973                 /* Ready to process next packet. */
974                 seq->inproc = 0;
975
976                 /* If packet was successfully delivered send ack. */
977                 if (error == 0) {
978                         /* Update recv sequence number */
979                         seq->nr++;
980                         /* Start receive ack timer, if not already running */
981                         if (!callout_active(&seq->xack_timer)) {
982                                 ng_callout(&seq->xack_timer, priv->node, NULL,
983                                     L2TP_DELAYED_ACK, ng_l2tp_seq_xack_timeout,
984                                     NULL, 0);
985                         }
986                 }
987                 mtx_unlock(&seq->mtx);
988
989                 ERROUT(error);
990         }
991
992         /* Per session packet, account it. */
993         hpriv->stats.recvPackets++;
994         hpriv->stats.recvOctets += plen;
995
996         /* Follow peer's lead in data sequencing, if configured to do so */
997         if (!hpriv->conf.control_dseq)
998                 hpriv->conf.enable_dseq = ((hdr & L2TP_HDR_SEQ) != 0);
999
1000         /* Handle data sequence numbers if present and enabled */
1001         if ((hdr & L2TP_HDR_SEQ) != 0) {
1002                 if (hpriv->conf.enable_dseq
1003                     && L2TP_SEQ_DIFF(ns, hpriv->nr) < 0) {
1004                         NG_FREE_ITEM(item);     /* duplicate or out of order */
1005                         NG_FREE_M(m);
1006                         priv->stats.recvDataDrops++;
1007                         ERROUT(0);
1008                 }
1009                 hpriv->nr = ns + 1;
1010         }
1011
1012         /* Drop empty data packets */
1013         if (m->m_pkthdr.len == 0) {
1014                 NG_FREE_ITEM(item);
1015                 NG_FREE_M(m);
1016                 ERROUT(0);
1017         }
1018
1019         /* Deliver data */
1020         NG_FWD_NEW_DATA(error, item, hook, m);
1021 done:
1022         /* Done */
1023         L2TP_SEQ_CHECK(&priv->seq);
1024         return (error);
1025 }
1026
1027 /*
1028  * Handle an outgoing control frame.
1029  */
1030 static int
1031 ng_l2tp_rcvdata_ctrl(hook_p hook, item_p item)
1032 {
1033         const node_p node = NG_HOOK_NODE(hook);
1034         const priv_p priv = NG_NODE_PRIVATE(node);
1035         struct l2tp_seq *const seq = &priv->seq;
1036         struct mbuf *m;
1037         int error;
1038         int i;
1039         u_int16_t       ns;
1040
1041         /* Sanity check */
1042         L2TP_SEQ_CHECK(&priv->seq);
1043
1044         /* If not configured, reject */
1045         if (!priv->conf.enabled) {
1046                 NG_FREE_ITEM(item);
1047                 ERROUT(ENXIO);
1048         }
1049
1050         /* Grab mbuf and discard other stuff XXX */
1051         NGI_GET_M(item, m);
1052         NG_FREE_ITEM(item);
1053
1054         /* Packet should have session ID prepended */
1055         if (m->m_pkthdr.len < 2) {
1056                 priv->stats.xmitInvalid++;
1057                 m_freem(m);
1058                 ERROUT(EINVAL);
1059         }
1060
1061         /* Check max length */
1062         if (m->m_pkthdr.len >= 0x10000 - 14) {
1063                 priv->stats.xmitTooBig++;
1064                 m_freem(m);
1065                 ERROUT(EOVERFLOW);
1066         }
1067
1068         mtx_lock(&seq->mtx);
1069
1070         /* Find next empty slot in transmit queue */
1071         for (i = 0; i < L2TP_MAX_XWIN && seq->xwin[i] != NULL; i++);
1072         if (i == L2TP_MAX_XWIN) {
1073                 mtx_unlock(&seq->mtx);
1074                 priv->stats.xmitDrops++;
1075                 m_freem(m);
1076                 ERROUT(ENOBUFS);
1077         }
1078         seq->xwin[i] = m;
1079
1080         /* If peer's receive window is already full, nothing else to do */
1081         if (i >= seq->cwnd) {
1082                 mtx_unlock(&seq->mtx);
1083                 ERROUT(0);
1084         }
1085
1086         /* Start retransmit timer if not already running */
1087         if (!callout_active(&seq->rack_timer))
1088                 ng_callout(&seq->rack_timer, node, NULL,
1089                     hz, ng_l2tp_seq_rack_timeout, NULL, 0);
1090         
1091         ns = seq->ns++;
1092         
1093         mtx_unlock(&seq->mtx);
1094
1095         /* Copy packet */
1096         if ((m = L2TP_COPY_MBUF(m, M_DONTWAIT)) == NULL) {
1097                 priv->stats.memoryFailures++;
1098                 ERROUT(ENOBUFS);
1099         }
1100
1101         /* Send packet and increment xmit sequence number */
1102         error = ng_l2tp_xmit_ctrl(priv, m, ns);
1103 done:
1104         /* Done */
1105         L2TP_SEQ_CHECK(&priv->seq);
1106         return (error);
1107 }
1108
1109 /*
1110  * Handle an outgoing data frame.
1111  */
1112 static int
1113 ng_l2tp_rcvdata(hook_p hook, item_p item)
1114 {
1115         const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1116         const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
1117         struct mbuf *m;
1118         u_int16_t hdr;
1119         int error;
1120         int i = 1;
1121
1122         /* Sanity check */
1123         L2TP_SEQ_CHECK(&priv->seq);
1124
1125         /* If not configured, reject */
1126         if (!priv->conf.enabled) {
1127                 NG_FREE_ITEM(item);
1128                 ERROUT(ENXIO);
1129         }
1130
1131         /* Get mbuf */
1132         NGI_GET_M(item, m);
1133
1134         /* Check max length */
1135         if (m->m_pkthdr.len >= 0x10000 - 12) {
1136                 priv->stats.xmitDataTooBig++;
1137                 NG_FREE_ITEM(item);
1138                 NG_FREE_M(m);
1139                 ERROUT(EOVERFLOW);
1140         }
1141
1142         /* Prepend L2TP header */
1143         M_PREPEND(m, 6
1144             + (2 * (hpriv->conf.include_length != 0))
1145             + (4 * (hpriv->conf.enable_dseq != 0)),
1146             M_DONTWAIT);
1147         if (m == NULL) {
1148                 priv->stats.memoryFailures++;
1149                 NG_FREE_ITEM(item);
1150                 ERROUT(ENOBUFS);
1151         }
1152         hdr = L2TP_DATA_HDR;
1153         if (hpriv->conf.include_length) {
1154                 hdr |= L2TP_HDR_LEN;
1155                 mtod(m, u_int16_t *)[i++] = htons(m->m_pkthdr.len);
1156         }
1157         mtod(m, u_int16_t *)[i++] = priv->conf.peer_id;
1158         mtod(m, u_int16_t *)[i++] = hpriv->conf.peer_id;
1159         if (hpriv->conf.enable_dseq) {
1160                 hdr |= L2TP_HDR_SEQ;
1161                 mtod(m, u_int16_t *)[i++] = htons(hpriv->ns);
1162                 mtod(m, u_int16_t *)[i++] = htons(hpriv->nr);
1163                 hpriv->ns++;
1164         }
1165         mtod(m, u_int16_t *)[0] = htons(hdr);
1166
1167         /* Update per session stats. */
1168         hpriv->stats.xmitPackets++;
1169         hpriv->stats.xmitOctets += m->m_pkthdr.len;
1170
1171         /* And the global one. */
1172         priv->stats.xmitPackets++;
1173         priv->stats.xmitOctets += m->m_pkthdr.len;
1174
1175         /* Send packet */
1176         NG_FWD_NEW_DATA(error, item, priv->lower, m);
1177 done:
1178         /* Done */
1179         L2TP_SEQ_CHECK(&priv->seq);
1180         return (error);
1181 }
1182
1183 /*
1184  * Send a message to our controlling node that we've failed.
1185  */
1186 static void
1187 ng_l2tp_seq_failure(priv_p priv)
1188 {
1189         struct ng_mesg *msg;
1190         int error;
1191
1192         NG_MKMESSAGE(msg, NGM_L2TP_COOKIE, NGM_L2TP_ACK_FAILURE, 0, M_NOWAIT);
1193         if (msg == NULL)
1194                 return;
1195         NG_SEND_MSG_ID(error, priv->node, msg, priv->ftarget, 0);
1196 }
1197
1198 /************************************************************************
1199                         SEQUENCE NUMBER HANDLING
1200 ************************************************************************/
1201
1202 /*
1203  * Initialize sequence number state.
1204  */
1205 static void
1206 ng_l2tp_seq_init(priv_p priv)
1207 {
1208         struct l2tp_seq *const seq = &priv->seq;
1209
1210         KASSERT(priv->conf.peer_win >= 1,
1211             ("%s: peer_win is zero", __func__));
1212         memset(seq, 0, sizeof(*seq));
1213         seq->cwnd = 1;
1214         seq->wmax = priv->conf.peer_win;
1215         if (seq->wmax > L2TP_MAX_XWIN)
1216                 seq->wmax = L2TP_MAX_XWIN;
1217         seq->ssth = seq->wmax;
1218         ng_callout_init(&seq->rack_timer);
1219         ng_callout_init(&seq->xack_timer);
1220         mtx_init(&seq->mtx, "ng_l2tp", NULL, MTX_DEF);
1221         L2TP_SEQ_CHECK(seq);
1222 }
1223
1224 /*
1225  * Set sequence number state as given from user.
1226  */
1227 static int
1228 ng_l2tp_seq_set(priv_p priv, const struct ng_l2tp_seq_config *conf)
1229 {
1230         struct l2tp_seq *const seq = &priv->seq;
1231
1232         /* If node is enabled, deny update to sequence numbers. */
1233         if (priv->conf.enabled)
1234                 return (EBUSY);
1235
1236         /* We only can handle the simple cases. */
1237         if (conf->xack != conf->nr || conf->ns != conf->rack)
1238                 return (EINVAL);
1239
1240         /* Set ns,nr,rack,xack parameters. */
1241         seq->ns = conf->ns;
1242         seq->nr = conf->nr;
1243         seq->rack = conf->rack;
1244         seq->xack = conf->xack;
1245
1246         return (0);
1247 }
1248
1249 /*
1250  * Adjust sequence number state accordingly after reconfiguration.
1251  */
1252 static int
1253 ng_l2tp_seq_adjust(priv_p priv, const struct ng_l2tp_config *conf)
1254 {
1255         struct l2tp_seq *const seq = &priv->seq;
1256         u_int16_t new_wmax;
1257
1258         /* If disabling node, reset state sequence number */
1259         if (!conf->enabled) {
1260                 ng_l2tp_seq_reset(priv);
1261                 return (0);
1262         }
1263
1264         /* Adjust peer's max recv window; it can only increase */
1265         new_wmax = conf->peer_win;
1266         if (new_wmax > L2TP_MAX_XWIN)
1267                 new_wmax = L2TP_MAX_XWIN;
1268         if (new_wmax == 0)
1269                 return (EINVAL);
1270         if (new_wmax < seq->wmax)
1271                 return (EBUSY);
1272         seq->wmax = new_wmax;
1273
1274         /* Done */
1275         return (0);
1276 }
1277
1278 /*
1279  * Reset sequence number state.
1280  */
1281 static void
1282 ng_l2tp_seq_reset(priv_p priv)
1283 {
1284         struct l2tp_seq *const seq = &priv->seq;
1285         hook_p hook;
1286         int i;
1287
1288         /* Sanity check */
1289         L2TP_SEQ_CHECK(seq);
1290
1291         /* Stop timers */
1292         ng_uncallout(&seq->rack_timer, priv->node);
1293         ng_uncallout(&seq->xack_timer, priv->node);
1294
1295         /* Free retransmit queue */
1296         for (i = 0; i < L2TP_MAX_XWIN; i++) {
1297                 if (seq->xwin[i] == NULL)
1298                         break;
1299                 m_freem(seq->xwin[i]);
1300         }
1301
1302         /* Reset session hooks' sequence number states */
1303         NG_NODE_FOREACH_HOOK(priv->node, ng_l2tp_reset_session, NULL, hook);
1304
1305         /* Reset node's sequence number state */
1306         seq->ns = 0;
1307         seq->nr = 0;
1308         seq->rack = 0;
1309         seq->xack = 0;
1310         seq->wmax = L2TP_MAX_XWIN;
1311         seq->cwnd = 1;
1312         seq->ssth = seq->wmax;
1313         seq->acks = 0;
1314         seq->rexmits = 0;
1315         bzero(seq->xwin, sizeof(seq->xwin));
1316
1317         /* Done */
1318         L2TP_SEQ_CHECK(seq);
1319 }
1320
1321 /*
1322  * Handle receipt of an acknowledgement value (Nr) from peer.
1323  */
1324 static void
1325 ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr)
1326 {
1327         struct l2tp_seq *const seq = &priv->seq;
1328         struct mbuf     *xwin[L2TP_MAX_XWIN];   /* partial local copy */
1329         int             nack;
1330         int             i, j;
1331         uint16_t        ns;
1332
1333         mtx_lock(&seq->mtx);
1334
1335         /* Verify peer's ACK is in range */
1336         if ((nack = L2TP_SEQ_DIFF(nr, seq->rack)) <= 0) {
1337                 mtx_unlock(&seq->mtx);
1338                 return;                         /* duplicate ack */
1339         }
1340         if (L2TP_SEQ_DIFF(nr, seq->ns) > 0) {
1341                 mtx_unlock(&seq->mtx);
1342                 priv->stats.recvBadAcks++;      /* ack for packet not sent */
1343                 return;
1344         }
1345         KASSERT(nack <= L2TP_MAX_XWIN,
1346             ("%s: nack=%d > %d", __func__, nack, L2TP_MAX_XWIN));
1347
1348         /* Update receive ack stats */
1349         seq->rack = nr;
1350         seq->rexmits = 0;
1351
1352         /* Free acknowledged packets and shift up packets in the xmit queue */
1353         for (i = 0; i < nack; i++)
1354                 m_freem(seq->xwin[i]);
1355         memmove(seq->xwin, seq->xwin + nack,
1356             (L2TP_MAX_XWIN - nack) * sizeof(*seq->xwin));
1357         memset(seq->xwin + (L2TP_MAX_XWIN - nack), 0,
1358             nack * sizeof(*seq->xwin));
1359
1360         /*
1361          * Do slow-start/congestion avoidance windowing algorithm described
1362          * in RFC 2661, Appendix A. Here we handle a multiple ACK as if each
1363          * ACK had arrived separately.
1364          */
1365         if (seq->cwnd < seq->wmax) {
1366
1367                 /* Handle slow start phase */
1368                 if (seq->cwnd < seq->ssth) {
1369                         seq->cwnd += nack;
1370                         nack = 0;
1371                         if (seq->cwnd > seq->ssth) {    /* into cg.av. phase */
1372                                 nack = seq->cwnd - seq->ssth;
1373                                 seq->cwnd = seq->ssth;
1374                         }
1375                 }
1376
1377                 /* Handle congestion avoidance phase */
1378                 if (seq->cwnd >= seq->ssth) {
1379                         seq->acks += nack;
1380                         while (seq->acks >= seq->cwnd) {
1381                                 seq->acks -= seq->cwnd;
1382                                 if (seq->cwnd < seq->wmax)
1383                                         seq->cwnd++;
1384                         }
1385                 }
1386         }
1387
1388         /* Stop xmit timer */
1389         if (callout_active(&seq->rack_timer))
1390                 ng_uncallout(&seq->rack_timer, priv->node);
1391
1392         /* If transmit queue is empty, we're done for now */
1393         if (seq->xwin[0] == NULL) {
1394                 mtx_unlock(&seq->mtx);
1395                 return;
1396         }
1397
1398         /* Start restransmit timer again */
1399         ng_callout(&seq->rack_timer, priv->node, NULL,
1400             hz, ng_l2tp_seq_rack_timeout, NULL, 0);
1401
1402         /*
1403          * Send more packets, trying to keep peer's receive window full.
1404          * Make copy of everything we need before lock release.
1405          */
1406         ns = seq->ns;
1407         j = 0;
1408         while ((i = L2TP_SEQ_DIFF(seq->ns, seq->rack)) < seq->cwnd
1409             && seq->xwin[i] != NULL) {
1410                 xwin[j++] = seq->xwin[i];
1411                 seq->ns++;
1412         }
1413
1414         mtx_unlock(&seq->mtx);
1415
1416         /*
1417          * Send prepared.
1418          * If there is a memory error, pretend packet was sent, as it
1419          * will get retransmitted later anyway.
1420          */
1421         for (i = 0; i < j; i++) {
1422                 struct mbuf     *m;
1423                 if ((m = L2TP_COPY_MBUF(xwin[i], M_DONTWAIT)) == NULL)
1424                         priv->stats.memoryFailures++;
1425                 else
1426                         ng_l2tp_xmit_ctrl(priv, m, ns);
1427                 ns++;
1428         }
1429 }
1430
1431 /*
1432  * Handle an ack timeout. We have an outstanding ack that we
1433  * were hoping to piggy-back, but haven't, so send a ZLB.
1434  */
1435 static void
1436 ng_l2tp_seq_xack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1437 {
1438         const priv_p priv = NG_NODE_PRIVATE(node);
1439         struct l2tp_seq *const seq = &priv->seq;
1440
1441         /* Make sure callout is still active before doing anything */
1442         if (callout_pending(&seq->xack_timer) ||
1443             (!callout_active(&seq->xack_timer)))
1444                 return;
1445
1446         /* Sanity check */
1447         L2TP_SEQ_CHECK(seq);
1448
1449         /* Send a ZLB */
1450         ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
1451
1452         /* callout_deactivate() is not needed here 
1453             as ng_uncallout() was called by ng_l2tp_xmit_ctrl() */
1454
1455         /* Sanity check */
1456         L2TP_SEQ_CHECK(seq);
1457 }
1458
1459 /* 
1460  * Handle a transmit timeout. The peer has failed to respond
1461  * with an ack for our packet, so retransmit it.
1462  */
1463 static void
1464 ng_l2tp_seq_rack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1465 {
1466         const priv_p priv = NG_NODE_PRIVATE(node);
1467         struct l2tp_seq *const seq = &priv->seq;
1468         struct mbuf *m;
1469         u_int delay;
1470
1471         /* Make sure callout is still active before doing anything */
1472         if (callout_pending(&seq->rack_timer) ||
1473             (!callout_active(&seq->rack_timer)))
1474                 return;
1475
1476         /* Sanity check */
1477         L2TP_SEQ_CHECK(seq);
1478
1479         priv->stats.xmitRetransmits++;
1480
1481         /* Have we reached the retransmit limit? If so, notify owner. */
1482         if (seq->rexmits++ >= priv->conf.rexmit_max)
1483                 ng_l2tp_seq_failure(priv);
1484
1485         /* Restart timer, this time with an increased delay */
1486         delay = (seq->rexmits > 12) ? (1 << 12) : (1 << seq->rexmits);
1487         if (delay > priv->conf.rexmit_max_to)
1488                 delay = priv->conf.rexmit_max_to;
1489         ng_callout(&seq->rack_timer, node, NULL,
1490             hz * delay, ng_l2tp_seq_rack_timeout, NULL, 0);
1491
1492         /* Do slow-start/congestion algorithm windowing algorithm */
1493         seq->ns = seq->rack;
1494         seq->ssth = (seq->cwnd + 1) / 2;
1495         seq->cwnd = 1;
1496         seq->acks = 0;
1497
1498         /* Retransmit oldest unack'd packet */
1499         if ((m = L2TP_COPY_MBUF(seq->xwin[0], M_DONTWAIT)) == NULL)
1500                 priv->stats.memoryFailures++;
1501         else
1502                 ng_l2tp_xmit_ctrl(priv, m, seq->ns++);
1503
1504         /* callout_deactivate() is not needed here 
1505             as ng_callout() is getting called each time */
1506
1507         /* Sanity check */
1508         L2TP_SEQ_CHECK(seq);
1509 }
1510
1511 /*
1512  * Transmit a control stream packet, payload optional.
1513  * The transmit sequence number is not incremented.
1514  */
1515 static int
1516 ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns)
1517 {
1518         struct l2tp_seq *const seq = &priv->seq;
1519         u_int16_t session_id = 0;
1520         int error;
1521
1522         mtx_lock(&seq->mtx);
1523
1524         /* Stop ack timer: we're sending an ack with this packet.
1525            Doing this before to keep state predictable after error. */
1526         if (callout_active(&seq->xack_timer))
1527                 ng_uncallout(&seq->xack_timer, priv->node);
1528
1529         seq->xack = seq->nr;
1530
1531         mtx_unlock(&seq->mtx);
1532
1533         /* If no mbuf passed, send an empty packet (ZLB) */
1534         if (m == NULL) {
1535
1536                 /* Create a new mbuf for ZLB packet */
1537                 MGETHDR(m, M_DONTWAIT, MT_DATA);
1538                 if (m == NULL) {
1539                         priv->stats.memoryFailures++;
1540                         return (ENOBUFS);
1541                 }
1542                 m->m_len = m->m_pkthdr.len = 12;
1543                 m->m_pkthdr.rcvif = NULL;
1544                 priv->stats.xmitZLBs++;
1545         } else {
1546
1547                 /* Strip off session ID */
1548                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
1549                         priv->stats.memoryFailures++;
1550                         return (ENOBUFS);
1551                 }
1552                 memcpy(&session_id, mtod(m, u_int16_t *), 2);
1553                 m_adj(m, 2);
1554
1555                 /* Make room for L2TP header */
1556                 M_PREPEND(m, 12, M_DONTWAIT);
1557                 if (m == NULL) {
1558                         priv->stats.memoryFailures++;
1559                         return (ENOBUFS);
1560                 }
1561         }
1562
1563         /* Fill in L2TP header */
1564         mtod(m, u_int16_t *)[0] = htons(L2TP_CTRL_HDR);
1565         mtod(m, u_int16_t *)[1] = htons(m->m_pkthdr.len);
1566         mtod(m, u_int16_t *)[2] = priv->conf.peer_id;
1567         mtod(m, u_int16_t *)[3] = session_id;
1568         mtod(m, u_int16_t *)[4] = htons(ns);
1569         mtod(m, u_int16_t *)[5] = htons(seq->nr);
1570
1571         /* Update sequence number info and stats */
1572         priv->stats.xmitPackets++;
1573         priv->stats.xmitOctets += m->m_pkthdr.len;
1574
1575         /* Send packet */
1576         NG_SEND_DATA_ONLY(error, priv->lower, m);
1577         return (error);
1578 }
1579
1580 #ifdef INVARIANTS
1581 /*
1582  * Sanity check sequence number state.
1583  */
1584 static void
1585 ng_l2tp_seq_check(struct l2tp_seq *seq)
1586 {
1587         int self_unack, peer_unack;
1588         int i;
1589
1590 #define CHECK(p)        KASSERT((p), ("%s: not: %s", __func__, #p))
1591
1592         mtx_lock(&seq->mtx);
1593
1594         self_unack = L2TP_SEQ_DIFF(seq->nr, seq->xack);
1595         peer_unack = L2TP_SEQ_DIFF(seq->ns, seq->rack);
1596         CHECK(seq->wmax <= L2TP_MAX_XWIN);
1597         CHECK(seq->cwnd >= 1);
1598         CHECK(seq->cwnd <= seq->wmax);
1599         CHECK(seq->ssth >= 1);
1600         CHECK(seq->ssth <= seq->wmax);
1601         if (seq->cwnd < seq->ssth)
1602                 CHECK(seq->acks == 0);
1603         else
1604                 CHECK(seq->acks <= seq->cwnd);
1605         CHECK(self_unack >= 0);
1606         CHECK(peer_unack >= 0);
1607         CHECK(peer_unack <= seq->wmax);
1608         CHECK((self_unack == 0) ^ callout_active(&seq->xack_timer));
1609         CHECK((peer_unack == 0) ^ callout_active(&seq->rack_timer));
1610         for (i = 0; i < peer_unack; i++)
1611                 CHECK(seq->xwin[i] != NULL);
1612         for ( ; i < seq->cwnd; i++)         /* verify peer's recv window full */
1613                 CHECK(seq->xwin[i] == NULL);
1614
1615         mtx_unlock(&seq->mtx);
1616
1617 #undef CHECK
1618 }
1619 #endif  /* INVARIANTS */