xref: /freebsd/sys/net/if_vlan.c (revision f02f7422801bb39f5eaab8fc383fa7b70c467ff9)
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 
30 /*
31  * if_vlan.c - pseudo-device driver for IEEE 802.1Q virtual LANs.
32  * Might be extended some day to also handle IEEE 802.1p priority
33  * tagging.  This is sort of sneaky in the implementation, since
34  * we need to pretend to be enough of an Ethernet implementation
35  * to make arp work.  The way we do this is by telling everyone
36  * that we are an Ethernet, and then catch the packets that
37  * ether_output() sends to us via if_transmit(), rewrite them for
38  * use by the real outgoing interface, and ask it to send them.
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_inet.h"
45 #include "opt_vlan.h"
46 
47 #include <sys/param.h>
48 #include <sys/eventhandler.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mbuf.h>
53 #include <sys/module.h>
54 #include <sys/rmlock.h>
55 #include <sys/queue.h>
56 #include <sys/socket.h>
57 #include <sys/sockio.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 #include <sys/sx.h>
61 
62 #include <net/bpf.h>
63 #include <net/ethernet.h>
64 #include <net/if.h>
65 #include <net/if_var.h>
66 #include <net/if_clone.h>
67 #include <net/if_dl.h>
68 #include <net/if_types.h>
69 #include <net/if_vlan_var.h>
70 #include <net/vnet.h>
71 
72 #ifdef INET
73 #include <netinet/in.h>
74 #include <netinet/if_ether.h>
75 #endif
76 
77 #define	VLAN_DEF_HWIDTH	4
78 #define	VLAN_IFFLAGS	(IFF_BROADCAST | IFF_MULTICAST)
79 
80 #define	UP_AND_RUNNING(ifp) \
81     ((ifp)->if_flags & IFF_UP && (ifp)->if_drv_flags & IFF_DRV_RUNNING)
82 
83 LIST_HEAD(ifvlanhead, ifvlan);
84 
85 struct ifvlantrunk {
86 	struct	ifnet   *parent;	/* parent interface of this trunk */
87 	struct	rmlock	lock;
88 #ifdef VLAN_ARRAY
89 #define	VLAN_ARRAY_SIZE	(EVL_VLID_MASK + 1)
90 	struct	ifvlan	*vlans[VLAN_ARRAY_SIZE]; /* static table */
91 #else
92 	struct	ifvlanhead *hash;	/* dynamic hash-list table */
93 	uint16_t	hmask;
94 	uint16_t	hwidth;
95 #endif
96 	int		refcnt;
97 };
98 
99 struct vlan_mc_entry {
100 	struct sockaddr_dl		mc_addr;
101 	SLIST_ENTRY(vlan_mc_entry)	mc_entries;
102 };
103 
104 struct	ifvlan {
105 	struct	ifvlantrunk *ifv_trunk;
106 	struct	ifnet *ifv_ifp;
107 	counter_u64_t	ifv_ipackets;
108 	counter_u64_t	ifv_ibytes;
109 	counter_u64_t	ifv_opackets;
110 	counter_u64_t	ifv_obytes;
111 	counter_u64_t	ifv_omcasts;
112 	counter_u64_t	ifv_oerrors;
113 #define	TRUNK(ifv)	((ifv)->ifv_trunk)
114 #define	PARENT(ifv)	((ifv)->ifv_trunk->parent)
115 	void	*ifv_cookie;
116 	int	ifv_pflags;	/* special flags we have set on parent */
117 	struct	ifv_linkmib {
118 		int	ifvm_encaplen;	/* encapsulation length */
119 		int	ifvm_mtufudge;	/* MTU fudged by this much */
120 		int	ifvm_mintu;	/* min transmission unit */
121 		uint16_t ifvm_proto;	/* encapsulation ethertype */
122 		uint16_t ifvm_tag;	/* tag to apply on packets leaving if */
123 	}	ifv_mib;
124 	SLIST_HEAD(, vlan_mc_entry) vlan_mc_listhead;
125 #ifndef VLAN_ARRAY
126 	LIST_ENTRY(ifvlan) ifv_list;
127 #endif
128 };
129 #define	ifv_proto	ifv_mib.ifvm_proto
130 #define	ifv_vid		ifv_mib.ifvm_tag
131 #define	ifv_encaplen	ifv_mib.ifvm_encaplen
132 #define	ifv_mtufudge	ifv_mib.ifvm_mtufudge
133 #define	ifv_mintu	ifv_mib.ifvm_mintu
134 
135 /* Special flags we should propagate to parent. */
136 static struct {
137 	int flag;
138 	int (*func)(struct ifnet *, int);
139 } vlan_pflags[] = {
140 	{IFF_PROMISC, ifpromisc},
141 	{IFF_ALLMULTI, if_allmulti},
142 	{0, NULL}
143 };
144 
145 SYSCTL_DECL(_net_link);
146 static SYSCTL_NODE(_net_link, IFT_L2VLAN, vlan, CTLFLAG_RW, 0,
147     "IEEE 802.1Q VLAN");
148 static SYSCTL_NODE(_net_link_vlan, PF_LINK, link, CTLFLAG_RW, 0,
149     "for consistency");
150 
151 static int soft_pad = 0;
152 SYSCTL_INT(_net_link_vlan, OID_AUTO, soft_pad, CTLFLAG_RW, &soft_pad, 0,
153 	   "pad short frames before tagging");
154 
155 static const char vlanname[] = "vlan";
156 static MALLOC_DEFINE(M_VLAN, vlanname, "802.1Q Virtual LAN Interface");
157 
158 static eventhandler_tag ifdetach_tag;
159 static eventhandler_tag iflladdr_tag;
160 
161 /*
162  * We have a global mutex, that is used to serialize configuration
163  * changes and isn't used in normal packet delivery.
164  *
165  * We also have a per-trunk rwlock, that is locked shared on packet
166  * processing and exclusive when configuration is changed.
167  *
168  * The VLAN_ARRAY substitutes the dynamic hash with a static array
169  * with 4096 entries. In theory this can give a boost in processing,
170  * however on practice it does not. Probably this is because array
171  * is too big to fit into CPU cache.
172  */
173 static struct sx ifv_lock;
174 #define	VLAN_LOCK_INIT()	sx_init(&ifv_lock, "vlan_global")
175 #define	VLAN_LOCK_DESTROY()	sx_destroy(&ifv_lock)
176 #define	VLAN_LOCK_ASSERT()	sx_assert(&ifv_lock, SA_LOCKED)
177 #define	VLAN_LOCK()		sx_xlock(&ifv_lock)
178 #define	VLAN_UNLOCK()		sx_xunlock(&ifv_lock)
179 #define	TRUNK_LOCK_INIT(trunk)	rm_init(&(trunk)->lock, vlanname)
180 #define	TRUNK_LOCK_DESTROY(trunk) rm_destroy(&(trunk)->lock)
181 #define	TRUNK_LOCK(trunk)	rm_wlock(&(trunk)->lock)
182 #define	TRUNK_UNLOCK(trunk)	rm_wunlock(&(trunk)->lock)
183 #define	TRUNK_LOCK_ASSERT(trunk) rm_assert(&(trunk)->lock, RA_WLOCKED)
184 #define	TRUNK_RLOCK(trunk)	rm_rlock(&(trunk)->lock, &tracker)
185 #define	TRUNK_RUNLOCK(trunk)	rm_runlock(&(trunk)->lock, &tracker)
186 #define	TRUNK_LOCK_RASSERT(trunk) rm_assert(&(trunk)->lock, RA_RLOCKED)
187 #define	TRUNK_LOCK_READER	struct rm_priotracker tracker
188 
189 #ifndef VLAN_ARRAY
190 static	void vlan_inithash(struct ifvlantrunk *trunk);
191 static	void vlan_freehash(struct ifvlantrunk *trunk);
192 static	int vlan_inshash(struct ifvlantrunk *trunk, struct ifvlan *ifv);
193 static	int vlan_remhash(struct ifvlantrunk *trunk, struct ifvlan *ifv);
194 static	void vlan_growhash(struct ifvlantrunk *trunk, int howmuch);
195 static __inline struct ifvlan * vlan_gethash(struct ifvlantrunk *trunk,
196 	uint16_t vid);
197 #endif
198 static	void trunk_destroy(struct ifvlantrunk *trunk);
199 
200 static	void vlan_init(void *foo);
201 static	void vlan_input(struct ifnet *ifp, struct mbuf *m);
202 static	int vlan_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr);
203 static	void vlan_qflush(struct ifnet *ifp);
204 static uint64_t vlan_get_counter(struct ifnet *ifp, ift_counter cnt);
205 static	int vlan_setflag(struct ifnet *ifp, int flag, int status,
206     int (*func)(struct ifnet *, int));
207 static	int vlan_setflags(struct ifnet *ifp, int status);
208 static	int vlan_setmulti(struct ifnet *ifp);
209 static	int vlan_transmit(struct ifnet *ifp, struct mbuf *m);
210 static	void vlan_unconfig(struct ifnet *ifp);
211 static	void vlan_unconfig_locked(struct ifnet *ifp, int departing);
212 static	int vlan_config(struct ifvlan *ifv, struct ifnet *p, uint16_t tag);
213 static	void vlan_link_state(struct ifnet *ifp);
214 static	void vlan_capabilities(struct ifvlan *ifv);
215 static	void vlan_trunk_capabilities(struct ifnet *ifp);
216 
217 static	struct ifnet *vlan_clone_match_ethervid(struct if_clone *,
218     const char *, int *);
219 static	int vlan_clone_match(struct if_clone *, const char *);
220 static	int vlan_clone_create(struct if_clone *, char *, size_t, caddr_t);
221 static	int vlan_clone_destroy(struct if_clone *, struct ifnet *);
222 
223 static	void vlan_ifdetach(void *arg, struct ifnet *ifp);
224 static  void vlan_iflladdr(void *arg, struct ifnet *ifp);
225 
226 static struct if_clone *vlan_cloner;
227 
228 #ifdef VIMAGE
229 static VNET_DEFINE(struct if_clone *, vlan_cloner);
230 #define	V_vlan_cloner	VNET(vlan_cloner)
231 #endif
232 
233 #ifndef VLAN_ARRAY
234 #define HASH(n, m)	((((n) >> 8) ^ ((n) >> 4) ^ (n)) & (m))
235 
236 static void
237 vlan_inithash(struct ifvlantrunk *trunk)
238 {
239 	int i, n;
240 
241 	/*
242 	 * The trunk must not be locked here since we call malloc(M_WAITOK).
243 	 * It is OK in case this function is called before the trunk struct
244 	 * gets hooked up and becomes visible from other threads.
245 	 */
246 
247 	KASSERT(trunk->hwidth == 0 && trunk->hash == NULL,
248 	    ("%s: hash already initialized", __func__));
249 
250 	trunk->hwidth = VLAN_DEF_HWIDTH;
251 	n = 1 << trunk->hwidth;
252 	trunk->hmask = n - 1;
253 	trunk->hash = malloc(sizeof(struct ifvlanhead) * n, M_VLAN, M_WAITOK);
254 	for (i = 0; i < n; i++)
255 		LIST_INIT(&trunk->hash[i]);
256 }
257 
258 static void
259 vlan_freehash(struct ifvlantrunk *trunk)
260 {
261 #ifdef INVARIANTS
262 	int i;
263 
264 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
265 	for (i = 0; i < (1 << trunk->hwidth); i++)
266 		KASSERT(LIST_EMPTY(&trunk->hash[i]),
267 		    ("%s: hash table not empty", __func__));
268 #endif
269 	free(trunk->hash, M_VLAN);
270 	trunk->hash = NULL;
271 	trunk->hwidth = trunk->hmask = 0;
272 }
273 
274 static int
275 vlan_inshash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
276 {
277 	int i, b;
278 	struct ifvlan *ifv2;
279 
280 	TRUNK_LOCK_ASSERT(trunk);
281 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
282 
283 	b = 1 << trunk->hwidth;
284 	i = HASH(ifv->ifv_vid, trunk->hmask);
285 	LIST_FOREACH(ifv2, &trunk->hash[i], ifv_list)
286 		if (ifv->ifv_vid == ifv2->ifv_vid)
287 			return (EEXIST);
288 
289 	/*
290 	 * Grow the hash when the number of vlans exceeds half of the number of
291 	 * hash buckets squared. This will make the average linked-list length
292 	 * buckets/2.
293 	 */
294 	if (trunk->refcnt > (b * b) / 2) {
295 		vlan_growhash(trunk, 1);
296 		i = HASH(ifv->ifv_vid, trunk->hmask);
297 	}
298 	LIST_INSERT_HEAD(&trunk->hash[i], ifv, ifv_list);
299 	trunk->refcnt++;
300 
301 	return (0);
302 }
303 
304 static int
305 vlan_remhash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
306 {
307 	int i, b;
308 	struct ifvlan *ifv2;
309 
310 	TRUNK_LOCK_ASSERT(trunk);
311 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
312 
313 	b = 1 << trunk->hwidth;
314 	i = HASH(ifv->ifv_vid, trunk->hmask);
315 	LIST_FOREACH(ifv2, &trunk->hash[i], ifv_list)
316 		if (ifv2 == ifv) {
317 			trunk->refcnt--;
318 			LIST_REMOVE(ifv2, ifv_list);
319 			if (trunk->refcnt < (b * b) / 2)
320 				vlan_growhash(trunk, -1);
321 			return (0);
322 		}
323 
324 	panic("%s: vlan not found\n", __func__);
325 	return (ENOENT); /*NOTREACHED*/
326 }
327 
328 /*
329  * Grow the hash larger or smaller if memory permits.
330  */
331 static void
332 vlan_growhash(struct ifvlantrunk *trunk, int howmuch)
333 {
334 	struct ifvlan *ifv;
335 	struct ifvlanhead *hash2;
336 	int hwidth2, i, j, n, n2;
337 
338 	TRUNK_LOCK_ASSERT(trunk);
339 	KASSERT(trunk->hwidth > 0, ("%s: hwidth not positive", __func__));
340 
341 	if (howmuch == 0) {
342 		/* Harmless yet obvious coding error */
343 		printf("%s: howmuch is 0\n", __func__);
344 		return;
345 	}
346 
347 	hwidth2 = trunk->hwidth + howmuch;
348 	n = 1 << trunk->hwidth;
349 	n2 = 1 << hwidth2;
350 	/* Do not shrink the table below the default */
351 	if (hwidth2 < VLAN_DEF_HWIDTH)
352 		return;
353 
354 	/* M_NOWAIT because we're called with trunk mutex held */
355 	hash2 = malloc(sizeof(struct ifvlanhead) * n2, M_VLAN, M_NOWAIT);
356 	if (hash2 == NULL) {
357 		printf("%s: out of memory -- hash size not changed\n",
358 		    __func__);
359 		return;		/* We can live with the old hash table */
360 	}
361 	for (j = 0; j < n2; j++)
362 		LIST_INIT(&hash2[j]);
363 	for (i = 0; i < n; i++)
364 		while ((ifv = LIST_FIRST(&trunk->hash[i])) != NULL) {
365 			LIST_REMOVE(ifv, ifv_list);
366 			j = HASH(ifv->ifv_vid, n2 - 1);
367 			LIST_INSERT_HEAD(&hash2[j], ifv, ifv_list);
368 		}
369 	free(trunk->hash, M_VLAN);
370 	trunk->hash = hash2;
371 	trunk->hwidth = hwidth2;
372 	trunk->hmask = n2 - 1;
373 
374 	if (bootverbose)
375 		if_printf(trunk->parent,
376 		    "VLAN hash table resized from %d to %d buckets\n", n, n2);
377 }
378 
379 static __inline struct ifvlan *
380 vlan_gethash(struct ifvlantrunk *trunk, uint16_t vid)
381 {
382 	struct ifvlan *ifv;
383 
384 	TRUNK_LOCK_RASSERT(trunk);
385 
386 	LIST_FOREACH(ifv, &trunk->hash[HASH(vid, trunk->hmask)], ifv_list)
387 		if (ifv->ifv_vid == vid)
388 			return (ifv);
389 	return (NULL);
390 }
391 
392 #if 0
393 /* Debugging code to view the hashtables. */
394 static void
395 vlan_dumphash(struct ifvlantrunk *trunk)
396 {
397 	int i;
398 	struct ifvlan *ifv;
399 
400 	for (i = 0; i < (1 << trunk->hwidth); i++) {
401 		printf("%d: ", i);
402 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list)
403 			printf("%s ", ifv->ifv_ifp->if_xname);
404 		printf("\n");
405 	}
406 }
407 #endif /* 0 */
408 #else
409 
410 static __inline struct ifvlan *
411 vlan_gethash(struct ifvlantrunk *trunk, uint16_t vid)
412 {
413 
414 	return trunk->vlans[vid];
415 }
416 
417 static __inline int
418 vlan_inshash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
419 {
420 
421 	if (trunk->vlans[ifv->ifv_vid] != NULL)
422 		return EEXIST;
423 	trunk->vlans[ifv->ifv_vid] = ifv;
424 	trunk->refcnt++;
425 
426 	return (0);
427 }
428 
429 static __inline int
430 vlan_remhash(struct ifvlantrunk *trunk, struct ifvlan *ifv)
431 {
432 
433 	trunk->vlans[ifv->ifv_vid] = NULL;
434 	trunk->refcnt--;
435 
436 	return (0);
437 }
438 
439 static __inline void
440 vlan_freehash(struct ifvlantrunk *trunk)
441 {
442 }
443 
444 static __inline void
445 vlan_inithash(struct ifvlantrunk *trunk)
446 {
447 }
448 
449 #endif /* !VLAN_ARRAY */
450 
451 static void
452 trunk_destroy(struct ifvlantrunk *trunk)
453 {
454 	VLAN_LOCK_ASSERT();
455 
456 	TRUNK_LOCK(trunk);
457 	vlan_freehash(trunk);
458 	trunk->parent->if_vlantrunk = NULL;
459 	TRUNK_UNLOCK(trunk);
460 	TRUNK_LOCK_DESTROY(trunk);
461 	free(trunk, M_VLAN);
462 }
463 
464 /*
465  * Program our multicast filter. What we're actually doing is
466  * programming the multicast filter of the parent. This has the
467  * side effect of causing the parent interface to receive multicast
468  * traffic that it doesn't really want, which ends up being discarded
469  * later by the upper protocol layers. Unfortunately, there's no way
470  * to avoid this: there really is only one physical interface.
471  */
472 static int
473 vlan_setmulti(struct ifnet *ifp)
474 {
475 	struct ifnet		*ifp_p;
476 	struct ifmultiaddr	*ifma;
477 	struct ifvlan		*sc;
478 	struct vlan_mc_entry	*mc;
479 	int			error;
480 
481 	/* Find the parent. */
482 	sc = ifp->if_softc;
483 	TRUNK_LOCK_ASSERT(TRUNK(sc));
484 	ifp_p = PARENT(sc);
485 
486 	CURVNET_SET_QUIET(ifp_p->if_vnet);
487 
488 	/* First, remove any existing filter entries. */
489 	while ((mc = SLIST_FIRST(&sc->vlan_mc_listhead)) != NULL) {
490 		SLIST_REMOVE_HEAD(&sc->vlan_mc_listhead, mc_entries);
491 		(void)if_delmulti(ifp_p, (struct sockaddr *)&mc->mc_addr);
492 		free(mc, M_VLAN);
493 	}
494 
495 	/* Now program new ones. */
496 	IF_ADDR_WLOCK(ifp);
497 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
498 		if (ifma->ifma_addr->sa_family != AF_LINK)
499 			continue;
500 		mc = malloc(sizeof(struct vlan_mc_entry), M_VLAN, M_NOWAIT);
501 		if (mc == NULL) {
502 			IF_ADDR_WUNLOCK(ifp);
503 			return (ENOMEM);
504 		}
505 		bcopy(ifma->ifma_addr, &mc->mc_addr, ifma->ifma_addr->sa_len);
506 		mc->mc_addr.sdl_index = ifp_p->if_index;
507 		SLIST_INSERT_HEAD(&sc->vlan_mc_listhead, mc, mc_entries);
508 	}
509 	IF_ADDR_WUNLOCK(ifp);
510 	SLIST_FOREACH (mc, &sc->vlan_mc_listhead, mc_entries) {
511 		error = if_addmulti(ifp_p, (struct sockaddr *)&mc->mc_addr,
512 		    NULL);
513 		if (error)
514 			return (error);
515 	}
516 
517 	CURVNET_RESTORE();
518 	return (0);
519 }
520 
521 /*
522  * A handler for parent interface link layer address changes.
523  * If the parent interface link layer address is changed we
524  * should also change it on all children vlans.
525  */
526 static void
527 vlan_iflladdr(void *arg __unused, struct ifnet *ifp)
528 {
529 	struct ifvlan *ifv;
530 #ifndef VLAN_ARRAY
531 	struct ifvlan *next;
532 #endif
533 	int i;
534 
535 	/*
536 	 * Check if it's a trunk interface first of all
537 	 * to avoid needless locking.
538 	 */
539 	if (ifp->if_vlantrunk == NULL)
540 		return;
541 
542 	VLAN_LOCK();
543 	/*
544 	 * OK, it's a trunk.  Loop over and change all vlan's lladdrs on it.
545 	 */
546 #ifdef VLAN_ARRAY
547 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
548 		if ((ifv = ifp->if_vlantrunk->vlans[i])) {
549 #else /* VLAN_ARRAY */
550 	for (i = 0; i < (1 << ifp->if_vlantrunk->hwidth); i++)
551 		LIST_FOREACH_SAFE(ifv, &ifp->if_vlantrunk->hash[i], ifv_list, next) {
552 #endif /* VLAN_ARRAY */
553 			VLAN_UNLOCK();
554 			if_setlladdr(ifv->ifv_ifp, IF_LLADDR(ifp),
555 			    ifp->if_addrlen);
556 			VLAN_LOCK();
557 		}
558 	VLAN_UNLOCK();
559 
560 }
561 
562 /*
563  * A handler for network interface departure events.
564  * Track departure of trunks here so that we don't access invalid
565  * pointers or whatever if a trunk is ripped from under us, e.g.,
566  * by ejecting its hot-plug card.  However, if an ifnet is simply
567  * being renamed, then there's no need to tear down the state.
568  */
569 static void
570 vlan_ifdetach(void *arg __unused, struct ifnet *ifp)
571 {
572 	struct ifvlan *ifv;
573 	int i;
574 
575 	/*
576 	 * Check if it's a trunk interface first of all
577 	 * to avoid needless locking.
578 	 */
579 	if (ifp->if_vlantrunk == NULL)
580 		return;
581 
582 	/* If the ifnet is just being renamed, don't do anything. */
583 	if (ifp->if_flags & IFF_RENAMING)
584 		return;
585 
586 	VLAN_LOCK();
587 	/*
588 	 * OK, it's a trunk.  Loop over and detach all vlan's on it.
589 	 * Check trunk pointer after each vlan_unconfig() as it will
590 	 * free it and set to NULL after the last vlan was detached.
591 	 */
592 #ifdef VLAN_ARRAY
593 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
594 		if ((ifv = ifp->if_vlantrunk->vlans[i])) {
595 			vlan_unconfig_locked(ifv->ifv_ifp, 1);
596 			if (ifp->if_vlantrunk == NULL)
597 				break;
598 		}
599 #else /* VLAN_ARRAY */
600 restart:
601 	for (i = 0; i < (1 << ifp->if_vlantrunk->hwidth); i++)
602 		if ((ifv = LIST_FIRST(&ifp->if_vlantrunk->hash[i]))) {
603 			vlan_unconfig_locked(ifv->ifv_ifp, 1);
604 			if (ifp->if_vlantrunk)
605 				goto restart;	/* trunk->hwidth can change */
606 			else
607 				break;
608 		}
609 #endif /* VLAN_ARRAY */
610 	/* Trunk should have been destroyed in vlan_unconfig(). */
611 	KASSERT(ifp->if_vlantrunk == NULL, ("%s: purge failed", __func__));
612 	VLAN_UNLOCK();
613 }
614 
615 /*
616  * Return the trunk device for a virtual interface.
617  */
618 static struct ifnet  *
619 vlan_trunkdev(struct ifnet *ifp)
620 {
621 	struct ifvlan *ifv;
622 
623 	if (ifp->if_type != IFT_L2VLAN)
624 		return (NULL);
625 	ifv = ifp->if_softc;
626 	ifp = NULL;
627 	VLAN_LOCK();
628 	if (ifv->ifv_trunk)
629 		ifp = PARENT(ifv);
630 	VLAN_UNLOCK();
631 	return (ifp);
632 }
633 
634 /*
635  * Return the 12-bit VLAN VID for this interface, for use by external
636  * components such as Infiniband.
637  *
638  * XXXRW: Note that the function name here is historical; it should be named
639  * vlan_vid().
640  */
641 static int
642 vlan_tag(struct ifnet *ifp, uint16_t *vidp)
643 {
644 	struct ifvlan *ifv;
645 
646 	if (ifp->if_type != IFT_L2VLAN)
647 		return (EINVAL);
648 	ifv = ifp->if_softc;
649 	*vidp = ifv->ifv_vid;
650 	return (0);
651 }
652 
653 /*
654  * Return a driver specific cookie for this interface.  Synchronization
655  * with setcookie must be provided by the driver.
656  */
657 static void *
658 vlan_cookie(struct ifnet *ifp)
659 {
660 	struct ifvlan *ifv;
661 
662 	if (ifp->if_type != IFT_L2VLAN)
663 		return (NULL);
664 	ifv = ifp->if_softc;
665 	return (ifv->ifv_cookie);
666 }
667 
668 /*
669  * Store a cookie in our softc that drivers can use to store driver
670  * private per-instance data in.
671  */
672 static int
673 vlan_setcookie(struct ifnet *ifp, void *cookie)
674 {
675 	struct ifvlan *ifv;
676 
677 	if (ifp->if_type != IFT_L2VLAN)
678 		return (EINVAL);
679 	ifv = ifp->if_softc;
680 	ifv->ifv_cookie = cookie;
681 	return (0);
682 }
683 
684 /*
685  * Return the vlan device present at the specific VID.
686  */
687 static struct ifnet *
688 vlan_devat(struct ifnet *ifp, uint16_t vid)
689 {
690 	struct ifvlantrunk *trunk;
691 	struct ifvlan *ifv;
692 	TRUNK_LOCK_READER;
693 
694 	trunk = ifp->if_vlantrunk;
695 	if (trunk == NULL)
696 		return (NULL);
697 	ifp = NULL;
698 	TRUNK_RLOCK(trunk);
699 	ifv = vlan_gethash(trunk, vid);
700 	if (ifv)
701 		ifp = ifv->ifv_ifp;
702 	TRUNK_RUNLOCK(trunk);
703 	return (ifp);
704 }
705 
706 /*
707  * VLAN support can be loaded as a module.  The only place in the
708  * system that's intimately aware of this is ether_input.  We hook
709  * into this code through vlan_input_p which is defined there and
710  * set here.  Noone else in the system should be aware of this so
711  * we use an explicit reference here.
712  */
713 extern	void (*vlan_input_p)(struct ifnet *, struct mbuf *);
714 
715 /* For if_link_state_change() eyes only... */
716 extern	void (*vlan_link_state_p)(struct ifnet *);
717 
718 static int
719 vlan_modevent(module_t mod, int type, void *data)
720 {
721 
722 	switch (type) {
723 	case MOD_LOAD:
724 		ifdetach_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
725 		    vlan_ifdetach, NULL, EVENTHANDLER_PRI_ANY);
726 		if (ifdetach_tag == NULL)
727 			return (ENOMEM);
728 		iflladdr_tag = EVENTHANDLER_REGISTER(iflladdr_event,
729 		    vlan_iflladdr, NULL, EVENTHANDLER_PRI_ANY);
730 		if (iflladdr_tag == NULL)
731 			return (ENOMEM);
732 		VLAN_LOCK_INIT();
733 		vlan_input_p = vlan_input;
734 		vlan_link_state_p = vlan_link_state;
735 		vlan_trunk_cap_p = vlan_trunk_capabilities;
736 		vlan_trunkdev_p = vlan_trunkdev;
737 		vlan_cookie_p = vlan_cookie;
738 		vlan_setcookie_p = vlan_setcookie;
739 		vlan_tag_p = vlan_tag;
740 		vlan_devat_p = vlan_devat;
741 #ifndef VIMAGE
742 		vlan_cloner = if_clone_advanced(vlanname, 0, vlan_clone_match,
743 		    vlan_clone_create, vlan_clone_destroy);
744 #endif
745 		if (bootverbose)
746 			printf("vlan: initialized, using "
747 #ifdef VLAN_ARRAY
748 			       "full-size arrays"
749 #else
750 			       "hash tables with chaining"
751 #endif
752 
753 			       "\n");
754 		break;
755 	case MOD_UNLOAD:
756 #ifndef VIMAGE
757 		if_clone_detach(vlan_cloner);
758 #endif
759 		EVENTHANDLER_DEREGISTER(ifnet_departure_event, ifdetach_tag);
760 		EVENTHANDLER_DEREGISTER(iflladdr_event, iflladdr_tag);
761 		vlan_input_p = NULL;
762 		vlan_link_state_p = NULL;
763 		vlan_trunk_cap_p = NULL;
764 		vlan_trunkdev_p = NULL;
765 		vlan_tag_p = NULL;
766 		vlan_cookie_p = NULL;
767 		vlan_setcookie_p = NULL;
768 		vlan_devat_p = NULL;
769 		VLAN_LOCK_DESTROY();
770 		if (bootverbose)
771 			printf("vlan: unloaded\n");
772 		break;
773 	default:
774 		return (EOPNOTSUPP);
775 	}
776 	return (0);
777 }
778 
779 static moduledata_t vlan_mod = {
780 	"if_vlan",
781 	vlan_modevent,
782 	0
783 };
784 
785 DECLARE_MODULE(if_vlan, vlan_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
786 MODULE_VERSION(if_vlan, 3);
787 
788 #ifdef VIMAGE
789 static void
790 vnet_vlan_init(const void *unused __unused)
791 {
792 
793 	vlan_cloner = if_clone_advanced(vlanname, 0, vlan_clone_match,
794 		    vlan_clone_create, vlan_clone_destroy);
795 	V_vlan_cloner = vlan_cloner;
796 }
797 VNET_SYSINIT(vnet_vlan_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
798     vnet_vlan_init, NULL);
799 
800 static void
801 vnet_vlan_uninit(const void *unused __unused)
802 {
803 
804 	if_clone_detach(V_vlan_cloner);
805 }
806 VNET_SYSUNINIT(vnet_vlan_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_FIRST,
807     vnet_vlan_uninit, NULL);
808 #endif
809 
810 static struct ifnet *
811 vlan_clone_match_ethervid(struct if_clone *ifc, const char *name, int *vidp)
812 {
813 	const char *cp;
814 	struct ifnet *ifp;
815 	int vid;
816 
817 	/* Check for <etherif>.<vlan> style interface names. */
818 	IFNET_RLOCK_NOSLEEP();
819 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
820 		/*
821 		 * We can handle non-ethernet hardware types as long as
822 		 * they handle the tagging and headers themselves.
823 		 */
824 		if (ifp->if_type != IFT_ETHER &&
825 		    (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) == 0)
826 			continue;
827 		if (strncmp(ifp->if_xname, name, strlen(ifp->if_xname)) != 0)
828 			continue;
829 		cp = name + strlen(ifp->if_xname);
830 		if (*cp++ != '.')
831 			continue;
832 		if (*cp == '\0')
833 			continue;
834 		vid = 0;
835 		for(; *cp >= '0' && *cp <= '9'; cp++)
836 			vid = (vid * 10) + (*cp - '0');
837 		if (*cp != '\0')
838 			continue;
839 		if (vidp != NULL)
840 			*vidp = vid;
841 		break;
842 	}
843 	IFNET_RUNLOCK_NOSLEEP();
844 
845 	return (ifp);
846 }
847 
848 static int
849 vlan_clone_match(struct if_clone *ifc, const char *name)
850 {
851 	const char *cp;
852 
853 	if (vlan_clone_match_ethervid(ifc, name, NULL) != NULL)
854 		return (1);
855 
856 	if (strncmp(vlanname, name, strlen(vlanname)) != 0)
857 		return (0);
858 	for (cp = name + 4; *cp != '\0'; cp++) {
859 		if (*cp < '0' || *cp > '9')
860 			return (0);
861 	}
862 
863 	return (1);
864 }
865 
866 static int
867 vlan_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
868 {
869 	char *dp;
870 	int wildcard;
871 	int unit;
872 	int error;
873 	int vid;
874 	int ethertag;
875 	struct ifvlan *ifv;
876 	struct ifnet *ifp;
877 	struct ifnet *p;
878 	struct ifaddr *ifa;
879 	struct sockaddr_dl *sdl;
880 	struct vlanreq vlr;
881 	static const u_char eaddr[ETHER_ADDR_LEN];	/* 00:00:00:00:00:00 */
882 
883 	/*
884 	 * There are 3 (ugh) ways to specify the cloned device:
885 	 * o pass a parameter block with the clone request.
886 	 * o specify parameters in the text of the clone device name
887 	 * o specify no parameters and get an unattached device that
888 	 *   must be configured separately.
889 	 * The first technique is preferred; the latter two are
890 	 * supported for backwards compatibilty.
891 	 *
892 	 * XXXRW: Note historic use of the word "tag" here.  New ioctls may be
893 	 * called for.
894 	 */
895 	if (params) {
896 		error = copyin(params, &vlr, sizeof(vlr));
897 		if (error)
898 			return error;
899 		p = ifunit(vlr.vlr_parent);
900 		if (p == NULL)
901 			return ENXIO;
902 		/*
903 		 * Don't let the caller set up a VLAN VID with
904 		 * anything except VLID bits.
905 		 */
906 		if (vlr.vlr_tag & ~EVL_VLID_MASK)
907 			return (EINVAL);
908 		error = ifc_name2unit(name, &unit);
909 		if (error != 0)
910 			return (error);
911 
912 		ethertag = 1;
913 		vid = vlr.vlr_tag;
914 		wildcard = (unit < 0);
915 	} else if ((p = vlan_clone_match_ethervid(ifc, name, &vid)) != NULL) {
916 		ethertag = 1;
917 		unit = -1;
918 		wildcard = 0;
919 
920 		/*
921 		 * Don't let the caller set up a VLAN VID with
922 		 * anything except VLID bits.
923 		 */
924 		if (vid & ~EVL_VLID_MASK)
925 			return (EINVAL);
926 	} else {
927 		ethertag = 0;
928 
929 		error = ifc_name2unit(name, &unit);
930 		if (error != 0)
931 			return (error);
932 
933 		wildcard = (unit < 0);
934 	}
935 
936 	error = ifc_alloc_unit(ifc, &unit);
937 	if (error != 0)
938 		return (error);
939 
940 	/* In the wildcard case, we need to update the name. */
941 	if (wildcard) {
942 		for (dp = name; *dp != '\0'; dp++);
943 		if (snprintf(dp, len - (dp-name), "%d", unit) >
944 		    len - (dp-name) - 1) {
945 			panic("%s: interface name too long", __func__);
946 		}
947 	}
948 
949 	ifv = malloc(sizeof(struct ifvlan), M_VLAN, M_WAITOK | M_ZERO);
950 	ifp = ifv->ifv_ifp = if_alloc(IFT_ETHER);
951 	if (ifp == NULL) {
952 		ifc_free_unit(ifc, unit);
953 		free(ifv, M_VLAN);
954 		return (ENOSPC);
955 	}
956 	SLIST_INIT(&ifv->vlan_mc_listhead);
957 	/* Prepare pcpu counters */
958 	ifv->ifv_ipackets = counter_u64_alloc(M_WAITOK);
959 	ifv->ifv_opackets = counter_u64_alloc(M_WAITOK);
960 	ifv->ifv_ibytes = counter_u64_alloc(M_WAITOK);
961 	ifv->ifv_obytes = counter_u64_alloc(M_WAITOK);
962 	ifv->ifv_omcasts = counter_u64_alloc(M_WAITOK);
963 	ifv->ifv_oerrors = counter_u64_alloc(M_WAITOK);
964 
965 	ifp->if_softc = ifv;
966 	/*
967 	 * Set the name manually rather than using if_initname because
968 	 * we don't conform to the default naming convention for interfaces.
969 	 */
970 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
971 	ifp->if_dname = vlanname;
972 	ifp->if_dunit = unit;
973 	/* NB: flags are not set here */
974 	ifp->if_linkmib = &ifv->ifv_mib;
975 	ifp->if_linkmiblen = sizeof(ifv->ifv_mib);
976 	/* NB: mtu is not set here */
977 
978 	ifp->if_init = vlan_init;
979 	ifp->if_transmit = vlan_transmit;
980 	ifp->if_qflush = vlan_qflush;
981 	ifp->if_ioctl = vlan_ioctl;
982 	ifp->if_flags = VLAN_IFFLAGS;
983 	ifp->if_get_counter = vlan_get_counter;
984 	ether_ifattach(ifp, eaddr);
985 	/* Now undo some of the damage... */
986 	ifp->if_baudrate = 0;
987 	ifp->if_type = IFT_L2VLAN;
988 	ifp->if_hdrlen = ETHER_VLAN_ENCAP_LEN;
989 	ifa = ifp->if_addr;
990 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
991 	sdl->sdl_type = IFT_L2VLAN;
992 
993 	if (ethertag) {
994 		error = vlan_config(ifv, p, vid);
995 		if (error != 0) {
996 			/*
997 			 * Since we've partially failed, we need to back
998 			 * out all the way, otherwise userland could get
999 			 * confused.  Thus, we destroy the interface.
1000 			 */
1001 			ether_ifdetach(ifp);
1002 			vlan_unconfig(ifp);
1003 			if_free(ifp);
1004 			ifc_free_unit(ifc, unit);
1005 			free(ifv, M_VLAN);
1006 
1007 			return (error);
1008 		}
1009 
1010 		/* Update flags on the parent, if necessary. */
1011 		vlan_setflags(ifp, 1);
1012 	}
1013 
1014 	return (0);
1015 }
1016 
1017 static int
1018 vlan_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
1019 {
1020 	struct ifvlan *ifv = ifp->if_softc;
1021 	int unit = ifp->if_dunit;
1022 
1023 	ether_ifdetach(ifp);	/* first, remove it from system-wide lists */
1024 	vlan_unconfig(ifp);	/* now it can be unconfigured and freed */
1025 	if_free(ifp);
1026 	counter_u64_free(ifv->ifv_ipackets);
1027 	counter_u64_free(ifv->ifv_opackets);
1028 	counter_u64_free(ifv->ifv_ibytes);
1029 	counter_u64_free(ifv->ifv_obytes);
1030 	counter_u64_free(ifv->ifv_omcasts);
1031 	counter_u64_free(ifv->ifv_oerrors);
1032 	free(ifv, M_VLAN);
1033 	ifc_free_unit(ifc, unit);
1034 
1035 	return (0);
1036 }
1037 
1038 /*
1039  * The ifp->if_init entry point for vlan(4) is a no-op.
1040  */
1041 static void
1042 vlan_init(void *foo __unused)
1043 {
1044 }
1045 
1046 /*
1047  * The if_transmit method for vlan(4) interface.
1048  */
1049 static int
1050 vlan_transmit(struct ifnet *ifp, struct mbuf *m)
1051 {
1052 	struct ifvlan *ifv;
1053 	struct ifnet *p;
1054 	int error, len, mcast;
1055 
1056 	ifv = ifp->if_softc;
1057 	p = PARENT(ifv);
1058 	len = m->m_pkthdr.len;
1059 	mcast = (m->m_flags & (M_MCAST | M_BCAST)) ? 1 : 0;
1060 
1061 	BPF_MTAP(ifp, m);
1062 
1063 	/*
1064 	 * Do not run parent's if_transmit() if the parent is not up,
1065 	 * or parent's driver will cause a system crash.
1066 	 */
1067 	if (!UP_AND_RUNNING(p)) {
1068 		m_freem(m);
1069 		counter_u64_add(ifv->ifv_oerrors, 1);
1070 		return (ENETDOWN);
1071 	}
1072 
1073 	/*
1074 	 * Pad the frame to the minimum size allowed if told to.
1075 	 * This option is in accord with IEEE Std 802.1Q, 2003 Ed.,
1076 	 * paragraph C.4.4.3.b.  It can help to work around buggy
1077 	 * bridges that violate paragraph C.4.4.3.a from the same
1078 	 * document, i.e., fail to pad short frames after untagging.
1079 	 * E.g., a tagged frame 66 bytes long (incl. FCS) is OK, but
1080 	 * untagging it will produce a 62-byte frame, which is a runt
1081 	 * and requires padding.  There are VLAN-enabled network
1082 	 * devices that just discard such runts instead or mishandle
1083 	 * them somehow.
1084 	 */
1085 	if (soft_pad && p->if_type == IFT_ETHER) {
1086 		static char pad[8];	/* just zeros */
1087 		int n;
1088 
1089 		for (n = ETHERMIN + ETHER_HDR_LEN - m->m_pkthdr.len;
1090 		     n > 0; n -= sizeof(pad))
1091 			if (!m_append(m, min(n, sizeof(pad)), pad))
1092 				break;
1093 
1094 		if (n > 0) {
1095 			if_printf(ifp, "cannot pad short frame\n");
1096 			counter_u64_add(ifv->ifv_oerrors, 1);
1097 			m_freem(m);
1098 			return (0);
1099 		}
1100 	}
1101 
1102 	/*
1103 	 * If underlying interface can do VLAN tag insertion itself,
1104 	 * just pass the packet along. However, we need some way to
1105 	 * tell the interface where the packet came from so that it
1106 	 * knows how to find the VLAN tag to use, so we attach a
1107 	 * packet tag that holds it.
1108 	 */
1109 	if (p->if_capenable & IFCAP_VLAN_HWTAGGING) {
1110 		m->m_pkthdr.ether_vtag = ifv->ifv_vid;
1111 		m->m_flags |= M_VLANTAG;
1112 	} else {
1113 		m = ether_vlanencap(m, ifv->ifv_vid);
1114 		if (m == NULL) {
1115 			if_printf(ifp, "unable to prepend VLAN header\n");
1116 			counter_u64_add(ifv->ifv_oerrors, 1);
1117 			return (0);
1118 		}
1119 	}
1120 
1121 	/*
1122 	 * Send it, precisely as ether_output() would have.
1123 	 */
1124 	error = (p->if_transmit)(p, m);
1125 	if (error == 0) {
1126 		counter_u64_add(ifv->ifv_opackets, 1);
1127 		counter_u64_add(ifv->ifv_obytes, len);
1128 		counter_u64_add(ifv->ifv_omcasts, mcast);
1129 	} else
1130 		counter_u64_add(ifv->ifv_oerrors, 1);
1131 	return (error);
1132 }
1133 
1134 static uint64_t
1135 vlan_get_counter(struct ifnet *ifp, ift_counter cnt)
1136 {
1137 	struct ifvlan *ifv;
1138 
1139 	ifv = ifp->if_softc;
1140 
1141 	switch (cnt) {
1142 		case IFCOUNTER_IPACKETS:
1143 			return (counter_u64_fetch(ifv->ifv_ipackets));
1144 		case IFCOUNTER_OPACKETS:
1145 			return (counter_u64_fetch(ifv->ifv_opackets));
1146 		case IFCOUNTER_IBYTES:
1147 			return (counter_u64_fetch(ifv->ifv_ibytes));
1148 		case IFCOUNTER_OBYTES:
1149 			return (counter_u64_fetch(ifv->ifv_obytes));
1150 		case IFCOUNTER_OMCASTS:
1151 			return (counter_u64_fetch(ifv->ifv_omcasts));
1152 		case IFCOUNTER_OERRORS:
1153 			return (counter_u64_fetch(ifv->ifv_oerrors));
1154 		default:
1155 			return (if_get_counter_default(ifp, cnt));
1156 	}
1157 	/* NOTREACHED */
1158 }
1159 
1160 /*
1161  * The ifp->if_qflush entry point for vlan(4) is a no-op.
1162  */
1163 static void
1164 vlan_qflush(struct ifnet *ifp __unused)
1165 {
1166 }
1167 
1168 static void
1169 vlan_input(struct ifnet *ifp, struct mbuf *m)
1170 {
1171 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
1172 	struct ifvlan *ifv;
1173 	TRUNK_LOCK_READER;
1174 	uint16_t vid;
1175 
1176 	KASSERT(trunk != NULL, ("%s: no trunk", __func__));
1177 
1178 	if (m->m_flags & M_VLANTAG) {
1179 		/*
1180 		 * Packet is tagged, but m contains a normal
1181 		 * Ethernet frame; the tag is stored out-of-band.
1182 		 */
1183 		vid = EVL_VLANOFTAG(m->m_pkthdr.ether_vtag);
1184 		m->m_flags &= ~M_VLANTAG;
1185 	} else {
1186 		struct ether_vlan_header *evl;
1187 
1188 		/*
1189 		 * Packet is tagged in-band as specified by 802.1q.
1190 		 */
1191 		switch (ifp->if_type) {
1192 		case IFT_ETHER:
1193 			if (m->m_len < sizeof(*evl) &&
1194 			    (m = m_pullup(m, sizeof(*evl))) == NULL) {
1195 				if_printf(ifp, "cannot pullup VLAN header\n");
1196 				return;
1197 			}
1198 			evl = mtod(m, struct ether_vlan_header *);
1199 			vid = EVL_VLANOFTAG(ntohs(evl->evl_tag));
1200 
1201 			/*
1202 			 * Remove the 802.1q header by copying the Ethernet
1203 			 * addresses over it and adjusting the beginning of
1204 			 * the data in the mbuf.  The encapsulated Ethernet
1205 			 * type field is already in place.
1206 			 */
1207 			bcopy((char *)evl, (char *)evl + ETHER_VLAN_ENCAP_LEN,
1208 			      ETHER_HDR_LEN - ETHER_TYPE_LEN);
1209 			m_adj(m, ETHER_VLAN_ENCAP_LEN);
1210 			break;
1211 
1212 		default:
1213 #ifdef INVARIANTS
1214 			panic("%s: %s has unsupported if_type %u",
1215 			      __func__, ifp->if_xname, ifp->if_type);
1216 #endif
1217 			m_freem(m);
1218 			if_inc_counter(ifp, IFCOUNTER_NOPROTO, 1);
1219 			return;
1220 		}
1221 	}
1222 
1223 	TRUNK_RLOCK(trunk);
1224 	ifv = vlan_gethash(trunk, vid);
1225 	if (ifv == NULL || !UP_AND_RUNNING(ifv->ifv_ifp)) {
1226 		TRUNK_RUNLOCK(trunk);
1227 		m_freem(m);
1228 		if_inc_counter(ifp, IFCOUNTER_NOPROTO, 1);
1229 		return;
1230 	}
1231 	TRUNK_RUNLOCK(trunk);
1232 
1233 	m->m_pkthdr.rcvif = ifv->ifv_ifp;
1234 	counter_u64_add(ifv->ifv_ipackets, 1);
1235 	counter_u64_add(ifv->ifv_ibytes, m->m_pkthdr.len);
1236 
1237 	/* Pass it back through the parent's input routine. */
1238 	(*ifp->if_input)(ifv->ifv_ifp, m);
1239 }
1240 
1241 static int
1242 vlan_config(struct ifvlan *ifv, struct ifnet *p, uint16_t vid)
1243 {
1244 	struct ifvlantrunk *trunk;
1245 	struct ifnet *ifp;
1246 	int error = 0;
1247 
1248 	/* VID numbers 0x0 and 0xFFF are reserved */
1249 	if (vid == 0 || vid == 0xFFF)
1250 		return (EINVAL);
1251 	if (p->if_type != IFT_ETHER &&
1252 	    (p->if_capenable & IFCAP_VLAN_HWTAGGING) == 0)
1253 		return (EPROTONOSUPPORT);
1254 	if ((p->if_flags & VLAN_IFFLAGS) != VLAN_IFFLAGS)
1255 		return (EPROTONOSUPPORT);
1256 	if (ifv->ifv_trunk)
1257 		return (EBUSY);
1258 
1259 	if (p->if_vlantrunk == NULL) {
1260 		trunk = malloc(sizeof(struct ifvlantrunk),
1261 		    M_VLAN, M_WAITOK | M_ZERO);
1262 		vlan_inithash(trunk);
1263 		VLAN_LOCK();
1264 		if (p->if_vlantrunk != NULL) {
1265 			/* A race that that is very unlikely to be hit. */
1266 			vlan_freehash(trunk);
1267 			free(trunk, M_VLAN);
1268 			goto exists;
1269 		}
1270 		TRUNK_LOCK_INIT(trunk);
1271 		TRUNK_LOCK(trunk);
1272 		p->if_vlantrunk = trunk;
1273 		trunk->parent = p;
1274 	} else {
1275 		VLAN_LOCK();
1276 exists:
1277 		trunk = p->if_vlantrunk;
1278 		TRUNK_LOCK(trunk);
1279 	}
1280 
1281 	ifv->ifv_vid = vid;	/* must set this before vlan_inshash() */
1282 	error = vlan_inshash(trunk, ifv);
1283 	if (error)
1284 		goto done;
1285 	ifv->ifv_proto = ETHERTYPE_VLAN;
1286 	ifv->ifv_encaplen = ETHER_VLAN_ENCAP_LEN;
1287 	ifv->ifv_mintu = ETHERMIN;
1288 	ifv->ifv_pflags = 0;
1289 
1290 	/*
1291 	 * If the parent supports the VLAN_MTU capability,
1292 	 * i.e. can Tx/Rx larger than ETHER_MAX_LEN frames,
1293 	 * use it.
1294 	 */
1295 	if (p->if_capenable & IFCAP_VLAN_MTU) {
1296 		/*
1297 		 * No need to fudge the MTU since the parent can
1298 		 * handle extended frames.
1299 		 */
1300 		ifv->ifv_mtufudge = 0;
1301 	} else {
1302 		/*
1303 		 * Fudge the MTU by the encapsulation size.  This
1304 		 * makes us incompatible with strictly compliant
1305 		 * 802.1Q implementations, but allows us to use
1306 		 * the feature with other NetBSD implementations,
1307 		 * which might still be useful.
1308 		 */
1309 		ifv->ifv_mtufudge = ifv->ifv_encaplen;
1310 	}
1311 
1312 	ifv->ifv_trunk = trunk;
1313 	ifp = ifv->ifv_ifp;
1314 	/*
1315 	 * Initialize fields from our parent.  This duplicates some
1316 	 * work with ether_ifattach() but allows for non-ethernet
1317 	 * interfaces to also work.
1318 	 */
1319 	ifp->if_mtu = p->if_mtu - ifv->ifv_mtufudge;
1320 	ifp->if_baudrate = p->if_baudrate;
1321 	ifp->if_output = p->if_output;
1322 	ifp->if_input = p->if_input;
1323 	ifp->if_resolvemulti = p->if_resolvemulti;
1324 	ifp->if_addrlen = p->if_addrlen;
1325 	ifp->if_broadcastaddr = p->if_broadcastaddr;
1326 
1327 	/*
1328 	 * Copy only a selected subset of flags from the parent.
1329 	 * Other flags are none of our business.
1330 	 */
1331 #define VLAN_COPY_FLAGS (IFF_SIMPLEX)
1332 	ifp->if_flags &= ~VLAN_COPY_FLAGS;
1333 	ifp->if_flags |= p->if_flags & VLAN_COPY_FLAGS;
1334 #undef VLAN_COPY_FLAGS
1335 
1336 	ifp->if_link_state = p->if_link_state;
1337 
1338 	vlan_capabilities(ifv);
1339 
1340 	/*
1341 	 * Set up our interface address to reflect the underlying
1342 	 * physical interface's.
1343 	 */
1344 	bcopy(IF_LLADDR(p), IF_LLADDR(ifp), p->if_addrlen);
1345 	((struct sockaddr_dl *)ifp->if_addr->ifa_addr)->sdl_alen =
1346 	    p->if_addrlen;
1347 
1348 	/*
1349 	 * Configure multicast addresses that may already be
1350 	 * joined on the vlan device.
1351 	 */
1352 	(void)vlan_setmulti(ifp); /* XXX: VLAN lock held */
1353 
1354 	/* We are ready for operation now. */
1355 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1356 done:
1357 	TRUNK_UNLOCK(trunk);
1358 	if (error == 0)
1359 		EVENTHANDLER_INVOKE(vlan_config, p, ifv->ifv_vid);
1360 	VLAN_UNLOCK();
1361 
1362 	return (error);
1363 }
1364 
1365 static void
1366 vlan_unconfig(struct ifnet *ifp)
1367 {
1368 
1369 	VLAN_LOCK();
1370 	vlan_unconfig_locked(ifp, 0);
1371 	VLAN_UNLOCK();
1372 }
1373 
1374 static void
1375 vlan_unconfig_locked(struct ifnet *ifp, int departing)
1376 {
1377 	struct ifvlantrunk *trunk;
1378 	struct vlan_mc_entry *mc;
1379 	struct ifvlan *ifv;
1380 	struct ifnet  *parent;
1381 	int error;
1382 
1383 	VLAN_LOCK_ASSERT();
1384 
1385 	ifv = ifp->if_softc;
1386 	trunk = ifv->ifv_trunk;
1387 	parent = NULL;
1388 
1389 	if (trunk != NULL) {
1390 
1391 		TRUNK_LOCK(trunk);
1392 		parent = trunk->parent;
1393 
1394 		/*
1395 		 * Since the interface is being unconfigured, we need to
1396 		 * empty the list of multicast groups that we may have joined
1397 		 * while we were alive from the parent's list.
1398 		 */
1399 		while ((mc = SLIST_FIRST(&ifv->vlan_mc_listhead)) != NULL) {
1400 			/*
1401 			 * If the parent interface is being detached,
1402 			 * all its multicast addresses have already
1403 			 * been removed.  Warn about errors if
1404 			 * if_delmulti() does fail, but don't abort as
1405 			 * all callers expect vlan destruction to
1406 			 * succeed.
1407 			 */
1408 			if (!departing) {
1409 				error = if_delmulti(parent,
1410 				    (struct sockaddr *)&mc->mc_addr);
1411 				if (error)
1412 					if_printf(ifp,
1413 		    "Failed to delete multicast address from parent: %d\n",
1414 					    error);
1415 			}
1416 			SLIST_REMOVE_HEAD(&ifv->vlan_mc_listhead, mc_entries);
1417 			free(mc, M_VLAN);
1418 		}
1419 
1420 		vlan_setflags(ifp, 0); /* clear special flags on parent */
1421 		vlan_remhash(trunk, ifv);
1422 		ifv->ifv_trunk = NULL;
1423 
1424 		/*
1425 		 * Check if we were the last.
1426 		 */
1427 		if (trunk->refcnt == 0) {
1428 			parent->if_vlantrunk = NULL;
1429 			/*
1430 			 * XXXGL: If some ithread has already entered
1431 			 * vlan_input() and is now blocked on the trunk
1432 			 * lock, then it should preempt us right after
1433 			 * unlock and finish its work. Then we will acquire
1434 			 * lock again in trunk_destroy().
1435 			 */
1436 			TRUNK_UNLOCK(trunk);
1437 			trunk_destroy(trunk);
1438 		} else
1439 			TRUNK_UNLOCK(trunk);
1440 	}
1441 
1442 	/* Disconnect from parent. */
1443 	if (ifv->ifv_pflags)
1444 		if_printf(ifp, "%s: ifv_pflags unclean\n", __func__);
1445 	ifp->if_mtu = ETHERMTU;
1446 	ifp->if_link_state = LINK_STATE_UNKNOWN;
1447 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1448 
1449 	/*
1450 	 * Only dispatch an event if vlan was
1451 	 * attached, otherwise there is nothing
1452 	 * to cleanup anyway.
1453 	 */
1454 	if (parent != NULL)
1455 		EVENTHANDLER_INVOKE(vlan_unconfig, parent, ifv->ifv_vid);
1456 }
1457 
1458 /* Handle a reference counted flag that should be set on the parent as well */
1459 static int
1460 vlan_setflag(struct ifnet *ifp, int flag, int status,
1461 	     int (*func)(struct ifnet *, int))
1462 {
1463 	struct ifvlan *ifv;
1464 	int error;
1465 
1466 	/* XXX VLAN_LOCK_ASSERT(); */
1467 
1468 	ifv = ifp->if_softc;
1469 	status = status ? (ifp->if_flags & flag) : 0;
1470 	/* Now "status" contains the flag value or 0 */
1471 
1472 	/*
1473 	 * See if recorded parent's status is different from what
1474 	 * we want it to be.  If it is, flip it.  We record parent's
1475 	 * status in ifv_pflags so that we won't clear parent's flag
1476 	 * we haven't set.  In fact, we don't clear or set parent's
1477 	 * flags directly, but get or release references to them.
1478 	 * That's why we can be sure that recorded flags still are
1479 	 * in accord with actual parent's flags.
1480 	 */
1481 	if (status != (ifv->ifv_pflags & flag)) {
1482 		error = (*func)(PARENT(ifv), status);
1483 		if (error)
1484 			return (error);
1485 		ifv->ifv_pflags &= ~flag;
1486 		ifv->ifv_pflags |= status;
1487 	}
1488 	return (0);
1489 }
1490 
1491 /*
1492  * Handle IFF_* flags that require certain changes on the parent:
1493  * if "status" is true, update parent's flags respective to our if_flags;
1494  * if "status" is false, forcedly clear the flags set on parent.
1495  */
1496 static int
1497 vlan_setflags(struct ifnet *ifp, int status)
1498 {
1499 	int error, i;
1500 
1501 	for (i = 0; vlan_pflags[i].flag; i++) {
1502 		error = vlan_setflag(ifp, vlan_pflags[i].flag,
1503 				     status, vlan_pflags[i].func);
1504 		if (error)
1505 			return (error);
1506 	}
1507 	return (0);
1508 }
1509 
1510 /* Inform all vlans that their parent has changed link state */
1511 static void
1512 vlan_link_state(struct ifnet *ifp)
1513 {
1514 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
1515 	struct ifvlan *ifv;
1516 	int i;
1517 
1518 	TRUNK_LOCK(trunk);
1519 #ifdef VLAN_ARRAY
1520 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
1521 		if (trunk->vlans[i] != NULL) {
1522 			ifv = trunk->vlans[i];
1523 #else
1524 	for (i = 0; i < (1 << trunk->hwidth); i++)
1525 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list) {
1526 #endif
1527 			ifv->ifv_ifp->if_baudrate = trunk->parent->if_baudrate;
1528 			if_link_state_change(ifv->ifv_ifp,
1529 			    trunk->parent->if_link_state);
1530 		}
1531 	TRUNK_UNLOCK(trunk);
1532 }
1533 
1534 static void
1535 vlan_capabilities(struct ifvlan *ifv)
1536 {
1537 	struct ifnet *p = PARENT(ifv);
1538 	struct ifnet *ifp = ifv->ifv_ifp;
1539 	struct ifnet_hw_tsomax hw_tsomax;
1540 
1541 	TRUNK_LOCK_ASSERT(TRUNK(ifv));
1542 
1543 	/*
1544 	 * If the parent interface can do checksum offloading
1545 	 * on VLANs, then propagate its hardware-assisted
1546 	 * checksumming flags. Also assert that checksum
1547 	 * offloading requires hardware VLAN tagging.
1548 	 */
1549 	if (p->if_capabilities & IFCAP_VLAN_HWCSUM)
1550 		ifp->if_capabilities = p->if_capabilities & IFCAP_HWCSUM;
1551 
1552 	if (p->if_capenable & IFCAP_VLAN_HWCSUM &&
1553 	    p->if_capenable & IFCAP_VLAN_HWTAGGING) {
1554 		ifp->if_capenable = p->if_capenable & IFCAP_HWCSUM;
1555 		ifp->if_hwassist = p->if_hwassist & (CSUM_IP | CSUM_TCP |
1556 		    CSUM_UDP | CSUM_SCTP);
1557 	} else {
1558 		ifp->if_capenable = 0;
1559 		ifp->if_hwassist = 0;
1560 	}
1561 	/*
1562 	 * If the parent interface can do TSO on VLANs then
1563 	 * propagate the hardware-assisted flag. TSO on VLANs
1564 	 * does not necessarily require hardware VLAN tagging.
1565 	 */
1566 	memset(&hw_tsomax, 0, sizeof(hw_tsomax));
1567 	if_hw_tsomax_common(p, &hw_tsomax);
1568 	if_hw_tsomax_update(ifp, &hw_tsomax);
1569 	if (p->if_capabilities & IFCAP_VLAN_HWTSO)
1570 		ifp->if_capabilities |= p->if_capabilities & IFCAP_TSO;
1571 	if (p->if_capenable & IFCAP_VLAN_HWTSO) {
1572 		ifp->if_capenable |= p->if_capenable & IFCAP_TSO;
1573 		ifp->if_hwassist |= p->if_hwassist & CSUM_TSO;
1574 	} else {
1575 		ifp->if_capenable &= ~(p->if_capenable & IFCAP_TSO);
1576 		ifp->if_hwassist &= ~(p->if_hwassist & CSUM_TSO);
1577 	}
1578 
1579 	/*
1580 	 * If the parent interface can offload TCP connections over VLANs then
1581 	 * propagate its TOE capability to the VLAN interface.
1582 	 *
1583 	 * All TOE drivers in the tree today can deal with VLANs.  If this
1584 	 * changes then IFCAP_VLAN_TOE should be promoted to a full capability
1585 	 * with its own bit.
1586 	 */
1587 #define	IFCAP_VLAN_TOE IFCAP_TOE
1588 	if (p->if_capabilities & IFCAP_VLAN_TOE)
1589 		ifp->if_capabilities |= p->if_capabilities & IFCAP_TOE;
1590 	if (p->if_capenable & IFCAP_VLAN_TOE) {
1591 		TOEDEV(ifp) = TOEDEV(p);
1592 		ifp->if_capenable |= p->if_capenable & IFCAP_TOE;
1593 	}
1594 }
1595 
1596 static void
1597 vlan_trunk_capabilities(struct ifnet *ifp)
1598 {
1599 	struct ifvlantrunk *trunk = ifp->if_vlantrunk;
1600 	struct ifvlan *ifv;
1601 	int i;
1602 
1603 	TRUNK_LOCK(trunk);
1604 #ifdef VLAN_ARRAY
1605 	for (i = 0; i < VLAN_ARRAY_SIZE; i++)
1606 		if (trunk->vlans[i] != NULL) {
1607 			ifv = trunk->vlans[i];
1608 #else
1609 	for (i = 0; i < (1 << trunk->hwidth); i++) {
1610 		LIST_FOREACH(ifv, &trunk->hash[i], ifv_list)
1611 #endif
1612 			vlan_capabilities(ifv);
1613 	}
1614 	TRUNK_UNLOCK(trunk);
1615 }
1616 
1617 static int
1618 vlan_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1619 {
1620 	struct ifnet *p;
1621 	struct ifreq *ifr;
1622 	struct ifaddr *ifa;
1623 	struct ifvlan *ifv;
1624 	struct ifvlantrunk *trunk;
1625 	struct vlanreq vlr;
1626 	int error = 0;
1627 
1628 	ifr = (struct ifreq *)data;
1629 	ifa = (struct ifaddr *) data;
1630 	ifv = ifp->if_softc;
1631 
1632 	switch (cmd) {
1633 	case SIOCSIFADDR:
1634 		ifp->if_flags |= IFF_UP;
1635 #ifdef INET
1636 		if (ifa->ifa_addr->sa_family == AF_INET)
1637 			arp_ifinit(ifp, ifa);
1638 #endif
1639 		break;
1640 	case SIOCGIFADDR:
1641                 {
1642 			struct sockaddr *sa;
1643 
1644 			sa = (struct sockaddr *)&ifr->ifr_data;
1645 			bcopy(IF_LLADDR(ifp), sa->sa_data, ifp->if_addrlen);
1646                 }
1647 		break;
1648 	case SIOCGIFMEDIA:
1649 		VLAN_LOCK();
1650 		if (TRUNK(ifv) != NULL) {
1651 			p = PARENT(ifv);
1652 			VLAN_UNLOCK();
1653 			error = (*p->if_ioctl)(p, SIOCGIFMEDIA, data);
1654 			/* Limit the result to the parent's current config. */
1655 			if (error == 0) {
1656 				struct ifmediareq *ifmr;
1657 
1658 				ifmr = (struct ifmediareq *)data;
1659 				if (ifmr->ifm_count >= 1 && ifmr->ifm_ulist) {
1660 					ifmr->ifm_count = 1;
1661 					error = copyout(&ifmr->ifm_current,
1662 						ifmr->ifm_ulist,
1663 						sizeof(int));
1664 				}
1665 			}
1666 		} else {
1667 			VLAN_UNLOCK();
1668 			error = EINVAL;
1669 		}
1670 		break;
1671 
1672 	case SIOCSIFMEDIA:
1673 		error = EINVAL;
1674 		break;
1675 
1676 	case SIOCSIFMTU:
1677 		/*
1678 		 * Set the interface MTU.
1679 		 */
1680 		VLAN_LOCK();
1681 		if (TRUNK(ifv) != NULL) {
1682 			if (ifr->ifr_mtu >
1683 			     (PARENT(ifv)->if_mtu - ifv->ifv_mtufudge) ||
1684 			    ifr->ifr_mtu <
1685 			     (ifv->ifv_mintu - ifv->ifv_mtufudge))
1686 				error = EINVAL;
1687 			else
1688 				ifp->if_mtu = ifr->ifr_mtu;
1689 		} else
1690 			error = EINVAL;
1691 		VLAN_UNLOCK();
1692 		break;
1693 
1694 	case SIOCSETVLAN:
1695 #ifdef VIMAGE
1696 		/*
1697 		 * XXXRW/XXXBZ: The goal in these checks is to allow a VLAN
1698 		 * interface to be delegated to a jail without allowing the
1699 		 * jail to change what underlying interface/VID it is
1700 		 * associated with.  We are not entirely convinced that this
1701 		 * is the right way to accomplish that policy goal.
1702 		 */
1703 		if (ifp->if_vnet != ifp->if_home_vnet) {
1704 			error = EPERM;
1705 			break;
1706 		}
1707 #endif
1708 		error = copyin(ifr->ifr_data, &vlr, sizeof(vlr));
1709 		if (error)
1710 			break;
1711 		if (vlr.vlr_parent[0] == '\0') {
1712 			vlan_unconfig(ifp);
1713 			break;
1714 		}
1715 		p = ifunit(vlr.vlr_parent);
1716 		if (p == NULL) {
1717 			error = ENOENT;
1718 			break;
1719 		}
1720 		/*
1721 		 * Don't let the caller set up a VLAN VID with
1722 		 * anything except VLID bits.
1723 		 */
1724 		if (vlr.vlr_tag & ~EVL_VLID_MASK) {
1725 			error = EINVAL;
1726 			break;
1727 		}
1728 		error = vlan_config(ifv, p, vlr.vlr_tag);
1729 		if (error)
1730 			break;
1731 
1732 		/* Update flags on the parent, if necessary. */
1733 		vlan_setflags(ifp, 1);
1734 		break;
1735 
1736 	case SIOCGETVLAN:
1737 #ifdef VIMAGE
1738 		if (ifp->if_vnet != ifp->if_home_vnet) {
1739 			error = EPERM;
1740 			break;
1741 		}
1742 #endif
1743 		bzero(&vlr, sizeof(vlr));
1744 		VLAN_LOCK();
1745 		if (TRUNK(ifv) != NULL) {
1746 			strlcpy(vlr.vlr_parent, PARENT(ifv)->if_xname,
1747 			    sizeof(vlr.vlr_parent));
1748 			vlr.vlr_tag = ifv->ifv_vid;
1749 		}
1750 		VLAN_UNLOCK();
1751 		error = copyout(&vlr, ifr->ifr_data, sizeof(vlr));
1752 		break;
1753 
1754 	case SIOCSIFFLAGS:
1755 		/*
1756 		 * We should propagate selected flags to the parent,
1757 		 * e.g., promiscuous mode.
1758 		 */
1759 		if (TRUNK(ifv) != NULL)
1760 			error = vlan_setflags(ifp, 1);
1761 		break;
1762 
1763 	case SIOCADDMULTI:
1764 	case SIOCDELMULTI:
1765 		/*
1766 		 * If we don't have a parent, just remember the membership for
1767 		 * when we do.
1768 		 */
1769 		trunk = TRUNK(ifv);
1770 		if (trunk != NULL) {
1771 			TRUNK_LOCK(trunk);
1772 			error = vlan_setmulti(ifp);
1773 			TRUNK_UNLOCK(trunk);
1774 		}
1775 		break;
1776 
1777 	default:
1778 		error = EINVAL;
1779 		break;
1780 	}
1781 
1782 	return (error);
1783 }
1784