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