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