xref: /dflybsd-src/sys/net/if.c (revision 8406cf706ddbb170b0137efbf9d6ea5f791388d6)
1 /*
2  * Copyright (c) 1980, 1986, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)if.c	8.3 (Berkeley) 1/4/94
30  * $FreeBSD: src/sys/net/if.c,v 1.185 2004/03/13 02:35:03 brooks Exp $
31  */
32 
33 #include "opt_inet6.h"
34 #include "opt_inet.h"
35 #include "opt_ifpoll.h"
36 
37 #include <sys/param.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/systm.h>
41 #include <sys/proc.h>
42 #include <sys/priv.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/socketops.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/mutex.h>
50 #include <sys/sockio.h>
51 #include <sys/syslog.h>
52 #include <sys/sysctl.h>
53 #include <sys/domain.h>
54 #include <sys/thread.h>
55 #include <sys/serialize.h>
56 #include <sys/bus.h>
57 
58 #include <sys/thread2.h>
59 #include <sys/msgport2.h>
60 #include <sys/mutex2.h>
61 
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/if_dl.h>
65 #include <net/if_types.h>
66 #include <net/if_var.h>
67 #include <net/if_ringmap.h>
68 #include <net/ifq_var.h>
69 #include <net/radix.h>
70 #include <net/route.h>
71 #include <net/if_clone.h>
72 #include <net/netisr2.h>
73 #include <net/netmsg2.h>
74 
75 #include <machine/atomic.h>
76 #include <machine/stdarg.h>
77 #include <machine/smp.h>
78 
79 #if defined(INET) || defined(INET6)
80 /*XXX*/
81 #include <netinet/in.h>
82 #include <netinet/in_var.h>
83 #include <netinet/if_ether.h>
84 #ifdef INET6
85 #include <netinet6/in6_var.h>
86 #include <netinet6/in6_ifattach.h>
87 #endif
88 #endif
89 
90 struct netmsg_ifaddr {
91 	struct netmsg_base base;
92 	struct ifaddr	*ifa;
93 	struct ifnet	*ifp;
94 	int		tail;
95 };
96 
97 struct ifsubq_stage_head {
98 	TAILQ_HEAD(, ifsubq_stage)	stg_head;
99 } __cachealign;
100 
101 struct if_ringmap {
102 	int		rm_cnt;
103 	int		rm_grid;
104 	int		rm_cpumap[];
105 };
106 
107 #define RINGMAP_FLAG_NONE		0x0
108 #define RINGMAP_FLAG_POWEROF2		0x1
109 
110 /*
111  * System initialization
112  */
113 static void	if_attachdomain(void *);
114 static void	if_attachdomain1(struct ifnet *);
115 static int	ifconf(u_long, caddr_t, struct ucred *);
116 static void	ifinit(void *);
117 static void	ifnetinit(void *);
118 static void	if_slowtimo(void *);
119 static void	link_rtrequest(int, struct rtentry *);
120 static int	if_rtdel(struct radix_node *, void *);
121 static void	if_slowtimo_dispatch(netmsg_t);
122 
123 /* Helper functions */
124 static void	ifsq_watchdog_reset(struct ifsubq_watchdog *);
125 static int	if_delmulti_serialized(struct ifnet *, struct sockaddr *);
126 static struct ifnet_array *ifnet_array_alloc(int);
127 static void	ifnet_array_free(struct ifnet_array *);
128 static struct ifnet_array *ifnet_array_add(struct ifnet *,
129 		    const struct ifnet_array *);
130 static struct ifnet_array *ifnet_array_del(struct ifnet *,
131 		    const struct ifnet_array *);
132 
133 #ifdef INET6
134 /*
135  * XXX: declare here to avoid to include many inet6 related files..
136  * should be more generalized?
137  */
138 extern void	nd6_setmtu(struct ifnet *);
139 #endif
140 
141 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
142 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
143 SYSCTL_NODE(_net_link, OID_AUTO, ringmap, CTLFLAG_RW, 0, "link ringmap");
144 
145 static int ifsq_stage_cntmax = 4;
146 TUNABLE_INT("net.link.stage_cntmax", &ifsq_stage_cntmax);
147 SYSCTL_INT(_net_link, OID_AUTO, stage_cntmax, CTLFLAG_RW,
148     &ifsq_stage_cntmax, 0, "ifq staging packet count max");
149 
150 static int if_stats_compat = 0;
151 SYSCTL_INT(_net_link, OID_AUTO, stats_compat, CTLFLAG_RW,
152     &if_stats_compat, 0, "Compat the old ifnet stats");
153 
154 static int if_ringmap_dumprdr = 0;
155 SYSCTL_INT(_net_link_ringmap, OID_AUTO, dump_rdr, CTLFLAG_RW,
156     &if_ringmap_dumprdr, 0, "dump redirect table");
157 
158 SYSINIT(interfaces, SI_SUB_PROTO_IF, SI_ORDER_FIRST, ifinit, NULL);
159 SYSINIT(ifnet, SI_SUB_PRE_DRIVERS, SI_ORDER_ANY, ifnetinit, NULL);
160 
161 static  if_com_alloc_t *if_com_alloc[256];
162 static  if_com_free_t *if_com_free[256];
163 
164 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
165 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
166 MALLOC_DEFINE(M_IFNET, "ifnet", "interface structure");
167 
168 int			ifqmaxlen = IFQ_MAXLEN;
169 struct ifnethead	ifnet = TAILQ_HEAD_INITIALIZER(ifnet);
170 
171 static struct ifnet_array	ifnet_array0;
172 static struct ifnet_array	*ifnet_array = &ifnet_array0;
173 
174 static struct callout		if_slowtimo_timer;
175 static struct netmsg_base	if_slowtimo_netmsg;
176 
177 int			if_index = 0;
178 struct ifnet		**ifindex2ifnet = NULL;
179 static struct mtx	ifnet_mtx = MTX_INITIALIZER("ifnet");
180 
181 static struct ifsubq_stage_head	ifsubq_stage_heads[MAXCPU];
182 
183 #ifdef notyet
184 #define IFQ_KTR_STRING		"ifq=%p"
185 #define IFQ_KTR_ARGS	struct ifaltq *ifq
186 #ifndef KTR_IFQ
187 #define KTR_IFQ			KTR_ALL
188 #endif
189 KTR_INFO_MASTER(ifq);
190 KTR_INFO(KTR_IFQ, ifq, enqueue, 0, IFQ_KTR_STRING, IFQ_KTR_ARGS);
191 KTR_INFO(KTR_IFQ, ifq, dequeue, 1, IFQ_KTR_STRING, IFQ_KTR_ARGS);
192 #define logifq(name, arg)	KTR_LOG(ifq_ ## name, arg)
193 
194 #define IF_START_KTR_STRING	"ifp=%p"
195 #define IF_START_KTR_ARGS	struct ifnet *ifp
196 #ifndef KTR_IF_START
197 #define KTR_IF_START		KTR_ALL
198 #endif
199 KTR_INFO_MASTER(if_start);
200 KTR_INFO(KTR_IF_START, if_start, run, 0,
201 	 IF_START_KTR_STRING, IF_START_KTR_ARGS);
202 KTR_INFO(KTR_IF_START, if_start, sched, 1,
203 	 IF_START_KTR_STRING, IF_START_KTR_ARGS);
204 KTR_INFO(KTR_IF_START, if_start, avoid, 2,
205 	 IF_START_KTR_STRING, IF_START_KTR_ARGS);
206 KTR_INFO(KTR_IF_START, if_start, contend_sched, 3,
207 	 IF_START_KTR_STRING, IF_START_KTR_ARGS);
208 KTR_INFO(KTR_IF_START, if_start, chase_sched, 4,
209 	 IF_START_KTR_STRING, IF_START_KTR_ARGS);
210 #define logifstart(name, arg)	KTR_LOG(if_start_ ## name, arg)
211 #endif
212 
213 TAILQ_HEAD(, ifg_group) ifg_head = TAILQ_HEAD_INITIALIZER(ifg_head);
214 
215 /*
216  * Network interface utility routines.
217  *
218  * Routines with ifa_ifwith* names take sockaddr *'s as
219  * parameters.
220  */
221 /* ARGSUSED*/
222 static void
223 ifinit(void *dummy)
224 {
225 	struct ifnet *ifp;
226 
227 	callout_init_mp(&if_slowtimo_timer);
228 	netmsg_init(&if_slowtimo_netmsg, NULL, &netisr_adone_rport,
229 	    MSGF_PRIORITY, if_slowtimo_dispatch);
230 
231 	/* XXX is this necessary? */
232 	ifnet_lock();
233 	TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
234 		if (ifp->if_snd.altq_maxlen == 0) {
235 			if_printf(ifp, "XXX: driver didn't set altq_maxlen\n");
236 			ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
237 		}
238 	}
239 	ifnet_unlock();
240 
241 	/* Start if_slowtimo */
242 	lwkt_sendmsg(netisr_cpuport(0), &if_slowtimo_netmsg.lmsg);
243 }
244 
245 static void
246 ifsq_ifstart_ipifunc(void *arg)
247 {
248 	struct ifaltq_subque *ifsq = arg;
249 	struct lwkt_msg *lmsg = ifsq_get_ifstart_lmsg(ifsq, mycpuid);
250 
251 	crit_enter();
252 	if (lmsg->ms_flags & MSGF_DONE)
253 		lwkt_sendmsg_oncpu(netisr_cpuport(mycpuid), lmsg);
254 	crit_exit();
255 }
256 
257 static __inline void
258 ifsq_stage_remove(struct ifsubq_stage_head *head, struct ifsubq_stage *stage)
259 {
260 	KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
261 	TAILQ_REMOVE(&head->stg_head, stage, stg_link);
262 	stage->stg_flags &= ~(IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED);
263 	stage->stg_cnt = 0;
264 	stage->stg_len = 0;
265 }
266 
267 static __inline void
268 ifsq_stage_insert(struct ifsubq_stage_head *head, struct ifsubq_stage *stage)
269 {
270 	KKASSERT((stage->stg_flags &
271 	    (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
272 	stage->stg_flags |= IFSQ_STAGE_FLAG_QUED;
273 	TAILQ_INSERT_TAIL(&head->stg_head, stage, stg_link);
274 }
275 
276 /*
277  * Schedule ifnet.if_start on the subqueue owner CPU
278  */
279 static void
280 ifsq_ifstart_schedule(struct ifaltq_subque *ifsq, int force)
281 {
282 	int cpu;
283 
284 	if (!force && curthread->td_type == TD_TYPE_NETISR &&
285 	    ifsq_stage_cntmax > 0) {
286 		struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
287 
288 		stage->stg_cnt = 0;
289 		stage->stg_len = 0;
290 		if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
291 			ifsq_stage_insert(&ifsubq_stage_heads[mycpuid], stage);
292 		stage->stg_flags |= IFSQ_STAGE_FLAG_SCHED;
293 		return;
294 	}
295 
296 	cpu = ifsq_get_cpuid(ifsq);
297 	if (cpu != mycpuid)
298 		lwkt_send_ipiq(globaldata_find(cpu), ifsq_ifstart_ipifunc, ifsq);
299 	else
300 		ifsq_ifstart_ipifunc(ifsq);
301 }
302 
303 /*
304  * NOTE:
305  * This function will release ifnet.if_start subqueue interlock,
306  * if ifnet.if_start for the subqueue does not need to be scheduled
307  */
308 static __inline int
309 ifsq_ifstart_need_schedule(struct ifaltq_subque *ifsq, int running)
310 {
311 	if (!running || ifsq_is_empty(ifsq)
312 #ifdef ALTQ
313 	    || ifsq->ifsq_altq->altq_tbr != NULL
314 #endif
315 	) {
316 		ALTQ_SQ_LOCK(ifsq);
317 		/*
318 		 * ifnet.if_start subqueue interlock is released, if:
319 		 * 1) Hardware can not take any packets, due to
320 		 *    o  interface is marked down
321 		 *    o  hardware queue is full (ifsq_is_oactive)
322 		 *    Under the second situation, hardware interrupt
323 		 *    or polling(4) will call/schedule ifnet.if_start
324 		 *    on the subqueue when hardware queue is ready
325 		 * 2) There is no packet in the subqueue.
326 		 *    Further ifq_dispatch or ifq_handoff will call/
327 		 *    schedule ifnet.if_start on the subqueue.
328 		 * 3) TBR is used and it does not allow further
329 		 *    dequeueing.
330 		 *    TBR callout will call ifnet.if_start on the
331 		 *    subqueue.
332 		 */
333 		if (!running || !ifsq_data_ready(ifsq)) {
334 			ifsq_clr_started(ifsq);
335 			ALTQ_SQ_UNLOCK(ifsq);
336 			return 0;
337 		}
338 		ALTQ_SQ_UNLOCK(ifsq);
339 	}
340 	return 1;
341 }
342 
343 static void
344 ifsq_ifstart_dispatch(netmsg_t msg)
345 {
346 	struct lwkt_msg *lmsg = &msg->base.lmsg;
347 	struct ifaltq_subque *ifsq = lmsg->u.ms_resultp;
348 	struct ifnet *ifp = ifsq_get_ifp(ifsq);
349 	struct globaldata *gd = mycpu;
350 	int running = 0, need_sched;
351 
352 	crit_enter_gd(gd);
353 
354 	lwkt_replymsg(lmsg, 0);	/* reply ASAP */
355 
356 	if (gd->gd_cpuid != ifsq_get_cpuid(ifsq)) {
357 		/*
358 		 * We need to chase the subqueue owner CPU change.
359 		 */
360 		ifsq_ifstart_schedule(ifsq, 1);
361 		crit_exit_gd(gd);
362 		return;
363 	}
364 
365 	ifsq_serialize_hw(ifsq);
366 	if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
367 		ifp->if_start(ifp, ifsq);
368 		if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
369 			running = 1;
370 	}
371 	need_sched = ifsq_ifstart_need_schedule(ifsq, running);
372 	ifsq_deserialize_hw(ifsq);
373 
374 	if (need_sched) {
375 		/*
376 		 * More data need to be transmitted, ifnet.if_start is
377 		 * scheduled on the subqueue owner CPU, and we keep going.
378 		 * NOTE: ifnet.if_start subqueue interlock is not released.
379 		 */
380 		ifsq_ifstart_schedule(ifsq, 0);
381 	}
382 
383 	crit_exit_gd(gd);
384 }
385 
386 /* Device driver ifnet.if_start helper function */
387 void
388 ifsq_devstart(struct ifaltq_subque *ifsq)
389 {
390 	struct ifnet *ifp = ifsq_get_ifp(ifsq);
391 	int running = 0;
392 
393 	ASSERT_ALTQ_SQ_SERIALIZED_HW(ifsq);
394 
395 	ALTQ_SQ_LOCK(ifsq);
396 	if (ifsq_is_started(ifsq) || !ifsq_data_ready(ifsq)) {
397 		ALTQ_SQ_UNLOCK(ifsq);
398 		return;
399 	}
400 	ifsq_set_started(ifsq);
401 	ALTQ_SQ_UNLOCK(ifsq);
402 
403 	ifp->if_start(ifp, ifsq);
404 
405 	if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
406 		running = 1;
407 
408 	if (ifsq_ifstart_need_schedule(ifsq, running)) {
409 		/*
410 		 * More data need to be transmitted, ifnet.if_start is
411 		 * scheduled on ifnet's CPU, and we keep going.
412 		 * NOTE: ifnet.if_start interlock is not released.
413 		 */
414 		ifsq_ifstart_schedule(ifsq, 0);
415 	}
416 }
417 
418 void
419 if_devstart(struct ifnet *ifp)
420 {
421 	ifsq_devstart(ifq_get_subq_default(&ifp->if_snd));
422 }
423 
424 /* Device driver ifnet.if_start schedule helper function */
425 void
426 ifsq_devstart_sched(struct ifaltq_subque *ifsq)
427 {
428 	ifsq_ifstart_schedule(ifsq, 1);
429 }
430 
431 void
432 if_devstart_sched(struct ifnet *ifp)
433 {
434 	ifsq_devstart_sched(ifq_get_subq_default(&ifp->if_snd));
435 }
436 
437 static void
438 if_default_serialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
439 {
440 	lwkt_serialize_enter(ifp->if_serializer);
441 }
442 
443 static void
444 if_default_deserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
445 {
446 	lwkt_serialize_exit(ifp->if_serializer);
447 }
448 
449 static int
450 if_default_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
451 {
452 	return lwkt_serialize_try(ifp->if_serializer);
453 }
454 
455 #ifdef INVARIANTS
456 static void
457 if_default_serialize_assert(struct ifnet *ifp,
458 			    enum ifnet_serialize slz __unused,
459 			    boolean_t serialized)
460 {
461 	if (serialized)
462 		ASSERT_SERIALIZED(ifp->if_serializer);
463 	else
464 		ASSERT_NOT_SERIALIZED(ifp->if_serializer);
465 }
466 #endif
467 
468 /*
469  * Attach an interface to the list of "active" interfaces.
470  *
471  * The serializer is optional.
472  */
473 void
474 if_attach(struct ifnet *ifp, lwkt_serialize_t serializer)
475 {
476 	unsigned socksize;
477 	int namelen, masklen;
478 	struct sockaddr_dl *sdl, *sdl_addr;
479 	struct ifaddr *ifa;
480 	struct ifaltq *ifq;
481 	struct ifnet **old_ifindex2ifnet = NULL;
482 	struct ifnet_array *old_ifnet_array;
483 	int i, q;
484 
485 	static int if_indexlim = 8;
486 
487 	if (ifp->if_serialize != NULL) {
488 		KASSERT(ifp->if_deserialize != NULL &&
489 			ifp->if_tryserialize != NULL &&
490 			ifp->if_serialize_assert != NULL,
491 			("serialize functions are partially setup"));
492 
493 		/*
494 		 * If the device supplies serialize functions,
495 		 * then clear if_serializer to catch any invalid
496 		 * usage of this field.
497 		 */
498 		KASSERT(serializer == NULL,
499 			("both serialize functions and default serializer "
500 			 "are supplied"));
501 		ifp->if_serializer = NULL;
502 	} else {
503 		KASSERT(ifp->if_deserialize == NULL &&
504 			ifp->if_tryserialize == NULL &&
505 			ifp->if_serialize_assert == NULL,
506 			("serialize functions are partially setup"));
507 		ifp->if_serialize = if_default_serialize;
508 		ifp->if_deserialize = if_default_deserialize;
509 		ifp->if_tryserialize = if_default_tryserialize;
510 #ifdef INVARIANTS
511 		ifp->if_serialize_assert = if_default_serialize_assert;
512 #endif
513 
514 		/*
515 		 * The serializer can be passed in from the device,
516 		 * allowing the same serializer to be used for both
517 		 * the interrupt interlock and the device queue.
518 		 * If not specified, the netif structure will use an
519 		 * embedded serializer.
520 		 */
521 		if (serializer == NULL) {
522 			serializer = &ifp->if_default_serializer;
523 			lwkt_serialize_init(serializer);
524 		}
525 		ifp->if_serializer = serializer;
526 	}
527 
528 	/*
529 	 * XXX -
530 	 * The old code would work if the interface passed a pre-existing
531 	 * chain of ifaddrs to this code.  We don't trust our callers to
532 	 * properly initialize the tailq, however, so we no longer allow
533 	 * this unlikely case.
534 	 */
535 	ifp->if_addrheads = kmalloc(ncpus * sizeof(struct ifaddrhead),
536 				    M_IFADDR, M_WAITOK | M_ZERO);
537 	for (i = 0; i < ncpus; ++i)
538 		TAILQ_INIT(&ifp->if_addrheads[i]);
539 
540 	TAILQ_INIT(&ifp->if_multiaddrs);
541 	TAILQ_INIT(&ifp->if_groups);
542 	getmicrotime(&ifp->if_lastchange);
543 
544 	/*
545 	 * create a Link Level name for this device
546 	 */
547 	namelen = strlen(ifp->if_xname);
548 	masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + namelen;
549 	socksize = masklen + ifp->if_addrlen;
550 	if (socksize < sizeof(*sdl))
551 		socksize = sizeof(*sdl);
552 	socksize = RT_ROUNDUP(socksize);
553 	ifa = ifa_create(sizeof(struct ifaddr) + 2 * socksize);
554 	sdl = sdl_addr = (struct sockaddr_dl *)(ifa + 1);
555 	sdl->sdl_len = socksize;
556 	sdl->sdl_family = AF_LINK;
557 	bcopy(ifp->if_xname, sdl->sdl_data, namelen);
558 	sdl->sdl_nlen = namelen;
559 	sdl->sdl_type = ifp->if_type;
560 	ifp->if_lladdr = ifa;
561 	ifa->ifa_ifp = ifp;
562 	ifa->ifa_rtrequest = link_rtrequest;
563 	ifa->ifa_addr = (struct sockaddr *)sdl;
564 	sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
565 	ifa->ifa_netmask = (struct sockaddr *)sdl;
566 	sdl->sdl_len = masklen;
567 	while (namelen != 0)
568 		sdl->sdl_data[--namelen] = 0xff;
569 	ifa_iflink(ifa, ifp, 0 /* Insert head */);
570 
571 	ifp->if_data_pcpu = kmalloc_cachealign(
572 	    ncpus * sizeof(struct ifdata_pcpu), M_DEVBUF, M_WAITOK | M_ZERO);
573 
574 	if (ifp->if_mapsubq == NULL)
575 		ifp->if_mapsubq = ifq_mapsubq_default;
576 
577 	ifq = &ifp->if_snd;
578 	ifq->altq_type = 0;
579 	ifq->altq_disc = NULL;
580 	ifq->altq_flags &= ALTQF_CANTCHANGE;
581 	ifq->altq_tbr = NULL;
582 	ifq->altq_ifp = ifp;
583 
584 	if (ifq->altq_subq_cnt <= 0)
585 		ifq->altq_subq_cnt = 1;
586 	ifq->altq_subq = kmalloc_cachealign(
587 	    ifq->altq_subq_cnt * sizeof(struct ifaltq_subque),
588 	    M_DEVBUF, M_WAITOK | M_ZERO);
589 
590 	if (ifq->altq_maxlen == 0) {
591 		if_printf(ifp, "driver didn't set altq_maxlen\n");
592 		ifq_set_maxlen(ifq, ifqmaxlen);
593 	}
594 
595 	for (q = 0; q < ifq->altq_subq_cnt; ++q) {
596 		struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
597 
598 		ALTQ_SQ_LOCK_INIT(ifsq);
599 		ifsq->ifsq_index = q;
600 
601 		ifsq->ifsq_altq = ifq;
602 		ifsq->ifsq_ifp = ifp;
603 
604 		ifsq->ifsq_maxlen = ifq->altq_maxlen;
605 		ifsq->ifsq_maxbcnt = ifsq->ifsq_maxlen * MCLBYTES;
606 		ifsq->ifsq_prepended = NULL;
607 		ifsq->ifsq_started = 0;
608 		ifsq->ifsq_hw_oactive = 0;
609 		ifsq_set_cpuid(ifsq, 0);
610 		if (ifp->if_serializer != NULL)
611 			ifsq_set_hw_serialize(ifsq, ifp->if_serializer);
612 
613 		ifsq->ifsq_stage =
614 		    kmalloc_cachealign(ncpus * sizeof(struct ifsubq_stage),
615 		    M_DEVBUF, M_WAITOK | M_ZERO);
616 		for (i = 0; i < ncpus; ++i)
617 			ifsq->ifsq_stage[i].stg_subq = ifsq;
618 
619 		ifsq->ifsq_ifstart_nmsg =
620 		    kmalloc(ncpus * sizeof(struct netmsg_base),
621 		    M_LWKTMSG, M_WAITOK);
622 		for (i = 0; i < ncpus; ++i) {
623 			netmsg_init(&ifsq->ifsq_ifstart_nmsg[i], NULL,
624 			    &netisr_adone_rport, 0, ifsq_ifstart_dispatch);
625 			ifsq->ifsq_ifstart_nmsg[i].lmsg.u.ms_resultp = ifsq;
626 		}
627 	}
628 	ifq_set_classic(ifq);
629 
630 	/*
631 	 * Increase mbuf cluster/jcluster limits for the mbufs that
632 	 * could sit on the device queues for quite some time.
633 	 */
634 	if (ifp->if_nmbclusters > 0)
635 		mcl_inclimit(ifp->if_nmbclusters);
636 	if (ifp->if_nmbjclusters > 0)
637 		mjcl_inclimit(ifp->if_nmbjclusters);
638 
639 	/*
640 	 * Install this ifp into ifindex2inet, ifnet queue and ifnet
641 	 * array after it is setup.
642 	 *
643 	 * Protect ifindex2ifnet, ifnet queue and ifnet array changes
644 	 * by ifnet lock, so that non-netisr threads could get a
645 	 * consistent view.
646 	 */
647 	ifnet_lock();
648 
649 	/* Don't update if_index until ifindex2ifnet is setup */
650 	ifp->if_index = if_index + 1;
651 	sdl_addr->sdl_index = ifp->if_index;
652 
653 	/*
654 	 * Install this ifp into ifindex2ifnet
655 	 */
656 	if (ifindex2ifnet == NULL || ifp->if_index >= if_indexlim) {
657 		unsigned int n;
658 		struct ifnet **q;
659 
660 		/*
661 		 * Grow ifindex2ifnet
662 		 */
663 		if_indexlim <<= 1;
664 		n = if_indexlim * sizeof(*q);
665 		q = kmalloc(n, M_IFADDR, M_WAITOK | M_ZERO);
666 		if (ifindex2ifnet != NULL) {
667 			bcopy(ifindex2ifnet, q, n/2);
668 			/* Free old ifindex2ifnet after sync all netisrs */
669 			old_ifindex2ifnet = ifindex2ifnet;
670 		}
671 		ifindex2ifnet = q;
672 	}
673 	ifindex2ifnet[ifp->if_index] = ifp;
674 	/*
675 	 * Update if_index after this ifp is installed into ifindex2ifnet,
676 	 * so that netisrs could get a consistent view of ifindex2ifnet.
677 	 */
678 	cpu_sfence();
679 	if_index = ifp->if_index;
680 
681 	/*
682 	 * Install this ifp into ifnet array.
683 	 */
684 	/* Free old ifnet array after sync all netisrs */
685 	old_ifnet_array = ifnet_array;
686 	ifnet_array = ifnet_array_add(ifp, old_ifnet_array);
687 
688 	/*
689 	 * Install this ifp into ifnet queue.
690 	 */
691 	TAILQ_INSERT_TAIL(&ifnetlist, ifp, if_link);
692 
693 	ifnet_unlock();
694 
695 	/*
696 	 * Sync all netisrs so that the old ifindex2ifnet and ifnet array
697 	 * are no longer accessed and we can free them safely later on.
698 	 */
699 	netmsg_service_sync();
700 	if (old_ifindex2ifnet != NULL)
701 		kfree(old_ifindex2ifnet, M_IFADDR);
702 	ifnet_array_free(old_ifnet_array);
703 
704 	if (!SLIST_EMPTY(&domains))
705 		if_attachdomain1(ifp);
706 
707 	/* Announce the interface. */
708 	EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
709 	devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
710 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
711 }
712 
713 static void
714 if_attachdomain(void *dummy)
715 {
716 	struct ifnet *ifp;
717 
718 	ifnet_lock();
719 	TAILQ_FOREACH(ifp, &ifnetlist, if_list)
720 		if_attachdomain1(ifp);
721 	ifnet_unlock();
722 }
723 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_FIRST,
724 	if_attachdomain, NULL);
725 
726 static void
727 if_attachdomain1(struct ifnet *ifp)
728 {
729 	struct domain *dp;
730 
731 	crit_enter();
732 
733 	/* address family dependent data region */
734 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
735 	SLIST_FOREACH(dp, &domains, dom_next)
736 		if (dp->dom_ifattach)
737 			ifp->if_afdata[dp->dom_family] =
738 				(*dp->dom_ifattach)(ifp);
739 	crit_exit();
740 }
741 
742 /*
743  * Purge all addresses whose type is _not_ AF_LINK
744  */
745 static void
746 if_purgeaddrs_nolink_dispatch(netmsg_t nmsg)
747 {
748 	struct lwkt_msg *lmsg = &nmsg->lmsg;
749 	struct ifnet *ifp = lmsg->u.ms_resultp;
750 	struct ifaddr_container *ifac, *next;
751 
752 	ASSERT_IN_NETISR(0);
753 
754 	/*
755 	 * The ifaddr processing in the following loop will block,
756 	 * however, this function is called in netisr0, in which
757 	 * ifaddr list changes happen, so we don't care about the
758 	 * blockness of the ifaddr processing here.
759 	 */
760 	TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
761 			      ifa_link, next) {
762 		struct ifaddr *ifa = ifac->ifa;
763 
764 		/* Ignore marker */
765 		if (ifa->ifa_addr->sa_family == AF_UNSPEC)
766 			continue;
767 
768 		/* Leave link ifaddr as it is */
769 		if (ifa->ifa_addr->sa_family == AF_LINK)
770 			continue;
771 #ifdef INET
772 		/* XXX: Ugly!! ad hoc just for INET */
773 		if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
774 			struct ifaliasreq ifr;
775 #ifdef IFADDR_DEBUG_VERBOSE
776 			int i;
777 
778 			kprintf("purge in4 addr %p: ", ifa);
779 			for (i = 0; i < ncpus; ++i)
780 				kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
781 			kprintf("\n");
782 #endif
783 
784 			bzero(&ifr, sizeof ifr);
785 			ifr.ifra_addr = *ifa->ifa_addr;
786 			if (ifa->ifa_dstaddr)
787 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
788 			if (in_control(SIOCDIFADDR, (caddr_t)&ifr, ifp,
789 				       NULL) == 0)
790 				continue;
791 		}
792 #endif /* INET */
793 #ifdef INET6
794 		if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
795 #ifdef IFADDR_DEBUG_VERBOSE
796 			int i;
797 
798 			kprintf("purge in6 addr %p: ", ifa);
799 			for (i = 0; i < ncpus; ++i)
800 				kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
801 			kprintf("\n");
802 #endif
803 
804 			in6_purgeaddr(ifa);
805 			/* ifp_addrhead is already updated */
806 			continue;
807 		}
808 #endif /* INET6 */
809 		ifa_ifunlink(ifa, ifp);
810 		ifa_destroy(ifa);
811 	}
812 
813 	lwkt_replymsg(lmsg, 0);
814 }
815 
816 void
817 if_purgeaddrs_nolink(struct ifnet *ifp)
818 {
819 	struct netmsg_base nmsg;
820 	struct lwkt_msg *lmsg = &nmsg.lmsg;
821 
822 	ASSERT_CANDOMSG_NETISR0(curthread);
823 
824 	netmsg_init(&nmsg, NULL, &curthread->td_msgport, 0,
825 	    if_purgeaddrs_nolink_dispatch);
826 	lmsg->u.ms_resultp = ifp;
827 	lwkt_domsg(netisr_cpuport(0), lmsg, 0);
828 }
829 
830 static void
831 ifq_stage_detach_handler(netmsg_t nmsg)
832 {
833 	struct ifaltq *ifq = nmsg->lmsg.u.ms_resultp;
834 	int q;
835 
836 	for (q = 0; q < ifq->altq_subq_cnt; ++q) {
837 		struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
838 		struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
839 
840 		if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED)
841 			ifsq_stage_remove(&ifsubq_stage_heads[mycpuid], stage);
842 	}
843 	lwkt_replymsg(&nmsg->lmsg, 0);
844 }
845 
846 static void
847 ifq_stage_detach(struct ifaltq *ifq)
848 {
849 	struct netmsg_base base;
850 	int cpu;
851 
852 	netmsg_init(&base, NULL, &curthread->td_msgport, 0,
853 	    ifq_stage_detach_handler);
854 	base.lmsg.u.ms_resultp = ifq;
855 
856 	for (cpu = 0; cpu < ncpus; ++cpu)
857 		lwkt_domsg(netisr_cpuport(cpu), &base.lmsg, 0);
858 }
859 
860 struct netmsg_if_rtdel {
861 	struct netmsg_base	base;
862 	struct ifnet		*ifp;
863 };
864 
865 static void
866 if_rtdel_dispatch(netmsg_t msg)
867 {
868 	struct netmsg_if_rtdel *rmsg = (void *)msg;
869 	int i, nextcpu, cpu;
870 
871 	cpu = mycpuid;
872 	for (i = 1; i <= AF_MAX; i++) {
873 		struct radix_node_head	*rnh;
874 
875 		if ((rnh = rt_tables[cpu][i]) == NULL)
876 			continue;
877 		rnh->rnh_walktree(rnh, if_rtdel, rmsg->ifp);
878 	}
879 
880 	nextcpu = cpu + 1;
881 	if (nextcpu < ncpus)
882 		lwkt_forwardmsg(netisr_cpuport(nextcpu), &rmsg->base.lmsg);
883 	else
884 		lwkt_replymsg(&rmsg->base.lmsg, 0);
885 }
886 
887 /*
888  * Detach an interface, removing it from the
889  * list of "active" interfaces.
890  */
891 void
892 if_detach(struct ifnet *ifp)
893 {
894 	struct ifnet_array *old_ifnet_array;
895 	struct netmsg_if_rtdel msg;
896 	struct domain *dp;
897 	int q;
898 
899 	/* Announce that the interface is gone. */
900 	EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
901 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
902 	devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
903 
904 	/*
905 	 * Remove this ifp from ifindex2inet, ifnet queue and ifnet
906 	 * array before it is whacked.
907 	 *
908 	 * Protect ifindex2ifnet, ifnet queue and ifnet array changes
909 	 * by ifnet lock, so that non-netisr threads could get a
910 	 * consistent view.
911 	 */
912 	ifnet_lock();
913 
914 	/*
915 	 * Remove this ifp from ifindex2ifnet and maybe decrement if_index.
916 	 */
917 	ifindex2ifnet[ifp->if_index] = NULL;
918 	while (if_index > 0 && ifindex2ifnet[if_index] == NULL)
919 		if_index--;
920 
921 	/*
922 	 * Remove this ifp from ifnet queue.
923 	 */
924 	TAILQ_REMOVE(&ifnetlist, ifp, if_link);
925 
926 	/*
927 	 * Remove this ifp from ifnet array.
928 	 */
929 	/* Free old ifnet array after sync all netisrs */
930 	old_ifnet_array = ifnet_array;
931 	ifnet_array = ifnet_array_del(ifp, old_ifnet_array);
932 
933 	ifnet_unlock();
934 
935 	/*
936 	 * Sync all netisrs so that the old ifnet array is no longer
937 	 * accessed and we can free it safely later on.
938 	 */
939 	netmsg_service_sync();
940 	ifnet_array_free(old_ifnet_array);
941 
942 	/*
943 	 * Remove routes and flush queues.
944 	 */
945 	crit_enter();
946 #ifdef IFPOLL_ENABLE
947 	if (ifp->if_flags & IFF_NPOLLING)
948 		ifpoll_deregister(ifp);
949 #endif
950 	if_down(ifp);
951 
952 	/* Decrease the mbuf clusters/jclusters limits increased by us */
953 	if (ifp->if_nmbclusters > 0)
954 		mcl_inclimit(-ifp->if_nmbclusters);
955 	if (ifp->if_nmbjclusters > 0)
956 		mjcl_inclimit(-ifp->if_nmbjclusters);
957 
958 #ifdef ALTQ
959 	if (ifq_is_enabled(&ifp->if_snd))
960 		altq_disable(&ifp->if_snd);
961 	if (ifq_is_attached(&ifp->if_snd))
962 		altq_detach(&ifp->if_snd);
963 #endif
964 
965 	/*
966 	 * Clean up all addresses.
967 	 */
968 	ifp->if_lladdr = NULL;
969 
970 	if_purgeaddrs_nolink(ifp);
971 	if (!TAILQ_EMPTY(&ifp->if_addrheads[mycpuid])) {
972 		struct ifaddr *ifa;
973 
974 		ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
975 		KASSERT(ifa->ifa_addr->sa_family == AF_LINK,
976 			("non-link ifaddr is left on if_addrheads"));
977 
978 		ifa_ifunlink(ifa, ifp);
979 		ifa_destroy(ifa);
980 		KASSERT(TAILQ_EMPTY(&ifp->if_addrheads[mycpuid]),
981 			("there are still ifaddrs left on if_addrheads"));
982 	}
983 
984 #ifdef INET
985 	/*
986 	 * Remove all IPv4 kernel structures related to ifp.
987 	 */
988 	in_ifdetach(ifp);
989 #endif
990 
991 #ifdef INET6
992 	/*
993 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
994 	 * before removing routing entries below, since IPv6 interface direct
995 	 * routes are expected to be removed by the IPv6-specific kernel API.
996 	 * Otherwise, the kernel will detect some inconsistency and bark it.
997 	 */
998 	in6_ifdetach(ifp);
999 #endif
1000 
1001 	/*
1002 	 * Delete all remaining routes using this interface
1003 	 */
1004 	netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
1005 	    if_rtdel_dispatch);
1006 	msg.ifp = ifp;
1007 	rt_domsg_global(&msg.base);
1008 
1009 	SLIST_FOREACH(dp, &domains, dom_next)
1010 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
1011 			(*dp->dom_ifdetach)(ifp,
1012 				ifp->if_afdata[dp->dom_family]);
1013 
1014 	kfree(ifp->if_addrheads, M_IFADDR);
1015 
1016 	lwkt_synchronize_ipiqs("if_detach");
1017 	ifq_stage_detach(&ifp->if_snd);
1018 
1019 	for (q = 0; q < ifp->if_snd.altq_subq_cnt; ++q) {
1020 		struct ifaltq_subque *ifsq = &ifp->if_snd.altq_subq[q];
1021 
1022 		kfree(ifsq->ifsq_ifstart_nmsg, M_LWKTMSG);
1023 		kfree(ifsq->ifsq_stage, M_DEVBUF);
1024 	}
1025 	kfree(ifp->if_snd.altq_subq, M_DEVBUF);
1026 
1027 	kfree(ifp->if_data_pcpu, M_DEVBUF);
1028 
1029 	crit_exit();
1030 }
1031 
1032 /*
1033  * Create interface group without members
1034  */
1035 struct ifg_group *
1036 if_creategroup(const char *groupname)
1037 {
1038         struct ifg_group        *ifg = NULL;
1039 
1040         if ((ifg = (struct ifg_group *)kmalloc(sizeof(struct ifg_group),
1041             M_TEMP, M_NOWAIT)) == NULL)
1042                 return (NULL);
1043 
1044         strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1045         ifg->ifg_refcnt = 0;
1046         ifg->ifg_carp_demoted = 0;
1047         TAILQ_INIT(&ifg->ifg_members);
1048 #if NPF > 0
1049         pfi_attach_ifgroup(ifg);
1050 #endif
1051         TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
1052 
1053         return (ifg);
1054 }
1055 
1056 /*
1057  * Add a group to an interface
1058  */
1059 int
1060 if_addgroup(struct ifnet *ifp, const char *groupname)
1061 {
1062 	struct ifg_list		*ifgl;
1063 	struct ifg_group	*ifg = NULL;
1064 	struct ifg_member	*ifgm;
1065 
1066 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1067 	    groupname[strlen(groupname) - 1] <= '9')
1068 		return (EINVAL);
1069 
1070 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1071 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1072 			return (EEXIST);
1073 
1074 	if ((ifgl = kmalloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL)
1075 		return (ENOMEM);
1076 
1077 	if ((ifgm = kmalloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
1078 		kfree(ifgl, M_TEMP);
1079 		return (ENOMEM);
1080 	}
1081 
1082 	TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1083 		if (!strcmp(ifg->ifg_group, groupname))
1084 			break;
1085 
1086 	if (ifg == NULL && (ifg = if_creategroup(groupname)) == NULL) {
1087 		kfree(ifgl, M_TEMP);
1088 		kfree(ifgm, M_TEMP);
1089 		return (ENOMEM);
1090 	}
1091 
1092 	ifg->ifg_refcnt++;
1093 	ifgl->ifgl_group = ifg;
1094 	ifgm->ifgm_ifp = ifp;
1095 
1096 	TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1097 	TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1098 
1099 #if NPF > 0
1100 	pfi_group_change(groupname);
1101 #endif
1102 
1103 	return (0);
1104 }
1105 
1106 /*
1107  * Remove a group from an interface
1108  */
1109 int
1110 if_delgroup(struct ifnet *ifp, const char *groupname)
1111 {
1112 	struct ifg_list		*ifgl;
1113 	struct ifg_member	*ifgm;
1114 
1115 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1116 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1117 			break;
1118 	if (ifgl == NULL)
1119 		return (ENOENT);
1120 
1121 	TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1122 
1123 	TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1124 		if (ifgm->ifgm_ifp == ifp)
1125 			break;
1126 
1127 	if (ifgm != NULL) {
1128 		TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1129 		kfree(ifgm, M_TEMP);
1130 	}
1131 
1132 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1133 		TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
1134 #if NPF > 0
1135 		pfi_detach_ifgroup(ifgl->ifgl_group);
1136 #endif
1137 		kfree(ifgl->ifgl_group, M_TEMP);
1138 	}
1139 
1140 	kfree(ifgl, M_TEMP);
1141 
1142 #if NPF > 0
1143 	pfi_group_change(groupname);
1144 #endif
1145 
1146 	return (0);
1147 }
1148 
1149 /*
1150  * Stores all groups from an interface in memory pointed
1151  * to by data
1152  */
1153 int
1154 if_getgroup(caddr_t data, struct ifnet *ifp)
1155 {
1156 	int			 len, error;
1157 	struct ifg_list		*ifgl;
1158 	struct ifg_req		 ifgrq, *ifgp;
1159 	struct ifgroupreq	*ifgr = (struct ifgroupreq *)data;
1160 
1161 	if (ifgr->ifgr_len == 0) {
1162 		TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1163 			ifgr->ifgr_len += sizeof(struct ifg_req);
1164 		return (0);
1165 	}
1166 
1167 	len = ifgr->ifgr_len;
1168 	ifgp = ifgr->ifgr_groups;
1169 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1170 		if (len < sizeof(ifgrq))
1171 			return (EINVAL);
1172 		bzero(&ifgrq, sizeof ifgrq);
1173 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1174 		    sizeof(ifgrq.ifgrq_group));
1175 		if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1176 		    sizeof(struct ifg_req))))
1177 			return (error);
1178 		len -= sizeof(ifgrq);
1179 		ifgp++;
1180 	}
1181 
1182 	return (0);
1183 }
1184 
1185 /*
1186  * Stores all members of a group in memory pointed to by data
1187  */
1188 int
1189 if_getgroupmembers(caddr_t data)
1190 {
1191 	struct ifgroupreq	*ifgr = (struct ifgroupreq *)data;
1192 	struct ifg_group	*ifg;
1193 	struct ifg_member	*ifgm;
1194 	struct ifg_req		 ifgrq, *ifgp;
1195 	int			 len, error;
1196 
1197 	TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1198 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1199 			break;
1200 	if (ifg == NULL)
1201 		return (ENOENT);
1202 
1203 	if (ifgr->ifgr_len == 0) {
1204 		TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1205 			ifgr->ifgr_len += sizeof(ifgrq);
1206 		return (0);
1207 	}
1208 
1209 	len = ifgr->ifgr_len;
1210 	ifgp = ifgr->ifgr_groups;
1211 	TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1212 		if (len < sizeof(ifgrq))
1213 			return (EINVAL);
1214 		bzero(&ifgrq, sizeof ifgrq);
1215 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1216 		    sizeof(ifgrq.ifgrq_member));
1217 		if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1218 		    sizeof(struct ifg_req))))
1219 			return (error);
1220 		len -= sizeof(ifgrq);
1221 		ifgp++;
1222 	}
1223 
1224 	return (0);
1225 }
1226 
1227 /*
1228  * Delete Routes for a Network Interface
1229  *
1230  * Called for each routing entry via the rnh->rnh_walktree() call above
1231  * to delete all route entries referencing a detaching network interface.
1232  *
1233  * Arguments:
1234  *	rn	pointer to node in the routing table
1235  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1236  *
1237  * Returns:
1238  *	0	successful
1239  *	errno	failed - reason indicated
1240  *
1241  */
1242 static int
1243 if_rtdel(struct radix_node *rn, void *arg)
1244 {
1245 	struct rtentry	*rt = (struct rtentry *)rn;
1246 	struct ifnet	*ifp = arg;
1247 	int		err;
1248 
1249 	if (rt->rt_ifp == ifp) {
1250 
1251 		/*
1252 		 * Protect (sorta) against walktree recursion problems
1253 		 * with cloned routes
1254 		 */
1255 		if (!(rt->rt_flags & RTF_UP))
1256 			return (0);
1257 
1258 		err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1259 				rt_mask(rt), rt->rt_flags,
1260 				NULL);
1261 		if (err) {
1262 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
1263 		}
1264 	}
1265 
1266 	return (0);
1267 }
1268 
1269 static __inline boolean_t
1270 ifa_prefer(const struct ifaddr *cur_ifa, const struct ifaddr *old_ifa)
1271 {
1272 	if (old_ifa == NULL)
1273 		return TRUE;
1274 
1275 	if ((old_ifa->ifa_ifp->if_flags & IFF_UP) == 0 &&
1276 	    (cur_ifa->ifa_ifp->if_flags & IFF_UP))
1277 		return TRUE;
1278 	if ((old_ifa->ifa_flags & IFA_ROUTE) == 0 &&
1279 	    (cur_ifa->ifa_flags & IFA_ROUTE))
1280 		return TRUE;
1281 	return FALSE;
1282 }
1283 
1284 /*
1285  * Locate an interface based on a complete address.
1286  */
1287 struct ifaddr *
1288 ifa_ifwithaddr(struct sockaddr *addr)
1289 {
1290 	const struct ifnet_array *arr;
1291 	int i;
1292 
1293 	arr = ifnet_array_get();
1294 	for (i = 0; i < arr->ifnet_count; ++i) {
1295 		struct ifnet *ifp = arr->ifnet_arr[i];
1296 		struct ifaddr_container *ifac;
1297 
1298 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1299 			struct ifaddr *ifa = ifac->ifa;
1300 
1301 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1302 				continue;
1303 			if (sa_equal(addr, ifa->ifa_addr))
1304 				return (ifa);
1305 			if ((ifp->if_flags & IFF_BROADCAST) &&
1306 			    ifa->ifa_broadaddr &&
1307 			    /* IPv6 doesn't have broadcast */
1308 			    ifa->ifa_broadaddr->sa_len != 0 &&
1309 			    sa_equal(ifa->ifa_broadaddr, addr))
1310 				return (ifa);
1311 		}
1312 	}
1313 	return (NULL);
1314 }
1315 
1316 /*
1317  * Locate the point to point interface with a given destination address.
1318  */
1319 struct ifaddr *
1320 ifa_ifwithdstaddr(struct sockaddr *addr)
1321 {
1322 	const struct ifnet_array *arr;
1323 	int i;
1324 
1325 	arr = ifnet_array_get();
1326 	for (i = 0; i < arr->ifnet_count; ++i) {
1327 		struct ifnet *ifp = arr->ifnet_arr[i];
1328 		struct ifaddr_container *ifac;
1329 
1330 		if (!(ifp->if_flags & IFF_POINTOPOINT))
1331 			continue;
1332 
1333 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1334 			struct ifaddr *ifa = ifac->ifa;
1335 
1336 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1337 				continue;
1338 			if (ifa->ifa_dstaddr &&
1339 			    sa_equal(addr, ifa->ifa_dstaddr))
1340 				return (ifa);
1341 		}
1342 	}
1343 	return (NULL);
1344 }
1345 
1346 /*
1347  * Find an interface on a specific network.  If many, choice
1348  * is most specific found.
1349  */
1350 struct ifaddr *
1351 ifa_ifwithnet(struct sockaddr *addr)
1352 {
1353 	struct ifaddr *ifa_maybe = NULL;
1354 	u_int af = addr->sa_family;
1355 	char *addr_data = addr->sa_data, *cplim;
1356 	const struct ifnet_array *arr;
1357 	int i;
1358 
1359 	/*
1360 	 * AF_LINK addresses can be looked up directly by their index number,
1361 	 * so do that if we can.
1362 	 */
1363 	if (af == AF_LINK) {
1364 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1365 
1366 		if (sdl->sdl_index && sdl->sdl_index <= if_index)
1367 			return (ifindex2ifnet[sdl->sdl_index]->if_lladdr);
1368 	}
1369 
1370 	/*
1371 	 * Scan though each interface, looking for ones that have
1372 	 * addresses in this address family.
1373 	 */
1374 	arr = ifnet_array_get();
1375 	for (i = 0; i < arr->ifnet_count; ++i) {
1376 		struct ifnet *ifp = arr->ifnet_arr[i];
1377 		struct ifaddr_container *ifac;
1378 
1379 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1380 			struct ifaddr *ifa = ifac->ifa;
1381 			char *cp, *cp2, *cp3;
1382 
1383 			if (ifa->ifa_addr->sa_family != af)
1384 next:				continue;
1385 			if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1386 				/*
1387 				 * This is a bit broken as it doesn't
1388 				 * take into account that the remote end may
1389 				 * be a single node in the network we are
1390 				 * looking for.
1391 				 * The trouble is that we don't know the
1392 				 * netmask for the remote end.
1393 				 */
1394 				if (ifa->ifa_dstaddr != NULL &&
1395 				    sa_equal(addr, ifa->ifa_dstaddr))
1396 					return (ifa);
1397 			} else {
1398 				/*
1399 				 * if we have a special address handler,
1400 				 * then use it instead of the generic one.
1401 				 */
1402 				if (ifa->ifa_claim_addr) {
1403 					if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1404 						return (ifa);
1405 					} else {
1406 						continue;
1407 					}
1408 				}
1409 
1410 				/*
1411 				 * Scan all the bits in the ifa's address.
1412 				 * If a bit dissagrees with what we are
1413 				 * looking for, mask it with the netmask
1414 				 * to see if it really matters.
1415 				 * (A byte at a time)
1416 				 */
1417 				if (ifa->ifa_netmask == 0)
1418 					continue;
1419 				cp = addr_data;
1420 				cp2 = ifa->ifa_addr->sa_data;
1421 				cp3 = ifa->ifa_netmask->sa_data;
1422 				cplim = ifa->ifa_netmask->sa_len +
1423 					(char *)ifa->ifa_netmask;
1424 				while (cp3 < cplim)
1425 					if ((*cp++ ^ *cp2++) & *cp3++)
1426 						goto next; /* next address! */
1427 				/*
1428 				 * If the netmask of what we just found
1429 				 * is more specific than what we had before
1430 				 * (if we had one) then remember the new one
1431 				 * before continuing to search for an even
1432 				 * better one.  If the netmasks are equal,
1433 				 * we prefer the this ifa based on the result
1434 				 * of ifa_prefer().
1435 				 */
1436 				if (ifa_maybe == NULL ||
1437 				    rn_refines((char *)ifa->ifa_netmask,
1438 				        (char *)ifa_maybe->ifa_netmask) ||
1439 				    (sa_equal(ifa_maybe->ifa_netmask,
1440 				        ifa->ifa_netmask) &&
1441 				     ifa_prefer(ifa, ifa_maybe)))
1442 					ifa_maybe = ifa;
1443 			}
1444 		}
1445 	}
1446 	return (ifa_maybe);
1447 }
1448 
1449 /*
1450  * Find an interface address specific to an interface best matching
1451  * a given address.
1452  */
1453 struct ifaddr *
1454 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1455 {
1456 	struct ifaddr_container *ifac;
1457 	char *cp, *cp2, *cp3;
1458 	char *cplim;
1459 	struct ifaddr *ifa_maybe = NULL;
1460 	u_int af = addr->sa_family;
1461 
1462 	if (af >= AF_MAX)
1463 		return (0);
1464 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1465 		struct ifaddr *ifa = ifac->ifa;
1466 
1467 		if (ifa->ifa_addr->sa_family != af)
1468 			continue;
1469 		if (ifa_maybe == NULL)
1470 			ifa_maybe = ifa;
1471 		if (ifa->ifa_netmask == NULL) {
1472 			if (sa_equal(addr, ifa->ifa_addr) ||
1473 			    (ifa->ifa_dstaddr != NULL &&
1474 			     sa_equal(addr, ifa->ifa_dstaddr)))
1475 				return (ifa);
1476 			continue;
1477 		}
1478 		if (ifp->if_flags & IFF_POINTOPOINT) {
1479 			if (sa_equal(addr, ifa->ifa_dstaddr))
1480 				return (ifa);
1481 		} else {
1482 			cp = addr->sa_data;
1483 			cp2 = ifa->ifa_addr->sa_data;
1484 			cp3 = ifa->ifa_netmask->sa_data;
1485 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1486 			for (; cp3 < cplim; cp3++)
1487 				if ((*cp++ ^ *cp2++) & *cp3)
1488 					break;
1489 			if (cp3 == cplim)
1490 				return (ifa);
1491 		}
1492 	}
1493 	return (ifa_maybe);
1494 }
1495 
1496 /*
1497  * Default action when installing a route with a Link Level gateway.
1498  * Lookup an appropriate real ifa to point to.
1499  * This should be moved to /sys/net/link.c eventually.
1500  */
1501 static void
1502 link_rtrequest(int cmd, struct rtentry *rt)
1503 {
1504 	struct ifaddr *ifa;
1505 	struct sockaddr *dst;
1506 	struct ifnet *ifp;
1507 
1508 	if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1509 	    (ifp = ifa->ifa_ifp) == NULL || (dst = rt_key(rt)) == NULL)
1510 		return;
1511 	ifa = ifaof_ifpforaddr(dst, ifp);
1512 	if (ifa != NULL) {
1513 		IFAFREE(rt->rt_ifa);
1514 		IFAREF(ifa);
1515 		rt->rt_ifa = ifa;
1516 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1517 			ifa->ifa_rtrequest(cmd, rt);
1518 	}
1519 }
1520 
1521 struct netmsg_ifroute {
1522 	struct netmsg_base	base;
1523 	struct ifnet		*ifp;
1524 	int			flag;
1525 	int			fam;
1526 };
1527 
1528 /*
1529  * Mark an interface down and notify protocols of the transition.
1530  */
1531 static void
1532 if_unroute_dispatch(netmsg_t nmsg)
1533 {
1534 	struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1535 	struct ifnet *ifp = msg->ifp;
1536 	int flag = msg->flag, fam = msg->fam;
1537 	struct ifaddr_container *ifac;
1538 
1539 	ifp->if_flags &= ~flag;
1540 	getmicrotime(&ifp->if_lastchange);
1541 	/*
1542 	 * The ifaddr processing in the following loop will block,
1543 	 * however, this function is called in netisr0, in which
1544 	 * ifaddr list changes happen, so we don't care about the
1545 	 * blockness of the ifaddr processing here.
1546 	 */
1547 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1548 		struct ifaddr *ifa = ifac->ifa;
1549 
1550 		/* Ignore marker */
1551 		if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1552 			continue;
1553 
1554 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1555 			kpfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1556 	}
1557 	ifq_purge_all(&ifp->if_snd);
1558 	rt_ifmsg(ifp);
1559 
1560 	lwkt_replymsg(&nmsg->lmsg, 0);
1561 }
1562 
1563 void
1564 if_unroute(struct ifnet *ifp, int flag, int fam)
1565 {
1566 	struct netmsg_ifroute msg;
1567 
1568 	ASSERT_CANDOMSG_NETISR0(curthread);
1569 
1570 	netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1571 	    if_unroute_dispatch);
1572 	msg.ifp = ifp;
1573 	msg.flag = flag;
1574 	msg.fam = fam;
1575 	lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1576 }
1577 
1578 /*
1579  * Mark an interface up and notify protocols of the transition.
1580  */
1581 static void
1582 if_route_dispatch(netmsg_t nmsg)
1583 {
1584 	struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1585 	struct ifnet *ifp = msg->ifp;
1586 	int flag = msg->flag, fam = msg->fam;
1587 	struct ifaddr_container *ifac;
1588 
1589 	ifq_purge_all(&ifp->if_snd);
1590 	ifp->if_flags |= flag;
1591 	getmicrotime(&ifp->if_lastchange);
1592 	/*
1593 	 * The ifaddr processing in the following loop will block,
1594 	 * however, this function is called in netisr0, in which
1595 	 * ifaddr list changes happen, so we don't care about the
1596 	 * blockness of the ifaddr processing here.
1597 	 */
1598 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1599 		struct ifaddr *ifa = ifac->ifa;
1600 
1601 		/* Ignore marker */
1602 		if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1603 			continue;
1604 
1605 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1606 			kpfctlinput(PRC_IFUP, ifa->ifa_addr);
1607 	}
1608 	rt_ifmsg(ifp);
1609 #ifdef INET6
1610 	in6_if_up(ifp);
1611 #endif
1612 
1613 	lwkt_replymsg(&nmsg->lmsg, 0);
1614 }
1615 
1616 void
1617 if_route(struct ifnet *ifp, int flag, int fam)
1618 {
1619 	struct netmsg_ifroute msg;
1620 
1621 	ASSERT_CANDOMSG_NETISR0(curthread);
1622 
1623 	netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1624 	    if_route_dispatch);
1625 	msg.ifp = ifp;
1626 	msg.flag = flag;
1627 	msg.fam = fam;
1628 	lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1629 }
1630 
1631 /*
1632  * Mark an interface down and notify protocols of the transition.  An
1633  * interface going down is also considered to be a synchronizing event.
1634  * We must ensure that all packet processing related to the interface
1635  * has completed before we return so e.g. the caller can free the ifnet
1636  * structure that the mbufs may be referencing.
1637  *
1638  * NOTE: must be called at splnet or eqivalent.
1639  */
1640 void
1641 if_down(struct ifnet *ifp)
1642 {
1643 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
1644 	netmsg_service_sync();
1645 }
1646 
1647 /*
1648  * Mark an interface up and notify protocols of
1649  * the transition.
1650  * NOTE: must be called at splnet or eqivalent.
1651  */
1652 void
1653 if_up(struct ifnet *ifp)
1654 {
1655 	if_route(ifp, IFF_UP, AF_UNSPEC);
1656 }
1657 
1658 /*
1659  * Process a link state change.
1660  * NOTE: must be called at splsoftnet or equivalent.
1661  */
1662 void
1663 if_link_state_change(struct ifnet *ifp)
1664 {
1665 	int link_state = ifp->if_link_state;
1666 
1667 	rt_ifmsg(ifp);
1668 	devctl_notify("IFNET", ifp->if_xname,
1669 	    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1670 }
1671 
1672 /*
1673  * Handle interface watchdog timer routines.  Called
1674  * from softclock, we decrement timers (if set) and
1675  * call the appropriate interface routine on expiration.
1676  */
1677 static void
1678 if_slowtimo_dispatch(netmsg_t nmsg)
1679 {
1680 	struct globaldata *gd = mycpu;
1681 	const struct ifnet_array *arr;
1682 	int i;
1683 
1684 	ASSERT_IN_NETISR(0);
1685 
1686 	crit_enter_gd(gd);
1687 	lwkt_replymsg(&nmsg->lmsg, 0);  /* reply ASAP */
1688 	crit_exit_gd(gd);
1689 
1690 	arr = ifnet_array_get();
1691 	for (i = 0; i < arr->ifnet_count; ++i) {
1692 		struct ifnet *ifp = arr->ifnet_arr[i];
1693 
1694 		crit_enter_gd(gd);
1695 
1696 		if (if_stats_compat) {
1697 			IFNET_STAT_GET(ifp, ipackets, ifp->if_ipackets);
1698 			IFNET_STAT_GET(ifp, ierrors, ifp->if_ierrors);
1699 			IFNET_STAT_GET(ifp, opackets, ifp->if_opackets);
1700 			IFNET_STAT_GET(ifp, oerrors, ifp->if_oerrors);
1701 			IFNET_STAT_GET(ifp, collisions, ifp->if_collisions);
1702 			IFNET_STAT_GET(ifp, ibytes, ifp->if_ibytes);
1703 			IFNET_STAT_GET(ifp, obytes, ifp->if_obytes);
1704 			IFNET_STAT_GET(ifp, imcasts, ifp->if_imcasts);
1705 			IFNET_STAT_GET(ifp, omcasts, ifp->if_omcasts);
1706 			IFNET_STAT_GET(ifp, iqdrops, ifp->if_iqdrops);
1707 			IFNET_STAT_GET(ifp, noproto, ifp->if_noproto);
1708 			IFNET_STAT_GET(ifp, oqdrops, ifp->if_oqdrops);
1709 		}
1710 
1711 		if (ifp->if_timer == 0 || --ifp->if_timer) {
1712 			crit_exit_gd(gd);
1713 			continue;
1714 		}
1715 		if (ifp->if_watchdog) {
1716 			if (ifnet_tryserialize_all(ifp)) {
1717 				(*ifp->if_watchdog)(ifp);
1718 				ifnet_deserialize_all(ifp);
1719 			} else {
1720 				/* try again next timeout */
1721 				++ifp->if_timer;
1722 			}
1723 		}
1724 
1725 		crit_exit_gd(gd);
1726 	}
1727 
1728 	callout_reset(&if_slowtimo_timer, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1729 }
1730 
1731 static void
1732 if_slowtimo(void *arg __unused)
1733 {
1734 	struct lwkt_msg *lmsg = &if_slowtimo_netmsg.lmsg;
1735 
1736 	KASSERT(mycpuid == 0, ("not on cpu0"));
1737 	crit_enter();
1738 	if (lmsg->ms_flags & MSGF_DONE)
1739 		lwkt_sendmsg_oncpu(netisr_cpuport(0), lmsg);
1740 	crit_exit();
1741 }
1742 
1743 /*
1744  * Map interface name to
1745  * interface structure pointer.
1746  */
1747 struct ifnet *
1748 ifunit(const char *name)
1749 {
1750 	struct ifnet *ifp;
1751 
1752 	/*
1753 	 * Search all the interfaces for this name/number
1754 	 */
1755 	KASSERT(mtx_owned(&ifnet_mtx), ("ifnet is not locked"));
1756 
1757 	TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
1758 		if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1759 			break;
1760 	}
1761 	return (ifp);
1762 }
1763 
1764 struct ifnet *
1765 ifunit_netisr(const char *name)
1766 {
1767 	const struct ifnet_array *arr;
1768 	int i;
1769 
1770 	/*
1771 	 * Search all the interfaces for this name/number
1772 	 */
1773 
1774 	arr = ifnet_array_get();
1775 	for (i = 0; i < arr->ifnet_count; ++i) {
1776 		struct ifnet *ifp = arr->ifnet_arr[i];
1777 
1778 		if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1779 			return ifp;
1780 	}
1781 	return NULL;
1782 }
1783 
1784 /*
1785  * Interface ioctls.
1786  */
1787 int
1788 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct ucred *cred)
1789 {
1790 	struct ifnet *ifp;
1791 	struct ifreq *ifr;
1792 	struct ifstat *ifs;
1793 	int error, do_ifup = 0;
1794 	short oif_flags;
1795 	int new_flags;
1796 	size_t namelen, onamelen;
1797 	char new_name[IFNAMSIZ];
1798 	struct ifaddr *ifa;
1799 	struct sockaddr_dl *sdl;
1800 
1801 	switch (cmd) {
1802 	case SIOCGIFCONF:
1803 	case OSIOCGIFCONF:
1804 		return (ifconf(cmd, data, cred));
1805 	default:
1806 		break;
1807 	}
1808 
1809 	ifr = (struct ifreq *)data;
1810 
1811 	switch (cmd) {
1812 	case SIOCIFCREATE:
1813 	case SIOCIFCREATE2:
1814 		if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1815 			return (error);
1816 		return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1817 		    	cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1818 	case SIOCIFDESTROY:
1819 		if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1820 			return (error);
1821 		return (if_clone_destroy(ifr->ifr_name));
1822 	case SIOCIFGCLONERS:
1823 		return (if_clone_list((struct if_clonereq *)data));
1824 	default:
1825 		break;
1826 	}
1827 
1828 	/*
1829 	 * Nominal ioctl through interface, lookup the ifp and obtain a
1830 	 * lock to serialize the ifconfig ioctl operation.
1831 	 */
1832 	ifnet_lock();
1833 
1834 	ifp = ifunit(ifr->ifr_name);
1835 	if (ifp == NULL) {
1836 		ifnet_unlock();
1837 		return (ENXIO);
1838 	}
1839 	error = 0;
1840 
1841 	switch (cmd) {
1842 	case SIOCGIFINDEX:
1843 		ifr->ifr_index = ifp->if_index;
1844 		break;
1845 
1846 	case SIOCGIFFLAGS:
1847 		ifr->ifr_flags = ifp->if_flags;
1848 		ifr->ifr_flagshigh = ifp->if_flags >> 16;
1849 		break;
1850 
1851 	case SIOCGIFCAP:
1852 		ifr->ifr_reqcap = ifp->if_capabilities;
1853 		ifr->ifr_curcap = ifp->if_capenable;
1854 		break;
1855 
1856 	case SIOCGIFMETRIC:
1857 		ifr->ifr_metric = ifp->if_metric;
1858 		break;
1859 
1860 	case SIOCGIFMTU:
1861 		ifr->ifr_mtu = ifp->if_mtu;
1862 		break;
1863 
1864 	case SIOCGIFTSOLEN:
1865 		ifr->ifr_tsolen = ifp->if_tsolen;
1866 		break;
1867 
1868 	case SIOCGIFDATA:
1869 		error = copyout((caddr_t)&ifp->if_data, ifr->ifr_data,
1870 				sizeof(ifp->if_data));
1871 		break;
1872 
1873 	case SIOCGIFPHYS:
1874 		ifr->ifr_phys = ifp->if_physical;
1875 		break;
1876 
1877 	case SIOCGIFPOLLCPU:
1878 		ifr->ifr_pollcpu = -1;
1879 		break;
1880 
1881 	case SIOCSIFPOLLCPU:
1882 		break;
1883 
1884 	case SIOCSIFFLAGS:
1885 		error = priv_check_cred(cred, PRIV_ROOT, 0);
1886 		if (error)
1887 			break;
1888 		new_flags = (ifr->ifr_flags & 0xffff) |
1889 		    (ifr->ifr_flagshigh << 16);
1890 		if (ifp->if_flags & IFF_SMART) {
1891 			/* Smart drivers twiddle their own routes */
1892 		} else if (ifp->if_flags & IFF_UP &&
1893 		    (new_flags & IFF_UP) == 0) {
1894 			if_down(ifp);
1895 		} else if (new_flags & IFF_UP &&
1896 		    (ifp->if_flags & IFF_UP) == 0) {
1897 			do_ifup = 1;
1898 		}
1899 
1900 #ifdef IFPOLL_ENABLE
1901 		if ((new_flags ^ ifp->if_flags) & IFF_NPOLLING) {
1902 			if (new_flags & IFF_NPOLLING)
1903 				ifpoll_register(ifp);
1904 			else
1905 				ifpoll_deregister(ifp);
1906 		}
1907 #endif
1908 
1909 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1910 			(new_flags &~ IFF_CANTCHANGE);
1911 		if (new_flags & IFF_PPROMISC) {
1912 			/* Permanently promiscuous mode requested */
1913 			ifp->if_flags |= IFF_PROMISC;
1914 		} else if (ifp->if_pcount == 0) {
1915 			ifp->if_flags &= ~IFF_PROMISC;
1916 		}
1917 		if (ifp->if_ioctl) {
1918 			ifnet_serialize_all(ifp);
1919 			ifp->if_ioctl(ifp, cmd, data, cred);
1920 			ifnet_deserialize_all(ifp);
1921 		}
1922 		if (do_ifup)
1923 			if_up(ifp);
1924 		getmicrotime(&ifp->if_lastchange);
1925 		break;
1926 
1927 	case SIOCSIFCAP:
1928 		error = priv_check_cred(cred, PRIV_ROOT, 0);
1929 		if (error)
1930 			break;
1931 		if (ifr->ifr_reqcap & ~ifp->if_capabilities) {
1932 			error = EINVAL;
1933 			break;
1934 		}
1935 		ifnet_serialize_all(ifp);
1936 		ifp->if_ioctl(ifp, cmd, data, cred);
1937 		ifnet_deserialize_all(ifp);
1938 		break;
1939 
1940 	case SIOCSIFNAME:
1941 		error = priv_check_cred(cred, PRIV_ROOT, 0);
1942 		if (error)
1943 			break;
1944 		error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1945 		if (error)
1946 			break;
1947 		if (new_name[0] == '\0') {
1948 			error = EINVAL;
1949 			break;
1950 		}
1951 		if (ifunit(new_name) != NULL) {
1952 			error = EEXIST;
1953 			break;
1954 		}
1955 
1956 		EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
1957 
1958 		/* Announce the departure of the interface. */
1959 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1960 
1961 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1962 		ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
1963 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1964 		namelen = strlen(new_name);
1965 		onamelen = sdl->sdl_nlen;
1966 		/*
1967 		 * Move the address if needed.  This is safe because we
1968 		 * allocate space for a name of length IFNAMSIZ when we
1969 		 * create this in if_attach().
1970 		 */
1971 		if (namelen != onamelen) {
1972 			bcopy(sdl->sdl_data + onamelen,
1973 			    sdl->sdl_data + namelen, sdl->sdl_alen);
1974 		}
1975 		bcopy(new_name, sdl->sdl_data, namelen);
1976 		sdl->sdl_nlen = namelen;
1977 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1978 		bzero(sdl->sdl_data, onamelen);
1979 		while (namelen != 0)
1980 			sdl->sdl_data[--namelen] = 0xff;
1981 
1982 		EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
1983 
1984 		/* Announce the return of the interface. */
1985 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1986 		break;
1987 
1988 	case SIOCSIFMETRIC:
1989 		error = priv_check_cred(cred, PRIV_ROOT, 0);
1990 		if (error)
1991 			break;
1992 		ifp->if_metric = ifr->ifr_metric;
1993 		getmicrotime(&ifp->if_lastchange);
1994 		break;
1995 
1996 	case SIOCSIFPHYS:
1997 		error = priv_check_cred(cred, PRIV_ROOT, 0);
1998 		if (error)
1999 			break;
2000 		if (ifp->if_ioctl == NULL) {
2001 		        error = EOPNOTSUPP;
2002 			break;
2003 		}
2004 		ifnet_serialize_all(ifp);
2005 		error = ifp->if_ioctl(ifp, cmd, data, cred);
2006 		ifnet_deserialize_all(ifp);
2007 		if (error == 0)
2008 			getmicrotime(&ifp->if_lastchange);
2009 		break;
2010 
2011 	case SIOCSIFMTU:
2012 	{
2013 		u_long oldmtu = ifp->if_mtu;
2014 
2015 		error = priv_check_cred(cred, PRIV_ROOT, 0);
2016 		if (error)
2017 			break;
2018 		if (ifp->if_ioctl == NULL) {
2019 			error = EOPNOTSUPP;
2020 			break;
2021 		}
2022 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU) {
2023 			error = EINVAL;
2024 			break;
2025 		}
2026 		ifnet_serialize_all(ifp);
2027 		error = ifp->if_ioctl(ifp, cmd, data, cred);
2028 		ifnet_deserialize_all(ifp);
2029 		if (error == 0) {
2030 			getmicrotime(&ifp->if_lastchange);
2031 			rt_ifmsg(ifp);
2032 		}
2033 		/*
2034 		 * If the link MTU changed, do network layer specific procedure.
2035 		 */
2036 		if (ifp->if_mtu != oldmtu) {
2037 #ifdef INET6
2038 			nd6_setmtu(ifp);
2039 #endif
2040 		}
2041 		break;
2042 	}
2043 
2044 	case SIOCSIFTSOLEN:
2045 		error = priv_check_cred(cred, PRIV_ROOT, 0);
2046 		if (error)
2047 			break;
2048 
2049 		/* XXX need driver supplied upper limit */
2050 		if (ifr->ifr_tsolen <= 0) {
2051 			error = EINVAL;
2052 			break;
2053 		}
2054 		ifp->if_tsolen = ifr->ifr_tsolen;
2055 		break;
2056 
2057 	case SIOCADDMULTI:
2058 	case SIOCDELMULTI:
2059 		error = priv_check_cred(cred, PRIV_ROOT, 0);
2060 		if (error)
2061 			break;
2062 
2063 		/* Don't allow group membership on non-multicast interfaces. */
2064 		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
2065 			error = EOPNOTSUPP;
2066 			break;
2067 		}
2068 
2069 		/* Don't let users screw up protocols' entries. */
2070 		if (ifr->ifr_addr.sa_family != AF_LINK) {
2071 			error = EINVAL;
2072 			break;
2073 		}
2074 
2075 		if (cmd == SIOCADDMULTI) {
2076 			struct ifmultiaddr *ifma;
2077 			error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2078 		} else {
2079 			error = if_delmulti(ifp, &ifr->ifr_addr);
2080 		}
2081 		if (error == 0)
2082 			getmicrotime(&ifp->if_lastchange);
2083 		break;
2084 
2085 	case SIOCSIFPHYADDR:
2086 	case SIOCDIFPHYADDR:
2087 #ifdef INET6
2088 	case SIOCSIFPHYADDR_IN6:
2089 #endif
2090 	case SIOCSLIFPHYADDR:
2091         case SIOCSIFMEDIA:
2092 	case SIOCSIFGENERIC:
2093 		error = priv_check_cred(cred, PRIV_ROOT, 0);
2094 		if (error)
2095 			break;
2096 		if (ifp->if_ioctl == 0) {
2097 			error = EOPNOTSUPP;
2098 			break;
2099 		}
2100 		ifnet_serialize_all(ifp);
2101 		error = ifp->if_ioctl(ifp, cmd, data, cred);
2102 		ifnet_deserialize_all(ifp);
2103 		if (error == 0)
2104 			getmicrotime(&ifp->if_lastchange);
2105 		break;
2106 
2107 	case SIOCGIFSTATUS:
2108 		ifs = (struct ifstat *)data;
2109 		ifs->ascii[0] = '\0';
2110 		/* fall through */
2111 	case SIOCGIFPSRCADDR:
2112 	case SIOCGIFPDSTADDR:
2113 	case SIOCGLIFPHYADDR:
2114 	case SIOCGIFMEDIA:
2115 	case SIOCGIFGENERIC:
2116 		if (ifp->if_ioctl == NULL) {
2117 			error = EOPNOTSUPP;
2118 			break;
2119 		}
2120 		ifnet_serialize_all(ifp);
2121 		error = ifp->if_ioctl(ifp, cmd, data, cred);
2122 		ifnet_deserialize_all(ifp);
2123 		break;
2124 
2125 	case SIOCSIFLLADDR:
2126 		error = priv_check_cred(cred, PRIV_ROOT, 0);
2127 		if (error)
2128 			break;
2129 		error = if_setlladdr(ifp, ifr->ifr_addr.sa_data,
2130 				     ifr->ifr_addr.sa_len);
2131 		EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2132 		break;
2133 
2134 	default:
2135 		oif_flags = ifp->if_flags;
2136 		if (so->so_proto == 0) {
2137 			error = EOPNOTSUPP;
2138 			break;
2139 		}
2140 		error = so_pru_control_direct(so, cmd, data, ifp);
2141 
2142 		if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2143 #ifdef INET6
2144 			DELAY(100);/* XXX: temporary workaround for fxp issue*/
2145 			if (ifp->if_flags & IFF_UP) {
2146 				crit_enter();
2147 				in6_if_up(ifp);
2148 				crit_exit();
2149 			}
2150 #endif
2151 		}
2152 		break;
2153 	}
2154 
2155 	ifnet_unlock();
2156 	return (error);
2157 }
2158 
2159 /*
2160  * Set/clear promiscuous mode on interface ifp based on the truth value
2161  * of pswitch.  The calls are reference counted so that only the first
2162  * "on" request actually has an effect, as does the final "off" request.
2163  * Results are undefined if the "off" and "on" requests are not matched.
2164  */
2165 int
2166 ifpromisc(struct ifnet *ifp, int pswitch)
2167 {
2168 	struct ifreq ifr;
2169 	int error;
2170 	int oldflags;
2171 
2172 	oldflags = ifp->if_flags;
2173 	if (ifp->if_flags & IFF_PPROMISC) {
2174 		/* Do nothing if device is in permanently promiscuous mode */
2175 		ifp->if_pcount += pswitch ? 1 : -1;
2176 		return (0);
2177 	}
2178 	if (pswitch) {
2179 		/*
2180 		 * If the device is not configured up, we cannot put it in
2181 		 * promiscuous mode.
2182 		 */
2183 		if ((ifp->if_flags & IFF_UP) == 0)
2184 			return (ENETDOWN);
2185 		if (ifp->if_pcount++ != 0)
2186 			return (0);
2187 		ifp->if_flags |= IFF_PROMISC;
2188 		log(LOG_INFO, "%s: promiscuous mode enabled\n",
2189 		    ifp->if_xname);
2190 	} else {
2191 		if (--ifp->if_pcount > 0)
2192 			return (0);
2193 		ifp->if_flags &= ~IFF_PROMISC;
2194 		log(LOG_INFO, "%s: promiscuous mode disabled\n",
2195 		    ifp->if_xname);
2196 	}
2197 	ifr.ifr_flags = ifp->if_flags;
2198 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2199 	ifnet_serialize_all(ifp);
2200 	error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
2201 	ifnet_deserialize_all(ifp);
2202 	if (error == 0)
2203 		rt_ifmsg(ifp);
2204 	else
2205 		ifp->if_flags = oldflags;
2206 	return error;
2207 }
2208 
2209 /*
2210  * Return interface configuration
2211  * of system.  List may be used
2212  * in later ioctl's (above) to get
2213  * other information.
2214  */
2215 static int
2216 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
2217 {
2218 	struct ifconf *ifc = (struct ifconf *)data;
2219 	struct ifnet *ifp;
2220 	struct sockaddr *sa;
2221 	struct ifreq ifr, *ifrp;
2222 	int space = ifc->ifc_len, error = 0;
2223 
2224 	ifrp = ifc->ifc_req;
2225 
2226 	ifnet_lock();
2227 	TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2228 		struct ifaddr_container *ifac, *ifac_mark;
2229 		struct ifaddr_marker mark;
2230 		struct ifaddrhead *head;
2231 		int addrs;
2232 
2233 		if (space <= sizeof ifr)
2234 			break;
2235 
2236 		/*
2237 		 * Zero the stack declared structure first to prevent
2238 		 * memory disclosure.
2239 		 */
2240 		bzero(&ifr, sizeof(ifr));
2241 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2242 		    >= sizeof(ifr.ifr_name)) {
2243 			error = ENAMETOOLONG;
2244 			break;
2245 		}
2246 
2247 		/*
2248 		 * Add a marker, since copyout() could block and during that
2249 		 * period the list could be changed.  Inserting the marker to
2250 		 * the header of the list will not cause trouble for the code
2251 		 * assuming that the first element of the list is AF_LINK; the
2252 		 * marker will be moved to the next position w/o blocking.
2253 		 */
2254 		ifa_marker_init(&mark, ifp);
2255 		ifac_mark = &mark.ifac;
2256 		head = &ifp->if_addrheads[mycpuid];
2257 
2258 		addrs = 0;
2259 		TAILQ_INSERT_HEAD(head, ifac_mark, ifa_link);
2260 		while ((ifac = TAILQ_NEXT(ifac_mark, ifa_link)) != NULL) {
2261 			struct ifaddr *ifa = ifac->ifa;
2262 
2263 			TAILQ_REMOVE(head, ifac_mark, ifa_link);
2264 			TAILQ_INSERT_AFTER(head, ifac, ifac_mark, ifa_link);
2265 
2266 			/* Ignore marker */
2267 			if (ifa->ifa_addr->sa_family == AF_UNSPEC)
2268 				continue;
2269 
2270 			if (space <= sizeof ifr)
2271 				break;
2272 			sa = ifa->ifa_addr;
2273 			if (cred->cr_prison &&
2274 			    prison_if(cred, sa))
2275 				continue;
2276 			addrs++;
2277 			/*
2278 			 * Keep a reference on this ifaddr, so that it will
2279 			 * not be destroyed when its address is copied to
2280 			 * the userland, which could block.
2281 			 */
2282 			IFAREF(ifa);
2283 			if (sa->sa_len <= sizeof(*sa)) {
2284 				ifr.ifr_addr = *sa;
2285 				error = copyout(&ifr, ifrp, sizeof ifr);
2286 				ifrp++;
2287 			} else {
2288 				if (space < (sizeof ifr) + sa->sa_len -
2289 					    sizeof(*sa)) {
2290 					IFAFREE(ifa);
2291 					break;
2292 				}
2293 				space -= sa->sa_len - sizeof(*sa);
2294 				error = copyout(&ifr, ifrp,
2295 						sizeof ifr.ifr_name);
2296 				if (error == 0)
2297 					error = copyout(sa, &ifrp->ifr_addr,
2298 							sa->sa_len);
2299 				ifrp = (struct ifreq *)
2300 					(sa->sa_len + (caddr_t)&ifrp->ifr_addr);
2301 			}
2302 			IFAFREE(ifa);
2303 			if (error)
2304 				break;
2305 			space -= sizeof ifr;
2306 		}
2307 		TAILQ_REMOVE(head, ifac_mark, ifa_link);
2308 		if (error)
2309 			break;
2310 		if (!addrs) {
2311 			bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
2312 			error = copyout(&ifr, ifrp, sizeof ifr);
2313 			if (error)
2314 				break;
2315 			space -= sizeof ifr;
2316 			ifrp++;
2317 		}
2318 	}
2319 	ifnet_unlock();
2320 
2321 	ifc->ifc_len -= space;
2322 	return (error);
2323 }
2324 
2325 /*
2326  * Just like if_promisc(), but for all-multicast-reception mode.
2327  */
2328 int
2329 if_allmulti(struct ifnet *ifp, int onswitch)
2330 {
2331 	int error = 0;
2332 	struct ifreq ifr;
2333 
2334 	crit_enter();
2335 
2336 	if (onswitch) {
2337 		if (ifp->if_amcount++ == 0) {
2338 			ifp->if_flags |= IFF_ALLMULTI;
2339 			ifr.ifr_flags = ifp->if_flags;
2340 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
2341 			ifnet_serialize_all(ifp);
2342 			error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2343 					      NULL);
2344 			ifnet_deserialize_all(ifp);
2345 		}
2346 	} else {
2347 		if (ifp->if_amcount > 1) {
2348 			ifp->if_amcount--;
2349 		} else {
2350 			ifp->if_amcount = 0;
2351 			ifp->if_flags &= ~IFF_ALLMULTI;
2352 			ifr.ifr_flags = ifp->if_flags;
2353 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
2354 			ifnet_serialize_all(ifp);
2355 			error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2356 					      NULL);
2357 			ifnet_deserialize_all(ifp);
2358 		}
2359 	}
2360 
2361 	crit_exit();
2362 
2363 	if (error == 0)
2364 		rt_ifmsg(ifp);
2365 	return error;
2366 }
2367 
2368 /*
2369  * Add a multicast listenership to the interface in question.
2370  * The link layer provides a routine which converts
2371  */
2372 int
2373 if_addmulti_serialized(struct ifnet *ifp, struct sockaddr *sa,
2374     struct ifmultiaddr **retifma)
2375 {
2376 	struct sockaddr *llsa, *dupsa;
2377 	int error;
2378 	struct ifmultiaddr *ifma;
2379 
2380 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
2381 
2382 	/*
2383 	 * If the matching multicast address already exists
2384 	 * then don't add a new one, just add a reference
2385 	 */
2386 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2387 		if (sa_equal(sa, ifma->ifma_addr)) {
2388 			ifma->ifma_refcount++;
2389 			if (retifma)
2390 				*retifma = ifma;
2391 			return 0;
2392 		}
2393 	}
2394 
2395 	/*
2396 	 * Give the link layer a chance to accept/reject it, and also
2397 	 * find out which AF_LINK address this maps to, if it isn't one
2398 	 * already.
2399 	 */
2400 	if (ifp->if_resolvemulti) {
2401 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
2402 		if (error)
2403 			return error;
2404 	} else {
2405 		llsa = NULL;
2406 	}
2407 
2408 	ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2409 	dupsa = kmalloc(sa->sa_len, M_IFMADDR, M_INTWAIT);
2410 	bcopy(sa, dupsa, sa->sa_len);
2411 
2412 	ifma->ifma_addr = dupsa;
2413 	ifma->ifma_lladdr = llsa;
2414 	ifma->ifma_ifp = ifp;
2415 	ifma->ifma_refcount = 1;
2416 	ifma->ifma_protospec = NULL;
2417 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2418 
2419 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2420 	if (retifma)
2421 		*retifma = ifma;
2422 
2423 	if (llsa != NULL) {
2424 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2425 			if (sa_equal(ifma->ifma_addr, llsa))
2426 				break;
2427 		}
2428 		if (ifma) {
2429 			ifma->ifma_refcount++;
2430 		} else {
2431 			ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2432 			dupsa = kmalloc(llsa->sa_len, M_IFMADDR, M_INTWAIT);
2433 			bcopy(llsa, dupsa, llsa->sa_len);
2434 			ifma->ifma_addr = dupsa;
2435 			ifma->ifma_ifp = ifp;
2436 			ifma->ifma_refcount = 1;
2437 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2438 		}
2439 	}
2440 	/*
2441 	 * We are certain we have added something, so call down to the
2442 	 * interface to let them know about it.
2443 	 */
2444 	if (ifp->if_ioctl)
2445 		ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2446 
2447 	return 0;
2448 }
2449 
2450 int
2451 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2452     struct ifmultiaddr **retifma)
2453 {
2454 	int error;
2455 
2456 	ifnet_serialize_all(ifp);
2457 	error = if_addmulti_serialized(ifp, sa, retifma);
2458 	ifnet_deserialize_all(ifp);
2459 
2460 	return error;
2461 }
2462 
2463 /*
2464  * Remove a reference to a multicast address on this interface.  Yell
2465  * if the request does not match an existing membership.
2466  */
2467 static int
2468 if_delmulti_serialized(struct ifnet *ifp, struct sockaddr *sa)
2469 {
2470 	struct ifmultiaddr *ifma;
2471 
2472 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
2473 
2474 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2475 		if (sa_equal(sa, ifma->ifma_addr))
2476 			break;
2477 	if (ifma == NULL)
2478 		return ENOENT;
2479 
2480 	if (ifma->ifma_refcount > 1) {
2481 		ifma->ifma_refcount--;
2482 		return 0;
2483 	}
2484 
2485 	rt_newmaddrmsg(RTM_DELMADDR, ifma);
2486 	sa = ifma->ifma_lladdr;
2487 	TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2488 	/*
2489 	 * Make sure the interface driver is notified
2490 	 * in the case of a link layer mcast group being left.
2491 	 */
2492 	if (ifma->ifma_addr->sa_family == AF_LINK && sa == NULL)
2493 		ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2494 	kfree(ifma->ifma_addr, M_IFMADDR);
2495 	kfree(ifma, M_IFMADDR);
2496 	if (sa == NULL)
2497 		return 0;
2498 
2499 	/*
2500 	 * Now look for the link-layer address which corresponds to
2501 	 * this network address.  It had been squirreled away in
2502 	 * ifma->ifma_lladdr for this purpose (so we don't have
2503 	 * to call ifp->if_resolvemulti() again), and we saved that
2504 	 * value in sa above.  If some nasty deleted the
2505 	 * link-layer address out from underneath us, we can deal because
2506 	 * the address we stored was is not the same as the one which was
2507 	 * in the record for the link-layer address.  (So we don't complain
2508 	 * in that case.)
2509 	 */
2510 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2511 		if (sa_equal(sa, ifma->ifma_addr))
2512 			break;
2513 	if (ifma == NULL)
2514 		return 0;
2515 
2516 	if (ifma->ifma_refcount > 1) {
2517 		ifma->ifma_refcount--;
2518 		return 0;
2519 	}
2520 
2521 	TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2522 	ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2523 	kfree(ifma->ifma_addr, M_IFMADDR);
2524 	kfree(sa, M_IFMADDR);
2525 	kfree(ifma, M_IFMADDR);
2526 
2527 	return 0;
2528 }
2529 
2530 int
2531 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2532 {
2533 	int error;
2534 
2535 	ifnet_serialize_all(ifp);
2536 	error = if_delmulti_serialized(ifp, sa);
2537 	ifnet_deserialize_all(ifp);
2538 
2539 	return error;
2540 }
2541 
2542 /*
2543  * Delete all multicast group membership for an interface.
2544  * Should be used to quickly flush all multicast filters.
2545  */
2546 void
2547 if_delallmulti_serialized(struct ifnet *ifp)
2548 {
2549 	struct ifmultiaddr *ifma, mark;
2550 	struct sockaddr sa;
2551 
2552 	ASSERT_IFNET_SERIALIZED_ALL(ifp);
2553 
2554 	bzero(&sa, sizeof(sa));
2555 	sa.sa_family = AF_UNSPEC;
2556 	sa.sa_len = sizeof(sa);
2557 
2558 	bzero(&mark, sizeof(mark));
2559 	mark.ifma_addr = &sa;
2560 
2561 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, &mark, ifma_link);
2562 	while ((ifma = TAILQ_NEXT(&mark, ifma_link)) != NULL) {
2563 		TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2564 		TAILQ_INSERT_AFTER(&ifp->if_multiaddrs, ifma, &mark,
2565 		    ifma_link);
2566 
2567 		if (ifma->ifma_addr->sa_family == AF_UNSPEC)
2568 			continue;
2569 
2570 		if_delmulti_serialized(ifp, ifma->ifma_addr);
2571 	}
2572 	TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2573 }
2574 
2575 
2576 /*
2577  * Set the link layer address on an interface.
2578  *
2579  * At this time we only support certain types of interfaces,
2580  * and we don't allow the length of the address to change.
2581  */
2582 int
2583 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2584 {
2585 	struct sockaddr_dl *sdl;
2586 	struct ifreq ifr;
2587 
2588 	sdl = IF_LLSOCKADDR(ifp);
2589 	if (sdl == NULL)
2590 		return (EINVAL);
2591 	if (len != sdl->sdl_alen)	/* don't allow length to change */
2592 		return (EINVAL);
2593 	switch (ifp->if_type) {
2594 	case IFT_ETHER:			/* these types use struct arpcom */
2595 	case IFT_XETHER:
2596 	case IFT_L2VLAN:
2597 	case IFT_IEEE8023ADLAG:
2598 		bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2599 		bcopy(lladdr, LLADDR(sdl), len);
2600 		break;
2601 	default:
2602 		return (ENODEV);
2603 	}
2604 	/*
2605 	 * If the interface is already up, we need
2606 	 * to re-init it in order to reprogram its
2607 	 * address filter.
2608 	 */
2609 	ifnet_serialize_all(ifp);
2610 	if ((ifp->if_flags & IFF_UP) != 0) {
2611 #ifdef INET
2612 		struct ifaddr_container *ifac;
2613 #endif
2614 
2615 		ifp->if_flags &= ~IFF_UP;
2616 		ifr.ifr_flags = ifp->if_flags;
2617 		ifr.ifr_flagshigh = ifp->if_flags >> 16;
2618 		ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2619 			      NULL);
2620 		ifp->if_flags |= IFF_UP;
2621 		ifr.ifr_flags = ifp->if_flags;
2622 		ifr.ifr_flagshigh = ifp->if_flags >> 16;
2623 		ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2624 				 NULL);
2625 #ifdef INET
2626 		/*
2627 		 * Also send gratuitous ARPs to notify other nodes about
2628 		 * the address change.
2629 		 */
2630 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2631 			struct ifaddr *ifa = ifac->ifa;
2632 
2633 			if (ifa->ifa_addr != NULL &&
2634 			    ifa->ifa_addr->sa_family == AF_INET)
2635 				arp_gratuitous(ifp, ifa);
2636 		}
2637 #endif
2638 	}
2639 	ifnet_deserialize_all(ifp);
2640 	return (0);
2641 }
2642 
2643 struct ifmultiaddr *
2644 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2645 {
2646 	struct ifmultiaddr *ifma;
2647 
2648 	/* TODO: need ifnet_serialize_main */
2649 	ifnet_serialize_all(ifp);
2650 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2651 		if (sa_equal(ifma->ifma_addr, sa))
2652 			break;
2653 	ifnet_deserialize_all(ifp);
2654 
2655 	return ifma;
2656 }
2657 
2658 /*
2659  * This function locates the first real ethernet MAC from a network
2660  * card and loads it into node, returning 0 on success or ENOENT if
2661  * no suitable interfaces were found.  It is used by the uuid code to
2662  * generate a unique 6-byte number.
2663  */
2664 int
2665 if_getanyethermac(uint16_t *node, int minlen)
2666 {
2667 	struct ifnet *ifp;
2668 	struct sockaddr_dl *sdl;
2669 
2670 	ifnet_lock();
2671 	TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2672 		if (ifp->if_type != IFT_ETHER)
2673 			continue;
2674 		sdl = IF_LLSOCKADDR(ifp);
2675 		if (sdl->sdl_alen < minlen)
2676 			continue;
2677 		bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2678 		      minlen);
2679 		ifnet_unlock();
2680 		return(0);
2681 	}
2682 	ifnet_unlock();
2683 	return (ENOENT);
2684 }
2685 
2686 /*
2687  * The name argument must be a pointer to storage which will last as
2688  * long as the interface does.  For physical devices, the result of
2689  * device_get_name(dev) is a good choice and for pseudo-devices a
2690  * static string works well.
2691  */
2692 void
2693 if_initname(struct ifnet *ifp, const char *name, int unit)
2694 {
2695 	ifp->if_dname = name;
2696 	ifp->if_dunit = unit;
2697 	if (unit != IF_DUNIT_NONE)
2698 		ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2699 	else
2700 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
2701 }
2702 
2703 int
2704 if_printf(struct ifnet *ifp, const char *fmt, ...)
2705 {
2706 	__va_list ap;
2707 	int retval;
2708 
2709 	retval = kprintf("%s: ", ifp->if_xname);
2710 	__va_start(ap, fmt);
2711 	retval += kvprintf(fmt, ap);
2712 	__va_end(ap);
2713 	return (retval);
2714 }
2715 
2716 struct ifnet *
2717 if_alloc(uint8_t type)
2718 {
2719         struct ifnet *ifp;
2720 	size_t size;
2721 
2722 	/*
2723 	 * XXX temporary hack until arpcom is setup in if_l2com
2724 	 */
2725 	if (type == IFT_ETHER)
2726 		size = sizeof(struct arpcom);
2727 	else
2728 		size = sizeof(struct ifnet);
2729 
2730 	ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2731 
2732 	ifp->if_type = type;
2733 
2734 	if (if_com_alloc[type] != NULL) {
2735 		ifp->if_l2com = if_com_alloc[type](type, ifp);
2736 		if (ifp->if_l2com == NULL) {
2737 			kfree(ifp, M_IFNET);
2738 			return (NULL);
2739 		}
2740 	}
2741 	return (ifp);
2742 }
2743 
2744 void
2745 if_free(struct ifnet *ifp)
2746 {
2747 	kfree(ifp, M_IFNET);
2748 }
2749 
2750 void
2751 ifq_set_classic(struct ifaltq *ifq)
2752 {
2753 	ifq_set_methods(ifq, ifq->altq_ifp->if_mapsubq,
2754 	    ifsq_classic_enqueue, ifsq_classic_dequeue, ifsq_classic_request);
2755 }
2756 
2757 void
2758 ifq_set_methods(struct ifaltq *ifq, altq_mapsubq_t mapsubq,
2759     ifsq_enqueue_t enqueue, ifsq_dequeue_t dequeue, ifsq_request_t request)
2760 {
2761 	int q;
2762 
2763 	KASSERT(mapsubq != NULL, ("mapsubq is not specified"));
2764 	KASSERT(enqueue != NULL, ("enqueue is not specified"));
2765 	KASSERT(dequeue != NULL, ("dequeue is not specified"));
2766 	KASSERT(request != NULL, ("request is not specified"));
2767 
2768 	ifq->altq_mapsubq = mapsubq;
2769 	for (q = 0; q < ifq->altq_subq_cnt; ++q) {
2770 		struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
2771 
2772 		ifsq->ifsq_enqueue = enqueue;
2773 		ifsq->ifsq_dequeue = dequeue;
2774 		ifsq->ifsq_request = request;
2775 	}
2776 }
2777 
2778 static void
2779 ifsq_norm_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2780 {
2781 
2782 	classq_add(&ifsq->ifsq_norm, m);
2783 	ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2784 }
2785 
2786 static void
2787 ifsq_prio_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2788 {
2789 
2790 	classq_add(&ifsq->ifsq_prio, m);
2791 	ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2792 	ALTQ_SQ_PRIO_CNTR_INC(ifsq, m->m_pkthdr.len);
2793 }
2794 
2795 static struct mbuf *
2796 ifsq_norm_dequeue(struct ifaltq_subque *ifsq)
2797 {
2798 	struct mbuf *m;
2799 
2800 	m = classq_get(&ifsq->ifsq_norm);
2801 	if (m != NULL)
2802 		ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2803 	return (m);
2804 }
2805 
2806 static struct mbuf *
2807 ifsq_prio_dequeue(struct ifaltq_subque *ifsq)
2808 {
2809 	struct mbuf *m;
2810 
2811 	m = classq_get(&ifsq->ifsq_prio);
2812 	if (m != NULL) {
2813 		ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2814 		ALTQ_SQ_PRIO_CNTR_DEC(ifsq, m->m_pkthdr.len);
2815 	}
2816 	return (m);
2817 }
2818 
2819 int
2820 ifsq_classic_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m,
2821     struct altq_pktattr *pa __unused)
2822 {
2823 
2824 	M_ASSERTPKTHDR(m);
2825 again:
2826 	if (ifsq->ifsq_len >= ifsq->ifsq_maxlen ||
2827 	    ifsq->ifsq_bcnt >= ifsq->ifsq_maxbcnt) {
2828 		struct mbuf *m_drop;
2829 
2830 		if (m->m_flags & M_PRIO) {
2831 			m_drop = NULL;
2832 			if (ifsq->ifsq_prio_len < (ifsq->ifsq_maxlen >> 1) &&
2833 			    ifsq->ifsq_prio_bcnt < (ifsq->ifsq_maxbcnt >> 1)) {
2834 				/* Try dropping some from normal queue. */
2835 				m_drop = ifsq_norm_dequeue(ifsq);
2836 			}
2837 			if (m_drop == NULL)
2838 				m_drop = ifsq_prio_dequeue(ifsq);
2839 		} else {
2840 			m_drop = ifsq_norm_dequeue(ifsq);
2841 		}
2842 		if (m_drop != NULL) {
2843 			IFNET_STAT_INC(ifsq->ifsq_ifp, oqdrops, 1);
2844 			m_freem(m_drop);
2845 			goto again;
2846 		}
2847 		/*
2848 		 * No old packets could be dropped!
2849 		 * NOTE: Caller increases oqdrops.
2850 		 */
2851 		m_freem(m);
2852 		return (ENOBUFS);
2853 	} else {
2854 		if (m->m_flags & M_PRIO)
2855 			ifsq_prio_enqueue(ifsq, m);
2856 		else
2857 			ifsq_norm_enqueue(ifsq, m);
2858 		return (0);
2859 	}
2860 }
2861 
2862 struct mbuf *
2863 ifsq_classic_dequeue(struct ifaltq_subque *ifsq, int op)
2864 {
2865 	struct mbuf *m;
2866 
2867 	switch (op) {
2868 	case ALTDQ_POLL:
2869 		m = classq_head(&ifsq->ifsq_prio);
2870 		if (m == NULL)
2871 			m = classq_head(&ifsq->ifsq_norm);
2872 		break;
2873 
2874 	case ALTDQ_REMOVE:
2875 		m = ifsq_prio_dequeue(ifsq);
2876 		if (m == NULL)
2877 			m = ifsq_norm_dequeue(ifsq);
2878 		break;
2879 
2880 	default:
2881 		panic("unsupported ALTQ dequeue op: %d", op);
2882 	}
2883 	return m;
2884 }
2885 
2886 int
2887 ifsq_classic_request(struct ifaltq_subque *ifsq, int req, void *arg)
2888 {
2889 	switch (req) {
2890 	case ALTRQ_PURGE:
2891 		for (;;) {
2892 			struct mbuf *m;
2893 
2894 			m = ifsq_classic_dequeue(ifsq, ALTDQ_REMOVE);
2895 			if (m == NULL)
2896 				break;
2897 			m_freem(m);
2898 		}
2899 		break;
2900 
2901 	default:
2902 		panic("unsupported ALTQ request: %d", req);
2903 	}
2904 	return 0;
2905 }
2906 
2907 static void
2908 ifsq_ifstart_try(struct ifaltq_subque *ifsq, int force_sched)
2909 {
2910 	struct ifnet *ifp = ifsq_get_ifp(ifsq);
2911 	int running = 0, need_sched;
2912 
2913 	/*
2914 	 * Try to do direct ifnet.if_start on the subqueue first, if there is
2915 	 * contention on the subqueue hardware serializer, ifnet.if_start on
2916 	 * the subqueue will be scheduled on the subqueue owner CPU.
2917 	 */
2918 	if (!ifsq_tryserialize_hw(ifsq)) {
2919 		/*
2920 		 * Subqueue hardware serializer contention happened,
2921 		 * ifnet.if_start on the subqueue is scheduled on
2922 		 * the subqueue owner CPU, and we keep going.
2923 		 */
2924 		ifsq_ifstart_schedule(ifsq, 1);
2925 		return;
2926 	}
2927 
2928 	if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
2929 		ifp->if_start(ifp, ifsq);
2930 		if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
2931 			running = 1;
2932 	}
2933 	need_sched = ifsq_ifstart_need_schedule(ifsq, running);
2934 
2935 	ifsq_deserialize_hw(ifsq);
2936 
2937 	if (need_sched) {
2938 		/*
2939 		 * More data need to be transmitted, ifnet.if_start on the
2940 		 * subqueue is scheduled on the subqueue owner CPU, and we
2941 		 * keep going.
2942 		 * NOTE: ifnet.if_start subqueue interlock is not released.
2943 		 */
2944 		ifsq_ifstart_schedule(ifsq, force_sched);
2945 	}
2946 }
2947 
2948 /*
2949  * Subqeue packets staging mechanism:
2950  *
2951  * The packets enqueued into the subqueue are staged to a certain amount
2952  * before the ifnet.if_start on the subqueue is called.  In this way, the
2953  * driver could avoid writing to hardware registers upon every packet,
2954  * instead, hardware registers could be written when certain amount of
2955  * packets are put onto hardware TX ring.  The measurement on several modern
2956  * NICs (emx(4), igb(4), bnx(4), bge(4), jme(4)) shows that the hardware
2957  * registers writing aggregation could save ~20% CPU time when 18bytes UDP
2958  * datagrams are transmitted at 1.48Mpps.  The performance improvement by
2959  * hardware registers writing aggeregation is also mentioned by Luigi Rizzo's
2960  * netmap paper (http://info.iet.unipi.it/~luigi/netmap/).
2961  *
2962  * Subqueue packets staging is performed for two entry points into drivers'
2963  * transmission function:
2964  * - Direct ifnet.if_start calling on the subqueue, i.e. ifsq_ifstart_try()
2965  * - ifnet.if_start scheduling on the subqueue, i.e. ifsq_ifstart_schedule()
2966  *
2967  * Subqueue packets staging will be stopped upon any of the following
2968  * conditions:
2969  * - If the count of packets enqueued on the current CPU is great than or
2970  *   equal to ifsq_stage_cntmax. (XXX this should be per-interface)
2971  * - If the total length of packets enqueued on the current CPU is great
2972  *   than or equal to the hardware's MTU - max_protohdr.  max_protohdr is
2973  *   cut from the hardware's MTU mainly bacause a full TCP segment's size
2974  *   is usually less than hardware's MTU.
2975  * - ifsq_ifstart_schedule() is not pending on the current CPU and
2976  *   ifnet.if_start subqueue interlock (ifaltq_subq.ifsq_started) is not
2977  *   released.
2978  * - The if_start_rollup(), which is registered as low priority netisr
2979  *   rollup function, is called; probably because no more work is pending
2980  *   for netisr.
2981  *
2982  * NOTE:
2983  * Currently subqueue packet staging is only performed in netisr threads.
2984  */
2985 int
2986 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
2987 {
2988 	struct ifaltq *ifq = &ifp->if_snd;
2989 	struct ifaltq_subque *ifsq;
2990 	int error, start = 0, len, mcast = 0, avoid_start = 0;
2991 	struct ifsubq_stage_head *head = NULL;
2992 	struct ifsubq_stage *stage = NULL;
2993 	struct globaldata *gd = mycpu;
2994 	struct thread *td = gd->gd_curthread;
2995 
2996 	crit_enter_quick(td);
2997 
2998 	ifsq = ifq_map_subq(ifq, gd->gd_cpuid);
2999 	ASSERT_ALTQ_SQ_NOT_SERIALIZED_HW(ifsq);
3000 
3001 	len = m->m_pkthdr.len;
3002 	if (m->m_flags & M_MCAST)
3003 		mcast = 1;
3004 
3005 	if (td->td_type == TD_TYPE_NETISR) {
3006 		head = &ifsubq_stage_heads[mycpuid];
3007 		stage = ifsq_get_stage(ifsq, mycpuid);
3008 
3009 		stage->stg_cnt++;
3010 		stage->stg_len += len;
3011 		if (stage->stg_cnt < ifsq_stage_cntmax &&
3012 		    stage->stg_len < (ifp->if_mtu - max_protohdr))
3013 			avoid_start = 1;
3014 	}
3015 
3016 	ALTQ_SQ_LOCK(ifsq);
3017 	error = ifsq_enqueue_locked(ifsq, m, pa);
3018 	if (error) {
3019 		IFNET_STAT_INC(ifp, oqdrops, 1);
3020 		if (!ifsq_data_ready(ifsq)) {
3021 			ALTQ_SQ_UNLOCK(ifsq);
3022 			crit_exit_quick(td);
3023 			return error;
3024 		}
3025 		avoid_start = 0;
3026 	}
3027 	if (!ifsq_is_started(ifsq)) {
3028 		if (avoid_start) {
3029 			ALTQ_SQ_UNLOCK(ifsq);
3030 
3031 			KKASSERT(!error);
3032 			if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
3033 				ifsq_stage_insert(head, stage);
3034 
3035 			IFNET_STAT_INC(ifp, obytes, len);
3036 			if (mcast)
3037 				IFNET_STAT_INC(ifp, omcasts, 1);
3038 			crit_exit_quick(td);
3039 			return error;
3040 		}
3041 
3042 		/*
3043 		 * Hold the subqueue interlock of ifnet.if_start
3044 		 */
3045 		ifsq_set_started(ifsq);
3046 		start = 1;
3047 	}
3048 	ALTQ_SQ_UNLOCK(ifsq);
3049 
3050 	if (!error) {
3051 		IFNET_STAT_INC(ifp, obytes, len);
3052 		if (mcast)
3053 			IFNET_STAT_INC(ifp, omcasts, 1);
3054 	}
3055 
3056 	if (stage != NULL) {
3057 		if (!start && (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)) {
3058 			KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
3059 			if (!avoid_start) {
3060 				ifsq_stage_remove(head, stage);
3061 				ifsq_ifstart_schedule(ifsq, 1);
3062 			}
3063 			crit_exit_quick(td);
3064 			return error;
3065 		}
3066 
3067 		if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED) {
3068 			ifsq_stage_remove(head, stage);
3069 		} else {
3070 			stage->stg_cnt = 0;
3071 			stage->stg_len = 0;
3072 		}
3073 	}
3074 
3075 	if (!start) {
3076 		crit_exit_quick(td);
3077 		return error;
3078 	}
3079 
3080 	ifsq_ifstart_try(ifsq, 0);
3081 
3082 	crit_exit_quick(td);
3083 	return error;
3084 }
3085 
3086 void *
3087 ifa_create(int size)
3088 {
3089 	struct ifaddr *ifa;
3090 	int i;
3091 
3092 	KASSERT(size >= sizeof(*ifa), ("ifaddr size too small"));
3093 
3094 	ifa = kmalloc(size, M_IFADDR, M_INTWAIT | M_ZERO);
3095 	ifa->ifa_containers =
3096 	    kmalloc_cachealign(ncpus * sizeof(struct ifaddr_container),
3097 	        M_IFADDR, M_INTWAIT | M_ZERO);
3098 
3099 	ifa->ifa_ncnt = ncpus;
3100 	for (i = 0; i < ncpus; ++i) {
3101 		struct ifaddr_container *ifac = &ifa->ifa_containers[i];
3102 
3103 		ifac->ifa_magic = IFA_CONTAINER_MAGIC;
3104 		ifac->ifa = ifa;
3105 		ifac->ifa_refcnt = 1;
3106 	}
3107 #ifdef IFADDR_DEBUG
3108 	kprintf("alloc ifa %p %d\n", ifa, size);
3109 #endif
3110 	return ifa;
3111 }
3112 
3113 void
3114 ifac_free(struct ifaddr_container *ifac, int cpu_id)
3115 {
3116 	struct ifaddr *ifa = ifac->ifa;
3117 
3118 	KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
3119 	KKASSERT(ifac->ifa_refcnt == 0);
3120 	KASSERT(ifac->ifa_listmask == 0,
3121 		("ifa is still on %#x lists", ifac->ifa_listmask));
3122 
3123 	ifac->ifa_magic = IFA_CONTAINER_DEAD;
3124 
3125 #ifdef IFADDR_DEBUG_VERBOSE
3126 	kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
3127 #endif
3128 
3129 	KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
3130 		("invalid # of ifac, %d", ifa->ifa_ncnt));
3131 	if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
3132 #ifdef IFADDR_DEBUG
3133 		kprintf("free ifa %p\n", ifa);
3134 #endif
3135 		kfree(ifa->ifa_containers, M_IFADDR);
3136 		kfree(ifa, M_IFADDR);
3137 	}
3138 }
3139 
3140 static void
3141 ifa_iflink_dispatch(netmsg_t nmsg)
3142 {
3143 	struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3144 	struct ifaddr *ifa = msg->ifa;
3145 	struct ifnet *ifp = msg->ifp;
3146 	int cpu = mycpuid;
3147 	struct ifaddr_container *ifac;
3148 
3149 	crit_enter();
3150 
3151 	ifac = &ifa->ifa_containers[cpu];
3152 	ASSERT_IFAC_VALID(ifac);
3153 	KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
3154 		("ifaddr is on if_addrheads"));
3155 
3156 	ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
3157 	if (msg->tail)
3158 		TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
3159 	else
3160 		TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
3161 
3162 	crit_exit();
3163 
3164 	netisr_forwardmsg(&nmsg->base, cpu + 1);
3165 }
3166 
3167 void
3168 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
3169 {
3170 	struct netmsg_ifaddr msg;
3171 
3172 	netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3173 		    0, ifa_iflink_dispatch);
3174 	msg.ifa = ifa;
3175 	msg.ifp = ifp;
3176 	msg.tail = tail;
3177 
3178 	netisr_domsg(&msg.base, 0);
3179 }
3180 
3181 static void
3182 ifa_ifunlink_dispatch(netmsg_t nmsg)
3183 {
3184 	struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3185 	struct ifaddr *ifa = msg->ifa;
3186 	struct ifnet *ifp = msg->ifp;
3187 	int cpu = mycpuid;
3188 	struct ifaddr_container *ifac;
3189 
3190 	crit_enter();
3191 
3192 	ifac = &ifa->ifa_containers[cpu];
3193 	ASSERT_IFAC_VALID(ifac);
3194 	KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
3195 		("ifaddr is not on if_addrhead"));
3196 
3197 	TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
3198 	ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
3199 
3200 	crit_exit();
3201 
3202 	netisr_forwardmsg(&nmsg->base, cpu + 1);
3203 }
3204 
3205 void
3206 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
3207 {
3208 	struct netmsg_ifaddr msg;
3209 
3210 	netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3211 		    0, ifa_ifunlink_dispatch);
3212 	msg.ifa = ifa;
3213 	msg.ifp = ifp;
3214 
3215 	netisr_domsg(&msg.base, 0);
3216 }
3217 
3218 static void
3219 ifa_destroy_dispatch(netmsg_t nmsg)
3220 {
3221 	struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3222 
3223 	IFAFREE(msg->ifa);
3224 	netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3225 }
3226 
3227 void
3228 ifa_destroy(struct ifaddr *ifa)
3229 {
3230 	struct netmsg_ifaddr msg;
3231 
3232 	netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3233 		    0, ifa_destroy_dispatch);
3234 	msg.ifa = ifa;
3235 
3236 	netisr_domsg(&msg.base, 0);
3237 }
3238 
3239 static void
3240 if_start_rollup(void)
3241 {
3242 	struct ifsubq_stage_head *head = &ifsubq_stage_heads[mycpuid];
3243 	struct ifsubq_stage *stage;
3244 
3245 	crit_enter();
3246 
3247 	while ((stage = TAILQ_FIRST(&head->stg_head)) != NULL) {
3248 		struct ifaltq_subque *ifsq = stage->stg_subq;
3249 		int is_sched = 0;
3250 
3251 		if (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)
3252 			is_sched = 1;
3253 		ifsq_stage_remove(head, stage);
3254 
3255 		if (is_sched) {
3256 			ifsq_ifstart_schedule(ifsq, 1);
3257 		} else {
3258 			int start = 0;
3259 
3260 			ALTQ_SQ_LOCK(ifsq);
3261 			if (!ifsq_is_started(ifsq)) {
3262 				/*
3263 				 * Hold the subqueue interlock of
3264 				 * ifnet.if_start
3265 				 */
3266 				ifsq_set_started(ifsq);
3267 				start = 1;
3268 			}
3269 			ALTQ_SQ_UNLOCK(ifsq);
3270 
3271 			if (start)
3272 				ifsq_ifstart_try(ifsq, 1);
3273 		}
3274 		KKASSERT((stage->stg_flags &
3275 		    (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
3276 	}
3277 
3278 	crit_exit();
3279 }
3280 
3281 static void
3282 ifnetinit(void *dummy __unused)
3283 {
3284 	int i;
3285 
3286 	for (i = 0; i < ncpus; ++i)
3287 		TAILQ_INIT(&ifsubq_stage_heads[i].stg_head);
3288 	netisr_register_rollup(if_start_rollup, NETISR_ROLLUP_PRIO_IFSTART);
3289 }
3290 
3291 void
3292 if_register_com_alloc(u_char type,
3293     if_com_alloc_t *a, if_com_free_t *f)
3294 {
3295 
3296         KASSERT(if_com_alloc[type] == NULL,
3297             ("if_register_com_alloc: %d already registered", type));
3298         KASSERT(if_com_free[type] == NULL,
3299             ("if_register_com_alloc: %d free already registered", type));
3300 
3301         if_com_alloc[type] = a;
3302         if_com_free[type] = f;
3303 }
3304 
3305 void
3306 if_deregister_com_alloc(u_char type)
3307 {
3308 
3309         KASSERT(if_com_alloc[type] != NULL,
3310             ("if_deregister_com_alloc: %d not registered", type));
3311         KASSERT(if_com_free[type] != NULL,
3312             ("if_deregister_com_alloc: %d free not registered", type));
3313         if_com_alloc[type] = NULL;
3314         if_com_free[type] = NULL;
3315 }
3316 
3317 void
3318 ifq_set_maxlen(struct ifaltq *ifq, int len)
3319 {
3320 	ifq->altq_maxlen = len + (ncpus * ifsq_stage_cntmax);
3321 }
3322 
3323 int
3324 ifq_mapsubq_default(struct ifaltq *ifq __unused, int cpuid __unused)
3325 {
3326 	return ALTQ_SUBQ_INDEX_DEFAULT;
3327 }
3328 
3329 int
3330 ifq_mapsubq_mask(struct ifaltq *ifq, int cpuid)
3331 {
3332 
3333 	return (cpuid & ifq->altq_subq_mappriv);
3334 }
3335 
3336 int
3337 ifq_mapsubq_modulo(struct ifaltq *ifq, int cpuid)
3338 {
3339 
3340 	return (cpuid % ifq->altq_subq_mappriv);
3341 }
3342 
3343 static void
3344 ifsq_watchdog(void *arg)
3345 {
3346 	struct ifsubq_watchdog *wd = arg;
3347 	struct ifnet *ifp;
3348 
3349 	if (__predict_true(wd->wd_timer == 0 || --wd->wd_timer))
3350 		goto done;
3351 
3352 	ifp = ifsq_get_ifp(wd->wd_subq);
3353 	if (ifnet_tryserialize_all(ifp)) {
3354 		wd->wd_watchdog(wd->wd_subq);
3355 		ifnet_deserialize_all(ifp);
3356 	} else {
3357 		/* try again next timeout */
3358 		wd->wd_timer = 1;
3359 	}
3360 done:
3361 	ifsq_watchdog_reset(wd);
3362 }
3363 
3364 static void
3365 ifsq_watchdog_reset(struct ifsubq_watchdog *wd)
3366 {
3367 	callout_reset_bycpu(&wd->wd_callout, hz, ifsq_watchdog, wd,
3368 	    ifsq_get_cpuid(wd->wd_subq));
3369 }
3370 
3371 void
3372 ifsq_watchdog_init(struct ifsubq_watchdog *wd, struct ifaltq_subque *ifsq,
3373     ifsq_watchdog_t watchdog)
3374 {
3375 	callout_init_mp(&wd->wd_callout);
3376 	wd->wd_timer = 0;
3377 	wd->wd_subq = ifsq;
3378 	wd->wd_watchdog = watchdog;
3379 }
3380 
3381 void
3382 ifsq_watchdog_start(struct ifsubq_watchdog *wd)
3383 {
3384 	wd->wd_timer = 0;
3385 	ifsq_watchdog_reset(wd);
3386 }
3387 
3388 void
3389 ifsq_watchdog_stop(struct ifsubq_watchdog *wd)
3390 {
3391 	wd->wd_timer = 0;
3392 	callout_stop(&wd->wd_callout);
3393 }
3394 
3395 void
3396 ifnet_lock(void)
3397 {
3398 	KASSERT(curthread->td_type != TD_TYPE_NETISR,
3399 	    ("try holding ifnet lock in netisr"));
3400 	mtx_lock(&ifnet_mtx);
3401 }
3402 
3403 void
3404 ifnet_unlock(void)
3405 {
3406 	KASSERT(curthread->td_type != TD_TYPE_NETISR,
3407 	    ("try holding ifnet lock in netisr"));
3408 	mtx_unlock(&ifnet_mtx);
3409 }
3410 
3411 static struct ifnet_array *
3412 ifnet_array_alloc(int count)
3413 {
3414 	struct ifnet_array *arr;
3415 
3416 	arr = kmalloc(__offsetof(struct ifnet_array, ifnet_arr[count]),
3417 	    M_IFNET, M_WAITOK);
3418 	arr->ifnet_count = count;
3419 
3420 	return arr;
3421 }
3422 
3423 static void
3424 ifnet_array_free(struct ifnet_array *arr)
3425 {
3426 	if (arr == &ifnet_array0)
3427 		return;
3428 	kfree(arr, M_IFNET);
3429 }
3430 
3431 static struct ifnet_array *
3432 ifnet_array_add(struct ifnet *ifp, const struct ifnet_array *old_arr)
3433 {
3434 	struct ifnet_array *arr;
3435 	int count, i;
3436 
3437 	KASSERT(old_arr->ifnet_count >= 0,
3438 	    ("invalid ifnet array count %d", old_arr->ifnet_count));
3439 	count = old_arr->ifnet_count + 1;
3440 	arr = ifnet_array_alloc(count);
3441 
3442 	/*
3443 	 * Save the old ifnet array and append this ifp to the end of
3444 	 * the new ifnet array.
3445 	 */
3446 	for (i = 0; i < old_arr->ifnet_count; ++i) {
3447 		KASSERT(old_arr->ifnet_arr[i] != ifp,
3448 		    ("%s is already in ifnet array", ifp->if_xname));
3449 		arr->ifnet_arr[i] = old_arr->ifnet_arr[i];
3450 	}
3451 	KASSERT(i == count - 1,
3452 	    ("add %s, ifnet array index mismatch, should be %d, but got %d",
3453 	     ifp->if_xname, count - 1, i));
3454 	arr->ifnet_arr[i] = ifp;
3455 
3456 	return arr;
3457 }
3458 
3459 static struct ifnet_array *
3460 ifnet_array_del(struct ifnet *ifp, const struct ifnet_array *old_arr)
3461 {
3462 	struct ifnet_array *arr;
3463 	int count, i, idx, found = 0;
3464 
3465 	KASSERT(old_arr->ifnet_count > 0,
3466 	    ("invalid ifnet array count %d", old_arr->ifnet_count));
3467 	count = old_arr->ifnet_count - 1;
3468 	arr = ifnet_array_alloc(count);
3469 
3470 	/*
3471 	 * Save the old ifnet array, but skip this ifp.
3472 	 */
3473 	idx = 0;
3474 	for (i = 0; i < old_arr->ifnet_count; ++i) {
3475 		if (old_arr->ifnet_arr[i] == ifp) {
3476 			KASSERT(!found,
3477 			    ("dup %s is in ifnet array", ifp->if_xname));
3478 			found = 1;
3479 			continue;
3480 		}
3481 		KASSERT(idx < count,
3482 		    ("invalid ifnet array index %d, count %d", idx, count));
3483 		arr->ifnet_arr[idx] = old_arr->ifnet_arr[i];
3484 		++idx;
3485 	}
3486 	KASSERT(found, ("%s is not in ifnet array", ifp->if_xname));
3487 	KASSERT(idx == count,
3488 	    ("del %s, ifnet array count mismatch, should be %d, but got %d ",
3489 	     ifp->if_xname, count, idx));
3490 
3491 	return arr;
3492 }
3493 
3494 const struct ifnet_array *
3495 ifnet_array_get(void)
3496 {
3497 	const struct ifnet_array *ret;
3498 
3499 	KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3500 	ret = ifnet_array;
3501 	/* Make sure 'ret' is really used. */
3502 	cpu_ccfence();
3503 	return (ret);
3504 }
3505 
3506 int
3507 ifnet_array_isempty(void)
3508 {
3509 	KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3510 	if (ifnet_array->ifnet_count == 0)
3511 		return 1;
3512 	else
3513 		return 0;
3514 }
3515 
3516 void
3517 ifa_marker_init(struct ifaddr_marker *mark, struct ifnet *ifp)
3518 {
3519 	struct ifaddr *ifa;
3520 
3521 	memset(mark, 0, sizeof(*mark));
3522 	ifa = &mark->ifa;
3523 
3524 	mark->ifac.ifa = ifa;
3525 
3526 	ifa->ifa_addr = &mark->addr;
3527 	ifa->ifa_dstaddr = &mark->dstaddr;
3528 	ifa->ifa_netmask = &mark->netmask;
3529 	ifa->ifa_ifp = ifp;
3530 }
3531 
3532 static int
3533 if_ringcnt_fixup(int ring_cnt, int ring_cntmax)
3534 {
3535 
3536 	KASSERT(ring_cntmax > 0, ("invalid ring count max %d", ring_cntmax));
3537 
3538 	if (ring_cnt <= 0 || ring_cnt > ring_cntmax)
3539 		ring_cnt = ring_cntmax;
3540 	if (ring_cnt > netisr_ncpus)
3541 		ring_cnt = netisr_ncpus;
3542 	return (ring_cnt);
3543 }
3544 
3545 static void
3546 if_ringmap_set_grid(device_t dev, struct if_ringmap *rm, int grid)
3547 {
3548 	int i, offset;
3549 
3550 	KASSERT(grid > 0, ("invalid if_ringmap grid %d", grid));
3551 	KASSERT(grid >= rm->rm_cnt, ("invalid if_ringmap grid %d, count %d",
3552 	    grid, rm->rm_cnt));
3553 	rm->rm_grid = grid;
3554 
3555 	offset = (rm->rm_grid * device_get_unit(dev)) % netisr_ncpus;
3556 	for (i = 0; i < rm->rm_cnt; ++i) {
3557 		rm->rm_cpumap[i] = offset + i;
3558 		KASSERT(rm->rm_cpumap[i] < netisr_ncpus,
3559 		    ("invalid cpumap[%d] = %d, offset %d", i,
3560 		     rm->rm_cpumap[i], offset));
3561 	}
3562 }
3563 
3564 static struct if_ringmap *
3565 if_ringmap_alloc_flags(device_t dev, int ring_cnt, int ring_cntmax,
3566     uint32_t flags)
3567 {
3568 	struct if_ringmap *rm;
3569 	int i, grid = 0, prev_grid;
3570 
3571 	ring_cnt = if_ringcnt_fixup(ring_cnt, ring_cntmax);
3572 	rm = kmalloc(__offsetof(struct if_ringmap, rm_cpumap[ring_cnt]),
3573 	    M_DEVBUF, M_WAITOK | M_ZERO);
3574 
3575 	rm->rm_cnt = ring_cnt;
3576 	if (flags & RINGMAP_FLAG_POWEROF2)
3577 		rm->rm_cnt = 1 << (fls(rm->rm_cnt) - 1);
3578 
3579 	prev_grid = netisr_ncpus;
3580 	for (i = 0; i < netisr_ncpus; ++i) {
3581 		if (netisr_ncpus % (i + 1) != 0)
3582 			continue;
3583 
3584 		grid = netisr_ncpus / (i + 1);
3585 		if (rm->rm_cnt > grid) {
3586 			grid = prev_grid;
3587 			break;
3588 		}
3589 
3590 		if (rm->rm_cnt > netisr_ncpus / (i + 2))
3591 			break;
3592 		prev_grid = grid;
3593 	}
3594 	if_ringmap_set_grid(dev, rm, grid);
3595 
3596 	return (rm);
3597 }
3598 
3599 struct if_ringmap *
3600 if_ringmap_alloc(device_t dev, int ring_cnt, int ring_cntmax)
3601 {
3602 
3603 	return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3604 	    RINGMAP_FLAG_NONE));
3605 }
3606 
3607 struct if_ringmap *
3608 if_ringmap_alloc2(device_t dev, int ring_cnt, int ring_cntmax)
3609 {
3610 
3611 	return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3612 	    RINGMAP_FLAG_POWEROF2));
3613 }
3614 
3615 void
3616 if_ringmap_free(struct if_ringmap *rm)
3617 {
3618 
3619 	kfree(rm, M_DEVBUF);
3620 }
3621 
3622 /*
3623  * Align the two ringmaps.
3624  *
3625  * e.g. 8 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3626  *
3627  * Before:
3628  *
3629  * CPU      0  1  2  3   4  5  6  7
3630  * NIC_RX               n0 n1 n2 n3
3631  * NIC_TX        N0 N1
3632  *
3633  * After:
3634  *
3635  * CPU      0  1  2  3   4  5  6  7
3636  * NIC_RX               n0 n1 n2 n3
3637  * NIC_TX               N0 N1
3638  */
3639 void
3640 if_ringmap_align(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3641 {
3642 
3643 	if (rm0->rm_grid > rm1->rm_grid)
3644 		if_ringmap_set_grid(dev, rm1, rm0->rm_grid);
3645 	else if (rm0->rm_grid < rm1->rm_grid)
3646 		if_ringmap_set_grid(dev, rm0, rm1->rm_grid);
3647 }
3648 
3649 void
3650 if_ringmap_match(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3651 {
3652 	int subset_grid, cnt, divisor, mod, offset, i;
3653 	struct if_ringmap *subset_rm, *rm;
3654 	int old_rm0_grid, old_rm1_grid;
3655 
3656 	if (rm0->rm_grid == rm1->rm_grid)
3657 		return;
3658 
3659 	/* Save grid for later use */
3660 	old_rm0_grid = rm0->rm_grid;
3661 	old_rm1_grid = rm1->rm_grid;
3662 
3663 	if_ringmap_align(dev, rm0, rm1);
3664 
3665 	/*
3666 	 * Re-shuffle rings to get more even distribution.
3667 	 *
3668 	 * e.g. 12 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3669 	 *
3670 	 * CPU       0  1  2  3   4  5  6  7   8  9 10 11
3671 	 *
3672 	 * NIC_RX   a0 a1 a2 a3  b0 b1 b2 b3  c0 c1 c2 c3
3673 	 * NIC_TX   A0 A1        B0 B1        C0 C1
3674 	 *
3675 	 * NIC_RX   d0 d1 d2 d3  e0 e1 e2 e3  f0 f1 f2 f3
3676 	 * NIC_TX         D0 D1        E0 E1        F0 F1
3677 	 */
3678 
3679 	if (rm0->rm_cnt >= (2 * old_rm1_grid)) {
3680 		cnt = rm0->rm_cnt;
3681 		subset_grid = old_rm1_grid;
3682 		subset_rm = rm1;
3683 		rm = rm0;
3684 	} else if (rm1->rm_cnt > (2 * old_rm0_grid)) {
3685 		cnt = rm1->rm_cnt;
3686 		subset_grid = old_rm0_grid;
3687 		subset_rm = rm0;
3688 		rm = rm1;
3689 	} else {
3690 		/* No space to shuffle. */
3691 		return;
3692 	}
3693 
3694 	mod = cnt / subset_grid;
3695 	KKASSERT(mod >= 2);
3696 	divisor = netisr_ncpus / rm->rm_grid;
3697 	offset = ((device_get_unit(dev) / divisor) % mod) * subset_grid;
3698 
3699 	for (i = 0; i < subset_rm->rm_cnt; ++i) {
3700 		subset_rm->rm_cpumap[i] += offset;
3701 		KASSERT(subset_rm->rm_cpumap[i] < netisr_ncpus,
3702 		    ("match: invalid cpumap[%d] = %d, offset %d",
3703 		     i, subset_rm->rm_cpumap[i], offset));
3704 	}
3705 #ifdef INVARIANTS
3706 	for (i = 0; i < subset_rm->rm_cnt; ++i) {
3707 		int j;
3708 
3709 		for (j = 0; j < rm->rm_cnt; ++j) {
3710 			if (rm->rm_cpumap[j] == subset_rm->rm_cpumap[i])
3711 				break;
3712 		}
3713 		KASSERT(j < rm->rm_cnt,
3714 		    ("subset cpumap[%d] = %d not found in superset",
3715 		     i, subset_rm->rm_cpumap[i]));
3716 	}
3717 #endif
3718 }
3719 
3720 int
3721 if_ringmap_count(const struct if_ringmap *rm)
3722 {
3723 
3724 	return (rm->rm_cnt);
3725 }
3726 
3727 int
3728 if_ringmap_cpumap(const struct if_ringmap *rm, int ring)
3729 {
3730 
3731 	KASSERT(ring >= 0 && ring < rm->rm_cnt, ("invalid ring %d", ring));
3732 	return (rm->rm_cpumap[ring]);
3733 }
3734 
3735 void
3736 if_ringmap_rdrtable(const struct if_ringmap *rm, int table[], int table_nent)
3737 {
3738 	int i, grid_idx, grid_cnt, patch_off, patch_cnt, ncopy;
3739 
3740 	KASSERT(table_nent > 0 && (table_nent & NETISR_CPUMASK) == 0,
3741 	    ("invalid redirect table entries %d", table_nent));
3742 
3743 	grid_idx = 0;
3744 	for (i = 0; i < NETISR_CPUMAX; ++i) {
3745 		table[i] = grid_idx++ % rm->rm_cnt;
3746 
3747 		if (grid_idx == rm->rm_grid)
3748 			grid_idx = 0;
3749 	}
3750 
3751 	/*
3752 	 * Make the ring distributed more evenly for the remainder
3753 	 * of each grid.
3754 	 *
3755 	 * e.g. 12 netisrs, rm contains 8 rings.
3756 	 *
3757 	 * Redirect table before:
3758 	 *
3759 	 *  0  1  2  3  4  5  6  7  0  1  2  3  0  1  2  3
3760 	 *  4  5  6  7  0  1  2  3  0  1  2  3  4  5  6  7
3761 	 *  0  1  2  3  0  1  2  3  4  5  6  7  0  1  2  3
3762 	 *  ....
3763 	 *
3764 	 * Redirect table after being patched (pX, patched entries):
3765 	 *
3766 	 *  0  1  2  3  4  5  6  7 p0 p1 p2 p3  0  1  2  3
3767 	 *  4  5  6  7 p4 p5 p6 p7  0  1  2  3  4  5  6  7
3768 	 * p0 p1 p2 p3  0  1  2  3  4  5  6  7 p4 p5 p6 p7
3769 	 *  ....
3770 	 */
3771 	patch_cnt = rm->rm_grid % rm->rm_cnt;
3772 	if (patch_cnt == 0)
3773 		goto done;
3774 	patch_off = rm->rm_grid - (rm->rm_grid % rm->rm_cnt);
3775 
3776 	grid_cnt = roundup(NETISR_CPUMAX, rm->rm_grid) / rm->rm_grid;
3777 	grid_idx = 0;
3778 	for (i = 0; i < grid_cnt; ++i) {
3779 		int j;
3780 
3781 		for (j = 0; j < patch_cnt; ++j) {
3782 			int fix_idx;
3783 
3784 			fix_idx = (i * rm->rm_grid) + patch_off + j;
3785 			if (fix_idx >= NETISR_CPUMAX)
3786 				goto done;
3787 			table[fix_idx] = grid_idx++ % rm->rm_cnt;
3788 		}
3789 	}
3790 done:
3791 	/*
3792 	 * If the device supports larger redirect table, duplicate
3793 	 * the first NETISR_CPUMAX entries to the rest of the table,
3794 	 * so that it matches upper layer's expectation:
3795 	 * (hash & NETISR_CPUMASK) % netisr_ncpus
3796 	 */
3797 	ncopy = table_nent / NETISR_CPUMAX;
3798 	for (i = 1; i < ncopy; ++i) {
3799 		memcpy(&table[i * NETISR_CPUMAX], table,
3800 		    NETISR_CPUMAX * sizeof(table[0]));
3801 	}
3802 	if (if_ringmap_dumprdr) {
3803 		for (i = 0; i < table_nent; ++i) {
3804 			if (i != 0 && i % 16 == 0)
3805 				kprintf("\n");
3806 			kprintf("%03d ", table[i]);
3807 		}
3808 		kprintf("\n");
3809 	}
3810 }
3811 
3812 int
3813 if_ringmap_cpumap_sysctl(SYSCTL_HANDLER_ARGS)
3814 {
3815 	struct if_ringmap *rm = arg1;
3816 	int i, error = 0;
3817 
3818 	for (i = 0; i < rm->rm_cnt; ++i) {
3819 		int cpu = rm->rm_cpumap[i];
3820 
3821 		error = SYSCTL_OUT(req, &cpu, sizeof(cpu));
3822 		if (error)
3823 			break;
3824 	}
3825 	return (error);
3826 }
3827 
3828 int
3829 if_ring_count2(int ring_cnt, int ring_cntmax)
3830 {
3831 
3832 	ring_cnt = if_ringcnt_fixup(ring_cnt, ring_cntmax);
3833 	return (1 << (fls(ring_cnt) - 1));
3834 }
3835