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