tcp: Cache align ACK queue header.
[dragonfly.git] / sys / net / if.c
blob8efbbfa53224087c50ff922cdc1c91392b6e78bb
1 /*
2 * Copyright (c) 1980, 1986, 1993
3 * The Regents of the University of California. All rights reserved.
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.
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.
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 $
33 #include "opt_inet6.h"
34 #include "opt_inet.h"
35 #include "opt_ifpoll.h"
37 #include <sys/param.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/systm.h>
41 #include <sys/proc.h>
42 #include <sys/priv.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/socketops.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/mutex.h>
50 #include <sys/sockio.h>
51 #include <sys/syslog.h>
52 #include <sys/sysctl.h>
53 #include <sys/domain.h>
54 #include <sys/thread.h>
55 #include <sys/serialize.h>
56 #include <sys/bus.h>
58 #include <sys/thread2.h>
59 #include <sys/msgport2.h>
60 #include <sys/mutex2.h>
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/if_dl.h>
65 #include <net/if_types.h>
66 #include <net/if_var.h>
67 #include <net/if_ringmap.h>
68 #include <net/ifq_var.h>
69 #include <net/radix.h>
70 #include <net/route.h>
71 #include <net/if_clone.h>
72 #include <net/netisr2.h>
73 #include <net/netmsg2.h>
75 #include <machine/atomic.h>
76 #include <machine/stdarg.h>
77 #include <machine/smp.h>
79 #if defined(INET) || defined(INET6)
80 /*XXX*/
81 #include <netinet/in.h>
82 #include <netinet/in_var.h>
83 #include <netinet/if_ether.h>
84 #ifdef INET6
85 #include <netinet6/in6_var.h>
86 #include <netinet6/in6_ifattach.h>
87 #endif
88 #endif
90 struct netmsg_ifaddr {
91 struct netmsg_base base;
92 struct ifaddr *ifa;
93 struct ifnet *ifp;
94 int tail;
97 struct ifsubq_stage_head {
98 TAILQ_HEAD(, ifsubq_stage) stg_head;
99 } __cachealign;
101 struct if_ringmap {
102 int rm_cnt;
103 int rm_grid;
104 int rm_cpumap[];
107 #define RINGMAP_FLAG_NONE 0x0
108 #define RINGMAP_FLAG_POWEROF2 0x1
111 * System initialization
113 static void if_attachdomain(void *);
114 static void if_attachdomain1(struct ifnet *);
115 static int ifconf(u_long, caddr_t, struct ucred *);
116 static void ifinit(void *);
117 static void ifnetinit(void *);
118 static void if_slowtimo(void *);
119 static void link_rtrequest(int, struct rtentry *);
120 static int if_rtdel(struct radix_node *, void *);
121 static void if_slowtimo_dispatch(netmsg_t);
123 /* Helper functions */
124 static void ifsq_watchdog_reset(struct ifsubq_watchdog *);
125 static int if_delmulti_serialized(struct ifnet *, struct sockaddr *);
126 static struct ifnet_array *ifnet_array_alloc(int);
127 static void ifnet_array_free(struct ifnet_array *);
128 static struct ifnet_array *ifnet_array_add(struct ifnet *,
129 const struct ifnet_array *);
130 static struct ifnet_array *ifnet_array_del(struct ifnet *,
131 const struct ifnet_array *);
133 #ifdef INET6
135 * XXX: declare here to avoid to include many inet6 related files..
136 * should be more generalized?
138 extern void nd6_setmtu(struct ifnet *);
139 #endif
141 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
142 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
143 SYSCTL_NODE(_net_link, OID_AUTO, ringmap, CTLFLAG_RW, 0, "link ringmap");
145 static int ifsq_stage_cntmax = 4;
146 TUNABLE_INT("net.link.stage_cntmax", &ifsq_stage_cntmax);
147 SYSCTL_INT(_net_link, OID_AUTO, stage_cntmax, CTLFLAG_RW,
148 &ifsq_stage_cntmax, 0, "ifq staging packet count max");
150 static int if_stats_compat = 0;
151 SYSCTL_INT(_net_link, OID_AUTO, stats_compat, CTLFLAG_RW,
152 &if_stats_compat, 0, "Compat the old ifnet stats");
154 static int if_ringmap_dumprdr = 0;
155 SYSCTL_INT(_net_link_ringmap, OID_AUTO, dump_rdr, CTLFLAG_RW,
156 &if_ringmap_dumprdr, 0, "dump redirect table");
158 SYSINIT(interfaces, SI_SUB_PROTO_IF, SI_ORDER_FIRST, ifinit, NULL);
159 SYSINIT(ifnet, SI_SUB_PRE_DRIVERS, SI_ORDER_ANY, ifnetinit, NULL);
161 static if_com_alloc_t *if_com_alloc[256];
162 static if_com_free_t *if_com_free[256];
164 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
165 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
166 MALLOC_DEFINE(M_IFNET, "ifnet", "interface structure");
168 int ifqmaxlen = IFQ_MAXLEN;
169 struct ifnethead ifnet = TAILQ_HEAD_INITIALIZER(ifnet);
171 static struct ifnet_array ifnet_array0;
172 static struct ifnet_array *ifnet_array = &ifnet_array0;
174 static struct callout if_slowtimo_timer;
175 static struct netmsg_base if_slowtimo_netmsg;
177 int if_index = 0;
178 struct ifnet **ifindex2ifnet = NULL;
179 static struct mtx ifnet_mtx = MTX_INITIALIZER("ifnet");
181 static struct ifsubq_stage_head ifsubq_stage_heads[MAXCPU];
183 #ifdef notyet
184 #define IFQ_KTR_STRING "ifq=%p"
185 #define IFQ_KTR_ARGS struct ifaltq *ifq
186 #ifndef KTR_IFQ
187 #define KTR_IFQ KTR_ALL
188 #endif
189 KTR_INFO_MASTER(ifq);
190 KTR_INFO(KTR_IFQ, ifq, enqueue, 0, IFQ_KTR_STRING, IFQ_KTR_ARGS);
191 KTR_INFO(KTR_IFQ, ifq, dequeue, 1, IFQ_KTR_STRING, IFQ_KTR_ARGS);
192 #define logifq(name, arg) KTR_LOG(ifq_ ## name, arg)
194 #define IF_START_KTR_STRING "ifp=%p"
195 #define IF_START_KTR_ARGS struct ifnet *ifp
196 #ifndef KTR_IF_START
197 #define KTR_IF_START KTR_ALL
198 #endif
199 KTR_INFO_MASTER(if_start);
200 KTR_INFO(KTR_IF_START, if_start, run, 0,
201 IF_START_KTR_STRING, IF_START_KTR_ARGS);
202 KTR_INFO(KTR_IF_START, if_start, sched, 1,
203 IF_START_KTR_STRING, IF_START_KTR_ARGS);
204 KTR_INFO(KTR_IF_START, if_start, avoid, 2,
205 IF_START_KTR_STRING, IF_START_KTR_ARGS);
206 KTR_INFO(KTR_IF_START, if_start, contend_sched, 3,
207 IF_START_KTR_STRING, IF_START_KTR_ARGS);
208 KTR_INFO(KTR_IF_START, if_start, chase_sched, 4,
209 IF_START_KTR_STRING, IF_START_KTR_ARGS);
210 #define logifstart(name, arg) KTR_LOG(if_start_ ## name, arg)
211 #endif
213 TAILQ_HEAD(, ifg_group) ifg_head = TAILQ_HEAD_INITIALIZER(ifg_head);
216 * Network interface utility routines.
218 * Routines with ifa_ifwith* names take sockaddr *'s as
219 * parameters.
221 /* ARGSUSED*/
222 static void
223 ifinit(void *dummy)
225 struct ifnet *ifp;
227 callout_init_mp(&if_slowtimo_timer);
228 netmsg_init(&if_slowtimo_netmsg, NULL, &netisr_adone_rport,
229 MSGF_PRIORITY, if_slowtimo_dispatch);
231 /* XXX is this necessary? */
232 ifnet_lock();
233 TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
234 if (ifp->if_snd.altq_maxlen == 0) {
235 if_printf(ifp, "XXX: driver didn't set altq_maxlen\n");
236 ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
239 ifnet_unlock();
241 /* Start if_slowtimo */
242 lwkt_sendmsg(netisr_cpuport(0), &if_slowtimo_netmsg.lmsg);
245 static void
246 ifsq_ifstart_ipifunc(void *arg)
248 struct ifaltq_subque *ifsq = arg;
249 struct lwkt_msg *lmsg = ifsq_get_ifstart_lmsg(ifsq, mycpuid);
251 crit_enter();
252 if (lmsg->ms_flags & MSGF_DONE)
253 lwkt_sendmsg_oncpu(netisr_cpuport(mycpuid), lmsg);
254 crit_exit();
257 static __inline void
258 ifsq_stage_remove(struct ifsubq_stage_head *head, struct ifsubq_stage *stage)
260 KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
261 TAILQ_REMOVE(&head->stg_head, stage, stg_link);
262 stage->stg_flags &= ~(IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED);
263 stage->stg_cnt = 0;
264 stage->stg_len = 0;
267 static __inline void
268 ifsq_stage_insert(struct ifsubq_stage_head *head, struct ifsubq_stage *stage)
270 KKASSERT((stage->stg_flags &
271 (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
272 stage->stg_flags |= IFSQ_STAGE_FLAG_QUED;
273 TAILQ_INSERT_TAIL(&head->stg_head, stage, stg_link);
277 * Schedule ifnet.if_start on the subqueue owner CPU
279 static void
280 ifsq_ifstart_schedule(struct ifaltq_subque *ifsq, int force)
282 int cpu;
284 if (!force && curthread->td_type == TD_TYPE_NETISR &&
285 ifsq_stage_cntmax > 0) {
286 struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
288 stage->stg_cnt = 0;
289 stage->stg_len = 0;
290 if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
291 ifsq_stage_insert(&ifsubq_stage_heads[mycpuid], stage);
292 stage->stg_flags |= IFSQ_STAGE_FLAG_SCHED;
293 return;
296 cpu = ifsq_get_cpuid(ifsq);
297 if (cpu != mycpuid)
298 lwkt_send_ipiq(globaldata_find(cpu), ifsq_ifstart_ipifunc, ifsq);
299 else
300 ifsq_ifstart_ipifunc(ifsq);
304 * NOTE:
305 * This function will release ifnet.if_start subqueue interlock,
306 * if ifnet.if_start for the subqueue does not need to be scheduled
308 static __inline int
309 ifsq_ifstart_need_schedule(struct ifaltq_subque *ifsq, int running)
311 if (!running || ifsq_is_empty(ifsq)
312 #ifdef ALTQ
313 || ifsq->ifsq_altq->altq_tbr != NULL
314 #endif
316 ALTQ_SQ_LOCK(ifsq);
318 * ifnet.if_start subqueue interlock is released, if:
319 * 1) Hardware can not take any packets, due to
320 * o interface is marked down
321 * o hardware queue is full (ifsq_is_oactive)
322 * Under the second situation, hardware interrupt
323 * or polling(4) will call/schedule ifnet.if_start
324 * on the subqueue when hardware queue is ready
325 * 2) There is no packet in the subqueue.
326 * Further ifq_dispatch or ifq_handoff will call/
327 * schedule ifnet.if_start on the subqueue.
328 * 3) TBR is used and it does not allow further
329 * dequeueing.
330 * TBR callout will call ifnet.if_start on the
331 * subqueue.
333 if (!running || !ifsq_data_ready(ifsq)) {
334 ifsq_clr_started(ifsq);
335 ALTQ_SQ_UNLOCK(ifsq);
336 return 0;
338 ALTQ_SQ_UNLOCK(ifsq);
340 return 1;
343 static void
344 ifsq_ifstart_dispatch(netmsg_t msg)
346 struct lwkt_msg *lmsg = &msg->base.lmsg;
347 struct ifaltq_subque *ifsq = lmsg->u.ms_resultp;
348 struct ifnet *ifp = ifsq_get_ifp(ifsq);
349 struct globaldata *gd = mycpu;
350 int running = 0, need_sched;
352 crit_enter_gd(gd);
354 lwkt_replymsg(lmsg, 0); /* reply ASAP */
356 if (gd->gd_cpuid != ifsq_get_cpuid(ifsq)) {
358 * We need to chase the subqueue owner CPU change.
360 ifsq_ifstart_schedule(ifsq, 1);
361 crit_exit_gd(gd);
362 return;
365 ifsq_serialize_hw(ifsq);
366 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
367 ifp->if_start(ifp, ifsq);
368 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
369 running = 1;
371 need_sched = ifsq_ifstart_need_schedule(ifsq, running);
372 ifsq_deserialize_hw(ifsq);
374 if (need_sched) {
376 * More data need to be transmitted, ifnet.if_start is
377 * scheduled on the subqueue owner CPU, and we keep going.
378 * NOTE: ifnet.if_start subqueue interlock is not released.
380 ifsq_ifstart_schedule(ifsq, 0);
383 crit_exit_gd(gd);
386 /* Device driver ifnet.if_start helper function */
387 void
388 ifsq_devstart(struct ifaltq_subque *ifsq)
390 struct ifnet *ifp = ifsq_get_ifp(ifsq);
391 int running = 0;
393 ASSERT_ALTQ_SQ_SERIALIZED_HW(ifsq);
395 ALTQ_SQ_LOCK(ifsq);
396 if (ifsq_is_started(ifsq) || !ifsq_data_ready(ifsq)) {
397 ALTQ_SQ_UNLOCK(ifsq);
398 return;
400 ifsq_set_started(ifsq);
401 ALTQ_SQ_UNLOCK(ifsq);
403 ifp->if_start(ifp, ifsq);
405 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
406 running = 1;
408 if (ifsq_ifstart_need_schedule(ifsq, running)) {
410 * More data need to be transmitted, ifnet.if_start is
411 * scheduled on ifnet's CPU, and we keep going.
412 * NOTE: ifnet.if_start interlock is not released.
414 ifsq_ifstart_schedule(ifsq, 0);
418 void
419 if_devstart(struct ifnet *ifp)
421 ifsq_devstart(ifq_get_subq_default(&ifp->if_snd));
424 /* Device driver ifnet.if_start schedule helper function */
425 void
426 ifsq_devstart_sched(struct ifaltq_subque *ifsq)
428 ifsq_ifstart_schedule(ifsq, 1);
431 void
432 if_devstart_sched(struct ifnet *ifp)
434 ifsq_devstart_sched(ifq_get_subq_default(&ifp->if_snd));
437 static void
438 if_default_serialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
440 lwkt_serialize_enter(ifp->if_serializer);
443 static void
444 if_default_deserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
446 lwkt_serialize_exit(ifp->if_serializer);
449 static int
450 if_default_tryserialize(struct ifnet *ifp, enum ifnet_serialize slz __unused)
452 return lwkt_serialize_try(ifp->if_serializer);
455 #ifdef INVARIANTS
456 static void
457 if_default_serialize_assert(struct ifnet *ifp,
458 enum ifnet_serialize slz __unused,
459 boolean_t serialized)
461 if (serialized)
462 ASSERT_SERIALIZED(ifp->if_serializer);
463 else
464 ASSERT_NOT_SERIALIZED(ifp->if_serializer);
466 #endif
469 * Attach an interface to the list of "active" interfaces.
471 * The serializer is optional.
473 void
474 if_attach(struct ifnet *ifp, lwkt_serialize_t serializer)
476 unsigned socksize;
477 int namelen, masklen;
478 struct sockaddr_dl *sdl, *sdl_addr;
479 struct ifaddr *ifa;
480 struct ifaltq *ifq;
481 struct ifnet **old_ifindex2ifnet = NULL;
482 struct ifnet_array *old_ifnet_array;
483 int i, q;
485 static int if_indexlim = 8;
487 if (ifp->if_serialize != NULL) {
488 KASSERT(ifp->if_deserialize != NULL &&
489 ifp->if_tryserialize != NULL &&
490 ifp->if_serialize_assert != NULL,
491 ("serialize functions are partially setup"));
494 * If the device supplies serialize functions,
495 * then clear if_serializer to catch any invalid
496 * usage of this field.
498 KASSERT(serializer == NULL,
499 ("both serialize functions and default serializer "
500 "are supplied"));
501 ifp->if_serializer = NULL;
502 } else {
503 KASSERT(ifp->if_deserialize == NULL &&
504 ifp->if_tryserialize == NULL &&
505 ifp->if_serialize_assert == NULL,
506 ("serialize functions are partially setup"));
507 ifp->if_serialize = if_default_serialize;
508 ifp->if_deserialize = if_default_deserialize;
509 ifp->if_tryserialize = if_default_tryserialize;
510 #ifdef INVARIANTS
511 ifp->if_serialize_assert = if_default_serialize_assert;
512 #endif
515 * The serializer can be passed in from the device,
516 * allowing the same serializer to be used for both
517 * the interrupt interlock and the device queue.
518 * If not specified, the netif structure will use an
519 * embedded serializer.
521 if (serializer == NULL) {
522 serializer = &ifp->if_default_serializer;
523 lwkt_serialize_init(serializer);
525 ifp->if_serializer = serializer;
529 * XXX -
530 * The old code would work if the interface passed a pre-existing
531 * chain of ifaddrs to this code. We don't trust our callers to
532 * properly initialize the tailq, however, so we no longer allow
533 * this unlikely case.
535 ifp->if_addrheads = kmalloc(ncpus * sizeof(struct ifaddrhead),
536 M_IFADDR, M_WAITOK | M_ZERO);
537 for (i = 0; i < ncpus; ++i)
538 TAILQ_INIT(&ifp->if_addrheads[i]);
540 TAILQ_INIT(&ifp->if_multiaddrs);
541 TAILQ_INIT(&ifp->if_groups);
542 getmicrotime(&ifp->if_lastchange);
545 * create a Link Level name for this device
547 namelen = strlen(ifp->if_xname);
548 masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + namelen;
549 socksize = masklen + ifp->if_addrlen;
550 if (socksize < sizeof(*sdl))
551 socksize = sizeof(*sdl);
552 socksize = RT_ROUNDUP(socksize);
553 ifa = ifa_create(sizeof(struct ifaddr) + 2 * socksize);
554 sdl = sdl_addr = (struct sockaddr_dl *)(ifa + 1);
555 sdl->sdl_len = socksize;
556 sdl->sdl_family = AF_LINK;
557 bcopy(ifp->if_xname, sdl->sdl_data, namelen);
558 sdl->sdl_nlen = namelen;
559 sdl->sdl_type = ifp->if_type;
560 ifp->if_lladdr = ifa;
561 ifa->ifa_ifp = ifp;
562 ifa->ifa_rtrequest = link_rtrequest;
563 ifa->ifa_addr = (struct sockaddr *)sdl;
564 sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
565 ifa->ifa_netmask = (struct sockaddr *)sdl;
566 sdl->sdl_len = masklen;
567 while (namelen != 0)
568 sdl->sdl_data[--namelen] = 0xff;
569 ifa_iflink(ifa, ifp, 0 /* Insert head */);
571 ifp->if_data_pcpu = kmalloc_cachealign(
572 ncpus * sizeof(struct ifdata_pcpu), M_DEVBUF, M_WAITOK | M_ZERO);
574 if (ifp->if_mapsubq == NULL)
575 ifp->if_mapsubq = ifq_mapsubq_default;
577 ifq = &ifp->if_snd;
578 ifq->altq_type = 0;
579 ifq->altq_disc = NULL;
580 ifq->altq_flags &= ALTQF_CANTCHANGE;
581 ifq->altq_tbr = NULL;
582 ifq->altq_ifp = ifp;
584 if (ifq->altq_subq_cnt <= 0)
585 ifq->altq_subq_cnt = 1;
586 ifq->altq_subq = kmalloc_cachealign(
587 ifq->altq_subq_cnt * sizeof(struct ifaltq_subque),
588 M_DEVBUF, M_WAITOK | M_ZERO);
590 if (ifq->altq_maxlen == 0) {
591 if_printf(ifp, "driver didn't set altq_maxlen\n");
592 ifq_set_maxlen(ifq, ifqmaxlen);
595 for (q = 0; q < ifq->altq_subq_cnt; ++q) {
596 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
598 ALTQ_SQ_LOCK_INIT(ifsq);
599 ifsq->ifsq_index = q;
601 ifsq->ifsq_altq = ifq;
602 ifsq->ifsq_ifp = ifp;
604 ifsq->ifsq_maxlen = ifq->altq_maxlen;
605 ifsq->ifsq_maxbcnt = ifsq->ifsq_maxlen * MCLBYTES;
606 ifsq->ifsq_prepended = NULL;
607 ifsq->ifsq_started = 0;
608 ifsq->ifsq_hw_oactive = 0;
609 ifsq_set_cpuid(ifsq, 0);
610 if (ifp->if_serializer != NULL)
611 ifsq_set_hw_serialize(ifsq, ifp->if_serializer);
613 ifsq->ifsq_stage =
614 kmalloc_cachealign(ncpus * sizeof(struct ifsubq_stage),
615 M_DEVBUF, M_WAITOK | M_ZERO);
616 for (i = 0; i < ncpus; ++i)
617 ifsq->ifsq_stage[i].stg_subq = ifsq;
619 ifsq->ifsq_ifstart_nmsg =
620 kmalloc(ncpus * sizeof(struct netmsg_base),
621 M_LWKTMSG, M_WAITOK);
622 for (i = 0; i < ncpus; ++i) {
623 netmsg_init(&ifsq->ifsq_ifstart_nmsg[i], NULL,
624 &netisr_adone_rport, 0, ifsq_ifstart_dispatch);
625 ifsq->ifsq_ifstart_nmsg[i].lmsg.u.ms_resultp = ifsq;
628 ifq_set_classic(ifq);
631 * Increase mbuf cluster/jcluster limits for the mbufs that
632 * could sit on the device queues for quite some time.
634 if (ifp->if_nmbclusters > 0)
635 mcl_inclimit(ifp->if_nmbclusters);
636 if (ifp->if_nmbjclusters > 0)
637 mjcl_inclimit(ifp->if_nmbjclusters);
640 * Install this ifp into ifindex2inet, ifnet queue and ifnet
641 * array after it is setup.
643 * Protect ifindex2ifnet, ifnet queue and ifnet array changes
644 * by ifnet lock, so that non-netisr threads could get a
645 * consistent view.
647 ifnet_lock();
649 /* Don't update if_index until ifindex2ifnet is setup */
650 ifp->if_index = if_index + 1;
651 sdl_addr->sdl_index = ifp->if_index;
654 * Install this ifp into ifindex2ifnet
656 if (ifindex2ifnet == NULL || ifp->if_index >= if_indexlim) {
657 unsigned int n;
658 struct ifnet **q;
661 * Grow ifindex2ifnet
663 if_indexlim <<= 1;
664 n = if_indexlim * sizeof(*q);
665 q = kmalloc(n, M_IFADDR, M_WAITOK | M_ZERO);
666 if (ifindex2ifnet != NULL) {
667 bcopy(ifindex2ifnet, q, n/2);
668 /* Free old ifindex2ifnet after sync all netisrs */
669 old_ifindex2ifnet = ifindex2ifnet;
671 ifindex2ifnet = q;
673 ifindex2ifnet[ifp->if_index] = ifp;
675 * Update if_index after this ifp is installed into ifindex2ifnet,
676 * so that netisrs could get a consistent view of ifindex2ifnet.
678 cpu_sfence();
679 if_index = ifp->if_index;
682 * Install this ifp into ifnet array.
684 /* Free old ifnet array after sync all netisrs */
685 old_ifnet_array = ifnet_array;
686 ifnet_array = ifnet_array_add(ifp, old_ifnet_array);
689 * Install this ifp into ifnet queue.
691 TAILQ_INSERT_TAIL(&ifnetlist, ifp, if_link);
693 ifnet_unlock();
696 * Sync all netisrs so that the old ifindex2ifnet and ifnet array
697 * are no longer accessed and we can free them safely later on.
699 netmsg_service_sync();
700 if (old_ifindex2ifnet != NULL)
701 kfree(old_ifindex2ifnet, M_IFADDR);
702 ifnet_array_free(old_ifnet_array);
704 if (!SLIST_EMPTY(&domains))
705 if_attachdomain1(ifp);
707 /* Announce the interface. */
708 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
709 devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
710 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
713 static void
714 if_attachdomain(void *dummy)
716 struct ifnet *ifp;
718 ifnet_lock();
719 TAILQ_FOREACH(ifp, &ifnetlist, if_list)
720 if_attachdomain1(ifp);
721 ifnet_unlock();
723 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_FIRST,
724 if_attachdomain, NULL);
726 static void
727 if_attachdomain1(struct ifnet *ifp)
729 struct domain *dp;
731 crit_enter();
733 /* address family dependent data region */
734 bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
735 SLIST_FOREACH(dp, &domains, dom_next)
736 if (dp->dom_ifattach)
737 ifp->if_afdata[dp->dom_family] =
738 (*dp->dom_ifattach)(ifp);
739 crit_exit();
743 * Purge all addresses whose type is _not_ AF_LINK
745 static void
746 if_purgeaddrs_nolink_dispatch(netmsg_t nmsg)
748 struct lwkt_msg *lmsg = &nmsg->lmsg;
749 struct ifnet *ifp = lmsg->u.ms_resultp;
750 struct ifaddr_container *ifac, *next;
752 ASSERT_IN_NETISR(0);
755 * The ifaddr processing in the following loop will block,
756 * however, this function is called in netisr0, in which
757 * ifaddr list changes happen, so we don't care about the
758 * blockness of the ifaddr processing here.
760 TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
761 ifa_link, next) {
762 struct ifaddr *ifa = ifac->ifa;
764 /* Ignore marker */
765 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
766 continue;
768 /* Leave link ifaddr as it is */
769 if (ifa->ifa_addr->sa_family == AF_LINK)
770 continue;
771 #ifdef INET
772 /* XXX: Ugly!! ad hoc just for INET */
773 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
774 struct ifaliasreq ifr;
775 #ifdef IFADDR_DEBUG_VERBOSE
776 int i;
778 kprintf("purge in4 addr %p: ", ifa);
779 for (i = 0; i < ncpus; ++i)
780 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
781 kprintf("\n");
782 #endif
784 bzero(&ifr, sizeof ifr);
785 ifr.ifra_addr = *ifa->ifa_addr;
786 if (ifa->ifa_dstaddr)
787 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
788 if (in_control(SIOCDIFADDR, (caddr_t)&ifr, ifp,
789 NULL) == 0)
790 continue;
792 #endif /* INET */
793 #ifdef INET6
794 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
795 #ifdef IFADDR_DEBUG_VERBOSE
796 int i;
798 kprintf("purge in6 addr %p: ", ifa);
799 for (i = 0; i < ncpus; ++i)
800 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
801 kprintf("\n");
802 #endif
804 in6_purgeaddr(ifa);
805 /* ifp_addrhead is already updated */
806 continue;
808 #endif /* INET6 */
809 ifa_ifunlink(ifa, ifp);
810 ifa_destroy(ifa);
813 lwkt_replymsg(lmsg, 0);
816 void
817 if_purgeaddrs_nolink(struct ifnet *ifp)
819 struct netmsg_base nmsg;
820 struct lwkt_msg *lmsg = &nmsg.lmsg;
822 ASSERT_CANDOMSG_NETISR0(curthread);
824 netmsg_init(&nmsg, NULL, &curthread->td_msgport, 0,
825 if_purgeaddrs_nolink_dispatch);
826 lmsg->u.ms_resultp = ifp;
827 lwkt_domsg(netisr_cpuport(0), lmsg, 0);
830 static void
831 ifq_stage_detach_handler(netmsg_t nmsg)
833 struct ifaltq *ifq = nmsg->lmsg.u.ms_resultp;
834 int q;
836 for (q = 0; q < ifq->altq_subq_cnt; ++q) {
837 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
838 struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
840 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED)
841 ifsq_stage_remove(&ifsubq_stage_heads[mycpuid], stage);
843 lwkt_replymsg(&nmsg->lmsg, 0);
846 static void
847 ifq_stage_detach(struct ifaltq *ifq)
849 struct netmsg_base base;
850 int cpu;
852 netmsg_init(&base, NULL, &curthread->td_msgport, 0,
853 ifq_stage_detach_handler);
854 base.lmsg.u.ms_resultp = ifq;
856 for (cpu = 0; cpu < ncpus; ++cpu)
857 lwkt_domsg(netisr_cpuport(cpu), &base.lmsg, 0);
860 struct netmsg_if_rtdel {
861 struct netmsg_base base;
862 struct ifnet *ifp;
865 static void
866 if_rtdel_dispatch(netmsg_t msg)
868 struct netmsg_if_rtdel *rmsg = (void *)msg;
869 int i, nextcpu, cpu;
871 cpu = mycpuid;
872 for (i = 1; i <= AF_MAX; i++) {
873 struct radix_node_head *rnh;
875 if ((rnh = rt_tables[cpu][i]) == NULL)
876 continue;
877 rnh->rnh_walktree(rnh, if_rtdel, rmsg->ifp);
880 nextcpu = cpu + 1;
881 if (nextcpu < ncpus)
882 lwkt_forwardmsg(netisr_cpuport(nextcpu), &rmsg->base.lmsg);
883 else
884 lwkt_replymsg(&rmsg->base.lmsg, 0);
888 * Detach an interface, removing it from the
889 * list of "active" interfaces.
891 void
892 if_detach(struct ifnet *ifp)
894 struct ifnet_array *old_ifnet_array;
895 struct netmsg_if_rtdel msg;
896 struct domain *dp;
897 int q;
899 /* Announce that the interface is gone. */
900 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
901 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
902 devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
905 * Remove this ifp from ifindex2inet, ifnet queue and ifnet
906 * array before it is whacked.
908 * Protect ifindex2ifnet, ifnet queue and ifnet array changes
909 * by ifnet lock, so that non-netisr threads could get a
910 * consistent view.
912 ifnet_lock();
915 * Remove this ifp from ifindex2ifnet and maybe decrement if_index.
917 ifindex2ifnet[ifp->if_index] = NULL;
918 while (if_index > 0 && ifindex2ifnet[if_index] == NULL)
919 if_index--;
922 * Remove this ifp from ifnet queue.
924 TAILQ_REMOVE(&ifnetlist, ifp, if_link);
927 * Remove this ifp from ifnet array.
929 /* Free old ifnet array after sync all netisrs */
930 old_ifnet_array = ifnet_array;
931 ifnet_array = ifnet_array_del(ifp, old_ifnet_array);
933 ifnet_unlock();
936 * Sync all netisrs so that the old ifnet array is no longer
937 * accessed and we can free it safely later on.
939 netmsg_service_sync();
940 ifnet_array_free(old_ifnet_array);
943 * Remove routes and flush queues.
945 crit_enter();
946 #ifdef IFPOLL_ENABLE
947 if (ifp->if_flags & IFF_NPOLLING)
948 ifpoll_deregister(ifp);
949 #endif
950 if_down(ifp);
952 /* Decrease the mbuf clusters/jclusters limits increased by us */
953 if (ifp->if_nmbclusters > 0)
954 mcl_inclimit(-ifp->if_nmbclusters);
955 if (ifp->if_nmbjclusters > 0)
956 mjcl_inclimit(-ifp->if_nmbjclusters);
958 #ifdef ALTQ
959 if (ifq_is_enabled(&ifp->if_snd))
960 altq_disable(&ifp->if_snd);
961 if (ifq_is_attached(&ifp->if_snd))
962 altq_detach(&ifp->if_snd);
963 #endif
966 * Clean up all addresses.
968 ifp->if_lladdr = NULL;
970 if_purgeaddrs_nolink(ifp);
971 if (!TAILQ_EMPTY(&ifp->if_addrheads[mycpuid])) {
972 struct ifaddr *ifa;
974 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
975 KASSERT(ifa->ifa_addr->sa_family == AF_LINK,
976 ("non-link ifaddr is left on if_addrheads"));
978 ifa_ifunlink(ifa, ifp);
979 ifa_destroy(ifa);
980 KASSERT(TAILQ_EMPTY(&ifp->if_addrheads[mycpuid]),
981 ("there are still ifaddrs left on if_addrheads"));
984 #ifdef INET
986 * Remove all IPv4 kernel structures related to ifp.
988 in_ifdetach(ifp);
989 #endif
991 #ifdef INET6
993 * Remove all IPv6 kernel structs related to ifp. This should be done
994 * before removing routing entries below, since IPv6 interface direct
995 * routes are expected to be removed by the IPv6-specific kernel API.
996 * Otherwise, the kernel will detect some inconsistency and bark it.
998 in6_ifdetach(ifp);
999 #endif
1002 * Delete all remaining routes using this interface
1004 netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
1005 if_rtdel_dispatch);
1006 msg.ifp = ifp;
1007 rt_domsg_global(&msg.base);
1009 SLIST_FOREACH(dp, &domains, dom_next)
1010 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
1011 (*dp->dom_ifdetach)(ifp,
1012 ifp->if_afdata[dp->dom_family]);
1014 kfree(ifp->if_addrheads, M_IFADDR);
1016 lwkt_synchronize_ipiqs("if_detach");
1017 ifq_stage_detach(&ifp->if_snd);
1019 for (q = 0; q < ifp->if_snd.altq_subq_cnt; ++q) {
1020 struct ifaltq_subque *ifsq = &ifp->if_snd.altq_subq[q];
1022 kfree(ifsq->ifsq_ifstart_nmsg, M_LWKTMSG);
1023 kfree(ifsq->ifsq_stage, M_DEVBUF);
1025 kfree(ifp->if_snd.altq_subq, M_DEVBUF);
1027 kfree(ifp->if_data_pcpu, M_DEVBUF);
1029 crit_exit();
1033 * Create interface group without members
1035 struct ifg_group *
1036 if_creategroup(const char *groupname)
1038 struct ifg_group *ifg = NULL;
1040 if ((ifg = (struct ifg_group *)kmalloc(sizeof(struct ifg_group),
1041 M_TEMP, M_NOWAIT)) == NULL)
1042 return (NULL);
1044 strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1045 ifg->ifg_refcnt = 0;
1046 ifg->ifg_carp_demoted = 0;
1047 TAILQ_INIT(&ifg->ifg_members);
1048 #if NPF > 0
1049 pfi_attach_ifgroup(ifg);
1050 #endif
1051 TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
1053 return (ifg);
1057 * Add a group to an interface
1060 if_addgroup(struct ifnet *ifp, const char *groupname)
1062 struct ifg_list *ifgl;
1063 struct ifg_group *ifg = NULL;
1064 struct ifg_member *ifgm;
1066 if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1067 groupname[strlen(groupname) - 1] <= '9')
1068 return (EINVAL);
1070 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1071 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1072 return (EEXIST);
1074 if ((ifgl = kmalloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL)
1075 return (ENOMEM);
1077 if ((ifgm = kmalloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
1078 kfree(ifgl, M_TEMP);
1079 return (ENOMEM);
1082 TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1083 if (!strcmp(ifg->ifg_group, groupname))
1084 break;
1086 if (ifg == NULL && (ifg = if_creategroup(groupname)) == NULL) {
1087 kfree(ifgl, M_TEMP);
1088 kfree(ifgm, M_TEMP);
1089 return (ENOMEM);
1092 ifg->ifg_refcnt++;
1093 ifgl->ifgl_group = ifg;
1094 ifgm->ifgm_ifp = ifp;
1096 TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1097 TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1099 #if NPF > 0
1100 pfi_group_change(groupname);
1101 #endif
1103 return (0);
1107 * Remove a group from an interface
1110 if_delgroup(struct ifnet *ifp, const char *groupname)
1112 struct ifg_list *ifgl;
1113 struct ifg_member *ifgm;
1115 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1116 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1117 break;
1118 if (ifgl == NULL)
1119 return (ENOENT);
1121 TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1123 TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1124 if (ifgm->ifgm_ifp == ifp)
1125 break;
1127 if (ifgm != NULL) {
1128 TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1129 kfree(ifgm, M_TEMP);
1132 if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1133 TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
1134 #if NPF > 0
1135 pfi_detach_ifgroup(ifgl->ifgl_group);
1136 #endif
1137 kfree(ifgl->ifgl_group, M_TEMP);
1140 kfree(ifgl, M_TEMP);
1142 #if NPF > 0
1143 pfi_group_change(groupname);
1144 #endif
1146 return (0);
1150 * Stores all groups from an interface in memory pointed
1151 * to by data
1154 if_getgroup(caddr_t data, struct ifnet *ifp)
1156 int len, error;
1157 struct ifg_list *ifgl;
1158 struct ifg_req ifgrq, *ifgp;
1159 struct ifgroupreq *ifgr = (struct ifgroupreq *)data;
1161 if (ifgr->ifgr_len == 0) {
1162 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1163 ifgr->ifgr_len += sizeof(struct ifg_req);
1164 return (0);
1167 len = ifgr->ifgr_len;
1168 ifgp = ifgr->ifgr_groups;
1169 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1170 if (len < sizeof(ifgrq))
1171 return (EINVAL);
1172 bzero(&ifgrq, sizeof ifgrq);
1173 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1174 sizeof(ifgrq.ifgrq_group));
1175 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1176 sizeof(struct ifg_req))))
1177 return (error);
1178 len -= sizeof(ifgrq);
1179 ifgp++;
1182 return (0);
1186 * Stores all members of a group in memory pointed to by data
1189 if_getgroupmembers(caddr_t data)
1191 struct ifgroupreq *ifgr = (struct ifgroupreq *)data;
1192 struct ifg_group *ifg;
1193 struct ifg_member *ifgm;
1194 struct ifg_req ifgrq, *ifgp;
1195 int len, error;
1197 TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1198 if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1199 break;
1200 if (ifg == NULL)
1201 return (ENOENT);
1203 if (ifgr->ifgr_len == 0) {
1204 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1205 ifgr->ifgr_len += sizeof(ifgrq);
1206 return (0);
1209 len = ifgr->ifgr_len;
1210 ifgp = ifgr->ifgr_groups;
1211 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1212 if (len < sizeof(ifgrq))
1213 return (EINVAL);
1214 bzero(&ifgrq, sizeof ifgrq);
1215 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1216 sizeof(ifgrq.ifgrq_member));
1217 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1218 sizeof(struct ifg_req))))
1219 return (error);
1220 len -= sizeof(ifgrq);
1221 ifgp++;
1224 return (0);
1228 * Delete Routes for a Network Interface
1230 * Called for each routing entry via the rnh->rnh_walktree() call above
1231 * to delete all route entries referencing a detaching network interface.
1233 * Arguments:
1234 * rn pointer to node in the routing table
1235 * arg argument passed to rnh->rnh_walktree() - detaching interface
1237 * Returns:
1238 * 0 successful
1239 * errno failed - reason indicated
1242 static int
1243 if_rtdel(struct radix_node *rn, void *arg)
1245 struct rtentry *rt = (struct rtentry *)rn;
1246 struct ifnet *ifp = arg;
1247 int err;
1249 if (rt->rt_ifp == ifp) {
1252 * Protect (sorta) against walktree recursion problems
1253 * with cloned routes
1255 if (!(rt->rt_flags & RTF_UP))
1256 return (0);
1258 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1259 rt_mask(rt), rt->rt_flags,
1260 NULL);
1261 if (err) {
1262 log(LOG_WARNING, "if_rtdel: error %d\n", err);
1266 return (0);
1269 static __inline boolean_t
1270 ifa_prefer(const struct ifaddr *cur_ifa, const struct ifaddr *old_ifa)
1272 if (old_ifa == NULL)
1273 return TRUE;
1275 if ((old_ifa->ifa_ifp->if_flags & IFF_UP) == 0 &&
1276 (cur_ifa->ifa_ifp->if_flags & IFF_UP))
1277 return TRUE;
1278 if ((old_ifa->ifa_flags & IFA_ROUTE) == 0 &&
1279 (cur_ifa->ifa_flags & IFA_ROUTE))
1280 return TRUE;
1281 return FALSE;
1285 * Locate an interface based on a complete address.
1287 struct ifaddr *
1288 ifa_ifwithaddr(struct sockaddr *addr)
1290 const struct ifnet_array *arr;
1291 int i;
1293 arr = ifnet_array_get();
1294 for (i = 0; i < arr->ifnet_count; ++i) {
1295 struct ifnet *ifp = arr->ifnet_arr[i];
1296 struct ifaddr_container *ifac;
1298 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1299 struct ifaddr *ifa = ifac->ifa;
1301 if (ifa->ifa_addr->sa_family != addr->sa_family)
1302 continue;
1303 if (sa_equal(addr, ifa->ifa_addr))
1304 return (ifa);
1305 if ((ifp->if_flags & IFF_BROADCAST) &&
1306 ifa->ifa_broadaddr &&
1307 /* IPv6 doesn't have broadcast */
1308 ifa->ifa_broadaddr->sa_len != 0 &&
1309 sa_equal(ifa->ifa_broadaddr, addr))
1310 return (ifa);
1313 return (NULL);
1317 * Locate the point to point interface with a given destination address.
1319 struct ifaddr *
1320 ifa_ifwithdstaddr(struct sockaddr *addr)
1322 const struct ifnet_array *arr;
1323 int i;
1325 arr = ifnet_array_get();
1326 for (i = 0; i < arr->ifnet_count; ++i) {
1327 struct ifnet *ifp = arr->ifnet_arr[i];
1328 struct ifaddr_container *ifac;
1330 if (!(ifp->if_flags & IFF_POINTOPOINT))
1331 continue;
1333 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1334 struct ifaddr *ifa = ifac->ifa;
1336 if (ifa->ifa_addr->sa_family != addr->sa_family)
1337 continue;
1338 if (ifa->ifa_dstaddr &&
1339 sa_equal(addr, ifa->ifa_dstaddr))
1340 return (ifa);
1343 return (NULL);
1347 * Find an interface on a specific network. If many, choice
1348 * is most specific found.
1350 struct ifaddr *
1351 ifa_ifwithnet(struct sockaddr *addr)
1353 struct ifaddr *ifa_maybe = NULL;
1354 u_int af = addr->sa_family;
1355 char *addr_data = addr->sa_data, *cplim;
1356 const struct ifnet_array *arr;
1357 int i;
1360 * AF_LINK addresses can be looked up directly by their index number,
1361 * so do that if we can.
1363 if (af == AF_LINK) {
1364 struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1366 if (sdl->sdl_index && sdl->sdl_index <= if_index)
1367 return (ifindex2ifnet[sdl->sdl_index]->if_lladdr);
1371 * Scan though each interface, looking for ones that have
1372 * addresses in this address family.
1374 arr = ifnet_array_get();
1375 for (i = 0; i < arr->ifnet_count; ++i) {
1376 struct ifnet *ifp = arr->ifnet_arr[i];
1377 struct ifaddr_container *ifac;
1379 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1380 struct ifaddr *ifa = ifac->ifa;
1381 char *cp, *cp2, *cp3;
1383 if (ifa->ifa_addr->sa_family != af)
1384 next: continue;
1385 if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1387 * This is a bit broken as it doesn't
1388 * take into account that the remote end may
1389 * be a single node in the network we are
1390 * looking for.
1391 * The trouble is that we don't know the
1392 * netmask for the remote end.
1394 if (ifa->ifa_dstaddr != NULL &&
1395 sa_equal(addr, ifa->ifa_dstaddr))
1396 return (ifa);
1397 } else {
1399 * if we have a special address handler,
1400 * then use it instead of the generic one.
1402 if (ifa->ifa_claim_addr) {
1403 if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1404 return (ifa);
1405 } else {
1406 continue;
1411 * Scan all the bits in the ifa's address.
1412 * If a bit dissagrees with what we are
1413 * looking for, mask it with the netmask
1414 * to see if it really matters.
1415 * (A byte at a time)
1417 if (ifa->ifa_netmask == 0)
1418 continue;
1419 cp = addr_data;
1420 cp2 = ifa->ifa_addr->sa_data;
1421 cp3 = ifa->ifa_netmask->sa_data;
1422 cplim = ifa->ifa_netmask->sa_len +
1423 (char *)ifa->ifa_netmask;
1424 while (cp3 < cplim)
1425 if ((*cp++ ^ *cp2++) & *cp3++)
1426 goto next; /* next address! */
1428 * If the netmask of what we just found
1429 * is more specific than what we had before
1430 * (if we had one) then remember the new one
1431 * before continuing to search for an even
1432 * better one. If the netmasks are equal,
1433 * we prefer the this ifa based on the result
1434 * of ifa_prefer().
1436 if (ifa_maybe == NULL ||
1437 rn_refines((char *)ifa->ifa_netmask,
1438 (char *)ifa_maybe->ifa_netmask) ||
1439 (sa_equal(ifa_maybe->ifa_netmask,
1440 ifa->ifa_netmask) &&
1441 ifa_prefer(ifa, ifa_maybe)))
1442 ifa_maybe = ifa;
1446 return (ifa_maybe);
1450 * Find an interface address specific to an interface best matching
1451 * a given address.
1453 struct ifaddr *
1454 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1456 struct ifaddr_container *ifac;
1457 char *cp, *cp2, *cp3;
1458 char *cplim;
1459 struct ifaddr *ifa_maybe = NULL;
1460 u_int af = addr->sa_family;
1462 if (af >= AF_MAX)
1463 return (0);
1464 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1465 struct ifaddr *ifa = ifac->ifa;
1467 if (ifa->ifa_addr->sa_family != af)
1468 continue;
1469 if (ifa_maybe == NULL)
1470 ifa_maybe = ifa;
1471 if (ifa->ifa_netmask == NULL) {
1472 if (sa_equal(addr, ifa->ifa_addr) ||
1473 (ifa->ifa_dstaddr != NULL &&
1474 sa_equal(addr, ifa->ifa_dstaddr)))
1475 return (ifa);
1476 continue;
1478 if (ifp->if_flags & IFF_POINTOPOINT) {
1479 if (sa_equal(addr, ifa->ifa_dstaddr))
1480 return (ifa);
1481 } else {
1482 cp = addr->sa_data;
1483 cp2 = ifa->ifa_addr->sa_data;
1484 cp3 = ifa->ifa_netmask->sa_data;
1485 cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1486 for (; cp3 < cplim; cp3++)
1487 if ((*cp++ ^ *cp2++) & *cp3)
1488 break;
1489 if (cp3 == cplim)
1490 return (ifa);
1493 return (ifa_maybe);
1497 * Default action when installing a route with a Link Level gateway.
1498 * Lookup an appropriate real ifa to point to.
1499 * This should be moved to /sys/net/link.c eventually.
1501 static void
1502 link_rtrequest(int cmd, struct rtentry *rt)
1504 struct ifaddr *ifa;
1505 struct sockaddr *dst;
1506 struct ifnet *ifp;
1508 if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1509 (ifp = ifa->ifa_ifp) == NULL || (dst = rt_key(rt)) == NULL)
1510 return;
1511 ifa = ifaof_ifpforaddr(dst, ifp);
1512 if (ifa != NULL) {
1513 IFAFREE(rt->rt_ifa);
1514 IFAREF(ifa);
1515 rt->rt_ifa = ifa;
1516 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1517 ifa->ifa_rtrequest(cmd, rt);
1521 struct netmsg_ifroute {
1522 struct netmsg_base base;
1523 struct ifnet *ifp;
1524 int flag;
1525 int fam;
1529 * Mark an interface down and notify protocols of the transition.
1531 static void
1532 if_unroute_dispatch(netmsg_t nmsg)
1534 struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1535 struct ifnet *ifp = msg->ifp;
1536 int flag = msg->flag, fam = msg->fam;
1537 struct ifaddr_container *ifac;
1539 ifp->if_flags &= ~flag;
1540 getmicrotime(&ifp->if_lastchange);
1542 * The ifaddr processing in the following loop will block,
1543 * however, this function is called in netisr0, in which
1544 * ifaddr list changes happen, so we don't care about the
1545 * blockness of the ifaddr processing here.
1547 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1548 struct ifaddr *ifa = ifac->ifa;
1550 /* Ignore marker */
1551 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1552 continue;
1554 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1555 kpfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1557 ifq_purge_all(&ifp->if_snd);
1558 rt_ifmsg(ifp);
1560 lwkt_replymsg(&nmsg->lmsg, 0);
1563 void
1564 if_unroute(struct ifnet *ifp, int flag, int fam)
1566 struct netmsg_ifroute msg;
1568 ASSERT_CANDOMSG_NETISR0(curthread);
1570 netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1571 if_unroute_dispatch);
1572 msg.ifp = ifp;
1573 msg.flag = flag;
1574 msg.fam = fam;
1575 lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1579 * Mark an interface up and notify protocols of the transition.
1581 static void
1582 if_route_dispatch(netmsg_t nmsg)
1584 struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1585 struct ifnet *ifp = msg->ifp;
1586 int flag = msg->flag, fam = msg->fam;
1587 struct ifaddr_container *ifac;
1589 ifq_purge_all(&ifp->if_snd);
1590 ifp->if_flags |= flag;
1591 getmicrotime(&ifp->if_lastchange);
1593 * The ifaddr processing in the following loop will block,
1594 * however, this function is called in netisr0, in which
1595 * ifaddr list changes happen, so we don't care about the
1596 * blockness of the ifaddr processing here.
1598 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1599 struct ifaddr *ifa = ifac->ifa;
1601 /* Ignore marker */
1602 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1603 continue;
1605 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1606 kpfctlinput(PRC_IFUP, ifa->ifa_addr);
1608 rt_ifmsg(ifp);
1609 #ifdef INET6
1610 in6_if_up(ifp);
1611 #endif
1613 lwkt_replymsg(&nmsg->lmsg, 0);
1616 void
1617 if_route(struct ifnet *ifp, int flag, int fam)
1619 struct netmsg_ifroute msg;
1621 ASSERT_CANDOMSG_NETISR0(curthread);
1623 netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1624 if_route_dispatch);
1625 msg.ifp = ifp;
1626 msg.flag = flag;
1627 msg.fam = fam;
1628 lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1632 * Mark an interface down and notify protocols of the transition. An
1633 * interface going down is also considered to be a synchronizing event.
1634 * We must ensure that all packet processing related to the interface
1635 * has completed before we return so e.g. the caller can free the ifnet
1636 * structure that the mbufs may be referencing.
1638 * NOTE: must be called at splnet or eqivalent.
1640 void
1641 if_down(struct ifnet *ifp)
1643 if_unroute(ifp, IFF_UP, AF_UNSPEC);
1644 netmsg_service_sync();
1648 * Mark an interface up and notify protocols of
1649 * the transition.
1650 * NOTE: must be called at splnet or eqivalent.
1652 void
1653 if_up(struct ifnet *ifp)
1655 if_route(ifp, IFF_UP, AF_UNSPEC);
1659 * Process a link state change.
1660 * NOTE: must be called at splsoftnet or equivalent.
1662 void
1663 if_link_state_change(struct ifnet *ifp)
1665 int link_state = ifp->if_link_state;
1667 rt_ifmsg(ifp);
1668 devctl_notify("IFNET", ifp->if_xname,
1669 (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1673 * Handle interface watchdog timer routines. Called
1674 * from softclock, we decrement timers (if set) and
1675 * call the appropriate interface routine on expiration.
1677 static void
1678 if_slowtimo_dispatch(netmsg_t nmsg)
1680 struct globaldata *gd = mycpu;
1681 const struct ifnet_array *arr;
1682 int i;
1684 ASSERT_IN_NETISR(0);
1686 crit_enter_gd(gd);
1687 lwkt_replymsg(&nmsg->lmsg, 0); /* reply ASAP */
1688 crit_exit_gd(gd);
1690 arr = ifnet_array_get();
1691 for (i = 0; i < arr->ifnet_count; ++i) {
1692 struct ifnet *ifp = arr->ifnet_arr[i];
1694 crit_enter_gd(gd);
1696 if (if_stats_compat) {
1697 IFNET_STAT_GET(ifp, ipackets, ifp->if_ipackets);
1698 IFNET_STAT_GET(ifp, ierrors, ifp->if_ierrors);
1699 IFNET_STAT_GET(ifp, opackets, ifp->if_opackets);
1700 IFNET_STAT_GET(ifp, oerrors, ifp->if_oerrors);
1701 IFNET_STAT_GET(ifp, collisions, ifp->if_collisions);
1702 IFNET_STAT_GET(ifp, ibytes, ifp->if_ibytes);
1703 IFNET_STAT_GET(ifp, obytes, ifp->if_obytes);
1704 IFNET_STAT_GET(ifp, imcasts, ifp->if_imcasts);
1705 IFNET_STAT_GET(ifp, omcasts, ifp->if_omcasts);
1706 IFNET_STAT_GET(ifp, iqdrops, ifp->if_iqdrops);
1707 IFNET_STAT_GET(ifp, noproto, ifp->if_noproto);
1708 IFNET_STAT_GET(ifp, oqdrops, ifp->if_oqdrops);
1711 if (ifp->if_timer == 0 || --ifp->if_timer) {
1712 crit_exit_gd(gd);
1713 continue;
1715 if (ifp->if_watchdog) {
1716 if (ifnet_tryserialize_all(ifp)) {
1717 (*ifp->if_watchdog)(ifp);
1718 ifnet_deserialize_all(ifp);
1719 } else {
1720 /* try again next timeout */
1721 ++ifp->if_timer;
1725 crit_exit_gd(gd);
1728 callout_reset(&if_slowtimo_timer, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1731 static void
1732 if_slowtimo(void *arg __unused)
1734 struct lwkt_msg *lmsg = &if_slowtimo_netmsg.lmsg;
1736 KASSERT(mycpuid == 0, ("not on cpu0"));
1737 crit_enter();
1738 if (lmsg->ms_flags & MSGF_DONE)
1739 lwkt_sendmsg_oncpu(netisr_cpuport(0), lmsg);
1740 crit_exit();
1744 * Map interface name to
1745 * interface structure pointer.
1747 struct ifnet *
1748 ifunit(const char *name)
1750 struct ifnet *ifp;
1753 * Search all the interfaces for this name/number
1755 KASSERT(mtx_owned(&ifnet_mtx), ("ifnet is not locked"));
1757 TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
1758 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1759 break;
1761 return (ifp);
1764 struct ifnet *
1765 ifunit_netisr(const char *name)
1767 const struct ifnet_array *arr;
1768 int i;
1771 * Search all the interfaces for this name/number
1774 arr = ifnet_array_get();
1775 for (i = 0; i < arr->ifnet_count; ++i) {
1776 struct ifnet *ifp = arr->ifnet_arr[i];
1778 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1779 return ifp;
1781 return NULL;
1785 * Interface ioctls.
1788 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct ucred *cred)
1790 struct ifnet *ifp;
1791 struct ifreq *ifr;
1792 struct ifstat *ifs;
1793 int error, do_ifup = 0;
1794 short oif_flags;
1795 int new_flags;
1796 size_t namelen, onamelen;
1797 char new_name[IFNAMSIZ];
1798 struct ifaddr *ifa;
1799 struct sockaddr_dl *sdl;
1801 switch (cmd) {
1802 case SIOCGIFCONF:
1803 case OSIOCGIFCONF:
1804 return (ifconf(cmd, data, cred));
1805 default:
1806 break;
1809 ifr = (struct ifreq *)data;
1811 switch (cmd) {
1812 case SIOCIFCREATE:
1813 case SIOCIFCREATE2:
1814 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1815 return (error);
1816 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1817 cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1818 case SIOCIFDESTROY:
1819 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1820 return (error);
1821 return (if_clone_destroy(ifr->ifr_name));
1822 case SIOCIFGCLONERS:
1823 return (if_clone_list((struct if_clonereq *)data));
1824 default:
1825 break;
1829 * Nominal ioctl through interface, lookup the ifp and obtain a
1830 * lock to serialize the ifconfig ioctl operation.
1832 ifnet_lock();
1834 ifp = ifunit(ifr->ifr_name);
1835 if (ifp == NULL) {
1836 ifnet_unlock();
1837 return (ENXIO);
1839 error = 0;
1841 switch (cmd) {
1842 case SIOCGIFINDEX:
1843 ifr->ifr_index = ifp->if_index;
1844 break;
1846 case SIOCGIFFLAGS:
1847 ifr->ifr_flags = ifp->if_flags;
1848 ifr->ifr_flagshigh = ifp->if_flags >> 16;
1849 break;
1851 case SIOCGIFCAP:
1852 ifr->ifr_reqcap = ifp->if_capabilities;
1853 ifr->ifr_curcap = ifp->if_capenable;
1854 break;
1856 case SIOCGIFMETRIC:
1857 ifr->ifr_metric = ifp->if_metric;
1858 break;
1860 case SIOCGIFMTU:
1861 ifr->ifr_mtu = ifp->if_mtu;
1862 break;
1864 case SIOCGIFTSOLEN:
1865 ifr->ifr_tsolen = ifp->if_tsolen;
1866 break;
1868 case SIOCGIFDATA:
1869 error = copyout((caddr_t)&ifp->if_data, ifr->ifr_data,
1870 sizeof(ifp->if_data));
1871 break;
1873 case SIOCGIFPHYS:
1874 ifr->ifr_phys = ifp->if_physical;
1875 break;
1877 case SIOCGIFPOLLCPU:
1878 ifr->ifr_pollcpu = -1;
1879 break;
1881 case SIOCSIFPOLLCPU:
1882 break;
1884 case SIOCSIFFLAGS:
1885 error = priv_check_cred(cred, PRIV_ROOT, 0);
1886 if (error)
1887 break;
1888 new_flags = (ifr->ifr_flags & 0xffff) |
1889 (ifr->ifr_flagshigh << 16);
1890 if (ifp->if_flags & IFF_SMART) {
1891 /* Smart drivers twiddle their own routes */
1892 } else if (ifp->if_flags & IFF_UP &&
1893 (new_flags & IFF_UP) == 0) {
1894 if_down(ifp);
1895 } else if (new_flags & IFF_UP &&
1896 (ifp->if_flags & IFF_UP) == 0) {
1897 do_ifup = 1;
1900 #ifdef IFPOLL_ENABLE
1901 if ((new_flags ^ ifp->if_flags) & IFF_NPOLLING) {
1902 if (new_flags & IFF_NPOLLING)
1903 ifpoll_register(ifp);
1904 else
1905 ifpoll_deregister(ifp);
1907 #endif
1909 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1910 (new_flags &~ IFF_CANTCHANGE);
1911 if (new_flags & IFF_PPROMISC) {
1912 /* Permanently promiscuous mode requested */
1913 ifp->if_flags |= IFF_PROMISC;
1914 } else if (ifp->if_pcount == 0) {
1915 ifp->if_flags &= ~IFF_PROMISC;
1917 if (ifp->if_ioctl) {
1918 ifnet_serialize_all(ifp);
1919 ifp->if_ioctl(ifp, cmd, data, cred);
1920 ifnet_deserialize_all(ifp);
1922 if (do_ifup)
1923 if_up(ifp);
1924 getmicrotime(&ifp->if_lastchange);
1925 break;
1927 case SIOCSIFCAP:
1928 error = priv_check_cred(cred, PRIV_ROOT, 0);
1929 if (error)
1930 break;
1931 if (ifr->ifr_reqcap & ~ifp->if_capabilities) {
1932 error = EINVAL;
1933 break;
1935 ifnet_serialize_all(ifp);
1936 ifp->if_ioctl(ifp, cmd, data, cred);
1937 ifnet_deserialize_all(ifp);
1938 break;
1940 case SIOCSIFNAME:
1941 error = priv_check_cred(cred, PRIV_ROOT, 0);
1942 if (error)
1943 break;
1944 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1945 if (error)
1946 break;
1947 if (new_name[0] == '\0') {
1948 error = EINVAL;
1949 break;
1951 if (ifunit(new_name) != NULL) {
1952 error = EEXIST;
1953 break;
1956 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
1958 /* Announce the departure of the interface. */
1959 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1961 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1962 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
1963 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1964 namelen = strlen(new_name);
1965 onamelen = sdl->sdl_nlen;
1967 * Move the address if needed. This is safe because we
1968 * allocate space for a name of length IFNAMSIZ when we
1969 * create this in if_attach().
1971 if (namelen != onamelen) {
1972 bcopy(sdl->sdl_data + onamelen,
1973 sdl->sdl_data + namelen, sdl->sdl_alen);
1975 bcopy(new_name, sdl->sdl_data, namelen);
1976 sdl->sdl_nlen = namelen;
1977 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1978 bzero(sdl->sdl_data, onamelen);
1979 while (namelen != 0)
1980 sdl->sdl_data[--namelen] = 0xff;
1982 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
1984 /* Announce the return of the interface. */
1985 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1986 break;
1988 case SIOCSIFMETRIC:
1989 error = priv_check_cred(cred, PRIV_ROOT, 0);
1990 if (error)
1991 break;
1992 ifp->if_metric = ifr->ifr_metric;
1993 getmicrotime(&ifp->if_lastchange);
1994 break;
1996 case SIOCSIFPHYS:
1997 error = priv_check_cred(cred, PRIV_ROOT, 0);
1998 if (error)
1999 break;
2000 if (ifp->if_ioctl == NULL) {
2001 error = EOPNOTSUPP;
2002 break;
2004 ifnet_serialize_all(ifp);
2005 error = ifp->if_ioctl(ifp, cmd, data, cred);
2006 ifnet_deserialize_all(ifp);
2007 if (error == 0)
2008 getmicrotime(&ifp->if_lastchange);
2009 break;
2011 case SIOCSIFMTU:
2013 u_long oldmtu = ifp->if_mtu;
2015 error = priv_check_cred(cred, PRIV_ROOT, 0);
2016 if (error)
2017 break;
2018 if (ifp->if_ioctl == NULL) {
2019 error = EOPNOTSUPP;
2020 break;
2022 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU) {
2023 error = EINVAL;
2024 break;
2026 ifnet_serialize_all(ifp);
2027 error = ifp->if_ioctl(ifp, cmd, data, cred);
2028 ifnet_deserialize_all(ifp);
2029 if (error == 0) {
2030 getmicrotime(&ifp->if_lastchange);
2031 rt_ifmsg(ifp);
2034 * If the link MTU changed, do network layer specific procedure.
2036 if (ifp->if_mtu != oldmtu) {
2037 #ifdef INET6
2038 nd6_setmtu(ifp);
2039 #endif
2041 break;
2044 case SIOCSIFTSOLEN:
2045 error = priv_check_cred(cred, PRIV_ROOT, 0);
2046 if (error)
2047 break;
2049 /* XXX need driver supplied upper limit */
2050 if (ifr->ifr_tsolen <= 0) {
2051 error = EINVAL;
2052 break;
2054 ifp->if_tsolen = ifr->ifr_tsolen;
2055 break;
2057 case SIOCADDMULTI:
2058 case SIOCDELMULTI:
2059 error = priv_check_cred(cred, PRIV_ROOT, 0);
2060 if (error)
2061 break;
2063 /* Don't allow group membership on non-multicast interfaces. */
2064 if ((ifp->if_flags & IFF_MULTICAST) == 0) {
2065 error = EOPNOTSUPP;
2066 break;
2069 /* Don't let users screw up protocols' entries. */
2070 if (ifr->ifr_addr.sa_family != AF_LINK) {
2071 error = EINVAL;
2072 break;
2075 if (cmd == SIOCADDMULTI) {
2076 struct ifmultiaddr *ifma;
2077 error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2078 } else {
2079 error = if_delmulti(ifp, &ifr->ifr_addr);
2081 if (error == 0)
2082 getmicrotime(&ifp->if_lastchange);
2083 break;
2085 case SIOCSIFPHYADDR:
2086 case SIOCDIFPHYADDR:
2087 #ifdef INET6
2088 case SIOCSIFPHYADDR_IN6:
2089 #endif
2090 case SIOCSLIFPHYADDR:
2091 case SIOCSIFMEDIA:
2092 case SIOCSIFGENERIC:
2093 error = priv_check_cred(cred, PRIV_ROOT, 0);
2094 if (error)
2095 break;
2096 if (ifp->if_ioctl == 0) {
2097 error = EOPNOTSUPP;
2098 break;
2100 ifnet_serialize_all(ifp);
2101 error = ifp->if_ioctl(ifp, cmd, data, cred);
2102 ifnet_deserialize_all(ifp);
2103 if (error == 0)
2104 getmicrotime(&ifp->if_lastchange);
2105 break;
2107 case SIOCGIFSTATUS:
2108 ifs = (struct ifstat *)data;
2109 ifs->ascii[0] = '\0';
2110 /* fall through */
2111 case SIOCGIFPSRCADDR:
2112 case SIOCGIFPDSTADDR:
2113 case SIOCGLIFPHYADDR:
2114 case SIOCGIFMEDIA:
2115 case SIOCGIFGENERIC:
2116 if (ifp->if_ioctl == NULL) {
2117 error = EOPNOTSUPP;
2118 break;
2120 ifnet_serialize_all(ifp);
2121 error = ifp->if_ioctl(ifp, cmd, data, cred);
2122 ifnet_deserialize_all(ifp);
2123 break;
2125 case SIOCSIFLLADDR:
2126 error = priv_check_cred(cred, PRIV_ROOT, 0);
2127 if (error)
2128 break;
2129 error = if_setlladdr(ifp, ifr->ifr_addr.sa_data,
2130 ifr->ifr_addr.sa_len);
2131 EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2132 break;
2134 default:
2135 oif_flags = ifp->if_flags;
2136 if (so->so_proto == 0) {
2137 error = EOPNOTSUPP;
2138 break;
2140 error = so_pru_control_direct(so, cmd, data, ifp);
2142 if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2143 #ifdef INET6
2144 DELAY(100);/* XXX: temporary workaround for fxp issue*/
2145 if (ifp->if_flags & IFF_UP) {
2146 crit_enter();
2147 in6_if_up(ifp);
2148 crit_exit();
2150 #endif
2152 break;
2155 ifnet_unlock();
2156 return (error);
2160 * Set/clear promiscuous mode on interface ifp based on the truth value
2161 * of pswitch. The calls are reference counted so that only the first
2162 * "on" request actually has an effect, as does the final "off" request.
2163 * Results are undefined if the "off" and "on" requests are not matched.
2166 ifpromisc(struct ifnet *ifp, int pswitch)
2168 struct ifreq ifr;
2169 int error;
2170 int oldflags;
2172 oldflags = ifp->if_flags;
2173 if (ifp->if_flags & IFF_PPROMISC) {
2174 /* Do nothing if device is in permanently promiscuous mode */
2175 ifp->if_pcount += pswitch ? 1 : -1;
2176 return (0);
2178 if (pswitch) {
2180 * If the device is not configured up, we cannot put it in
2181 * promiscuous mode.
2183 if ((ifp->if_flags & IFF_UP) == 0)
2184 return (ENETDOWN);
2185 if (ifp->if_pcount++ != 0)
2186 return (0);
2187 ifp->if_flags |= IFF_PROMISC;
2188 log(LOG_INFO, "%s: promiscuous mode enabled\n",
2189 ifp->if_xname);
2190 } else {
2191 if (--ifp->if_pcount > 0)
2192 return (0);
2193 ifp->if_flags &= ~IFF_PROMISC;
2194 log(LOG_INFO, "%s: promiscuous mode disabled\n",
2195 ifp->if_xname);
2197 ifr.ifr_flags = ifp->if_flags;
2198 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2199 ifnet_serialize_all(ifp);
2200 error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
2201 ifnet_deserialize_all(ifp);
2202 if (error == 0)
2203 rt_ifmsg(ifp);
2204 else
2205 ifp->if_flags = oldflags;
2206 return error;
2210 * Return interface configuration
2211 * of system. List may be used
2212 * in later ioctl's (above) to get
2213 * other information.
2215 static int
2216 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
2218 struct ifconf *ifc = (struct ifconf *)data;
2219 struct ifnet *ifp;
2220 struct sockaddr *sa;
2221 struct ifreq ifr, *ifrp;
2222 int space = ifc->ifc_len, error = 0;
2224 ifrp = ifc->ifc_req;
2226 ifnet_lock();
2227 TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2228 struct ifaddr_container *ifac, *ifac_mark;
2229 struct ifaddr_marker mark;
2230 struct ifaddrhead *head;
2231 int addrs;
2233 if (space <= sizeof ifr)
2234 break;
2237 * Zero the stack declared structure first to prevent
2238 * memory disclosure.
2240 bzero(&ifr, sizeof(ifr));
2241 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2242 >= sizeof(ifr.ifr_name)) {
2243 error = ENAMETOOLONG;
2244 break;
2248 * Add a marker, since copyout() could block and during that
2249 * period the list could be changed. Inserting the marker to
2250 * the header of the list will not cause trouble for the code
2251 * assuming that the first element of the list is AF_LINK; the
2252 * marker will be moved to the next position w/o blocking.
2254 ifa_marker_init(&mark, ifp);
2255 ifac_mark = &mark.ifac;
2256 head = &ifp->if_addrheads[mycpuid];
2258 addrs = 0;
2259 TAILQ_INSERT_HEAD(head, ifac_mark, ifa_link);
2260 while ((ifac = TAILQ_NEXT(ifac_mark, ifa_link)) != NULL) {
2261 struct ifaddr *ifa = ifac->ifa;
2263 TAILQ_REMOVE(head, ifac_mark, ifa_link);
2264 TAILQ_INSERT_AFTER(head, ifac, ifac_mark, ifa_link);
2266 /* Ignore marker */
2267 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
2268 continue;
2270 if (space <= sizeof ifr)
2271 break;
2272 sa = ifa->ifa_addr;
2273 if (cred->cr_prison &&
2274 prison_if(cred, sa))
2275 continue;
2276 addrs++;
2278 * Keep a reference on this ifaddr, so that it will
2279 * not be destroyed when its address is copied to
2280 * the userland, which could block.
2282 IFAREF(ifa);
2283 if (sa->sa_len <= sizeof(*sa)) {
2284 ifr.ifr_addr = *sa;
2285 error = copyout(&ifr, ifrp, sizeof ifr);
2286 ifrp++;
2287 } else {
2288 if (space < (sizeof ifr) + sa->sa_len -
2289 sizeof(*sa)) {
2290 IFAFREE(ifa);
2291 break;
2293 space -= sa->sa_len - sizeof(*sa);
2294 error = copyout(&ifr, ifrp,
2295 sizeof ifr.ifr_name);
2296 if (error == 0)
2297 error = copyout(sa, &ifrp->ifr_addr,
2298 sa->sa_len);
2299 ifrp = (struct ifreq *)
2300 (sa->sa_len + (caddr_t)&ifrp->ifr_addr);
2302 IFAFREE(ifa);
2303 if (error)
2304 break;
2305 space -= sizeof ifr;
2307 TAILQ_REMOVE(head, ifac_mark, ifa_link);
2308 if (error)
2309 break;
2310 if (!addrs) {
2311 bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
2312 error = copyout(&ifr, ifrp, sizeof ifr);
2313 if (error)
2314 break;
2315 space -= sizeof ifr;
2316 ifrp++;
2319 ifnet_unlock();
2321 ifc->ifc_len -= space;
2322 return (error);
2326 * Just like if_promisc(), but for all-multicast-reception mode.
2329 if_allmulti(struct ifnet *ifp, int onswitch)
2331 int error = 0;
2332 struct ifreq ifr;
2334 crit_enter();
2336 if (onswitch) {
2337 if (ifp->if_amcount++ == 0) {
2338 ifp->if_flags |= IFF_ALLMULTI;
2339 ifr.ifr_flags = ifp->if_flags;
2340 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2341 ifnet_serialize_all(ifp);
2342 error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2343 NULL);
2344 ifnet_deserialize_all(ifp);
2346 } else {
2347 if (ifp->if_amcount > 1) {
2348 ifp->if_amcount--;
2349 } else {
2350 ifp->if_amcount = 0;
2351 ifp->if_flags &= ~IFF_ALLMULTI;
2352 ifr.ifr_flags = ifp->if_flags;
2353 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2354 ifnet_serialize_all(ifp);
2355 error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2356 NULL);
2357 ifnet_deserialize_all(ifp);
2361 crit_exit();
2363 if (error == 0)
2364 rt_ifmsg(ifp);
2365 return error;
2369 * Add a multicast listenership to the interface in question.
2370 * The link layer provides a routine which converts
2373 if_addmulti_serialized(struct ifnet *ifp, struct sockaddr *sa,
2374 struct ifmultiaddr **retifma)
2376 struct sockaddr *llsa, *dupsa;
2377 int error;
2378 struct ifmultiaddr *ifma;
2380 ASSERT_IFNET_SERIALIZED_ALL(ifp);
2383 * If the matching multicast address already exists
2384 * then don't add a new one, just add a reference
2386 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2387 if (sa_equal(sa, ifma->ifma_addr)) {
2388 ifma->ifma_refcount++;
2389 if (retifma)
2390 *retifma = ifma;
2391 return 0;
2396 * Give the link layer a chance to accept/reject it, and also
2397 * find out which AF_LINK address this maps to, if it isn't one
2398 * already.
2400 if (ifp->if_resolvemulti) {
2401 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2402 if (error)
2403 return error;
2404 } else {
2405 llsa = NULL;
2408 ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2409 dupsa = kmalloc(sa->sa_len, M_IFMADDR, M_INTWAIT);
2410 bcopy(sa, dupsa, sa->sa_len);
2412 ifma->ifma_addr = dupsa;
2413 ifma->ifma_lladdr = llsa;
2414 ifma->ifma_ifp = ifp;
2415 ifma->ifma_refcount = 1;
2416 ifma->ifma_protospec = NULL;
2417 rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2419 TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2420 if (retifma)
2421 *retifma = ifma;
2423 if (llsa != NULL) {
2424 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2425 if (sa_equal(ifma->ifma_addr, llsa))
2426 break;
2428 if (ifma) {
2429 ifma->ifma_refcount++;
2430 } else {
2431 ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2432 dupsa = kmalloc(llsa->sa_len, M_IFMADDR, M_INTWAIT);
2433 bcopy(llsa, dupsa, llsa->sa_len);
2434 ifma->ifma_addr = dupsa;
2435 ifma->ifma_ifp = ifp;
2436 ifma->ifma_refcount = 1;
2437 TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2441 * We are certain we have added something, so call down to the
2442 * interface to let them know about it.
2444 if (ifp->if_ioctl)
2445 ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2447 return 0;
2451 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2452 struct ifmultiaddr **retifma)
2454 int error;
2456 ifnet_serialize_all(ifp);
2457 error = if_addmulti_serialized(ifp, sa, retifma);
2458 ifnet_deserialize_all(ifp);
2460 return error;
2464 * Remove a reference to a multicast address on this interface. Yell
2465 * if the request does not match an existing membership.
2467 static int
2468 if_delmulti_serialized(struct ifnet *ifp, struct sockaddr *sa)
2470 struct ifmultiaddr *ifma;
2472 ASSERT_IFNET_SERIALIZED_ALL(ifp);
2474 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2475 if (sa_equal(sa, ifma->ifma_addr))
2476 break;
2477 if (ifma == NULL)
2478 return ENOENT;
2480 if (ifma->ifma_refcount > 1) {
2481 ifma->ifma_refcount--;
2482 return 0;
2485 rt_newmaddrmsg(RTM_DELMADDR, ifma);
2486 sa = ifma->ifma_lladdr;
2487 TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2489 * Make sure the interface driver is notified
2490 * in the case of a link layer mcast group being left.
2492 if (ifma->ifma_addr->sa_family == AF_LINK && sa == NULL)
2493 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2494 kfree(ifma->ifma_addr, M_IFMADDR);
2495 kfree(ifma, M_IFMADDR);
2496 if (sa == NULL)
2497 return 0;
2500 * Now look for the link-layer address which corresponds to
2501 * this network address. It had been squirreled away in
2502 * ifma->ifma_lladdr for this purpose (so we don't have
2503 * to call ifp->if_resolvemulti() again), and we saved that
2504 * value in sa above. If some nasty deleted the
2505 * link-layer address out from underneath us, we can deal because
2506 * the address we stored was is not the same as the one which was
2507 * in the record for the link-layer address. (So we don't complain
2508 * in that case.)
2510 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2511 if (sa_equal(sa, ifma->ifma_addr))
2512 break;
2513 if (ifma == NULL)
2514 return 0;
2516 if (ifma->ifma_refcount > 1) {
2517 ifma->ifma_refcount--;
2518 return 0;
2521 TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2522 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2523 kfree(ifma->ifma_addr, M_IFMADDR);
2524 kfree(sa, M_IFMADDR);
2525 kfree(ifma, M_IFMADDR);
2527 return 0;
2531 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2533 int error;
2535 ifnet_serialize_all(ifp);
2536 error = if_delmulti_serialized(ifp, sa);
2537 ifnet_deserialize_all(ifp);
2539 return error;
2543 * Delete all multicast group membership for an interface.
2544 * Should be used to quickly flush all multicast filters.
2546 void
2547 if_delallmulti_serialized(struct ifnet *ifp)
2549 struct ifmultiaddr *ifma, mark;
2550 struct sockaddr sa;
2552 ASSERT_IFNET_SERIALIZED_ALL(ifp);
2554 bzero(&sa, sizeof(sa));
2555 sa.sa_family = AF_UNSPEC;
2556 sa.sa_len = sizeof(sa);
2558 bzero(&mark, sizeof(mark));
2559 mark.ifma_addr = &sa;
2561 TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, &mark, ifma_link);
2562 while ((ifma = TAILQ_NEXT(&mark, ifma_link)) != NULL) {
2563 TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2564 TAILQ_INSERT_AFTER(&ifp->if_multiaddrs, ifma, &mark,
2565 ifma_link);
2567 if (ifma->ifma_addr->sa_family == AF_UNSPEC)
2568 continue;
2570 if_delmulti_serialized(ifp, ifma->ifma_addr);
2572 TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2577 * Set the link layer address on an interface.
2579 * At this time we only support certain types of interfaces,
2580 * and we don't allow the length of the address to change.
2583 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2585 struct sockaddr_dl *sdl;
2586 struct ifreq ifr;
2588 sdl = IF_LLSOCKADDR(ifp);
2589 if (sdl == NULL)
2590 return (EINVAL);
2591 if (len != sdl->sdl_alen) /* don't allow length to change */
2592 return (EINVAL);
2593 switch (ifp->if_type) {
2594 case IFT_ETHER: /* these types use struct arpcom */
2595 case IFT_XETHER:
2596 case IFT_L2VLAN:
2597 case IFT_IEEE8023ADLAG:
2598 bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2599 bcopy(lladdr, LLADDR(sdl), len);
2600 break;
2601 default:
2602 return (ENODEV);
2605 * If the interface is already up, we need
2606 * to re-init it in order to reprogram its
2607 * address filter.
2609 ifnet_serialize_all(ifp);
2610 if ((ifp->if_flags & IFF_UP) != 0) {
2611 #ifdef INET
2612 struct ifaddr_container *ifac;
2613 #endif
2615 ifp->if_flags &= ~IFF_UP;
2616 ifr.ifr_flags = ifp->if_flags;
2617 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2618 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2619 NULL);
2620 ifp->if_flags |= IFF_UP;
2621 ifr.ifr_flags = ifp->if_flags;
2622 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2623 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2624 NULL);
2625 #ifdef INET
2627 * Also send gratuitous ARPs to notify other nodes about
2628 * the address change.
2630 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2631 struct ifaddr *ifa = ifac->ifa;
2633 if (ifa->ifa_addr != NULL &&
2634 ifa->ifa_addr->sa_family == AF_INET)
2635 arp_gratuitous(ifp, ifa);
2637 #endif
2639 ifnet_deserialize_all(ifp);
2640 return (0);
2643 struct ifmultiaddr *
2644 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2646 struct ifmultiaddr *ifma;
2648 /* TODO: need ifnet_serialize_main */
2649 ifnet_serialize_all(ifp);
2650 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2651 if (sa_equal(ifma->ifma_addr, sa))
2652 break;
2653 ifnet_deserialize_all(ifp);
2655 return ifma;
2659 * This function locates the first real ethernet MAC from a network
2660 * card and loads it into node, returning 0 on success or ENOENT if
2661 * no suitable interfaces were found. It is used by the uuid code to
2662 * generate a unique 6-byte number.
2665 if_getanyethermac(uint16_t *node, int minlen)
2667 struct ifnet *ifp;
2668 struct sockaddr_dl *sdl;
2670 ifnet_lock();
2671 TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2672 if (ifp->if_type != IFT_ETHER)
2673 continue;
2674 sdl = IF_LLSOCKADDR(ifp);
2675 if (sdl->sdl_alen < minlen)
2676 continue;
2677 bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2678 minlen);
2679 ifnet_unlock();
2680 return(0);
2682 ifnet_unlock();
2683 return (ENOENT);
2687 * The name argument must be a pointer to storage which will last as
2688 * long as the interface does. For physical devices, the result of
2689 * device_get_name(dev) is a good choice and for pseudo-devices a
2690 * static string works well.
2692 void
2693 if_initname(struct ifnet *ifp, const char *name, int unit)
2695 ifp->if_dname = name;
2696 ifp->if_dunit = unit;
2697 if (unit != IF_DUNIT_NONE)
2698 ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2699 else
2700 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2704 if_printf(struct ifnet *ifp, const char *fmt, ...)
2706 __va_list ap;
2707 int retval;
2709 retval = kprintf("%s: ", ifp->if_xname);
2710 __va_start(ap, fmt);
2711 retval += kvprintf(fmt, ap);
2712 __va_end(ap);
2713 return (retval);
2716 struct ifnet *
2717 if_alloc(uint8_t type)
2719 struct ifnet *ifp;
2720 size_t size;
2723 * XXX temporary hack until arpcom is setup in if_l2com
2725 if (type == IFT_ETHER)
2726 size = sizeof(struct arpcom);
2727 else
2728 size = sizeof(struct ifnet);
2730 ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2732 ifp->if_type = type;
2734 if (if_com_alloc[type] != NULL) {
2735 ifp->if_l2com = if_com_alloc[type](type, ifp);
2736 if (ifp->if_l2com == NULL) {
2737 kfree(ifp, M_IFNET);
2738 return (NULL);
2741 return (ifp);
2744 void
2745 if_free(struct ifnet *ifp)
2747 kfree(ifp, M_IFNET);
2750 void
2751 ifq_set_classic(struct ifaltq *ifq)
2753 ifq_set_methods(ifq, ifq->altq_ifp->if_mapsubq,
2754 ifsq_classic_enqueue, ifsq_classic_dequeue, ifsq_classic_request);
2757 void
2758 ifq_set_methods(struct ifaltq *ifq, altq_mapsubq_t mapsubq,
2759 ifsq_enqueue_t enqueue, ifsq_dequeue_t dequeue, ifsq_request_t request)
2761 int q;
2763 KASSERT(mapsubq != NULL, ("mapsubq is not specified"));
2764 KASSERT(enqueue != NULL, ("enqueue is not specified"));
2765 KASSERT(dequeue != NULL, ("dequeue is not specified"));
2766 KASSERT(request != NULL, ("request is not specified"));
2768 ifq->altq_mapsubq = mapsubq;
2769 for (q = 0; q < ifq->altq_subq_cnt; ++q) {
2770 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
2772 ifsq->ifsq_enqueue = enqueue;
2773 ifsq->ifsq_dequeue = dequeue;
2774 ifsq->ifsq_request = request;
2778 static void
2779 ifsq_norm_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2782 classq_add(&ifsq->ifsq_norm, m);
2783 ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2786 static void
2787 ifsq_prio_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2790 classq_add(&ifsq->ifsq_prio, m);
2791 ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2792 ALTQ_SQ_PRIO_CNTR_INC(ifsq, m->m_pkthdr.len);
2795 static struct mbuf *
2796 ifsq_norm_dequeue(struct ifaltq_subque *ifsq)
2798 struct mbuf *m;
2800 m = classq_get(&ifsq->ifsq_norm);
2801 if (m != NULL)
2802 ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2803 return (m);
2806 static struct mbuf *
2807 ifsq_prio_dequeue(struct ifaltq_subque *ifsq)
2809 struct mbuf *m;
2811 m = classq_get(&ifsq->ifsq_prio);
2812 if (m != NULL) {
2813 ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2814 ALTQ_SQ_PRIO_CNTR_DEC(ifsq, m->m_pkthdr.len);
2816 return (m);
2820 ifsq_classic_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m,
2821 struct altq_pktattr *pa __unused)
2824 M_ASSERTPKTHDR(m);
2825 again:
2826 if (ifsq->ifsq_len >= ifsq->ifsq_maxlen ||
2827 ifsq->ifsq_bcnt >= ifsq->ifsq_maxbcnt) {
2828 struct mbuf *m_drop;
2830 if (m->m_flags & M_PRIO) {
2831 m_drop = NULL;
2832 if (ifsq->ifsq_prio_len < (ifsq->ifsq_maxlen >> 1) &&
2833 ifsq->ifsq_prio_bcnt < (ifsq->ifsq_maxbcnt >> 1)) {
2834 /* Try dropping some from normal queue. */
2835 m_drop = ifsq_norm_dequeue(ifsq);
2837 if (m_drop == NULL)
2838 m_drop = ifsq_prio_dequeue(ifsq);
2839 } else {
2840 m_drop = ifsq_norm_dequeue(ifsq);
2842 if (m_drop != NULL) {
2843 IFNET_STAT_INC(ifsq->ifsq_ifp, oqdrops, 1);
2844 m_freem(m_drop);
2845 goto again;
2848 * No old packets could be dropped!
2849 * NOTE: Caller increases oqdrops.
2851 m_freem(m);
2852 return (ENOBUFS);
2853 } else {
2854 if (m->m_flags & M_PRIO)
2855 ifsq_prio_enqueue(ifsq, m);
2856 else
2857 ifsq_norm_enqueue(ifsq, m);
2858 return (0);
2862 struct mbuf *
2863 ifsq_classic_dequeue(struct ifaltq_subque *ifsq, int op)
2865 struct mbuf *m;
2867 switch (op) {
2868 case ALTDQ_POLL:
2869 m = classq_head(&ifsq->ifsq_prio);
2870 if (m == NULL)
2871 m = classq_head(&ifsq->ifsq_norm);
2872 break;
2874 case ALTDQ_REMOVE:
2875 m = ifsq_prio_dequeue(ifsq);
2876 if (m == NULL)
2877 m = ifsq_norm_dequeue(ifsq);
2878 break;
2880 default:
2881 panic("unsupported ALTQ dequeue op: %d", op);
2883 return m;
2887 ifsq_classic_request(struct ifaltq_subque *ifsq, int req, void *arg)
2889 switch (req) {
2890 case ALTRQ_PURGE:
2891 for (;;) {
2892 struct mbuf *m;
2894 m = ifsq_classic_dequeue(ifsq, ALTDQ_REMOVE);
2895 if (m == NULL)
2896 break;
2897 m_freem(m);
2899 break;
2901 default:
2902 panic("unsupported ALTQ request: %d", req);
2904 return 0;
2907 static void
2908 ifsq_ifstart_try(struct ifaltq_subque *ifsq, int force_sched)
2910 struct ifnet *ifp = ifsq_get_ifp(ifsq);
2911 int running = 0, need_sched;
2914 * Try to do direct ifnet.if_start on the subqueue first, if there is
2915 * contention on the subqueue hardware serializer, ifnet.if_start on
2916 * the subqueue will be scheduled on the subqueue owner CPU.
2918 if (!ifsq_tryserialize_hw(ifsq)) {
2920 * Subqueue hardware serializer contention happened,
2921 * ifnet.if_start on the subqueue is scheduled on
2922 * the subqueue owner CPU, and we keep going.
2924 ifsq_ifstart_schedule(ifsq, 1);
2925 return;
2928 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
2929 ifp->if_start(ifp, ifsq);
2930 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
2931 running = 1;
2933 need_sched = ifsq_ifstart_need_schedule(ifsq, running);
2935 ifsq_deserialize_hw(ifsq);
2937 if (need_sched) {
2939 * More data need to be transmitted, ifnet.if_start on the
2940 * subqueue is scheduled on the subqueue owner CPU, and we
2941 * keep going.
2942 * NOTE: ifnet.if_start subqueue interlock is not released.
2944 ifsq_ifstart_schedule(ifsq, force_sched);
2949 * Subqeue packets staging mechanism:
2951 * The packets enqueued into the subqueue are staged to a certain amount
2952 * before the ifnet.if_start on the subqueue is called. In this way, the
2953 * driver could avoid writing to hardware registers upon every packet,
2954 * instead, hardware registers could be written when certain amount of
2955 * packets are put onto hardware TX ring. The measurement on several modern
2956 * NICs (emx(4), igb(4), bnx(4), bge(4), jme(4)) shows that the hardware
2957 * registers writing aggregation could save ~20% CPU time when 18bytes UDP
2958 * datagrams are transmitted at 1.48Mpps. The performance improvement by
2959 * hardware registers writing aggeregation is also mentioned by Luigi Rizzo's
2960 * netmap paper (http://info.iet.unipi.it/~luigi/netmap/).
2962 * Subqueue packets staging is performed for two entry points into drivers'
2963 * transmission function:
2964 * - Direct ifnet.if_start calling on the subqueue, i.e. ifsq_ifstart_try()
2965 * - ifnet.if_start scheduling on the subqueue, i.e. ifsq_ifstart_schedule()
2967 * Subqueue packets staging will be stopped upon any of the following
2968 * conditions:
2969 * - If the count of packets enqueued on the current CPU is great than or
2970 * equal to ifsq_stage_cntmax. (XXX this should be per-interface)
2971 * - If the total length of packets enqueued on the current CPU is great
2972 * than or equal to the hardware's MTU - max_protohdr. max_protohdr is
2973 * cut from the hardware's MTU mainly bacause a full TCP segment's size
2974 * is usually less than hardware's MTU.
2975 * - ifsq_ifstart_schedule() is not pending on the current CPU and
2976 * ifnet.if_start subqueue interlock (ifaltq_subq.ifsq_started) is not
2977 * released.
2978 * - The if_start_rollup(), which is registered as low priority netisr
2979 * rollup function, is called; probably because no more work is pending
2980 * for netisr.
2982 * NOTE:
2983 * Currently subqueue packet staging is only performed in netisr threads.
2986 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
2988 struct ifaltq *ifq = &ifp->if_snd;
2989 struct ifaltq_subque *ifsq;
2990 int error, start = 0, len, mcast = 0, avoid_start = 0;
2991 struct ifsubq_stage_head *head = NULL;
2992 struct ifsubq_stage *stage = NULL;
2993 struct globaldata *gd = mycpu;
2994 struct thread *td = gd->gd_curthread;
2996 crit_enter_quick(td);
2998 ifsq = ifq_map_subq(ifq, gd->gd_cpuid);
2999 ASSERT_ALTQ_SQ_NOT_SERIALIZED_HW(ifsq);
3001 len = m->m_pkthdr.len;
3002 if (m->m_flags & M_MCAST)
3003 mcast = 1;
3005 if (td->td_type == TD_TYPE_NETISR) {
3006 head = &ifsubq_stage_heads[mycpuid];
3007 stage = ifsq_get_stage(ifsq, mycpuid);
3009 stage->stg_cnt++;
3010 stage->stg_len += len;
3011 if (stage->stg_cnt < ifsq_stage_cntmax &&
3012 stage->stg_len < (ifp->if_mtu - max_protohdr))
3013 avoid_start = 1;
3016 ALTQ_SQ_LOCK(ifsq);
3017 error = ifsq_enqueue_locked(ifsq, m, pa);
3018 if (error) {
3019 IFNET_STAT_INC(ifp, oqdrops, 1);
3020 if (!ifsq_data_ready(ifsq)) {
3021 ALTQ_SQ_UNLOCK(ifsq);
3022 crit_exit_quick(td);
3023 return error;
3025 avoid_start = 0;
3027 if (!ifsq_is_started(ifsq)) {
3028 if (avoid_start) {
3029 ALTQ_SQ_UNLOCK(ifsq);
3031 KKASSERT(!error);
3032 if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
3033 ifsq_stage_insert(head, stage);
3035 IFNET_STAT_INC(ifp, obytes, len);
3036 if (mcast)
3037 IFNET_STAT_INC(ifp, omcasts, 1);
3038 crit_exit_quick(td);
3039 return error;
3043 * Hold the subqueue interlock of ifnet.if_start
3045 ifsq_set_started(ifsq);
3046 start = 1;
3048 ALTQ_SQ_UNLOCK(ifsq);
3050 if (!error) {
3051 IFNET_STAT_INC(ifp, obytes, len);
3052 if (mcast)
3053 IFNET_STAT_INC(ifp, omcasts, 1);
3056 if (stage != NULL) {
3057 if (!start && (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)) {
3058 KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
3059 if (!avoid_start) {
3060 ifsq_stage_remove(head, stage);
3061 ifsq_ifstart_schedule(ifsq, 1);
3063 crit_exit_quick(td);
3064 return error;
3067 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED) {
3068 ifsq_stage_remove(head, stage);
3069 } else {
3070 stage->stg_cnt = 0;
3071 stage->stg_len = 0;
3075 if (!start) {
3076 crit_exit_quick(td);
3077 return error;
3080 ifsq_ifstart_try(ifsq, 0);
3082 crit_exit_quick(td);
3083 return error;
3086 void *
3087 ifa_create(int size)
3089 struct ifaddr *ifa;
3090 int i;
3092 KASSERT(size >= sizeof(*ifa), ("ifaddr size too small"));
3094 ifa = kmalloc(size, M_IFADDR, M_INTWAIT | M_ZERO);
3095 ifa->ifa_containers =
3096 kmalloc_cachealign(ncpus * sizeof(struct ifaddr_container),
3097 M_IFADDR, M_INTWAIT | M_ZERO);
3099 ifa->ifa_ncnt = ncpus;
3100 for (i = 0; i < ncpus; ++i) {
3101 struct ifaddr_container *ifac = &ifa->ifa_containers[i];
3103 ifac->ifa_magic = IFA_CONTAINER_MAGIC;
3104 ifac->ifa = ifa;
3105 ifac->ifa_refcnt = 1;
3107 #ifdef IFADDR_DEBUG
3108 kprintf("alloc ifa %p %d\n", ifa, size);
3109 #endif
3110 return ifa;
3113 void
3114 ifac_free(struct ifaddr_container *ifac, int cpu_id)
3116 struct ifaddr *ifa = ifac->ifa;
3118 KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
3119 KKASSERT(ifac->ifa_refcnt == 0);
3120 KASSERT(ifac->ifa_listmask == 0,
3121 ("ifa is still on %#x lists", ifac->ifa_listmask));
3123 ifac->ifa_magic = IFA_CONTAINER_DEAD;
3125 #ifdef IFADDR_DEBUG_VERBOSE
3126 kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
3127 #endif
3129 KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
3130 ("invalid # of ifac, %d", ifa->ifa_ncnt));
3131 if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
3132 #ifdef IFADDR_DEBUG
3133 kprintf("free ifa %p\n", ifa);
3134 #endif
3135 kfree(ifa->ifa_containers, M_IFADDR);
3136 kfree(ifa, M_IFADDR);
3140 static void
3141 ifa_iflink_dispatch(netmsg_t nmsg)
3143 struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3144 struct ifaddr *ifa = msg->ifa;
3145 struct ifnet *ifp = msg->ifp;
3146 int cpu = mycpuid;
3147 struct ifaddr_container *ifac;
3149 crit_enter();
3151 ifac = &ifa->ifa_containers[cpu];
3152 ASSERT_IFAC_VALID(ifac);
3153 KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
3154 ("ifaddr is on if_addrheads"));
3156 ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
3157 if (msg->tail)
3158 TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
3159 else
3160 TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
3162 crit_exit();
3164 netisr_forwardmsg(&nmsg->base, cpu + 1);
3167 void
3168 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
3170 struct netmsg_ifaddr msg;
3172 netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3173 0, ifa_iflink_dispatch);
3174 msg.ifa = ifa;
3175 msg.ifp = ifp;
3176 msg.tail = tail;
3178 netisr_domsg(&msg.base, 0);
3181 static void
3182 ifa_ifunlink_dispatch(netmsg_t nmsg)
3184 struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3185 struct ifaddr *ifa = msg->ifa;
3186 struct ifnet *ifp = msg->ifp;
3187 int cpu = mycpuid;
3188 struct ifaddr_container *ifac;
3190 crit_enter();
3192 ifac = &ifa->ifa_containers[cpu];
3193 ASSERT_IFAC_VALID(ifac);
3194 KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
3195 ("ifaddr is not on if_addrhead"));
3197 TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
3198 ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
3200 crit_exit();
3202 netisr_forwardmsg(&nmsg->base, cpu + 1);
3205 void
3206 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
3208 struct netmsg_ifaddr msg;
3210 netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3211 0, ifa_ifunlink_dispatch);
3212 msg.ifa = ifa;
3213 msg.ifp = ifp;
3215 netisr_domsg(&msg.base, 0);
3218 static void
3219 ifa_destroy_dispatch(netmsg_t nmsg)
3221 struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3223 IFAFREE(msg->ifa);
3224 netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3227 void
3228 ifa_destroy(struct ifaddr *ifa)
3230 struct netmsg_ifaddr msg;
3232 netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3233 0, ifa_destroy_dispatch);
3234 msg.ifa = ifa;
3236 netisr_domsg(&msg.base, 0);
3239 static void
3240 if_start_rollup(void)
3242 struct ifsubq_stage_head *head = &ifsubq_stage_heads[mycpuid];
3243 struct ifsubq_stage *stage;
3245 crit_enter();
3247 while ((stage = TAILQ_FIRST(&head->stg_head)) != NULL) {
3248 struct ifaltq_subque *ifsq = stage->stg_subq;
3249 int is_sched = 0;
3251 if (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)
3252 is_sched = 1;
3253 ifsq_stage_remove(head, stage);
3255 if (is_sched) {
3256 ifsq_ifstart_schedule(ifsq, 1);
3257 } else {
3258 int start = 0;
3260 ALTQ_SQ_LOCK(ifsq);
3261 if (!ifsq_is_started(ifsq)) {
3263 * Hold the subqueue interlock of
3264 * ifnet.if_start
3266 ifsq_set_started(ifsq);
3267 start = 1;
3269 ALTQ_SQ_UNLOCK(ifsq);
3271 if (start)
3272 ifsq_ifstart_try(ifsq, 1);
3274 KKASSERT((stage->stg_flags &
3275 (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
3278 crit_exit();
3281 static void
3282 ifnetinit(void *dummy __unused)
3284 int i;
3286 for (i = 0; i < ncpus; ++i)
3287 TAILQ_INIT(&ifsubq_stage_heads[i].stg_head);
3288 netisr_register_rollup(if_start_rollup, NETISR_ROLLUP_PRIO_IFSTART);
3291 void
3292 if_register_com_alloc(u_char type,
3293 if_com_alloc_t *a, if_com_free_t *f)
3296 KASSERT(if_com_alloc[type] == NULL,
3297 ("if_register_com_alloc: %d already registered", type));
3298 KASSERT(if_com_free[type] == NULL,
3299 ("if_register_com_alloc: %d free already registered", type));
3301 if_com_alloc[type] = a;
3302 if_com_free[type] = f;
3305 void
3306 if_deregister_com_alloc(u_char type)
3309 KASSERT(if_com_alloc[type] != NULL,
3310 ("if_deregister_com_alloc: %d not registered", type));
3311 KASSERT(if_com_free[type] != NULL,
3312 ("if_deregister_com_alloc: %d free not registered", type));
3313 if_com_alloc[type] = NULL;
3314 if_com_free[type] = NULL;
3317 void
3318 ifq_set_maxlen(struct ifaltq *ifq, int len)
3320 ifq->altq_maxlen = len + (ncpus * ifsq_stage_cntmax);
3324 ifq_mapsubq_default(struct ifaltq *ifq __unused, int cpuid __unused)
3326 return ALTQ_SUBQ_INDEX_DEFAULT;
3330 ifq_mapsubq_modulo(struct ifaltq *ifq, int cpuid)
3333 return (cpuid % ifq->altq_subq_mappriv);
3336 static void
3337 ifsq_watchdog(void *arg)
3339 struct ifsubq_watchdog *wd = arg;
3340 struct ifnet *ifp;
3342 if (__predict_true(wd->wd_timer == 0 || --wd->wd_timer))
3343 goto done;
3345 ifp = ifsq_get_ifp(wd->wd_subq);
3346 if (ifnet_tryserialize_all(ifp)) {
3347 wd->wd_watchdog(wd->wd_subq);
3348 ifnet_deserialize_all(ifp);
3349 } else {
3350 /* try again next timeout */
3351 wd->wd_timer = 1;
3353 done:
3354 ifsq_watchdog_reset(wd);
3357 static void
3358 ifsq_watchdog_reset(struct ifsubq_watchdog *wd)
3360 callout_reset_bycpu(&wd->wd_callout, hz, ifsq_watchdog, wd,
3361 ifsq_get_cpuid(wd->wd_subq));
3364 void
3365 ifsq_watchdog_init(struct ifsubq_watchdog *wd, struct ifaltq_subque *ifsq,
3366 ifsq_watchdog_t watchdog)
3368 callout_init_mp(&wd->wd_callout);
3369 wd->wd_timer = 0;
3370 wd->wd_subq = ifsq;
3371 wd->wd_watchdog = watchdog;
3374 void
3375 ifsq_watchdog_start(struct ifsubq_watchdog *wd)
3377 wd->wd_timer = 0;
3378 ifsq_watchdog_reset(wd);
3381 void
3382 ifsq_watchdog_stop(struct ifsubq_watchdog *wd)
3384 wd->wd_timer = 0;
3385 callout_stop(&wd->wd_callout);
3388 void
3389 ifnet_lock(void)
3391 KASSERT(curthread->td_type != TD_TYPE_NETISR,
3392 ("try holding ifnet lock in netisr"));
3393 mtx_lock(&ifnet_mtx);
3396 void
3397 ifnet_unlock(void)
3399 KASSERT(curthread->td_type != TD_TYPE_NETISR,
3400 ("try holding ifnet lock in netisr"));
3401 mtx_unlock(&ifnet_mtx);
3404 static struct ifnet_array *
3405 ifnet_array_alloc(int count)
3407 struct ifnet_array *arr;
3409 arr = kmalloc(__offsetof(struct ifnet_array, ifnet_arr[count]),
3410 M_IFNET, M_WAITOK);
3411 arr->ifnet_count = count;
3413 return arr;
3416 static void
3417 ifnet_array_free(struct ifnet_array *arr)
3419 if (arr == &ifnet_array0)
3420 return;
3421 kfree(arr, M_IFNET);
3424 static struct ifnet_array *
3425 ifnet_array_add(struct ifnet *ifp, const struct ifnet_array *old_arr)
3427 struct ifnet_array *arr;
3428 int count, i;
3430 KASSERT(old_arr->ifnet_count >= 0,
3431 ("invalid ifnet array count %d", old_arr->ifnet_count));
3432 count = old_arr->ifnet_count + 1;
3433 arr = ifnet_array_alloc(count);
3436 * Save the old ifnet array and append this ifp to the end of
3437 * the new ifnet array.
3439 for (i = 0; i < old_arr->ifnet_count; ++i) {
3440 KASSERT(old_arr->ifnet_arr[i] != ifp,
3441 ("%s is already in ifnet array", ifp->if_xname));
3442 arr->ifnet_arr[i] = old_arr->ifnet_arr[i];
3444 KASSERT(i == count - 1,
3445 ("add %s, ifnet array index mismatch, should be %d, but got %d",
3446 ifp->if_xname, count - 1, i));
3447 arr->ifnet_arr[i] = ifp;
3449 return arr;
3452 static struct ifnet_array *
3453 ifnet_array_del(struct ifnet *ifp, const struct ifnet_array *old_arr)
3455 struct ifnet_array *arr;
3456 int count, i, idx, found = 0;
3458 KASSERT(old_arr->ifnet_count > 0,
3459 ("invalid ifnet array count %d", old_arr->ifnet_count));
3460 count = old_arr->ifnet_count - 1;
3461 arr = ifnet_array_alloc(count);
3464 * Save the old ifnet array, but skip this ifp.
3466 idx = 0;
3467 for (i = 0; i < old_arr->ifnet_count; ++i) {
3468 if (old_arr->ifnet_arr[i] == ifp) {
3469 KASSERT(!found,
3470 ("dup %s is in ifnet array", ifp->if_xname));
3471 found = 1;
3472 continue;
3474 KASSERT(idx < count,
3475 ("invalid ifnet array index %d, count %d", idx, count));
3476 arr->ifnet_arr[idx] = old_arr->ifnet_arr[i];
3477 ++idx;
3479 KASSERT(found, ("%s is not in ifnet array", ifp->if_xname));
3480 KASSERT(idx == count,
3481 ("del %s, ifnet array count mismatch, should be %d, but got %d ",
3482 ifp->if_xname, count, idx));
3484 return arr;
3487 const struct ifnet_array *
3488 ifnet_array_get(void)
3490 const struct ifnet_array *ret;
3492 KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3493 ret = ifnet_array;
3494 /* Make sure 'ret' is really used. */
3495 cpu_ccfence();
3496 return (ret);
3500 ifnet_array_isempty(void)
3502 KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3503 if (ifnet_array->ifnet_count == 0)
3504 return 1;
3505 else
3506 return 0;
3509 void
3510 ifa_marker_init(struct ifaddr_marker *mark, struct ifnet *ifp)
3512 struct ifaddr *ifa;
3514 memset(mark, 0, sizeof(*mark));
3515 ifa = &mark->ifa;
3517 mark->ifac.ifa = ifa;
3519 ifa->ifa_addr = &mark->addr;
3520 ifa->ifa_dstaddr = &mark->dstaddr;
3521 ifa->ifa_netmask = &mark->netmask;
3522 ifa->ifa_ifp = ifp;
3525 static int
3526 if_ringcnt_fixup(int ring_cnt, int ring_cntmax)
3529 KASSERT(ring_cntmax > 0, ("invalid ring count max %d", ring_cntmax));
3531 if (ring_cnt <= 0 || ring_cnt > ring_cntmax)
3532 ring_cnt = ring_cntmax;
3533 if (ring_cnt > netisr_ncpus)
3534 ring_cnt = netisr_ncpus;
3535 return (ring_cnt);
3538 static void
3539 if_ringmap_set_grid(device_t dev, struct if_ringmap *rm, int grid)
3541 int i, offset;
3543 KASSERT(grid > 0, ("invalid if_ringmap grid %d", grid));
3544 KASSERT(grid >= rm->rm_cnt, ("invalid if_ringmap grid %d, count %d",
3545 grid, rm->rm_cnt));
3546 rm->rm_grid = grid;
3548 offset = (rm->rm_grid * device_get_unit(dev)) % netisr_ncpus;
3549 for (i = 0; i < rm->rm_cnt; ++i) {
3550 rm->rm_cpumap[i] = offset + i;
3551 KASSERT(rm->rm_cpumap[i] < netisr_ncpus,
3552 ("invalid cpumap[%d] = %d, offset %d", i,
3553 rm->rm_cpumap[i], offset));
3557 static struct if_ringmap *
3558 if_ringmap_alloc_flags(device_t dev, int ring_cnt, int ring_cntmax,
3559 uint32_t flags)
3561 struct if_ringmap *rm;
3562 int i, grid = 0, prev_grid;
3564 ring_cnt = if_ringcnt_fixup(ring_cnt, ring_cntmax);
3565 rm = kmalloc(__offsetof(struct if_ringmap, rm_cpumap[ring_cnt]),
3566 M_DEVBUF, M_WAITOK | M_ZERO);
3568 rm->rm_cnt = ring_cnt;
3569 if (flags & RINGMAP_FLAG_POWEROF2)
3570 rm->rm_cnt = 1 << (fls(rm->rm_cnt) - 1);
3572 prev_grid = netisr_ncpus;
3573 for (i = 0; i < netisr_ncpus; ++i) {
3574 if (netisr_ncpus % (i + 1) != 0)
3575 continue;
3577 grid = netisr_ncpus / (i + 1);
3578 if (rm->rm_cnt > grid) {
3579 grid = prev_grid;
3580 break;
3583 if (rm->rm_cnt > netisr_ncpus / (i + 2))
3584 break;
3585 prev_grid = grid;
3587 if_ringmap_set_grid(dev, rm, grid);
3589 return (rm);
3592 struct if_ringmap *
3593 if_ringmap_alloc(device_t dev, int ring_cnt, int ring_cntmax)
3596 return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3597 RINGMAP_FLAG_NONE));
3600 struct if_ringmap *
3601 if_ringmap_alloc2(device_t dev, int ring_cnt, int ring_cntmax)
3604 return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3605 RINGMAP_FLAG_POWEROF2));
3608 void
3609 if_ringmap_free(struct if_ringmap *rm)
3612 kfree(rm, M_DEVBUF);
3616 * Align the two ringmaps.
3618 * e.g. 8 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3620 * Before:
3622 * CPU 0 1 2 3 4 5 6 7
3623 * NIC_RX n0 n1 n2 n3
3624 * NIC_TX N0 N1
3626 * After:
3628 * CPU 0 1 2 3 4 5 6 7
3629 * NIC_RX n0 n1 n2 n3
3630 * NIC_TX N0 N1
3632 void
3633 if_ringmap_align(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3636 if (rm0->rm_grid > rm1->rm_grid)
3637 if_ringmap_set_grid(dev, rm1, rm0->rm_grid);
3638 else if (rm0->rm_grid < rm1->rm_grid)
3639 if_ringmap_set_grid(dev, rm0, rm1->rm_grid);
3642 void
3643 if_ringmap_match(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3645 int subset_grid, cnt, divisor, mod, offset, i;
3646 struct if_ringmap *subset_rm, *rm;
3647 int old_rm0_grid, old_rm1_grid;
3649 if (rm0->rm_grid == rm1->rm_grid)
3650 return;
3652 /* Save grid for later use */
3653 old_rm0_grid = rm0->rm_grid;
3654 old_rm1_grid = rm1->rm_grid;
3656 if_ringmap_align(dev, rm0, rm1);
3659 * Re-shuffle rings to get more even distribution.
3661 * e.g. 12 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3663 * CPU 0 1 2 3 4 5 6 7 8 9 10 11
3665 * NIC_RX a0 a1 a2 a3 b0 b1 b2 b3 c0 c1 c2 c3
3666 * NIC_TX A0 A1 B0 B1 C0 C1
3668 * NIC_RX d0 d1 d2 d3 e0 e1 e2 e3 f0 f1 f2 f3
3669 * NIC_TX D0 D1 E0 E1 F0 F1
3672 if (rm0->rm_cnt >= (2 * old_rm1_grid)) {
3673 cnt = rm0->rm_cnt;
3674 subset_grid = old_rm1_grid;
3675 subset_rm = rm1;
3676 rm = rm0;
3677 } else if (rm1->rm_cnt > (2 * old_rm0_grid)) {
3678 cnt = rm1->rm_cnt;
3679 subset_grid = old_rm0_grid;
3680 subset_rm = rm0;
3681 rm = rm1;
3682 } else {
3683 /* No space to shuffle. */
3684 return;
3687 mod = cnt / subset_grid;
3688 KKASSERT(mod >= 2);
3689 divisor = netisr_ncpus / rm->rm_grid;
3690 offset = ((device_get_unit(dev) / divisor) % mod) * subset_grid;
3692 for (i = 0; i < subset_rm->rm_cnt; ++i) {
3693 subset_rm->rm_cpumap[i] += offset;
3694 KASSERT(subset_rm->rm_cpumap[i] < netisr_ncpus,
3695 ("match: invalid cpumap[%d] = %d, offset %d",
3696 i, subset_rm->rm_cpumap[i], offset));
3698 #ifdef INVARIANTS
3699 for (i = 0; i < subset_rm->rm_cnt; ++i) {
3700 int j;
3702 for (j = 0; j < rm->rm_cnt; ++j) {
3703 if (rm->rm_cpumap[j] == subset_rm->rm_cpumap[i])
3704 break;
3706 KASSERT(j < rm->rm_cnt,
3707 ("subset cpumap[%d] = %d not found in superset",
3708 i, subset_rm->rm_cpumap[i]));
3710 #endif
3714 if_ringmap_count(const struct if_ringmap *rm)
3717 return (rm->rm_cnt);
3721 if_ringmap_cpumap(const struct if_ringmap *rm, int ring)
3724 KASSERT(ring >= 0 && ring < rm->rm_cnt, ("invalid ring %d", ring));
3725 return (rm->rm_cpumap[ring]);
3728 void
3729 if_ringmap_rdrtable(const struct if_ringmap *rm, int table[], int table_nent)
3731 int i, grid_idx, grid_cnt, patch_off, patch_cnt, ncopy;
3733 KASSERT(table_nent > 0 && (table_nent & NETISR_CPUMASK) == 0,
3734 ("invalid redirect table entries %d", table_nent));
3736 grid_idx = 0;
3737 for (i = 0; i < NETISR_CPUMAX; ++i) {
3738 table[i] = grid_idx++ % rm->rm_cnt;
3740 if (grid_idx == rm->rm_grid)
3741 grid_idx = 0;
3745 * Make the ring distributed more evenly for the remainder
3746 * of each grid.
3748 * e.g. 12 netisrs, rm contains 8 rings.
3750 * Redirect table before:
3752 * 0 1 2 3 4 5 6 7 0 1 2 3 0 1 2 3
3753 * 4 5 6 7 0 1 2 3 0 1 2 3 4 5 6 7
3754 * 0 1 2 3 0 1 2 3 4 5 6 7 0 1 2 3
3755 * ....
3757 * Redirect table after being patched (pX, patched entries):
3759 * 0 1 2 3 4 5 6 7 p0 p1 p2 p3 0 1 2 3
3760 * 4 5 6 7 p4 p5 p6 p7 0 1 2 3 4 5 6 7
3761 * p0 p1 p2 p3 0 1 2 3 4 5 6 7 p4 p5 p6 p7
3762 * ....
3764 patch_cnt = rm->rm_grid % rm->rm_cnt;
3765 if (patch_cnt == 0)
3766 goto done;
3767 patch_off = rm->rm_grid - (rm->rm_grid % rm->rm_cnt);
3769 grid_cnt = roundup(NETISR_CPUMAX, rm->rm_grid) / rm->rm_grid;
3770 grid_idx = 0;
3771 for (i = 0; i < grid_cnt; ++i) {
3772 int j;
3774 for (j = 0; j < patch_cnt; ++j) {
3775 int fix_idx;
3777 fix_idx = (i * rm->rm_grid) + patch_off + j;
3778 if (fix_idx >= NETISR_CPUMAX)
3779 goto done;
3780 table[fix_idx] = grid_idx++ % rm->rm_cnt;
3783 done:
3785 * If the device supports larger redirect table, duplicate
3786 * the first NETISR_CPUMAX entries to the rest of the table,
3787 * so that it matches upper layer's expectation:
3788 * (hash & NETISR_CPUMASK) % netisr_ncpus
3790 ncopy = table_nent / NETISR_CPUMAX;
3791 for (i = 1; i < ncopy; ++i) {
3792 memcpy(&table[i * NETISR_CPUMAX], table,
3793 NETISR_CPUMAX * sizeof(table[0]));
3795 if (if_ringmap_dumprdr) {
3796 for (i = 0; i < table_nent; ++i) {
3797 if (i != 0 && i % 16 == 0)
3798 kprintf("\n");
3799 kprintf("%03d ", table[i]);
3801 kprintf("\n");
3806 if_ringmap_cpumap_sysctl(SYSCTL_HANDLER_ARGS)
3808 struct if_ringmap *rm = arg1;
3809 int i, error = 0;
3811 for (i = 0; i < rm->rm_cnt; ++i) {
3812 int cpu = rm->rm_cpumap[i];
3814 error = SYSCTL_OUT(req, &cpu, sizeof(cpu));
3815 if (error)
3816 break;
3818 return (error);