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