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