xref: /freebsd/sys/net/if_vlan.c (revision 282a3889ebf826db9839be296ff1dd903f6d6d6e)
1 /*-
2  * Copyright 1998 Massachusetts Institute of Technology
3  *
4  * Permission to use, copy, modify, and distribute this software and
5  * its documentation for any purpose and without fee is hereby
6  * granted, provided that both the above copyright notice and this
7  * permission notice appear in all copies, that both the above
8  * copyright notice and this permission notice appear in all
9  * supporting documentation, and that the name of M.I.T. not be used
10  * in advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.  M.I.T. makes
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied
14  * warranty.
15  *
16  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
17  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
20  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 /*
33  * if_vlan.c - pseudo-device driver for IEEE 802.1Q virtual LANs.
34  * Might be extended some day to also handle IEEE 802.1p priority
35  * tagging.  This is sort of sneaky in the implementation, since
36  * we need to pretend to be enough of an Ethernet implementation
37  * to make arp work.  The way we do this is by telling everyone
38  * that we are an Ethernet, and then catch the packets that
39  * ether_output() left on our output queue when it calls
40  * if_start(), rewrite them for use by the real outgoing interface,
41  * and ask it to send them.
42  */
43 
44 #include "opt_vlan.h"
45 
46 #include <sys/param.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/module.h>
52 #include <sys/rwlock.h>
53 #include <sys/queue.h>
54 #include <sys/socket.h>
55 #include <sys/sockio.h>
56 #include <sys/sysctl.h>
57 #include <sys/systm.h>
58 
59 #include <net/bpf.h>
60 #include <net/ethernet.h>
61 #include <net/if.h>
62 #include <net/if_clone.h>
63 #include <net/if_dl.h>
64 #include <net/if_types.h>
65 #include <net/if_vlan_var.h>
66 
67 #define VLANNAME	"vlan"
68 #define	VLAN_DEF_HWIDTH	4
69 #define	VLAN_IFFLAGS	(IFF_BROADCAST | IFF_MULTICAST)
70 
71 #define	UP_AND_RUNNING(ifp) \
72     ((ifp)->if_flags & IFF_UP && (ifp)->if_drv_flags & IFF_DRV_RUNNING)
73 
74 LIST_HEAD(ifvlanhead, ifvlan);
75 
76 struct ifvlantrunk {
77 	struct	ifnet   *parent;	/* parent interface of this trunk */
78 	struct	rwlock	rw;
79 #ifdef VLAN_ARRAY
80 #define	VLAN_ARRAY_SIZE	(EVL_VLID_MASK + 1)
81 	struct	ifvlan	*vlans[VLAN_ARRAY_SIZE]; /* static table */
82 #else
83 	struct	ifvlanhead *hash;	/* dynamic hash-list table */
84 	uint16_t	hmask;
85 	uint16_t	hwidth;
86 #endif
87 	int		refcnt;
88 };
89 
90 struct vlan_mc_entry {
91 	struct ether_addr		mc_addr;
92 	SLIST_ENTRY(vlan_mc_entry)	mc_entries;
93 };
94 
95 struct	ifvlan {
96 	struct	ifvlantrunk *ifv_trunk;
97 	struct	ifnet *ifv_ifp;
98 #define	TRUNK(ifv)	((ifv)->ifv_trunk)
99 #define	PARENT(ifv)	((ifv)->ifv_trunk->parent)
100 	int	ifv_pflags;	/* special flags we have set on parent */
101 	struct	ifv_linkmib {
102 		int	ifvm_encaplen;	/* encapsulation length */
103 		int	ifvm_mtufudge;	/* MTU fudged by this much */
104 		int	ifvm_mintu;	/* min transmission unit */
105 		uint16_t ifvm_proto;	/* encapsulation ethertype */
106 		uint16_t ifvm_tag;	/* tag to apply on packets leaving if */
107 	}	ifv_mib;
108 	SLIST_HEAD(, vlan_mc_entry) vlan_mc_listhead;
109 #ifndef VLAN_ARRAY
110 	LIST_ENTRY(ifvlan) ifv_list;
111 #endif
112 };
113 #define	ifv_proto	ifv_mib.ifvm_proto
114 #define	ifv_tag		ifv_mib.ifvm_tag
115 #define	ifv_encaplen	ifv_mib.ifvm_encaplen
116 #define	ifv_mtufudge	ifv_mib.ifvm_mtufudge
117 #define	ifv_mintu	ifv_mib.ifvm_mintu
118 
119 /* Special flags we should propagate to parent. */
120 static struct {
121 	int flag;
122 	int (*func)(struct ifnet *, int);
123 } vlan_pflags[] = {
124 	{IFF_PROMISC, ifpromisc},
125 	{IFF_ALLMULTI, if_allmulti},
126 	{0, NULL}
127 };
128 
129 SYSCTL_DECL(_net_link);
130 SYSCTL_NODE(_net_link, IFT_L2VLAN, vlan, CTLFLAG_RW, 0, "IEEE 802.1Q VLAN");
131 SYSCTL_NODE(_net_link_vlan, PF_LINK, link, CTLFLAG_RW, 0, "for consistency");
132 
133 static int soft_pad = 0;
134 SYSCTL_INT(_net_link_vlan, OID_AUTO, soft_pad, CTLFLAG_RW, &soft_pad, 0,
135 	   "pad short frames before tagging");
136 
137 static MALLOC_DEFINE(M_VLAN, VLANNAME, "802.1Q Virtual LAN Interface");
138 
139 static eventhandler_tag ifdetach_tag;
140 
141 /*
142  * We have a global mutex, that is used to serialize configuration
143  * changes and isn't used in normal packet delivery.
144  *
145  * We also have a per-trunk rwlock, that is locked shared on packet
146  * processing and exclusive when configuration is changed.
147  *
148  * The VLAN_ARRAY substitutes the dynamic hash with a static array
149  * with 4096 entries. In theory this can give a boost in processing,
150  * however on practice it does not. Probably this is because array
151  * is too big to fit into CPU cache.
152  */
153 static struct mtx ifv_mtx;
154 #define	VLAN_LOCK_INIT()	mtx_init(&ifv_mtx, "vlan_global", NULL, MTX_DEF)
155 #define	VLAN_LOCK_DESTROY()	mtx_destroy(&ifv_mtx)
156 #define	VLAN_LOCK_ASSERT()	mtx_assert(&ifv_mtx, MA_OWNED)
157 #define	VLAN_LOCK()		mtx_lock(&ifv_mtx)
158 #define	VLAN_UNLOCK()		mtx_unlock(&ifv_mtx)
159 #define	TRUNK_LOCK_INIT(trunk)	rw_init(&(trunk)->rw, VLANNAME)
160 #define	TRUNK_LOCK_DESTROY(trunk) rw_destroy(&(trunk)->rw)
161 #define	TRUNK_LOCK(trunk)	rw_wlock(&(trunk)->rw)
162 #define	TRUNK_UNLOCK(trunk)	rw_wunlock(&(trunk)->rw)
163 #define	TRUNK_LOCK_ASSERT(trunk) rw_assert(&(trunk)->rw, RA_WLOCKED)
164 #define	TRUNK_RLOCK(trunk)	rw_rlock(&(trunk)->rw)
165 #define	TRUNK_RUNLOCK(trunk)	rw_runlock(&(trunk)->rw)
166 #define	TRUNK_LOCK_RASSERT(trunk) rw_assert(&(trunk)->rw, RA_RLOCKED)
167 
168 #ifndef VLAN_ARRAY
169 static	void vlan_inithash(struct ifvlantrunk *trunk);
170 static	void vlan_freehash(struct ifvlantrunk *trunk);
171 static	int vlan_inshash(struct ifvlantrunk *trunk, struct ifvlan *ifv);
172 static	int vlan_remhash(struct ifvlantrunk *trunk, struct ifvlan *ifv);
173 static	void vlan_growhash(struct ifvlantrunk *trunk, int howmuch);
174 static __inline struct ifvlan * vlan_gethash(struct ifvlantrunk *trunk,
175 	uint16_t tag);
176 #endif
177 static	void trunk_destroy(struct ifvlantrunk *trunk);
178 
179 static	void vlan_start(struct ifnet *ifp);
180 static	void vlan_init(void *foo);
181 static	void vlan_input(struct ifnet *ifp, struct mbuf *m);
182 static	int vlan_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr);
183 static	int vlan_setflag(struct ifnet *ifp, int flag, int status,
184     int (*func)(struct ifnet *, int));
185 static	int vlan_setflags(struct ifnet *ifp, int status);
186 static	int vlan_setmulti(struct ifnet *ifp);
187 static	int vlan_unconfig(struct ifnet *ifp);
188 static	int vlan_unconfig_locked(struct ifnet *ifp);
189 static	int vlan_config(struct ifvlan *ifv, struct ifnet *p, uint16_t tag);
190 static	void vlan_link_state(struct ifnet *ifp, int link);
191 static	void vlan_capabilities(struct ifvlan *ifv);
192 static	void vlan_trunk_capabilities(struct ifnet *ifp);
193 
194 static	struct ifnet *vlan_clone_match_ethertag(struct if_clone *,
195     const char *, int *);
196 static	int vlan_clone_match(struct if_clone *, const char *);
197 static	int vlan_clone_create(struct if_clone *, char *, size_t, caddr_t);
198 static	int vlan_clone_destroy(struct if_clone *, struct ifnet *);
199 
200 static	void vlan_ifdetach(void *arg, struct ifnet *ifp);
201 
202 static	struct if_clone vlan_cloner = IFC_CLONE_INITIALIZER(VLANNAME, NULL,
203     IF_MAXUNIT, NULL, vlan_clone_match, vlan_clone_create, vlan_clone_destroy);
204 
205 #ifndef VLAN_ARRAY
206 #define HASH(n, m)	((((n) >> 8) ^ ((n) >> 4) ^ (n)) & (m))
207 
208 static void
209 vlan_inithash(struct ifvlantrunk *trunk)
210 {
211 	int i, n;
212 
213 	/*
214 	 * The trunk must not be locked here since we call malloc(M_WAITOK).
215 	 * It is OK in case this function is called before the trunk struct
216 	 * gets hooked up and becomes visible from other threads.
217 	 */
218 
219 	KASSERT(trunk->hwidth == 0 && trunk->hash == NULL,
220 	    ("%s: hash already initialized", __func__));
221 
222 	trunk->hwidth = VLAN_DEF_HWIDTH;
223 	n = 1 << trunk->hwidth;
224 	trunk->hmask = n - 1;
225 	trunk->hash = malloc(sizeof(struct ifvlanhead) * n, M_VLAN, M_WAITOK);
226 	for (i = 0; i < n; i++)
227 		LIST_INIT(&trunk->hash[i]);
228 }
229 
230 static void
231 vlan_freehash(struct ifvlantrunk *trunk)
232 {
233 #ifdef INVARIANTS
234 	int i;
235 
236 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
237 	for (i = 0; i < (1 << trunk->hwidth); i++)
238 		KASSERT(LIST_EMPTY(&trunk->hash[i]),
239 		    ("%s: hash table not empty", __func__));
240 #endif
241 	free(trunk->hash, M_VLAN);
242 	trunk->hash = NULL;
243 	trunk->hwidth = trunk->hmask = 0;
244 }
245 
246 static int
247 vlan_inshash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
248 {
249 	int i, b;
250 	struct ifvlan *ifv2;
251 
252 	TRUNK_LOCK_ASSERT(trunk);
253 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
254 
255 	b = 1 << trunk->hwidth;
256 	i = HASH(ifv->ifv_tag, trunk->hmask);
257 	LIST_FOREACH(ifv2, &trunk->hash[i], ifv_list)
258 		if (ifv->ifv_tag == ifv2->ifv_tag)
259 			return (EEXIST);
260 
261 	/*
262 	 * Grow the hash when the number of vlans exceeds half of the number of
263 	 * hash buckets squared. This will make the average linked-list length
264 	 * buckets/2.
265 	 */
266 	if (trunk->refcnt > (b * b) / 2) {
267 		vlan_growhash(trunk, 1);
268 		i = HASH(ifv->ifv_tag, trunk->hmask);
269 	}
270 	LIST_INSERT_HEAD(&trunk->hash[i], ifv, ifv_list);
271 	trunk->refcnt++;
272 
273 	return (0);
274 }
275 
276 static int
277 vlan_remhash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
278 {
279 	int i, b;
280 	struct ifvlan *ifv2;
281 
282 	TRUNK_LOCK_ASSERT(trunk);
283 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
284 
285 	b = 1 << trunk->hwidth;
286 	i = HASH(ifv->ifv_tag, trunk->hmask);
287 	LIST_FOREACH(ifv2, &trunk->hash[i], ifv_list)
288 		if (ifv2 == ifv) {
289 			trunk->refcnt--;
290 			LIST_REMOVE(ifv2, ifv_list);
291 			if (trunk->refcnt < (b * b) / 2)
292 				vlan_growhash(trunk, -1);
293 			return (0);
294 		}
295 
296 	panic("%s: vlan not found\n", __func__);
297 	return (ENOENT); /*NOTREACHED*/
298 }
299 
300 /*
301  * Grow the hash larger or smaller if memory permits.
302  */
303 static void
304 vlan_growhash(struct ifvlantrunk *trunk, int howmuch)
305 {
306 	struct ifvlan *ifv;
307 	struct ifvlanhead *hash2;
308 	int hwidth2, i, j, n, n2;
309 
310 	TRUNK_LOCK_ASSERT(trunk);
311 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
312 
313 	if (howmuch == 0) {
314 		/* Harmless yet obvious coding error */
315 		printf("%s: howmuch is 0\n", __func__);
316 		return;
317 	}
318 
319 	hwidth2 = trunk->hwidth + howmuch;
320 	n = 1 << trunk->hwidth;
321 	n2 = 1 << hwidth2;
322 	/* Do not shrink the table below the default */
323 	if (hwidth2 < VLAN_DEF_HWIDTH)
324 		return;
325 
326 	/* M_NOWAIT because we're called with trunk mutex held */
327 	hash2 = malloc(sizeof(struct ifvlanhead) * n2, M_VLAN, M_NOWAIT);
328 	if (hash2 == NULL) {
329 		printf("%s: out of memory -- hash size not changed\n",
330 		    __func__);
331 		return;		/* We can live with the old hash table */
332 	}
333 	for (j = 0; j < n2; j++)
334 		LIST_INIT(&hash2[j]);
335 	for (i = 0; i < n; i++)
336 		while ((ifv = LIST_FIRST(&trunk->hash[i])) != NULL) {
337 			LIST_REMOVE(ifv, ifv_list);
338 			j = HASH(ifv->ifv_tag, n2 - 1);
339 			LIST_INSERT_HEAD(&hash2[j], ifv, ifv_list);
340 		}
341 	free(trunk->hash, M_VLAN);
342 	trunk->hash = hash2;
343 	trunk->hwidth = hwidth2;
344 	trunk->hmask = n2 - 1;
345 
346 	if (bootverbose)
347 		if_printf(trunk->parent,
348 		    "VLAN hash table resized from %d to %d buckets\n", n, n2);
349 }
350 
351 static __inline struct ifvlan *
352 vlan_gethash(struct ifvlantrunk *trunk, uint16_t tag)
353 {
354 	struct ifvlan *ifv;
355 
356 	TRUNK_LOCK_RASSERT(trunk);
357 
358 	LIST_FOREACH(ifv, &trunk->hash[HASH(tag, trunk->hmask)], ifv_list)
359 		if (ifv->ifv_tag == tag)
360 			return (ifv);
361 	return (NULL);
362 }
363 
364 #if 0
365 /* Debugging code to view the hashtables. */
366 static void
367 vlan_dumphash(struct ifvlantrunk *trunk)
368 {
369 	int i;
370 	struct ifvlan *ifv;
371 
372 	for (i = 0; i < (1 << trunk->hwidth); i++) {
373 		printf("%d: ", i);
374 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list)
375 			printf("%s ", ifv->ifv_ifp->if_xname);
376 		printf("\n");
377 	}
378 }
379 #endif /* 0 */
380 #endif /* !VLAN_ARRAY */
381 
382 static void
383 trunk_destroy(struct ifvlantrunk *trunk)
384 {
385 	VLAN_LOCK_ASSERT();
386 
387 	TRUNK_LOCK(trunk);
388 #ifndef VLAN_ARRAY
389 	vlan_freehash(trunk);
390 #endif
391 	trunk->parent->if_vlantrunk = NULL;
392 	TRUNK_UNLOCK(trunk);
393 	TRUNK_LOCK_DESTROY(trunk);
394 	free(trunk, M_VLAN);
395 }
396 
397 /*
398  * Program our multicast filter. What we're actually doing is
399  * programming the multicast filter of the parent. This has the
400  * side effect of causing the parent interface to receive multicast
401  * traffic that it doesn't really want, which ends up being discarded
402  * later by the upper protocol layers. Unfortunately, there's no way
403  * to avoid this: there really is only one physical interface.
404  *
405  * XXX: There is a possible race here if more than one thread is
406  *      modifying the multicast state of the vlan interface at the same time.
407  */
408 static int
409 vlan_setmulti(struct ifnet *ifp)
410 {
411 	struct ifnet		*ifp_p;
412 	struct ifmultiaddr	*ifma, *rifma = NULL;
413 	struct ifvlan		*sc;
414 	struct vlan_mc_entry	*mc;
415 	struct sockaddr_dl	sdl;
416 	int			error;
417 
418 	/*VLAN_LOCK_ASSERT();*/
419 
420 	/* Find the parent. */
421 	sc = ifp->if_softc;
422 	ifp_p = PARENT(sc);
423 
424 	bzero((char *)&sdl, sizeof(sdl));
425 	sdl.sdl_len = sizeof(sdl);
426 	sdl.sdl_family = AF_LINK;
427 	sdl.sdl_index = ifp_p->if_index;
428 	sdl.sdl_type = IFT_ETHER;
429 	sdl.sdl_alen = ETHER_ADDR_LEN;
430 
431 	/* First, remove any existing filter entries. */
432 	while ((mc = SLIST_FIRST(&sc->vlan_mc_listhead)) != NULL) {
433 		bcopy((char *)&mc->mc_addr, LLADDR(&sdl), ETHER_ADDR_LEN);
434 		error = if_delmulti(ifp_p, (struct sockaddr *)&sdl);
435 		if (error)
436 			return (error);
437 		SLIST_REMOVE_HEAD(&sc->vlan_mc_listhead, mc_entries);
438 		free(mc, M_VLAN);
439 	}
440 
441 	/* Now program new ones. */
442 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
443 		if (ifma->ifma_addr->sa_family != AF_LINK)
444 			continue;
445 		mc = malloc(sizeof(struct vlan_mc_entry), M_VLAN, M_NOWAIT);
446 		if (mc == NULL)
447 			return (ENOMEM);
448 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
449 		    (char *)&mc->mc_addr, ETHER_ADDR_LEN);
450 		SLIST_INSERT_HEAD(&sc->vlan_mc_listhead, mc, mc_entries);
451 		bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
452 		    LLADDR(&sdl), ETHER_ADDR_LEN);
453 		error = if_addmulti(ifp_p, (struct sockaddr *)&sdl, &rifma);
454 		if (error)
455 			return (error);
456 	}
457 
458 	return (0);
459 }
460 
461 /*
462  * A handler for network interface departure events.
463  * Track departure of trunks here so that we don't access invalid
464  * pointers or whatever if a trunk is ripped from under us, e.g.,
465  * by ejecting its hot-plug card.
466  */
467 static void
468 vlan_ifdetach(void *arg __unused, struct ifnet *ifp)
469 {
470 	struct ifvlan *ifv;
471 	int i;
472 
473 	/*
474 	 * Check if it's a trunk interface first of all
475 	 * to avoid needless locking.
476 	 */
477 	if (ifp->if_vlantrunk == NULL)
478 		return;
479 
480 	VLAN_LOCK();
481 	/*
482 	 * OK, it's a trunk.  Loop over and detach all vlan's on it.
483 	 * Check trunk pointer after each vlan_unconfig() as it will
484 	 * free it and set to NULL after the last vlan was detached.
485 	 */
486 #ifdef VLAN_ARRAY
487 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
488 		if ((ifv = ifp->if_vlantrunk->vlans[i])) {
489 			vlan_unconfig_locked(ifv->ifv_ifp);
490 			if (ifp->if_vlantrunk == NULL)
491 				break;
492 		}
493 #else /* VLAN_ARRAY */
494 restart:
495 	for (i = 0; i < (1 << ifp->if_vlantrunk->hwidth); i++)
496 		if ((ifv = LIST_FIRST(&ifp->if_vlantrunk->hash[i]))) {
497 			vlan_unconfig_locked(ifv->ifv_ifp);
498 			if (ifp->if_vlantrunk)
499 				goto restart;	/* trunk->hwidth can change */
500 			else
501 				break;
502 		}
503 #endif /* VLAN_ARRAY */
504 	/* Trunk should have been destroyed in vlan_unconfig(). */
505 	KASSERT(ifp->if_vlantrunk == NULL, ("%s: purge failed", __func__));
506 	VLAN_UNLOCK();
507 }
508 
509 /*
510  * VLAN support can be loaded as a module.  The only place in the
511  * system that's intimately aware of this is ether_input.  We hook
512  * into this code through vlan_input_p which is defined there and
513  * set here.  Noone else in the system should be aware of this so
514  * we use an explicit reference here.
515  */
516 extern	void (*vlan_input_p)(struct ifnet *, struct mbuf *);
517 
518 /* For if_link_state_change() eyes only... */
519 extern	void (*vlan_link_state_p)(struct ifnet *, int);
520 
521 static int
522 vlan_modevent(module_t mod, int type, void *data)
523 {
524 
525 	switch (type) {
526 	case MOD_LOAD:
527 		ifdetach_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
528 		    vlan_ifdetach, NULL, EVENTHANDLER_PRI_ANY);
529 		if (ifdetach_tag == NULL)
530 			return (ENOMEM);
531 		VLAN_LOCK_INIT();
532 		vlan_input_p = vlan_input;
533 		vlan_link_state_p = vlan_link_state;
534 		vlan_trunk_cap_p = vlan_trunk_capabilities;
535 		if_clone_attach(&vlan_cloner);
536 		if (bootverbose)
537 			printf("vlan: initialized, using "
538 #ifdef VLAN_ARRAY
539 			       "full-size arrays"
540 #else
541 			       "hash tables with chaining"
542 #endif
543 
544 			       "\n");
545 		break;
546 	case MOD_UNLOAD:
547 		if_clone_detach(&vlan_cloner);
548 		EVENTHANDLER_DEREGISTER(ifnet_departure_event, ifdetach_tag);
549 		vlan_input_p = NULL;
550 		vlan_link_state_p = NULL;
551 		vlan_trunk_cap_p = NULL;
552 		VLAN_LOCK_DESTROY();
553 		if (bootverbose)
554 			printf("vlan: unloaded\n");
555 		break;
556 	default:
557 		return (EOPNOTSUPP);
558 	}
559 	return (0);
560 }
561 
562 static moduledata_t vlan_mod = {
563 	"if_vlan",
564 	vlan_modevent,
565 	0
566 };
567 
568 DECLARE_MODULE(if_vlan, vlan_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
569 MODULE_VERSION(if_vlan, 3);
570 MODULE_DEPEND(if_vlan, miibus, 1, 1, 1);
571 
572 static struct ifnet *
573 vlan_clone_match_ethertag(struct if_clone *ifc, const char *name, int *tag)
574 {
575 	const char *cp;
576 	struct ifnet *ifp;
577 	int t = 0;
578 
579 	/* Check for <etherif>.<vlan> style interface names. */
580 	IFNET_RLOCK();
581 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
582 		if (ifp->if_type != IFT_ETHER)
583 			continue;
584 		if (strncmp(ifp->if_xname, name, strlen(ifp->if_xname)) != 0)
585 			continue;
586 		cp = name + strlen(ifp->if_xname);
587 		if (*cp != '.')
588 			continue;
589 		for(; *cp != '\0'; cp++) {
590 			if (*cp < '0' || *cp > '9')
591 				continue;
592 			t = (t * 10) + (*cp - '0');
593 		}
594 		if (tag != NULL)
595 			*tag = t;
596 		break;
597 	}
598 	IFNET_RUNLOCK();
599 
600 	return (ifp);
601 }
602 
603 static int
604 vlan_clone_match(struct if_clone *ifc, const char *name)
605 {
606 	const char *cp;
607 
608 	if (vlan_clone_match_ethertag(ifc, name, NULL) != NULL)
609 		return (1);
610 
611 	if (strncmp(VLANNAME, name, strlen(VLANNAME)) != 0)
612 		return (0);
613 	for (cp = name + 4; *cp != '\0'; cp++) {
614 		if (*cp < '0' || *cp > '9')
615 			return (0);
616 	}
617 
618 	return (1);
619 }
620 
621 static int
622 vlan_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
623 {
624 	char *dp;
625 	int wildcard;
626 	int unit;
627 	int error;
628 	int tag;
629 	int ethertag;
630 	struct ifvlan *ifv;
631 	struct ifnet *ifp;
632 	struct ifnet *p;
633 	struct vlanreq vlr;
634 	static const u_char eaddr[ETHER_ADDR_LEN];	/* 00:00:00:00:00:00 */
635 
636 	/*
637 	 * There are 3 (ugh) ways to specify the cloned device:
638 	 * o pass a parameter block with the clone request.
639 	 * o specify parameters in the text of the clone device name
640 	 * o specify no parameters and get an unattached device that
641 	 *   must be configured separately.
642 	 * The first technique is preferred; the latter two are
643 	 * supported for backwards compatibilty.
644 	 */
645 	if (params) {
646 		error = copyin(params, &vlr, sizeof(vlr));
647 		if (error)
648 			return error;
649 		p = ifunit(vlr.vlr_parent);
650 		if (p == NULL)
651 			return ENXIO;
652 		/*
653 		 * Don't let the caller set up a VLAN tag with
654 		 * anything except VLID bits.
655 		 */
656 		if (vlr.vlr_tag & ~EVL_VLID_MASK)
657 			return (EINVAL);
658 		error = ifc_name2unit(name, &unit);
659 		if (error != 0)
660 			return (error);
661 
662 		ethertag = 1;
663 		tag = vlr.vlr_tag;
664 		wildcard = (unit < 0);
665 	} else if ((p = vlan_clone_match_ethertag(ifc, name, &tag)) != NULL) {
666 		ethertag = 1;
667 		unit = -1;
668 		wildcard = 0;
669 
670 		/*
671 		 * Don't let the caller set up a VLAN tag with
672 		 * anything except VLID bits.
673 		 */
674 		if (tag & ~EVL_VLID_MASK)
675 			return (EINVAL);
676 	} else {
677 		ethertag = 0;
678 
679 		error = ifc_name2unit(name, &unit);
680 		if (error != 0)
681 			return (error);
682 
683 		wildcard = (unit < 0);
684 	}
685 
686 	error = ifc_alloc_unit(ifc, &unit);
687 	if (error != 0)
688 		return (error);
689 
690 	/* In the wildcard case, we need to update the name. */
691 	if (wildcard) {
692 		for (dp = name; *dp != '\0'; dp++);
693 		if (snprintf(dp, len - (dp-name), "%d", unit) >
694 		    len - (dp-name) - 1) {
695 			panic("%s: interface name too long", __func__);
696 		}
697 	}
698 
699 	ifv = malloc(sizeof(struct ifvlan), M_VLAN, M_WAITOK | M_ZERO);
700 	ifp = ifv->ifv_ifp = if_alloc(IFT_ETHER);
701 	if (ifp == NULL) {
702 		ifc_free_unit(ifc, unit);
703 		free(ifv, M_VLAN);
704 		return (ENOSPC);
705 	}
706 	SLIST_INIT(&ifv->vlan_mc_listhead);
707 
708 	ifp->if_softc = ifv;
709 	/*
710 	 * Set the name manually rather than using if_initname because
711 	 * we don't conform to the default naming convention for interfaces.
712 	 */
713 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
714 	ifp->if_dname = ifc->ifc_name;
715 	ifp->if_dunit = unit;
716 	/* NB: flags are not set here */
717 	ifp->if_linkmib = &ifv->ifv_mib;
718 	ifp->if_linkmiblen = sizeof(ifv->ifv_mib);
719 	/* NB: mtu is not set here */
720 
721 	ifp->if_init = vlan_init;
722 	ifp->if_start = vlan_start;
723 	ifp->if_ioctl = vlan_ioctl;
724 	ifp->if_snd.ifq_maxlen = ifqmaxlen;
725 	ifp->if_flags = VLAN_IFFLAGS;
726 	ether_ifattach(ifp, eaddr);
727 	/* Now undo some of the damage... */
728 	ifp->if_baudrate = 0;
729 	ifp->if_type = IFT_L2VLAN;
730 	ifp->if_hdrlen = ETHER_VLAN_ENCAP_LEN;
731 
732 	if (ethertag) {
733 		error = vlan_config(ifv, p, tag);
734 		if (error != 0) {
735 			/*
736 			 * Since we've partialy failed, we need to back
737 			 * out all the way, otherwise userland could get
738 			 * confused.  Thus, we destroy the interface.
739 			 */
740 			ether_ifdetach(ifp);
741 			vlan_unconfig(ifp);
742 			if_free_type(ifp, IFT_ETHER);
743 			free(ifv, M_VLAN);
744 
745 			return (error);
746 		}
747 
748 		/* Update flags on the parent, if necessary. */
749 		vlan_setflags(ifp, 1);
750 	}
751 
752 	return (0);
753 }
754 
755 static int
756 vlan_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
757 {
758 	struct ifvlan *ifv = ifp->if_softc;
759 	int unit = ifp->if_dunit;
760 
761 	ether_ifdetach(ifp);	/* first, remove it from system-wide lists */
762 	vlan_unconfig(ifp);	/* now it can be unconfigured and freed */
763 	if_free_type(ifp, IFT_ETHER);
764 	free(ifv, M_VLAN);
765 	ifc_free_unit(ifc, unit);
766 
767 	return (0);
768 }
769 
770 /*
771  * The ifp->if_init entry point for vlan(4) is a no-op.
772  */
773 static void
774 vlan_init(void *foo __unused)
775 {
776 }
777 
778 /*
779  * The if_start method for vlan(4) interface. It doesn't
780  * raises the IFF_DRV_OACTIVE flag, since it is called
781  * only from IFQ_HANDOFF() macro in ether_output_frame().
782  * If the interface queue is full, and vlan_start() is
783  * not called, the queue would never get emptied and
784  * interface would stall forever.
785  */
786 static void
787 vlan_start(struct ifnet *ifp)
788 {
789 	struct ifvlan *ifv;
790 	struct ifnet *p;
791 	struct mbuf *m;
792 	int error;
793 
794 	ifv = ifp->if_softc;
795 	p = PARENT(ifv);
796 
797 	for (;;) {
798 		IF_DEQUEUE(&ifp->if_snd, m);
799 		if (m == NULL)
800 			break;
801 		BPF_MTAP(ifp, m);
802 
803 		/*
804 		 * Do not run parent's if_start() if the parent is not up,
805 		 * or parent's driver will cause a system crash.
806 		 */
807 		if (!UP_AND_RUNNING(p)) {
808 			m_freem(m);
809 			ifp->if_collisions++;
810 			continue;
811 		}
812 
813 		/*
814 		 * Pad the frame to the minimum size allowed if told to.
815 		 * This option is in accord with IEEE Std 802.1Q, 2003 Ed.,
816 		 * paragraph C.4.4.3.b.  It can help to work around buggy
817 		 * bridges that violate paragraph C.4.4.3.a from the same
818 		 * document, i.e., fail to pad short frames after untagging.
819 		 * E.g., a tagged frame 66 bytes long (incl. FCS) is OK, but
820 		 * untagging it will produce a 62-byte frame, which is a runt
821 		 * and requires padding.  There are VLAN-enabled network
822 		 * devices that just discard such runts instead or mishandle
823 		 * them somehow.
824 		 */
825 		if (soft_pad) {
826 			static char pad[8];	/* just zeros */
827 			int n;
828 
829 			for (n = ETHERMIN + ETHER_HDR_LEN - m->m_pkthdr.len;
830 			     n > 0; n -= sizeof(pad))
831 				if (!m_append(m, min(n, sizeof(pad)), pad))
832 					break;
833 
834 			if (n > 0) {
835 				if_printf(ifp, "cannot pad short frame\n");
836 				ifp->if_oerrors++;
837 				m_freem(m);
838 				continue;
839 			}
840 		}
841 
842 		/*
843 		 * If underlying interface can do VLAN tag insertion itself,
844 		 * just pass the packet along. However, we need some way to
845 		 * tell the interface where the packet came from so that it
846 		 * knows how to find the VLAN tag to use, so we attach a
847 		 * packet tag that holds it.
848 		 */
849 		if (p->if_capenable & IFCAP_VLAN_HWTAGGING) {
850 			m->m_pkthdr.ether_vtag = ifv->ifv_tag;
851 			m->m_flags |= M_VLANTAG;
852 		} else {
853 			struct ether_vlan_header *evl;
854 
855 			M_PREPEND(m, ifv->ifv_encaplen, M_DONTWAIT);
856 			if (m == NULL) {
857 				if_printf(ifp,
858 				    "unable to prepend VLAN header\n");
859 				ifp->if_oerrors++;
860 				continue;
861 			}
862 			/* M_PREPEND takes care of m_len, m_pkthdr.len for us */
863 
864 			if (m->m_len < sizeof(*evl)) {
865 				m = m_pullup(m, sizeof(*evl));
866 				if (m == NULL) {
867 					if_printf(ifp,
868 					    "cannot pullup VLAN header\n");
869 					ifp->if_oerrors++;
870 					continue;
871 				}
872 			}
873 
874 			/*
875 			 * Transform the Ethernet header into an Ethernet header
876 			 * with 802.1Q encapsulation.
877 			 */
878 			evl = mtod(m, struct ether_vlan_header *);
879 			bcopy((char *)evl + ifv->ifv_encaplen,
880 			      (char *)evl, ETHER_HDR_LEN - ETHER_TYPE_LEN);
881 			evl->evl_encap_proto = htons(ifv->ifv_proto);
882 			evl->evl_tag = htons(ifv->ifv_tag);
883 #ifdef DEBUG
884 			printf("%s: %*D\n", __func__, (int)sizeof(*evl),
885 			    (unsigned char *)evl, ":");
886 #endif
887 		}
888 
889 		/*
890 		 * Send it, precisely as ether_output() would have.
891 		 * We are already running at splimp.
892 		 */
893 		IFQ_HANDOFF(p, m, error);
894 		if (!error)
895 			ifp->if_opackets++;
896 		else
897 			ifp->if_oerrors++;
898 	}
899 }
900 
901 static void
902 vlan_input(struct ifnet *ifp, struct mbuf *m)
903 {
904 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
905 	struct ifvlan *ifv;
906 	uint16_t tag;
907 
908 	KASSERT(trunk != NULL, ("%s: no trunk", __func__));
909 
910 	if (m->m_flags & M_VLANTAG) {
911 		/*
912 		 * Packet is tagged, but m contains a normal
913 		 * Ethernet frame; the tag is stored out-of-band.
914 		 */
915 		tag = EVL_VLANOFTAG(m->m_pkthdr.ether_vtag);
916 		m->m_flags &= ~M_VLANTAG;
917 	} else {
918 		struct ether_vlan_header *evl;
919 
920 		/*
921 		 * Packet is tagged in-band as specified by 802.1q.
922 		 */
923 		switch (ifp->if_type) {
924 		case IFT_ETHER:
925 			if (m->m_len < sizeof(*evl) &&
926 			    (m = m_pullup(m, sizeof(*evl))) == NULL) {
927 				if_printf(ifp, "cannot pullup VLAN header\n");
928 				return;
929 			}
930 			evl = mtod(m, struct ether_vlan_header *);
931 			tag = EVL_VLANOFTAG(ntohs(evl->evl_tag));
932 
933 			/*
934 			 * Remove the 802.1q header by copying the Ethernet
935 			 * addresses over it and adjusting the beginning of
936 			 * the data in the mbuf.  The encapsulated Ethernet
937 			 * type field is already in place.
938 			 */
939 			bcopy((char *)evl, (char *)evl + ETHER_VLAN_ENCAP_LEN,
940 			      ETHER_HDR_LEN - ETHER_TYPE_LEN);
941 			m_adj(m, ETHER_VLAN_ENCAP_LEN);
942 			break;
943 
944 		default:
945 #ifdef INVARIANTS
946 			panic("%s: %s has unsupported if_type %u",
947 			      __func__, ifp->if_xname, ifp->if_type);
948 #endif
949 			m_freem(m);
950 			ifp->if_noproto++;
951 			return;
952 		}
953 	}
954 
955 	TRUNK_RLOCK(trunk);
956 #ifdef VLAN_ARRAY
957 	ifv = trunk->vlans[tag];
958 #else
959 	ifv = vlan_gethash(trunk, tag);
960 #endif
961 	if (ifv == NULL || !UP_AND_RUNNING(ifv->ifv_ifp)) {
962 		TRUNK_RUNLOCK(trunk);
963 		m_freem(m);
964 		ifp->if_noproto++;
965 		return;
966 	}
967 	TRUNK_RUNLOCK(trunk);
968 
969 	m->m_pkthdr.rcvif = ifv->ifv_ifp;
970 	ifv->ifv_ifp->if_ipackets++;
971 
972 	/* Pass it back through the parent's input routine. */
973 	(*ifp->if_input)(ifv->ifv_ifp, m);
974 }
975 
976 static int
977 vlan_config(struct ifvlan *ifv, struct ifnet *p, uint16_t tag)
978 {
979 	struct ifvlantrunk *trunk;
980 	struct ifnet *ifp;
981 	int error = 0;
982 
983 	/* VID numbers 0x0 and 0xFFF are reserved */
984 	if (tag == 0 || tag == 0xFFF)
985 		return (EINVAL);
986 	if (p->if_type != IFT_ETHER)
987 		return (EPROTONOSUPPORT);
988 	if ((p->if_flags & VLAN_IFFLAGS) != VLAN_IFFLAGS)
989 		return (EPROTONOSUPPORT);
990 	if (ifv->ifv_trunk)
991 		return (EBUSY);
992 
993 	if (p->if_vlantrunk == NULL) {
994 		trunk = malloc(sizeof(struct ifvlantrunk),
995 		    M_VLAN, M_WAITOK | M_ZERO);
996 #ifndef VLAN_ARRAY
997 		vlan_inithash(trunk);
998 #endif
999 		VLAN_LOCK();
1000 		if (p->if_vlantrunk != NULL) {
1001 			/* A race that that is very unlikely to be hit. */
1002 #ifndef VLAN_ARRAY
1003 			vlan_freehash(trunk);
1004 #endif
1005 			free(trunk, M_VLAN);
1006 			goto exists;
1007 		}
1008 		TRUNK_LOCK_INIT(trunk);
1009 		TRUNK_LOCK(trunk);
1010 		p->if_vlantrunk = trunk;
1011 		trunk->parent = p;
1012 	} else {
1013 		VLAN_LOCK();
1014 exists:
1015 		trunk = p->if_vlantrunk;
1016 		TRUNK_LOCK(trunk);
1017 	}
1018 
1019 	ifv->ifv_tag = tag;	/* must set this before vlan_inshash() */
1020 #ifdef VLAN_ARRAY
1021 	if (trunk->vlans[tag] != NULL) {
1022 		error = EEXIST;
1023 		goto done;
1024 	}
1025 	trunk->vlans[tag] = ifv;
1026 	trunk->refcnt++;
1027 #else
1028 	error = vlan_inshash(trunk, ifv);
1029 	if (error)
1030 		goto done;
1031 #endif
1032 	ifv->ifv_proto = ETHERTYPE_VLAN;
1033 	ifv->ifv_encaplen = ETHER_VLAN_ENCAP_LEN;
1034 	ifv->ifv_mintu = ETHERMIN;
1035 	ifv->ifv_pflags = 0;
1036 
1037 	/*
1038 	 * If the parent supports the VLAN_MTU capability,
1039 	 * i.e. can Tx/Rx larger than ETHER_MAX_LEN frames,
1040 	 * use it.
1041 	 */
1042 	if (p->if_capenable & IFCAP_VLAN_MTU) {
1043 		/*
1044 		 * No need to fudge the MTU since the parent can
1045 		 * handle extended frames.
1046 		 */
1047 		ifv->ifv_mtufudge = 0;
1048 	} else {
1049 		/*
1050 		 * Fudge the MTU by the encapsulation size.  This
1051 		 * makes us incompatible with strictly compliant
1052 		 * 802.1Q implementations, but allows us to use
1053 		 * the feature with other NetBSD implementations,
1054 		 * which might still be useful.
1055 		 */
1056 		ifv->ifv_mtufudge = ifv->ifv_encaplen;
1057 	}
1058 
1059 	ifv->ifv_trunk = trunk;
1060 	ifp = ifv->ifv_ifp;
1061 	ifp->if_mtu = p->if_mtu - ifv->ifv_mtufudge;
1062 	ifp->if_baudrate = p->if_baudrate;
1063 	/*
1064 	 * Copy only a selected subset of flags from the parent.
1065 	 * Other flags are none of our business.
1066 	 */
1067 #define VLAN_COPY_FLAGS (IFF_SIMPLEX)
1068 	ifp->if_flags &= ~VLAN_COPY_FLAGS;
1069 	ifp->if_flags |= p->if_flags & VLAN_COPY_FLAGS;
1070 #undef VLAN_COPY_FLAGS
1071 
1072 	ifp->if_link_state = p->if_link_state;
1073 
1074 	vlan_capabilities(ifv);
1075 
1076 	/*
1077 	 * Set up our ``Ethernet address'' to reflect the underlying
1078 	 * physical interface's.
1079 	 */
1080 	bcopy(IF_LLADDR(p), IF_LLADDR(ifp), ETHER_ADDR_LEN);
1081 
1082 	/*
1083 	 * Configure multicast addresses that may already be
1084 	 * joined on the vlan device.
1085 	 */
1086 	(void)vlan_setmulti(ifp); /* XXX: VLAN lock held */
1087 
1088 	/* We are ready for operation now. */
1089 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1090 done:
1091 	TRUNK_UNLOCK(trunk);
1092 	VLAN_UNLOCK();
1093 
1094 	return (error);
1095 }
1096 
1097 static int
1098 vlan_unconfig(struct ifnet *ifp)
1099 {
1100 	int ret;
1101 
1102 	VLAN_LOCK();
1103 	ret = vlan_unconfig_locked(ifp);
1104 	VLAN_UNLOCK();
1105 	return (ret);
1106 }
1107 
1108 static int
1109 vlan_unconfig_locked(struct ifnet *ifp)
1110 {
1111 	struct ifvlantrunk *trunk;
1112 	struct vlan_mc_entry *mc;
1113 	struct ifvlan *ifv;
1114 	int error;
1115 
1116 	VLAN_LOCK_ASSERT();
1117 
1118 	ifv = ifp->if_softc;
1119 	trunk = ifv->ifv_trunk;
1120 
1121 	if (trunk) {
1122 		struct sockaddr_dl sdl;
1123 		struct ifnet *p = trunk->parent;
1124 
1125 		TRUNK_LOCK(trunk);
1126 
1127 		/*
1128 		 * Since the interface is being unconfigured, we need to
1129 		 * empty the list of multicast groups that we may have joined
1130 		 * while we were alive from the parent's list.
1131 		 */
1132 		bzero((char *)&sdl, sizeof(sdl));
1133 		sdl.sdl_len = sizeof(sdl);
1134 		sdl.sdl_family = AF_LINK;
1135 		sdl.sdl_index = p->if_index;
1136 		sdl.sdl_type = IFT_ETHER;
1137 		sdl.sdl_alen = ETHER_ADDR_LEN;
1138 
1139 		while ((mc = SLIST_FIRST(&ifv->vlan_mc_listhead)) != NULL) {
1140 			bcopy((char *)&mc->mc_addr, LLADDR(&sdl),
1141 			    ETHER_ADDR_LEN);
1142 			error = if_delmulti(p, (struct sockaddr *)&sdl);
1143 			if (error)
1144 				return (error);
1145 			SLIST_REMOVE_HEAD(&ifv->vlan_mc_listhead, mc_entries);
1146 			free(mc, M_VLAN);
1147 		}
1148 
1149 		vlan_setflags(ifp, 0); /* clear special flags on parent */
1150 #ifdef VLAN_ARRAY
1151 		trunk->vlans[ifv->ifv_tag] = NULL;
1152 		trunk->refcnt--;
1153 #else
1154 		vlan_remhash(trunk, ifv);
1155 #endif
1156 		ifv->ifv_trunk = NULL;
1157 
1158 		/*
1159 		 * Check if we were the last.
1160 		 */
1161 		if (trunk->refcnt == 0) {
1162 			trunk->parent->if_vlantrunk = NULL;
1163 			/*
1164 			 * XXXGL: If some ithread has already entered
1165 			 * vlan_input() and is now blocked on the trunk
1166 			 * lock, then it should preempt us right after
1167 			 * unlock and finish its work. Then we will acquire
1168 			 * lock again in trunk_destroy().
1169 			 */
1170 			TRUNK_UNLOCK(trunk);
1171 			trunk_destroy(trunk);
1172 		} else
1173 			TRUNK_UNLOCK(trunk);
1174 	}
1175 
1176 	/* Disconnect from parent. */
1177 	if (ifv->ifv_pflags)
1178 		if_printf(ifp, "%s: ifv_pflags unclean\n", __func__);
1179 	ifp->if_mtu = ETHERMTU;
1180 	ifp->if_link_state = LINK_STATE_UNKNOWN;
1181 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1182 
1183 	return (0);
1184 }
1185 
1186 /* Handle a reference counted flag that should be set on the parent as well */
1187 static int
1188 vlan_setflag(struct ifnet *ifp, int flag, int status,
1189 	     int (*func)(struct ifnet *, int))
1190 {
1191 	struct ifvlan *ifv;
1192 	int error;
1193 
1194 	/* XXX VLAN_LOCK_ASSERT(); */
1195 
1196 	ifv = ifp->if_softc;
1197 	status = status ? (ifp->if_flags & flag) : 0;
1198 	/* Now "status" contains the flag value or 0 */
1199 
1200 	/*
1201 	 * See if recorded parent's status is different from what
1202 	 * we want it to be.  If it is, flip it.  We record parent's
1203 	 * status in ifv_pflags so that we won't clear parent's flag
1204 	 * we haven't set.  In fact, we don't clear or set parent's
1205 	 * flags directly, but get or release references to them.
1206 	 * That's why we can be sure that recorded flags still are
1207 	 * in accord with actual parent's flags.
1208 	 */
1209 	if (status != (ifv->ifv_pflags & flag)) {
1210 		error = (*func)(PARENT(ifv), status);
1211 		if (error)
1212 			return (error);
1213 		ifv->ifv_pflags &= ~flag;
1214 		ifv->ifv_pflags |= status;
1215 	}
1216 	return (0);
1217 }
1218 
1219 /*
1220  * Handle IFF_* flags that require certain changes on the parent:
1221  * if "status" is true, update parent's flags respective to our if_flags;
1222  * if "status" is false, forcedly clear the flags set on parent.
1223  */
1224 static int
1225 vlan_setflags(struct ifnet *ifp, int status)
1226 {
1227 	int error, i;
1228 
1229 	for (i = 0; vlan_pflags[i].flag; i++) {
1230 		error = vlan_setflag(ifp, vlan_pflags[i].flag,
1231 				     status, vlan_pflags[i].func);
1232 		if (error)
1233 			return (error);
1234 	}
1235 	return (0);
1236 }
1237 
1238 /* Inform all vlans that their parent has changed link state */
1239 static void
1240 vlan_link_state(struct ifnet *ifp, int link)
1241 {
1242 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
1243 	struct ifvlan *ifv;
1244 	int i;
1245 
1246 	TRUNK_LOCK(trunk);
1247 #ifdef VLAN_ARRAY
1248 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
1249 		if (trunk->vlans[i] != NULL) {
1250 			ifv = trunk->vlans[i];
1251 #else
1252 	for (i = 0; i < (1 << trunk->hwidth); i++)
1253 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list) {
1254 #endif
1255 			ifv->ifv_ifp->if_baudrate = trunk->parent->if_baudrate;
1256 			if_link_state_change(ifv->ifv_ifp,
1257 			    trunk->parent->if_link_state);
1258 		}
1259 	TRUNK_UNLOCK(trunk);
1260 }
1261 
1262 static void
1263 vlan_capabilities(struct ifvlan *ifv)
1264 {
1265 	struct ifnet *p = PARENT(ifv);
1266 	struct ifnet *ifp = ifv->ifv_ifp;
1267 
1268 	TRUNK_LOCK_ASSERT(TRUNK(ifv));
1269 
1270 	/*
1271 	 * If the parent interface can do checksum offloading
1272 	 * on VLANs, then propagate its hardware-assisted
1273 	 * checksumming flags. Also assert that checksum
1274 	 * offloading requires hardware VLAN tagging.
1275 	 */
1276 	if (p->if_capabilities & IFCAP_VLAN_HWCSUM)
1277 		ifp->if_capabilities = p->if_capabilities & IFCAP_HWCSUM;
1278 
1279 	if (p->if_capenable & IFCAP_VLAN_HWCSUM &&
1280 	    p->if_capenable & IFCAP_VLAN_HWTAGGING) {
1281 		ifp->if_capenable = p->if_capenable & IFCAP_HWCSUM;
1282 		ifp->if_hwassist = p->if_hwassist;
1283 	} else {
1284 		ifp->if_capenable = 0;
1285 		ifp->if_hwassist = 0;
1286 	}
1287 }
1288 
1289 static void
1290 vlan_trunk_capabilities(struct ifnet *ifp)
1291 {
1292 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
1293 	struct ifvlan *ifv;
1294 	int i;
1295 
1296 	TRUNK_LOCK(trunk);
1297 #ifdef VLAN_ARRAY
1298 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
1299 		if (trunk->vlans[i] != NULL) {
1300 			ifv = trunk->vlans[i];
1301 #else
1302 	for (i = 0; i < (1 << trunk->hwidth); i++) {
1303 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list)
1304 #endif
1305 			vlan_capabilities(ifv);
1306 	}
1307 	TRUNK_UNLOCK(trunk);
1308 }
1309 
1310 static int
1311 vlan_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1312 {
1313 	struct ifaddr *ifa;
1314 	struct ifnet *p;
1315 	struct ifreq *ifr;
1316 	struct ifvlan *ifv;
1317 	struct vlanreq vlr;
1318 	int error = 0;
1319 
1320 	ifr = (struct ifreq *)data;
1321 	ifa = (struct ifaddr *)data;
1322 	ifv = ifp->if_softc;
1323 
1324 	switch (cmd) {
1325 	case SIOCGIFMEDIA:
1326 		VLAN_LOCK();
1327 		if (TRUNK(ifv) != NULL) {
1328 			error = (*PARENT(ifv)->if_ioctl)(PARENT(ifv),
1329 					SIOCGIFMEDIA, data);
1330 			VLAN_UNLOCK();
1331 			/* Limit the result to the parent's current config. */
1332 			if (error == 0) {
1333 				struct ifmediareq *ifmr;
1334 
1335 				ifmr = (struct ifmediareq *)data;
1336 				if (ifmr->ifm_count >= 1 && ifmr->ifm_ulist) {
1337 					ifmr->ifm_count = 1;
1338 					error = copyout(&ifmr->ifm_current,
1339 						ifmr->ifm_ulist,
1340 						sizeof(int));
1341 				}
1342 			}
1343 		} else {
1344 			VLAN_UNLOCK();
1345 			error = EINVAL;
1346 		}
1347 		break;
1348 
1349 	case SIOCSIFMEDIA:
1350 		error = EINVAL;
1351 		break;
1352 
1353 	case SIOCSIFMTU:
1354 		/*
1355 		 * Set the interface MTU.
1356 		 */
1357 		VLAN_LOCK();
1358 		if (TRUNK(ifv) != NULL) {
1359 			if (ifr->ifr_mtu >
1360 			     (PARENT(ifv)->if_mtu - ifv->ifv_mtufudge) ||
1361 			    ifr->ifr_mtu <
1362 			     (ifv->ifv_mintu - ifv->ifv_mtufudge))
1363 				error = EINVAL;
1364 			else
1365 				ifp->if_mtu = ifr->ifr_mtu;
1366 		} else
1367 			error = EINVAL;
1368 		VLAN_UNLOCK();
1369 		break;
1370 
1371 	case SIOCSETVLAN:
1372 		error = copyin(ifr->ifr_data, &vlr, sizeof(vlr));
1373 		if (error)
1374 			break;
1375 		if (vlr.vlr_parent[0] == '\0') {
1376 			vlan_unconfig(ifp);
1377 			break;
1378 		}
1379 		p = ifunit(vlr.vlr_parent);
1380 		if (p == 0) {
1381 			error = ENOENT;
1382 			break;
1383 		}
1384 		/*
1385 		 * Don't let the caller set up a VLAN tag with
1386 		 * anything except VLID bits.
1387 		 */
1388 		if (vlr.vlr_tag & ~EVL_VLID_MASK) {
1389 			error = EINVAL;
1390 			break;
1391 		}
1392 		error = vlan_config(ifv, p, vlr.vlr_tag);
1393 		if (error)
1394 			break;
1395 
1396 		/* Update flags on the parent, if necessary. */
1397 		vlan_setflags(ifp, 1);
1398 		break;
1399 
1400 	case SIOCGETVLAN:
1401 		bzero(&vlr, sizeof(vlr));
1402 		VLAN_LOCK();
1403 		if (TRUNK(ifv) != NULL) {
1404 			strlcpy(vlr.vlr_parent, PARENT(ifv)->if_xname,
1405 			    sizeof(vlr.vlr_parent));
1406 			vlr.vlr_tag = ifv->ifv_tag;
1407 		}
1408 		VLAN_UNLOCK();
1409 		error = copyout(&vlr, ifr->ifr_data, sizeof(vlr));
1410 		break;
1411 
1412 	case SIOCSIFFLAGS:
1413 		/*
1414 		 * We should propagate selected flags to the parent,
1415 		 * e.g., promiscuous mode.
1416 		 */
1417 		if (TRUNK(ifv) != NULL)
1418 			error = vlan_setflags(ifp, 1);
1419 		break;
1420 
1421 	case SIOCADDMULTI:
1422 	case SIOCDELMULTI:
1423 		/*
1424 		 * If we don't have a parent, just remember the membership for
1425 		 * when we do.
1426 		 */
1427 		if (TRUNK(ifv) != NULL)
1428 			error = vlan_setmulti(ifp);
1429 		break;
1430 
1431 	default:
1432 		error = ether_ioctl(ifp, cmd, data);
1433 	}
1434 
1435 	return (error);
1436 }
1437