xref: /freebsd/sys/netgraph/ng_lmi.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
1 /*
2  * ng_lmi.c
3  */
4 
5 /*-
6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
7  * All rights reserved.
8  *
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  *
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Author: Julian Elischer <julian@freebsd.org>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_lmi.c,v 1.38 1999/11/01 09:24:52 julian Exp $
42  */
43 
44 /*
45  * This node performs the frame relay LMI protocol. It knows how
46  * to do ITU Annex A, ANSI Annex D, and "Group-of-Four" variants
47  * of the protocol.
48  *
49  * A specific protocol can be forced by connecting the corresponding
50  * hook to DLCI 0 or 1023 (as appropriate) of a frame relay link.
51  *
52  * Alternately, this node can do auto-detection of the LMI protocol
53  * by connecting hook "auto0" to DLCI 0 and "auto1023" to DLCI 1023.
54  */
55 
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/errno.h>
59 #include <sys/kernel.h>
60 #include <sys/malloc.h>
61 #include <sys/mbuf.h>
62 #include <sys/syslog.h>
63 #include <netgraph/ng_message.h>
64 #include <netgraph/netgraph.h>
65 #include <netgraph/ng_lmi.h>
66 
67 /*
68  * Human readable names for LMI
69  */
70 #define NAME_ANNEXA	NG_LMI_HOOK_ANNEXA
71 #define NAME_ANNEXD	NG_LMI_HOOK_ANNEXD
72 #define NAME_GROUP4	NG_LMI_HOOK_GROUPOF4
73 #define NAME_NONE	"None"
74 
75 #define MAX_DLCIS	128
76 #define MAXDLCI		1023
77 
78 /*
79  * DLCI states
80  */
81 #define DLCI_NULL	0
82 #define DLCI_UP		1
83 #define DLCI_DOWN	2
84 
85 /*
86  * Any received LMI frame should be at least this long
87  */
88 #define LMI_MIN_LENGTH	8	/* XXX verify */
89 
90 /*
91  * Netgraph node methods and type descriptor
92  */
93 static ng_constructor_t	nglmi_constructor;
94 static ng_rcvmsg_t	nglmi_rcvmsg;
95 static ng_shutdown_t	nglmi_shutdown;
96 static ng_newhook_t	nglmi_newhook;
97 static ng_rcvdata_t	nglmi_rcvdata;
98 static ng_disconnect_t	nglmi_disconnect;
99 static int	nglmi_checkdata(hook_p hook, struct mbuf *m);
100 
101 static struct ng_type typestruct = {
102 	.version =	NG_ABI_VERSION,
103 	.name =		NG_LMI_NODE_TYPE,
104 	.constructor =	nglmi_constructor,
105 	.rcvmsg	=	nglmi_rcvmsg,
106 	.shutdown =	nglmi_shutdown,
107 	.newhook =	nglmi_newhook,
108 	.rcvdata =	nglmi_rcvdata,
109 	.disconnect =	nglmi_disconnect,
110 };
111 NETGRAPH_INIT(lmi, &typestruct);
112 
113 /*
114  * Info and status per node
115  */
116 struct nglmi_softc {
117 	node_p  node;		/* netgraph node */
118 	int     flags;		/* state */
119 	int     poll_count;	/* the count of times for autolmi */
120 	int     poll_state;	/* state of auto detect machine */
121 	u_char  remote_seq;	/* sequence number the remote sent */
122 	u_char  local_seq;	/* last sequence number we sent */
123 	u_char  protoID;	/* 9 for group of 4, 8 otherwise */
124 	u_long  seq_retries;	/* sent this how many time so far */
125 	struct	callout	handle;	/* see timeout(9) */
126 	int     liv_per_full;
127 	int     liv_rate;
128 	int     livs;
129 	int     need_full;
130 	hook_p  lmi_channel;	/* whatever we ended up using */
131 	hook_p  lmi_annexA;
132 	hook_p  lmi_annexD;
133 	hook_p  lmi_group4;
134 	hook_p  lmi_channel0;	/* auto-detect on DLCI 0 */
135 	hook_p  lmi_channel1023;/* auto-detect on DLCI 1023 */
136 	char   *protoname;	/* cache protocol name */
137 	u_char  dlci_state[MAXDLCI + 1];
138 	int     invalidx;	/* next dlci's to invalidate */
139 };
140 typedef struct nglmi_softc *sc_p;
141 
142 /*
143  * Other internal functions
144  */
145 static void	LMI_ticker(node_p node, hook_p hook, void *arg1, int arg2);
146 static void	nglmi_startup_fixed(sc_p sc, hook_p hook);
147 static void	nglmi_startup_auto(sc_p sc);
148 static void	nglmi_startup(sc_p sc);
149 static void	nglmi_inquire(sc_p sc, int full);
150 static void	ngauto_state_machine(sc_p sc);
151 
152 /*
153  * Values for 'flags' field
154  * NB: the SCF_CONNECTED flag is set if and only if the timer is running.
155  */
156 #define	SCF_CONNECTED	0x01	/* connected to something */
157 #define	SCF_AUTO	0x02	/* we are auto-detecting */
158 #define	SCF_FIXED	0x04	/* we are fixed from the start */
159 
160 #define	SCF_LMITYPE	0x18	/* mask for determining Annex mode */
161 #define	SCF_NOLMI	0x00	/* no LMI type selected yet */
162 #define	SCF_ANNEX_A	0x08	/* running annex A mode */
163 #define	SCF_ANNEX_D	0x10	/* running annex D mode */
164 #define	SCF_GROUP4	0x18	/* running group of 4 */
165 
166 #define SETLMITYPE(sc, annex)						\
167 do {									\
168 	(sc)->flags &= ~SCF_LMITYPE;					\
169 	(sc)->flags |= (annex);						\
170 } while (0)
171 
172 #define NOPROTO(sc) (((sc)->flags & SCF_LMITYPE) == SCF_NOLMI)
173 #define ANNEXA(sc) (((sc)->flags & SCF_LMITYPE) == SCF_ANNEX_A)
174 #define ANNEXD(sc) (((sc)->flags & SCF_LMITYPE) == SCF_ANNEX_D)
175 #define GROUP4(sc) (((sc)->flags & SCF_LMITYPE) == SCF_GROUP4)
176 
177 #define LMIPOLLSIZE	3
178 #define LMI_PATIENCE	8	/* declare all DLCI DOWN after N LMI failures */
179 
180 /*
181  * Node constructor
182  */
183 static int
184 nglmi_constructor(node_p node)
185 {
186 	sc_p sc;
187 
188 	MALLOC(sc, sc_p, sizeof(*sc), M_NETGRAPH, M_NOWAIT | M_ZERO);
189 	if (sc == NULL)
190 		return (ENOMEM);
191 
192 	NG_NODE_SET_PRIVATE(node, sc);
193 	sc->node = node;
194 
195 	ng_callout_init(&sc->handle);
196 	sc->protoname = NAME_NONE;
197 	sc->liv_per_full = NG_LMI_SEQ_PER_FULL;	/* make this dynamic */
198 	sc->liv_rate = NG_LMI_KEEPALIVE_RATE;
199 	return (0);
200 }
201 
202 /*
203  * The LMI channel has a private pointer which is the same as the
204  * node private pointer. The debug channel has a NULL private pointer.
205  */
206 static int
207 nglmi_newhook(node_p node, hook_p hook, const char *name)
208 {
209 	sc_p sc = NG_NODE_PRIVATE(node);
210 
211 	if (strcmp(name, NG_LMI_HOOK_DEBUG) == 0) {
212 		NG_HOOK_SET_PRIVATE(hook, NULL);
213 		return (0);
214 	}
215 	if (sc->flags & SCF_CONNECTED) {
216 		/* already connected, return an error */
217 		return (EINVAL);
218 	}
219 	if (strcmp(name, NG_LMI_HOOK_ANNEXA) == 0) {
220 		sc->lmi_annexA = hook;
221 		NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
222 		sc->protoID = 8;
223 		SETLMITYPE(sc, SCF_ANNEX_A);
224 		sc->protoname = NAME_ANNEXA;
225 		nglmi_startup_fixed(sc, hook);
226 	} else if (strcmp(name, NG_LMI_HOOK_ANNEXD) == 0) {
227 		sc->lmi_annexD = hook;
228 		NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
229 		sc->protoID = 8;
230 		SETLMITYPE(sc, SCF_ANNEX_D);
231 		sc->protoname = NAME_ANNEXD;
232 		nglmi_startup_fixed(sc, hook);
233 	} else if (strcmp(name, NG_LMI_HOOK_GROUPOF4) == 0) {
234 		sc->lmi_group4 = hook;
235 		NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
236 		sc->protoID = 9;
237 		SETLMITYPE(sc, SCF_GROUP4);
238 		sc->protoname = NAME_GROUP4;
239 		nglmi_startup_fixed(sc, hook);
240 	} else if (strcmp(name, NG_LMI_HOOK_AUTO0) == 0) {
241 		/* Note this, and if B is already installed, we're complete */
242 		sc->lmi_channel0 = hook;
243 		sc->protoname = NAME_NONE;
244 		NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
245 		if (sc->lmi_channel1023)
246 			nglmi_startup_auto(sc);
247 	} else if (strcmp(name, NG_LMI_HOOK_AUTO1023) == 0) {
248 		/* Note this, and if A is already installed, we're complete */
249 		sc->lmi_channel1023 = hook;
250 		sc->protoname = NAME_NONE;
251 		NG_HOOK_SET_PRIVATE(hook, NG_NODE_PRIVATE(node));
252 		if (sc->lmi_channel0)
253 			nglmi_startup_auto(sc);
254 	} else
255 		return (EINVAL);		/* unknown hook */
256 	return (0);
257 }
258 
259 /*
260  * We have just attached to a live (we hope) node.
261  * Fire out a LMI inquiry, and then start up the timers.
262  */
263 static void
264 LMI_ticker(node_p node, hook_p hook, void *arg1, int arg2)
265 {
266 	sc_p sc = NG_NODE_PRIVATE(node);
267 
268 	if (sc->flags & SCF_AUTO) {
269 		ngauto_state_machine(sc);
270 		ng_callout(&sc->handle, node, NULL, NG_LMI_POLL_RATE * hz,
271 		    LMI_ticker, NULL, 0);
272 	} else {
273 		if (sc->livs++ >= sc->liv_per_full) {
274 			nglmi_inquire(sc, 1);
275 			/* sc->livs = 0; *//* do this when we get the answer! */
276 		} else {
277 			nglmi_inquire(sc, 0);
278 		}
279 		ng_callout(&sc->handle, node, NULL, sc->liv_rate * hz,
280 		    LMI_ticker, NULL, 0);
281 	}
282 }
283 
284 static void
285 nglmi_startup_fixed(sc_p sc, hook_p hook)
286 {
287 	sc->flags |= (SCF_FIXED | SCF_CONNECTED);
288 	sc->lmi_channel = hook;
289 	nglmi_startup(sc);
290 }
291 
292 static void
293 nglmi_startup_auto(sc_p sc)
294 {
295 	sc->flags |= (SCF_AUTO | SCF_CONNECTED);
296 	sc->poll_state = 0;	/* reset state machine */
297 	sc->poll_count = 0;
298 	nglmi_startup(sc);
299 }
300 
301 static void
302 nglmi_startup(sc_p sc)
303 {
304 	sc->remote_seq = 0;
305 	sc->local_seq = 1;
306 	sc->seq_retries = 0;
307 	sc->livs = sc->liv_per_full - 1;
308 	/* start off the ticker in 1 sec */
309 	ng_callout(&sc->handle, sc->node, NULL, hz, LMI_ticker, NULL, 0);
310 }
311 
312 static void
313 nglmi_inquire(sc_p sc, int full)
314 {
315 	struct mbuf *m;
316 	struct ng_tag_prio *ptag;
317 	char   *cptr, *start;
318 	int     error;
319 
320 	if (sc->lmi_channel == NULL)
321 		return;
322 	MGETHDR(m, M_DONTWAIT, MT_DATA);
323 	if (m == NULL) {
324 		log(LOG_ERR, "nglmi: unable to start up LMI processing\n");
325 		return;
326 	}
327 	m->m_pkthdr.rcvif = NULL;
328 
329 	/* Attach a tag to packet, marking it of link level state priority, so
330 	 * that device driver would put it in the beginning of queue */
331 
332 	ptag = (struct ng_tag_prio *)m_tag_alloc(NGM_GENERIC_COOKIE, NG_TAG_PRIO,
333 	    (sizeof(struct ng_tag_prio) - sizeof(struct m_tag)), M_NOWAIT);
334 	if (ptag != NULL) {	/* if it failed, well, it was optional anyhow */
335 		ptag->priority = NG_PRIO_LINKSTATE;
336 		ptag->discardability = -1;
337 		m_tag_prepend(m, &ptag->tag);
338 	}
339 
340 	m->m_data += 4;		/* leave some room for a header */
341 	cptr = start = mtod(m, char *);
342 	/* add in the header for an LMI inquiry. */
343 	*cptr++ = 0x03;		/* UI frame */
344 	if (GROUP4(sc))
345 		*cptr++ = 0x09;	/* proto discriminator */
346 	else
347 		*cptr++ = 0x08;	/* proto discriminator */
348 	*cptr++ = 0x00;		/* call reference */
349 	*cptr++ = 0x75;		/* inquiry */
350 
351 	/* If we are Annex-D, add locking shift to codeset 5. */
352 	if (ANNEXD(sc))
353 		*cptr++ = 0x95;	/* locking shift */
354 	/* Add a request type */
355 	if (ANNEXA(sc))
356 		*cptr++ = 0x51;	/* report type */
357 	else
358 		*cptr++ = 0x01;	/* report type */
359 	*cptr++ = 0x01;		/* size = 1 */
360 	if (full)
361 		*cptr++ = 0x00;	/* full */
362 	else
363 		*cptr++ = 0x01;	/* partial */
364 
365 	/* Add a link verification IE */
366 	if (ANNEXA(sc))
367 		*cptr++ = 0x53;	/* verification IE */
368 	else
369 		*cptr++ = 0x03;	/* verification IE */
370 	*cptr++ = 0x02;		/* 2 extra bytes */
371 	*cptr++ = sc->local_seq;
372 	*cptr++ = sc->remote_seq;
373 	sc->seq_retries++;
374 
375 	/* Send it */
376 	m->m_len = m->m_pkthdr.len = cptr - start;
377 	NG_SEND_DATA_ONLY(error, sc->lmi_channel, m);
378 
379 	/* If we've been sending requests for long enough, and there has
380 	 * been no response, then mark as DOWN, any DLCIs that are UP. */
381 	if (sc->seq_retries == LMI_PATIENCE) {
382 		int     count;
383 
384 		for (count = 0; count < MAXDLCI; count++)
385 			if (sc->dlci_state[count] == DLCI_UP)
386 				sc->dlci_state[count] = DLCI_DOWN;
387 	}
388 }
389 
390 /*
391  * State machine for LMI auto-detect. The transitions are ordered
392  * to try the more likely possibilities first.
393  */
394 static void
395 ngauto_state_machine(sc_p sc)
396 {
397 	if ((sc->poll_count <= 0) || (sc->poll_count > LMIPOLLSIZE)) {
398 		/* time to change states in the auto probe machine */
399 		/* capture wild values of poll_count while we are at it */
400 		sc->poll_count = LMIPOLLSIZE;
401 		sc->poll_state++;
402 	}
403 	switch (sc->poll_state) {
404 	case 7:
405 		log(LOG_WARNING, "nglmi: no response from exchange\n");
406 	default:		/* capture bad states */
407 		sc->poll_state = 1;
408 	case 1:
409 		sc->lmi_channel = sc->lmi_channel0;
410 		SETLMITYPE(sc, SCF_ANNEX_D);
411 		break;
412 	case 2:
413 		sc->lmi_channel = sc->lmi_channel1023;
414 		SETLMITYPE(sc, SCF_ANNEX_D);
415 		break;
416 	case 3:
417 		sc->lmi_channel = sc->lmi_channel0;
418 		SETLMITYPE(sc, SCF_ANNEX_A);
419 		break;
420 	case 4:
421 		sc->lmi_channel = sc->lmi_channel1023;
422 		SETLMITYPE(sc, SCF_GROUP4);
423 		break;
424 	case 5:
425 		sc->lmi_channel = sc->lmi_channel1023;
426 		SETLMITYPE(sc, SCF_ANNEX_A);
427 		break;
428 	case 6:
429 		sc->lmi_channel = sc->lmi_channel0;
430 		SETLMITYPE(sc, SCF_GROUP4);
431 		break;
432 	}
433 
434 	/* send an inquirey encoded appropriatly */
435 	nglmi_inquire(sc, 0);
436 	sc->poll_count--;
437 }
438 
439 /*
440  * Receive a netgraph control message.
441  */
442 static int
443 nglmi_rcvmsg(node_p node, item_p item, hook_p lasthook)
444 {
445 	sc_p    sc = NG_NODE_PRIVATE(node);
446 	struct ng_mesg *resp = NULL;
447 	int     error = 0;
448 	struct ng_mesg *msg;
449 
450 	NGI_GET_MSG(item, msg);
451 	switch (msg->header.typecookie) {
452 	case NGM_GENERIC_COOKIE:
453 		switch (msg->header.cmd) {
454 		case NGM_TEXT_STATUS:
455 		    {
456 			char   *arg;
457 			int     pos, count;
458 
459 			NG_MKRESPONSE(resp, msg, NG_TEXTRESPONSE, M_NOWAIT);
460 			if (resp == NULL) {
461 				error = ENOMEM;
462 				break;
463 			}
464 			arg = resp->data;
465 			pos = sprintf(arg, "protocol %s ", sc->protoname);
466 			if (sc->flags & SCF_FIXED)
467 				pos += sprintf(arg + pos, "fixed\n");
468 			else if (sc->flags & SCF_AUTO)
469 				pos += sprintf(arg + pos, "auto-detecting\n");
470 			else
471 				pos += sprintf(arg + pos, "auto on dlci %d\n",
472 				    (sc->lmi_channel == sc->lmi_channel0) ?
473 				    0 : 1023);
474 			pos += sprintf(arg + pos,
475 			    "keepalive period: %d seconds\n", sc->liv_rate);
476 			pos += sprintf(arg + pos,
477 			    "unacknowledged keepalives: %ld\n",
478 			    sc->seq_retries);
479 			for (count = 0;
480 			     ((count <= MAXDLCI)
481 			      && (pos < (NG_TEXTRESPONSE - 20)));
482 			     count++) {
483 				if (sc->dlci_state[count]) {
484 					pos += sprintf(arg + pos,
485 					       "dlci %d %s\n", count,
486 					       (sc->dlci_state[count]
487 					== DLCI_UP) ? "up" : "down");
488 				}
489 			}
490 			resp->header.arglen = pos + 1;
491 			break;
492 		    }
493 		default:
494 			error = EINVAL;
495 			break;
496 		}
497 		break;
498 	case NGM_LMI_COOKIE:
499 		switch (msg->header.cmd) {
500 		case NGM_LMI_GET_STATUS:
501 		    {
502 			struct nglmistat *stat;
503 			int k;
504 
505 			NG_MKRESPONSE(resp, msg, sizeof(*stat), M_NOWAIT);
506 			if (!resp) {
507 				error = ENOMEM;
508 				break;
509 			}
510 			stat = (struct nglmistat *) resp->data;
511 			strncpy(stat->proto,
512 			     sc->protoname, sizeof(stat->proto) - 1);
513 			strncpy(stat->hook,
514 			      sc->protoname, sizeof(stat->hook) - 1);
515 			stat->autod = !!(sc->flags & SCF_AUTO);
516 			stat->fixed = !!(sc->flags & SCF_FIXED);
517 			for (k = 0; k <= MAXDLCI; k++) {
518 				switch (sc->dlci_state[k]) {
519 				case DLCI_UP:
520 					stat->up[k / 8] |= (1 << (k % 8));
521 					/* fall through */
522 				case DLCI_DOWN:
523 					stat->seen[k / 8] |= (1 << (k % 8));
524 					break;
525 				}
526 			}
527 			break;
528 		    }
529 		default:
530 			error = EINVAL;
531 			break;
532 		}
533 		break;
534 	default:
535 		error = EINVAL;
536 		break;
537 	}
538 
539 	NG_RESPOND_MSG(error, node, item, resp);
540 	NG_FREE_MSG(msg);
541 	return (error);
542 }
543 
544 #define STEPBY(stepsize)			\
545 	do {					\
546 		packetlen -= (stepsize);	\
547 		data += (stepsize);		\
548 	} while (0)
549 
550 /*
551  * receive data, and use it to update our status.
552  * Anything coming in on the debug port is discarded.
553  */
554 static int
555 nglmi_rcvdata(hook_p hook, item_p item)
556 {
557 	sc_p    sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
558 	const	u_char *data;
559 	unsigned short dlci;
560 	u_short packetlen;
561 	int     resptype_seen = 0;
562 	int     seq_seen = 0;
563 	struct mbuf *m;
564 
565 	NGI_GET_M(item, m);
566 	NG_FREE_ITEM(item);
567 	if (NG_HOOK_PRIVATE(hook) == NULL) {
568 		goto drop;
569 	}
570 	packetlen = m->m_hdr.mh_len;
571 
572 	/* XXX what if it's more than 1 mbuf? */
573 	if ((packetlen > MHLEN) && !(m->m_flags & M_EXT)) {
574 		log(LOG_WARNING, "nglmi: packetlen (%d) too big\n", packetlen);
575 		goto drop;
576 	}
577 	if (m->m_len < packetlen && (m = m_pullup(m, packetlen)) == NULL) {
578 		log(LOG_WARNING,
579 		    "nglmi: m_pullup failed for %d bytes\n", packetlen);
580 		return (0);
581 	}
582 	if (nglmi_checkdata(hook, m) == 0)
583 		return (0);
584 
585 	/* pass the first 4 bytes (already checked in the nglmi_checkdata()) */
586 	data = mtod(m, const u_char *);
587 	STEPBY(4);
588 
589 	/* Now check if there is a 'locking shift'. This is only seen in
590 	 * Annex D frames. don't bother checking, we already did that. Don't
591 	 * increment immediatly as it might not be there. */
592 	if (ANNEXD(sc))
593 		STEPBY(1);
594 
595 	/* If we get this far we should consider that it is a legitimate
596 	 * frame and we know what it is. */
597 	if (sc->flags & SCF_AUTO) {
598 		/* note the hook that this valid channel came from and drop
599 		 * out of auto probe mode. */
600 		if (ANNEXA(sc))
601 			sc->protoname = NAME_ANNEXA;
602 		else if (ANNEXD(sc))
603 			sc->protoname = NAME_ANNEXD;
604 		else if (GROUP4(sc))
605 			sc->protoname = NAME_GROUP4;
606 		else {
607 			log(LOG_ERR, "nglmi: No known type\n");
608 			goto drop;
609 		}
610 		sc->lmi_channel = hook;
611 		sc->flags &= ~SCF_AUTO;
612 		log(LOG_INFO, "nglmi: auto-detected %s LMI on DLCI %d\n",
613 		    sc->protoname, hook == sc->lmi_channel0 ? 0 : 1023);
614 	}
615 
616 	/* While there is more data in the status packet, keep processing
617 	 * status items. First make sure there is enough data for the
618 	 * segment descriptor's length field. */
619 	while (packetlen >= 2) {
620 		u_int   segtype = data[0];
621 		u_int   segsize = data[1];
622 
623 		/* Now that we know how long it claims to be, make sure
624 		 * there is enough data for the next seg. */
625 		if (packetlen < segsize + 2)
626 			break;
627 		switch (segtype) {
628 		case 0x01:
629 		case 0x51:
630 			if (resptype_seen) {
631 				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
632 				goto nextIE;
633 			}
634 			resptype_seen++;
635 			/* The remote end tells us what kind of response
636 			 * this is. Only expect a type 0 or 1. if we are a
637 			 * full status, invalidate a few DLCIs just to see
638 			 * that they are still ok. */
639 			if (segsize != 1)
640 				goto nextIE;
641 			switch (data[2]) {
642 			case 1:
643 				/* partial status, do no extra processing */
644 				break;
645 			case 0:
646 			    {
647 				int     count = 0;
648 				int     idx = sc->invalidx;
649 
650 				for (count = 0; count < 10; count++) {
651 					if (idx > MAXDLCI)
652 						idx = 0;
653 					if (sc->dlci_state[idx] == DLCI_UP)
654 						sc->dlci_state[idx] = DLCI_DOWN;
655 					idx++;
656 				}
657 				sc->invalidx = idx;
658 				/* we got and we wanted one. relax
659 				 * now.. but don't reset to 0 if it
660 				 * was unrequested. */
661 				if (sc->livs > sc->liv_per_full)
662 					sc->livs = 0;
663 				break;
664 			    }
665 			}
666 			break;
667 		case 0x03:
668 		case 0x53:
669 			/* The remote tells us what it thinks the sequence
670 			 * numbers are. If it's not size 2, it must be a
671 			 * duplicate to have gotten this far, skip it. */
672 			if (seq_seen != 0)	/* already seen seq numbers */
673 				goto nextIE;
674 			if (segsize != 2)
675 				goto nextIE;
676 			sc->remote_seq = data[2];
677 			if (sc->local_seq == data[3]) {
678 				sc->local_seq++;
679 				sc->seq_retries = 0;
680 				/* Note that all 3 Frame protocols seem to
681 				 * not like 0 as a sequence number. */
682 				if (sc->local_seq == 0)
683 					sc->local_seq = 1;
684 			}
685 			break;
686 		case 0x07:
687 		case 0x57:
688 			/* The remote tells us about a DLCI that it knows
689 			 * about. There may be many of these in a single
690 			 * status response */
691 			switch (segsize) {
692 			case 6:/* only on 'group of 4' */
693 				dlci = ((u_short) data[2] & 0xff) << 8;
694 				dlci |= (data[3] & 0xff);
695 				if ((dlci < 1024) && (dlci > 0)) {
696 				  /* XXX */
697 				}
698 				break;
699 			case 3:
700 				dlci = ((u_short) data[2] & 0x3f) << 4;
701 				dlci |= ((data[3] & 0x78) >> 3);
702 				if ((dlci < 1024) && (dlci > 0)) {
703 					/* set up the bottom half of the
704 					 * support for that dlci if it's not
705 					 * already been done */
706 					/* store this information somewhere */
707 				}
708 				break;
709 			default:
710 				goto nextIE;
711 			}
712 			if (sc->dlci_state[dlci] != DLCI_UP) {
713 				/* bring new DLCI to life */
714 				/* may do more here some day */
715 				if (sc->dlci_state[dlci] != DLCI_DOWN)
716 					log(LOG_INFO,
717 					    "nglmi: DLCI %d became active\n",
718 					    dlci);
719 				sc->dlci_state[dlci] = DLCI_UP;
720 			}
721 			break;
722 		}
723 nextIE:
724 		STEPBY(segsize + 2);
725 	}
726 	NG_FREE_M(m);
727 	return (0);
728 
729 drop:
730 	NG_FREE_M(m);
731 	return (EINVAL);
732 }
733 
734 /*
735  * Check that a packet is entirely kosha.
736  * return 1 of ok, and 0 if not.
737  * All data is discarded if a 0 is returned.
738  */
739 static int
740 nglmi_checkdata(hook_p hook, struct mbuf *m)
741 {
742 	sc_p    sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
743 	const	u_char *data;
744 	u_short packetlen;
745 	unsigned short dlci;
746 	u_char  type;
747 	u_char  nextbyte;
748 	int     seq_seen = 0;
749 	int     resptype_seen = 0;	/* 0 , 1 (partial) or 2 (full) */
750 	int     highest_dlci = 0;
751 
752 	packetlen = m->m_hdr.mh_len;
753 	data = mtod(m, const u_char *);
754 	if (*data != 0x03) {
755 		log(LOG_WARNING, "nglmi: unexpected value in LMI(%d)\n", 1);
756 		goto reject;
757 	}
758 	STEPBY(1);
759 
760 	/* look at the protocol ID */
761 	nextbyte = *data;
762 	if (sc->flags & SCF_AUTO) {
763 		SETLMITYPE(sc, SCF_NOLMI);	/* start with a clean slate */
764 		switch (nextbyte) {
765 		case 0x8:
766 			sc->protoID = 8;
767 			break;
768 		case 0x9:
769 			SETLMITYPE(sc, SCF_GROUP4);
770 			sc->protoID = 9;
771 			break;
772 		default:
773 			log(LOG_WARNING, "nglmi: bad Protocol ID(%d)\n",
774 			    (int) nextbyte);
775 			goto reject;
776 		}
777 	} else {
778 		if (nextbyte != sc->protoID) {
779 			log(LOG_WARNING, "nglmi: unexpected Protocol ID(%d)\n",
780 			    (int) nextbyte);
781 			goto reject;
782 		}
783 	}
784 	STEPBY(1);
785 
786 	/* check call reference (always null in non ISDN frame relay) */
787 	if (*data != 0x00) {
788 		log(LOG_WARNING, "nglmi: unexpected Call Reference (0x%x)\n",
789 		    data[-1]);
790 		goto reject;
791 	}
792 	STEPBY(1);
793 
794 	/* check message type */
795 	switch ((type = *data)) {
796 	case 0x75:		/* Status enquiry */
797 		log(LOG_WARNING, "nglmi: unexpected message type(0x%x)\n",
798 		    data[-1]);
799 		goto reject;
800 	case 0x7D:		/* Status message */
801 		break;
802 	default:
803 		log(LOG_WARNING,
804 		    "nglmi: unexpected msg type(0x%x) \n", (int) type);
805 		goto reject;
806 	}
807 	STEPBY(1);
808 
809 	/* Now check if there is a 'locking shift'. This is only seen in
810 	 * Annex D frames. Don't increment immediately as it might not be
811 	 * there. */
812 	nextbyte = *data;
813 	if (sc->flags & SCF_AUTO) {
814 		if (!(GROUP4(sc))) {
815 			if (nextbyte == 0x95) {
816 				SETLMITYPE(sc, SCF_ANNEX_D);
817 				STEPBY(1);
818 			} else
819 				SETLMITYPE(sc, SCF_ANNEX_A);
820 		} else if (nextbyte == 0x95) {
821 			log(LOG_WARNING, "nglmi: locking shift seen in G4\n");
822 			goto reject;
823 		}
824 	} else {
825 		if (ANNEXD(sc)) {
826 			if (*data == 0x95)
827 				STEPBY(1);
828 			else {
829 				log(LOG_WARNING,
830 				    "nglmi: locking shift missing\n");
831 				goto reject;
832 			}
833 		} else if (*data == 0x95) {
834 			log(LOG_WARNING, "nglmi: locking shift seen\n");
835 			goto reject;
836 		}
837 	}
838 
839 	/* While there is more data in the status packet, keep processing
840 	 * status items. First make sure there is enough data for the
841 	 * segment descriptor's length field. */
842 	while (packetlen >= 2) {
843 		u_int   segtype = data[0];
844 		u_int   segsize = data[1];
845 
846 		/* Now that we know how long it claims to be, make sure
847 		 * there is enough data for the next seg. */
848 		if (packetlen < (segsize + 2)) {
849 			log(LOG_WARNING, "nglmi: IE longer than packet\n");
850 			break;
851 		}
852 		switch (segtype) {
853 		case 0x01:
854 		case 0x51:
855 			/* According to MCI's HP analyser, we should just
856 			 * ignore if there is mor ethan one of these (?). */
857 			if (resptype_seen) {
858 				log(LOG_WARNING, "nglmi: dup MSGTYPE\n");
859 				goto nextIE;
860 			}
861 			if (segsize != 1) {
862 				log(LOG_WARNING, "nglmi: MSGTYPE wrong size\n");
863 				goto reject;
864 			}
865 			/* The remote end tells us what kind of response
866 			 * this is. Only expect a type 0 or 1. if it was a
867 			 * full (type 0) check we just asked for a type
868 			 * full. */
869 			switch (data[2]) {
870 			case 1:/* partial */
871 				if (sc->livs > sc->liv_per_full) {
872 					log(LOG_WARNING,
873 					  "nglmi: LIV when FULL expected\n");
874 					goto reject;	/* need full */
875 				}
876 				resptype_seen = 1;
877 				break;
878 			case 0:/* full */
879 				/* Full response is always acceptable */
880 				resptype_seen = 2;
881 				break;
882 			default:
883 				log(LOG_WARNING,
884 				 "nglmi: Unknown report type %d\n", data[2]);
885 				goto reject;
886 			}
887 			break;
888 		case 0x03:
889 		case 0x53:
890 			/* The remote tells us what it thinks the sequence
891 			 * numbers are. I would have thought that there
892 			 * needs to be one and only one of these, but MCI
893 			 * want us to just ignore extras. (?) */
894 			if (resptype_seen == 0) {
895 				log(LOG_WARNING, "nglmi: no TYPE before SEQ\n");
896 				goto reject;
897 			}
898 			if (seq_seen != 0)	/* already seen seq numbers */
899 				goto nextIE;
900 			if (segsize != 2) {
901 				log(LOG_WARNING, "nglmi: bad SEQ sts size\n");
902 				goto reject;
903 			}
904 			if (sc->local_seq != data[3]) {
905 				log(LOG_WARNING, "nglmi: unexpected SEQ\n");
906 				goto reject;
907 			}
908 			seq_seen = 1;
909 			break;
910 		case 0x07:
911 		case 0x57:
912 			/* The remote tells us about a DLCI that it knows
913 			 * about. There may be many of these in a single
914 			 * status response */
915 			if (seq_seen != 1) {	/* already seen seq numbers? */
916 				log(LOG_WARNING,
917 				    "nglmi: No sequence before DLCI\n");
918 				goto reject;
919 			}
920 			if (resptype_seen != 2) {	/* must be full */
921 				log(LOG_WARNING,
922 				    "nglmi: No resp type before DLCI\n");
923 				goto reject;
924 			}
925 			if (GROUP4(sc)) {
926 				if (segsize != 6) {
927 					log(LOG_WARNING,
928 					    "nglmi: wrong IE segsize\n");
929 					goto reject;
930 				}
931 				dlci = ((u_short) data[2] & 0xff) << 8;
932 				dlci |= (data[3] & 0xff);
933 			} else {
934 				if (segsize != 3) {
935 					log(LOG_WARNING,
936 					    "nglmi: DLCI headersize of %d"
937 					    " not supported\n", segsize - 1);
938 					goto reject;
939 				}
940 				dlci = ((u_short) data[2] & 0x3f) << 4;
941 				dlci |= ((data[3] & 0x78) >> 3);
942 			}
943 			/* async can only have one of these */
944 #if 0				/* async not yet accepted */
945 			if (async && highest_dlci) {
946 				log(LOG_WARNING,
947 				    "nglmi: Async with > 1 DLCI\n");
948 				goto reject;
949 			}
950 #endif
951 			/* Annex D says these will always be Ascending, but
952 			 * the HP test for G4 says we should accept
953 			 * duplicates, so for now allow that. ( <= vs. < ) */
954 #if 0
955 			/* MCI tests want us to accept out of order for AnxD */
956 			if ((!GROUP4(sc)) && (dlci < highest_dlci)) {
957 				/* duplicate or mis-ordered dlci */
958 				/* (spec says they will increase in number) */
959 				log(LOG_WARNING, "nglmi: DLCI out of order\n");
960 				goto reject;
961 			}
962 #endif
963 			if (dlci > 1023) {
964 				log(LOG_WARNING, "nglmi: DLCI out of range\n");
965 				goto reject;
966 			}
967 			highest_dlci = dlci;
968 			break;
969 		default:
970 			log(LOG_WARNING,
971 			    "nglmi: unknown LMI segment type %d\n", segtype);
972 		}
973 nextIE:
974 		STEPBY(segsize + 2);
975 	}
976 	if (packetlen != 0) {	/* partial junk at end? */
977 		log(LOG_WARNING,
978 		    "nglmi: %d bytes extra at end of packet\n", packetlen);
979 		goto print;
980 	}
981 	if (resptype_seen == 0) {
982 		log(LOG_WARNING, "nglmi: No response type seen\n");
983 		goto reject;	/* had no response type */
984 	}
985 	if (seq_seen == 0) {
986 		log(LOG_WARNING, "nglmi: No sequence numbers seen\n");
987 		goto reject;	/* had no sequence numbers */
988 	}
989 	return (1);
990 
991 print:
992 	{
993 		int     i, j, k, pos;
994 		char    buf[100];
995 		int     loc;
996 		const	u_char *bp = mtod(m, const u_char *);
997 
998 		k = i = 0;
999 		loc = (m->m_hdr.mh_len - packetlen);
1000 		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1001 		while (k < m->m_hdr.mh_len) {
1002 			pos = 0;
1003 			j = 0;
1004 			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1005 				pos += sprintf(buf + pos, "%c%02x",
1006 					       ((loc == k) ? '>' : ' '),
1007 					       bp[k]);
1008 				k++;
1009 			}
1010 			if (i == 0)
1011 				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1012 			else
1013 				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1014 			i++;
1015 		}
1016 	}
1017 	return (1);
1018 reject:
1019 	{
1020 		int     i, j, k, pos;
1021 		char    buf[100];
1022 		int     loc;
1023 		const	u_char *bp = mtod(m, const u_char *);
1024 
1025 		k = i = 0;
1026 		loc = (m->m_hdr.mh_len - packetlen);
1027 		log(LOG_WARNING, "nglmi: error at location %d\n", loc);
1028 		while (k < m->m_hdr.mh_len) {
1029 			pos = 0;
1030 			j = 0;
1031 			while ((j++ < 16) && k < m->m_hdr.mh_len) {
1032 				pos += sprintf(buf + pos, "%c%02x",
1033 					       ((loc == k) ? '>' : ' '),
1034 					       bp[k]);
1035 				k++;
1036 			}
1037 			if (i == 0)
1038 				log(LOG_WARNING, "nglmi: packet data:%s\n", buf);
1039 			else
1040 				log(LOG_WARNING, "%04d              :%s\n", k, buf);
1041 			i++;
1042 		}
1043 	}
1044 	NG_FREE_M(m);
1045 	return (0);
1046 }
1047 
1048 /*
1049  * Do local shutdown processing..
1050  * Cut any remaining links and free our local resources.
1051  */
1052 static int
1053 nglmi_shutdown(node_p node)
1054 {
1055 	const sc_p sc = NG_NODE_PRIVATE(node);
1056 
1057 	NG_NODE_SET_PRIVATE(node, NULL);
1058 	NG_NODE_UNREF(sc->node);
1059 	FREE(sc, M_NETGRAPH);
1060 	return (0);
1061 }
1062 
1063 /*
1064  * Hook disconnection
1065  * For this type, removal of any link except "debug" destroys the node.
1066  */
1067 static int
1068 nglmi_disconnect(hook_p hook)
1069 {
1070 	const sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1071 
1072 	/* OK to remove debug hook(s) */
1073 	if (NG_HOOK_PRIVATE(hook) == NULL)
1074 		return (0);
1075 
1076 	/* Stop timer if it's currently active */
1077 	if (sc->flags & SCF_CONNECTED)
1078 		ng_uncallout(&sc->handle, sc->node);
1079 
1080 	/* Self-destruct */
1081 	if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
1082 		ng_rmnode_self(NG_HOOK_NODE(hook));
1083 	return (0);
1084 }
1085 
1086