ifnet: Log rarely used ifnet address destruction.
[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                 if_printf(ifp, "destrot ifaddr family %d\n",
829                     ifa->ifa_addr->sa_family);
830                 ifa_ifunlink(ifa, ifp);
831                 ifa_destroy(ifa);
832         }
833
834         lwkt_replymsg(lmsg, 0);
835 }
836
837 void
838 if_purgeaddrs_nolink(struct ifnet *ifp)
839 {
840         struct netmsg_base nmsg;
841         struct lwkt_msg *lmsg = &nmsg.lmsg;
842
843         ASSERT_CANDOMSG_NETISR0(curthread);
844
845         netmsg_init(&nmsg, NULL, &curthread->td_msgport, 0,
846             if_purgeaddrs_nolink_dispatch);
847         lmsg->u.ms_resultp = ifp;
848         lwkt_domsg(netisr_cpuport(0), lmsg, 0);
849 }
850
851 static void
852 ifq_stage_detach_handler(netmsg_t nmsg)
853 {
854         struct ifaltq *ifq = nmsg->lmsg.u.ms_resultp;
855         int q;
856
857         for (q = 0; q < ifq->altq_subq_cnt; ++q) {
858                 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
859                 struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
860
861                 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED)
862                         ifsq_stage_remove(&ifsubq_stage_heads[mycpuid], stage);
863         }
864         lwkt_replymsg(&nmsg->lmsg, 0);
865 }
866
867 static void
868 ifq_stage_detach(struct ifaltq *ifq)
869 {
870         struct netmsg_base base;
871         int cpu;
872
873         netmsg_init(&base, NULL, &curthread->td_msgport, 0,
874             ifq_stage_detach_handler);
875         base.lmsg.u.ms_resultp = ifq;
876
877         for (cpu = 0; cpu < ncpus; ++cpu)
878                 lwkt_domsg(netisr_cpuport(cpu), &base.lmsg, 0);
879 }
880
881 struct netmsg_if_rtdel {
882         struct netmsg_base      base;
883         struct ifnet            *ifp;
884 };
885
886 static void
887 if_rtdel_dispatch(netmsg_t msg)
888 {
889         struct netmsg_if_rtdel *rmsg = (void *)msg;
890         int i, nextcpu, cpu;
891
892         cpu = mycpuid;
893         for (i = 1; i <= AF_MAX; i++) {
894                 struct radix_node_head  *rnh;
895
896                 if ((rnh = rt_tables[cpu][i]) == NULL)
897                         continue;
898                 rnh->rnh_walktree(rnh, if_rtdel, rmsg->ifp);
899         }
900
901         nextcpu = cpu + 1;
902         if (nextcpu < ncpus)
903                 lwkt_forwardmsg(netisr_cpuport(nextcpu), &rmsg->base.lmsg);
904         else
905                 lwkt_replymsg(&rmsg->base.lmsg, 0);
906 }
907
908 /*
909  * Detach an interface, removing it from the
910  * list of "active" interfaces.
911  */
912 void
913 if_detach(struct ifnet *ifp)
914 {
915         struct ifnet_array *old_ifnet_array;
916         struct netmsg_if_rtdel msg;
917         struct domain *dp;
918         int q;
919
920         /* Announce that the interface is gone. */
921         EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
922         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
923         devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
924
925         /*
926          * Remove this ifp from ifindex2inet, ifnet queue and ifnet
927          * array before it is whacked.
928          *
929          * Protect ifindex2ifnet, ifnet queue and ifnet array changes
930          * by ifnet lock, so that non-netisr threads could get a
931          * consistent view.
932          */
933         ifnet_lock();
934
935         /*
936          * Remove this ifp from ifindex2ifnet and maybe decrement if_index.
937          */
938         ifindex2ifnet[ifp->if_index] = NULL;
939         while (if_index > 0 && ifindex2ifnet[if_index] == NULL)
940                 if_index--;
941
942         /*
943          * Remove this ifp from ifnet queue.
944          */
945         TAILQ_REMOVE(&ifnetlist, ifp, if_link);
946
947         /*
948          * Remove this ifp from ifnet array.
949          */
950         /* Free old ifnet array after sync all netisrs */
951         old_ifnet_array = ifnet_array;
952         ifnet_array = ifnet_array_del(ifp, old_ifnet_array);
953
954         ifnet_unlock();
955
956         /*
957          * Sync all netisrs so that the old ifnet array is no longer
958          * accessed and we can free it safely later on.
959          */
960         netmsg_service_sync();
961         ifnet_array_free(old_ifnet_array);
962
963         /*
964          * Remove routes and flush queues.
965          */
966         crit_enter();
967 #ifdef IFPOLL_ENABLE
968         if (ifp->if_flags & IFF_NPOLLING)
969                 ifpoll_deregister(ifp);
970 #endif
971         if_down(ifp);
972
973         /* Decrease the mbuf clusters/jclusters limits increased by us */
974         if (ifp->if_nmbclusters > 0)
975                 mcl_inclimit(-ifp->if_nmbclusters);
976         if (ifp->if_nmbjclusters > 0)
977                 mjcl_inclimit(-ifp->if_nmbjclusters);
978
979 #ifdef ALTQ
980         if (ifq_is_enabled(&ifp->if_snd))
981                 altq_disable(&ifp->if_snd);
982         if (ifq_is_attached(&ifp->if_snd))
983                 altq_detach(&ifp->if_snd);
984 #endif
985
986         /*
987          * Clean up all addresses.
988          */
989         ifp->if_lladdr = NULL;
990
991         if_purgeaddrs_nolink(ifp);
992         if (!TAILQ_EMPTY(&ifp->if_addrheads[mycpuid])) {
993                 struct ifaddr *ifa;
994
995                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
996                 KASSERT(ifa->ifa_addr->sa_family == AF_LINK,
997                         ("non-link ifaddr is left on if_addrheads"));
998
999                 ifa_ifunlink(ifa, ifp);
1000                 ifa_destroy(ifa);
1001                 KASSERT(TAILQ_EMPTY(&ifp->if_addrheads[mycpuid]),
1002                         ("there are still ifaddrs left on if_addrheads"));
1003         }
1004
1005 #ifdef INET
1006         /*
1007          * Remove all IPv4 kernel structures related to ifp.
1008          */
1009         in_ifdetach(ifp);
1010 #endif
1011
1012 #ifdef INET6
1013         /*
1014          * Remove all IPv6 kernel structs related to ifp.  This should be done
1015          * before removing routing entries below, since IPv6 interface direct
1016          * routes are expected to be removed by the IPv6-specific kernel API.
1017          * Otherwise, the kernel will detect some inconsistency and bark it.
1018          */
1019         in6_ifdetach(ifp);
1020 #endif
1021
1022         /*
1023          * Delete all remaining routes using this interface
1024          */
1025         netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
1026             if_rtdel_dispatch);
1027         msg.ifp = ifp;
1028         rt_domsg_global(&msg.base);
1029
1030         SLIST_FOREACH(dp, &domains, dom_next)
1031                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
1032                         (*dp->dom_ifdetach)(ifp,
1033                                 ifp->if_afdata[dp->dom_family]);
1034
1035         kfree(ifp->if_addrheads, M_IFADDR);
1036
1037         lwkt_synchronize_ipiqs("if_detach");
1038         ifq_stage_detach(&ifp->if_snd);
1039
1040         for (q = 0; q < ifp->if_snd.altq_subq_cnt; ++q) {
1041                 struct ifaltq_subque *ifsq = &ifp->if_snd.altq_subq[q];
1042
1043                 kfree(ifsq->ifsq_ifstart_nmsg, M_LWKTMSG);
1044                 kfree(ifsq->ifsq_stage, M_DEVBUF);
1045         }
1046         kfree(ifp->if_snd.altq_subq, M_DEVBUF);
1047
1048         kfree(ifp->if_data_pcpu, M_DEVBUF);
1049
1050         crit_exit();
1051 }
1052
1053 /*
1054  * Create interface group without members
1055  */
1056 struct ifg_group *
1057 if_creategroup(const char *groupname)
1058 {
1059         struct ifg_group        *ifg = NULL;
1060
1061         if ((ifg = (struct ifg_group *)kmalloc(sizeof(struct ifg_group),
1062             M_TEMP, M_NOWAIT)) == NULL)
1063                 return (NULL);
1064
1065         strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1066         ifg->ifg_refcnt = 0;
1067         ifg->ifg_carp_demoted = 0;
1068         TAILQ_INIT(&ifg->ifg_members);
1069 #if NPF > 0
1070         pfi_attach_ifgroup(ifg);
1071 #endif
1072         TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
1073
1074         return (ifg);
1075 }
1076
1077 /*
1078  * Add a group to an interface
1079  */
1080 int
1081 if_addgroup(struct ifnet *ifp, const char *groupname)
1082 {
1083         struct ifg_list         *ifgl;
1084         struct ifg_group        *ifg = NULL;
1085         struct ifg_member       *ifgm;
1086
1087         if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1088             groupname[strlen(groupname) - 1] <= '9')
1089                 return (EINVAL);
1090
1091         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1092                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1093                         return (EEXIST);
1094
1095         if ((ifgl = kmalloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL)
1096                 return (ENOMEM);
1097
1098         if ((ifgm = kmalloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
1099                 kfree(ifgl, M_TEMP);
1100                 return (ENOMEM);
1101         }
1102
1103         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1104                 if (!strcmp(ifg->ifg_group, groupname))
1105                         break;
1106
1107         if (ifg == NULL && (ifg = if_creategroup(groupname)) == NULL) {
1108                 kfree(ifgl, M_TEMP);
1109                 kfree(ifgm, M_TEMP);
1110                 return (ENOMEM);
1111         }
1112
1113         ifg->ifg_refcnt++;
1114         ifgl->ifgl_group = ifg;
1115         ifgm->ifgm_ifp = ifp;
1116
1117         TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1118         TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1119
1120 #if NPF > 0
1121         pfi_group_change(groupname);
1122 #endif
1123
1124         return (0);
1125 }
1126
1127 /*
1128  * Remove a group from an interface
1129  */
1130 int
1131 if_delgroup(struct ifnet *ifp, const char *groupname)
1132 {
1133         struct ifg_list         *ifgl;
1134         struct ifg_member       *ifgm;
1135
1136         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1137                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1138                         break;
1139         if (ifgl == NULL)
1140                 return (ENOENT);
1141
1142         TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1143
1144         TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1145                 if (ifgm->ifgm_ifp == ifp)
1146                         break;
1147
1148         if (ifgm != NULL) {
1149                 TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1150                 kfree(ifgm, M_TEMP);
1151         }
1152
1153         if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1154                 TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
1155 #if NPF > 0
1156                 pfi_detach_ifgroup(ifgl->ifgl_group);
1157 #endif
1158                 kfree(ifgl->ifgl_group, M_TEMP);
1159         }
1160
1161         kfree(ifgl, M_TEMP);
1162
1163 #if NPF > 0
1164         pfi_group_change(groupname);
1165 #endif
1166
1167         return (0);
1168 }
1169
1170 /*
1171  * Stores all groups from an interface in memory pointed
1172  * to by data
1173  */
1174 int
1175 if_getgroup(caddr_t data, struct ifnet *ifp)
1176 {
1177         int                      len, error;
1178         struct ifg_list         *ifgl;
1179         struct ifg_req           ifgrq, *ifgp;
1180         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
1181
1182         if (ifgr->ifgr_len == 0) {
1183                 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1184                         ifgr->ifgr_len += sizeof(struct ifg_req);
1185                 return (0);
1186         }
1187
1188         len = ifgr->ifgr_len;
1189         ifgp = ifgr->ifgr_groups;
1190         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1191                 if (len < sizeof(ifgrq))
1192                         return (EINVAL);
1193                 bzero(&ifgrq, sizeof ifgrq);
1194                 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1195                     sizeof(ifgrq.ifgrq_group));
1196                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1197                     sizeof(struct ifg_req))))
1198                         return (error);
1199                 len -= sizeof(ifgrq);
1200                 ifgp++;
1201         }
1202
1203         return (0);
1204 }
1205
1206 /*
1207  * Stores all members of a group in memory pointed to by data
1208  */
1209 int
1210 if_getgroupmembers(caddr_t data)
1211 {
1212         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
1213         struct ifg_group        *ifg;
1214         struct ifg_member       *ifgm;
1215         struct ifg_req           ifgrq, *ifgp;
1216         int                      len, error;
1217
1218         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1219                 if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1220                         break;
1221         if (ifg == NULL)
1222                 return (ENOENT);
1223
1224         if (ifgr->ifgr_len == 0) {
1225                 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1226                         ifgr->ifgr_len += sizeof(ifgrq);
1227                 return (0);
1228         }
1229
1230         len = ifgr->ifgr_len;
1231         ifgp = ifgr->ifgr_groups;
1232         TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1233                 if (len < sizeof(ifgrq))
1234                         return (EINVAL);
1235                 bzero(&ifgrq, sizeof ifgrq);
1236                 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1237                     sizeof(ifgrq.ifgrq_member));
1238                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1239                     sizeof(struct ifg_req))))
1240                         return (error);
1241                 len -= sizeof(ifgrq);
1242                 ifgp++;
1243         }
1244
1245         return (0);
1246 }
1247
1248 /*
1249  * Delete Routes for a Network Interface
1250  *
1251  * Called for each routing entry via the rnh->rnh_walktree() call above
1252  * to delete all route entries referencing a detaching network interface.
1253  *
1254  * Arguments:
1255  *      rn      pointer to node in the routing table
1256  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
1257  *
1258  * Returns:
1259  *      0       successful
1260  *      errno   failed - reason indicated
1261  *
1262  */
1263 static int
1264 if_rtdel(struct radix_node *rn, void *arg)
1265 {
1266         struct rtentry  *rt = (struct rtentry *)rn;
1267         struct ifnet    *ifp = arg;
1268         int             err;
1269
1270         if (rt->rt_ifp == ifp) {
1271
1272                 /*
1273                  * Protect (sorta) against walktree recursion problems
1274                  * with cloned routes
1275                  */
1276                 if (!(rt->rt_flags & RTF_UP))
1277                         return (0);
1278
1279                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1280                                 rt_mask(rt), rt->rt_flags,
1281                                 NULL);
1282                 if (err) {
1283                         log(LOG_WARNING, "if_rtdel: error %d\n", err);
1284                 }
1285         }
1286
1287         return (0);
1288 }
1289
1290 static __inline boolean_t
1291 ifa_prefer(const struct ifaddr *cur_ifa, const struct ifaddr *old_ifa)
1292 {
1293         if (old_ifa == NULL)
1294                 return TRUE;
1295
1296         if ((old_ifa->ifa_ifp->if_flags & IFF_UP) == 0 &&
1297             (cur_ifa->ifa_ifp->if_flags & IFF_UP))
1298                 return TRUE;
1299         if ((old_ifa->ifa_flags & IFA_ROUTE) == 0 &&
1300             (cur_ifa->ifa_flags & IFA_ROUTE))
1301                 return TRUE;
1302         return FALSE;
1303 }
1304
1305 /*
1306  * Locate an interface based on a complete address.
1307  */
1308 struct ifaddr *
1309 ifa_ifwithaddr(struct sockaddr *addr)
1310 {
1311         const struct ifnet_array *arr;
1312         int i;
1313
1314         arr = ifnet_array_get();
1315         for (i = 0; i < arr->ifnet_count; ++i) {
1316                 struct ifnet *ifp = arr->ifnet_arr[i];
1317                 struct ifaddr_container *ifac;
1318
1319                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1320                         struct ifaddr *ifa = ifac->ifa;
1321
1322                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1323                                 continue;
1324                         if (sa_equal(addr, ifa->ifa_addr))
1325                                 return (ifa);
1326                         if ((ifp->if_flags & IFF_BROADCAST) &&
1327                             ifa->ifa_broadaddr &&
1328                             /* IPv6 doesn't have broadcast */
1329                             ifa->ifa_broadaddr->sa_len != 0 &&
1330                             sa_equal(ifa->ifa_broadaddr, addr))
1331                                 return (ifa);
1332                 }
1333         }
1334         return (NULL);
1335 }
1336
1337 /*
1338  * Locate the point to point interface with a given destination address.
1339  */
1340 struct ifaddr *
1341 ifa_ifwithdstaddr(struct sockaddr *addr)
1342 {
1343         const struct ifnet_array *arr;
1344         int i;
1345
1346         arr = ifnet_array_get();
1347         for (i = 0; i < arr->ifnet_count; ++i) {
1348                 struct ifnet *ifp = arr->ifnet_arr[i];
1349                 struct ifaddr_container *ifac;
1350
1351                 if (!(ifp->if_flags & IFF_POINTOPOINT))
1352                         continue;
1353
1354                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1355                         struct ifaddr *ifa = ifac->ifa;
1356
1357                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1358                                 continue;
1359                         if (ifa->ifa_dstaddr &&
1360                             sa_equal(addr, ifa->ifa_dstaddr))
1361                                 return (ifa);
1362                 }
1363         }
1364         return (NULL);
1365 }
1366
1367 /*
1368  * Find an interface on a specific network.  If many, choice
1369  * is most specific found.
1370  */
1371 struct ifaddr *
1372 ifa_ifwithnet(struct sockaddr *addr)
1373 {
1374         struct ifaddr *ifa_maybe = NULL;
1375         u_int af = addr->sa_family;
1376         char *addr_data = addr->sa_data, *cplim;
1377         const struct ifnet_array *arr;
1378         int i;
1379
1380         /*
1381          * AF_LINK addresses can be looked up directly by their index number,
1382          * so do that if we can.
1383          */
1384         if (af == AF_LINK) {
1385                 struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1386
1387                 if (sdl->sdl_index && sdl->sdl_index <= if_index)
1388                         return (ifindex2ifnet[sdl->sdl_index]->if_lladdr);
1389         }
1390
1391         /*
1392          * Scan though each interface, looking for ones that have
1393          * addresses in this address family.
1394          */
1395         arr = ifnet_array_get();
1396         for (i = 0; i < arr->ifnet_count; ++i) {
1397                 struct ifnet *ifp = arr->ifnet_arr[i];
1398                 struct ifaddr_container *ifac;
1399
1400                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1401                         struct ifaddr *ifa = ifac->ifa;
1402                         char *cp, *cp2, *cp3;
1403
1404                         if (ifa->ifa_addr->sa_family != af)
1405 next:                           continue;
1406                         if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1407                                 /*
1408                                  * This is a bit broken as it doesn't
1409                                  * take into account that the remote end may
1410                                  * be a single node in the network we are
1411                                  * looking for.
1412                                  * The trouble is that we don't know the
1413                                  * netmask for the remote end.
1414                                  */
1415                                 if (ifa->ifa_dstaddr != NULL &&
1416                                     sa_equal(addr, ifa->ifa_dstaddr))
1417                                         return (ifa);
1418                         } else {
1419                                 /*
1420                                  * if we have a special address handler,
1421                                  * then use it instead of the generic one.
1422                                  */
1423                                 if (ifa->ifa_claim_addr) {
1424                                         if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1425                                                 return (ifa);
1426                                         } else {
1427                                                 continue;
1428                                         }
1429                                 }
1430
1431                                 /*
1432                                  * Scan all the bits in the ifa's address.
1433                                  * If a bit dissagrees with what we are
1434                                  * looking for, mask it with the netmask
1435                                  * to see if it really matters.
1436                                  * (A byte at a time)
1437                                  */
1438                                 if (ifa->ifa_netmask == 0)
1439                                         continue;
1440                                 cp = addr_data;
1441                                 cp2 = ifa->ifa_addr->sa_data;
1442                                 cp3 = ifa->ifa_netmask->sa_data;
1443                                 cplim = ifa->ifa_netmask->sa_len +
1444                                         (char *)ifa->ifa_netmask;
1445                                 while (cp3 < cplim)
1446                                         if ((*cp++ ^ *cp2++) & *cp3++)
1447                                                 goto next; /* next address! */
1448                                 /*
1449                                  * If the netmask of what we just found
1450                                  * is more specific than what we had before
1451                                  * (if we had one) then remember the new one
1452                                  * before continuing to search for an even
1453                                  * better one.  If the netmasks are equal,
1454                                  * we prefer the this ifa based on the result
1455                                  * of ifa_prefer().
1456                                  */
1457                                 if (ifa_maybe == NULL ||
1458                                     rn_refines((char *)ifa->ifa_netmask,
1459                                         (char *)ifa_maybe->ifa_netmask) ||
1460                                     (sa_equal(ifa_maybe->ifa_netmask,
1461                                         ifa->ifa_netmask) &&
1462                                      ifa_prefer(ifa, ifa_maybe)))
1463                                         ifa_maybe = ifa;
1464                         }
1465                 }
1466         }
1467         return (ifa_maybe);
1468 }
1469
1470 /*
1471  * Find an interface address specific to an interface best matching
1472  * a given address.
1473  */
1474 struct ifaddr *
1475 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1476 {
1477         struct ifaddr_container *ifac;
1478         char *cp, *cp2, *cp3;
1479         char *cplim;
1480         struct ifaddr *ifa_maybe = NULL;
1481         u_int af = addr->sa_family;
1482
1483         if (af >= AF_MAX)
1484                 return (0);
1485         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1486                 struct ifaddr *ifa = ifac->ifa;
1487
1488                 if (ifa->ifa_addr->sa_family != af)
1489                         continue;
1490                 if (ifa_maybe == NULL)
1491                         ifa_maybe = ifa;
1492                 if (ifa->ifa_netmask == NULL) {
1493                         if (sa_equal(addr, ifa->ifa_addr) ||
1494                             (ifa->ifa_dstaddr != NULL &&
1495                              sa_equal(addr, ifa->ifa_dstaddr)))
1496                                 return (ifa);
1497                         continue;
1498                 }
1499                 if (ifp->if_flags & IFF_POINTOPOINT) {
1500                         if (sa_equal(addr, ifa->ifa_dstaddr))
1501                                 return (ifa);
1502                 } else {
1503                         cp = addr->sa_data;
1504                         cp2 = ifa->ifa_addr->sa_data;
1505                         cp3 = ifa->ifa_netmask->sa_data;
1506                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1507                         for (; cp3 < cplim; cp3++)
1508                                 if ((*cp++ ^ *cp2++) & *cp3)
1509                                         break;
1510                         if (cp3 == cplim)
1511                                 return (ifa);
1512                 }
1513         }
1514         return (ifa_maybe);
1515 }
1516
1517 /*
1518  * Default action when installing a route with a Link Level gateway.
1519  * Lookup an appropriate real ifa to point to.
1520  * This should be moved to /sys/net/link.c eventually.
1521  */
1522 static void
1523 link_rtrequest(int cmd, struct rtentry *rt)
1524 {
1525         struct ifaddr *ifa;
1526         struct sockaddr *dst;
1527         struct ifnet *ifp;
1528
1529         if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1530             (ifp = ifa->ifa_ifp) == NULL || (dst = rt_key(rt)) == NULL)
1531                 return;
1532         ifa = ifaof_ifpforaddr(dst, ifp);
1533         if (ifa != NULL) {
1534                 IFAFREE(rt->rt_ifa);
1535                 IFAREF(ifa);
1536                 rt->rt_ifa = ifa;
1537                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1538                         ifa->ifa_rtrequest(cmd, rt);
1539         }
1540 }
1541
1542 struct netmsg_ifroute {
1543         struct netmsg_base      base;
1544         struct ifnet            *ifp;
1545         int                     flag;
1546         int                     fam;
1547 };
1548
1549 /*
1550  * Mark an interface down and notify protocols of the transition.
1551  */
1552 static void
1553 if_unroute_dispatch(netmsg_t nmsg)
1554 {
1555         struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1556         struct ifnet *ifp = msg->ifp;
1557         int flag = msg->flag, fam = msg->fam;
1558         struct ifaddr_container *ifac;
1559
1560         ifp->if_flags &= ~flag;
1561         getmicrotime(&ifp->if_lastchange);
1562         /*
1563          * The ifaddr processing in the following loop will block,
1564          * however, this function is called in netisr0, in which
1565          * ifaddr list changes happen, so we don't care about the
1566          * blockness of the ifaddr processing here.
1567          */
1568         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1569                 struct ifaddr *ifa = ifac->ifa;
1570
1571                 /* Ignore marker */
1572                 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1573                         continue;
1574
1575                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1576                         kpfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1577         }
1578         ifq_purge_all(&ifp->if_snd);
1579         rt_ifmsg(ifp);
1580
1581         lwkt_replymsg(&nmsg->lmsg, 0);
1582 }
1583
1584 void
1585 if_unroute(struct ifnet *ifp, int flag, int fam)
1586 {
1587         struct netmsg_ifroute msg;
1588
1589         ASSERT_CANDOMSG_NETISR0(curthread);
1590
1591         netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1592             if_unroute_dispatch);
1593         msg.ifp = ifp;
1594         msg.flag = flag;
1595         msg.fam = fam;
1596         lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1597 }
1598
1599 /*
1600  * Mark an interface up and notify protocols of the transition.
1601  */
1602 static void
1603 if_route_dispatch(netmsg_t nmsg)
1604 {
1605         struct netmsg_ifroute *msg = (struct netmsg_ifroute *)nmsg;
1606         struct ifnet *ifp = msg->ifp;
1607         int flag = msg->flag, fam = msg->fam;
1608         struct ifaddr_container *ifac;
1609
1610         ifq_purge_all(&ifp->if_snd);
1611         ifp->if_flags |= flag;
1612         getmicrotime(&ifp->if_lastchange);
1613         /*
1614          * The ifaddr processing in the following loop will block,
1615          * however, this function is called in netisr0, in which
1616          * ifaddr list changes happen, so we don't care about the
1617          * blockness of the ifaddr processing here.
1618          */
1619         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1620                 struct ifaddr *ifa = ifac->ifa;
1621
1622                 /* Ignore marker */
1623                 if (ifa->ifa_addr->sa_family == AF_UNSPEC)
1624                         continue;
1625
1626                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1627                         kpfctlinput(PRC_IFUP, ifa->ifa_addr);
1628         }
1629         rt_ifmsg(ifp);
1630 #ifdef INET6
1631         in6_if_up(ifp);
1632 #endif
1633
1634         lwkt_replymsg(&nmsg->lmsg, 0);
1635 }
1636
1637 void
1638 if_route(struct ifnet *ifp, int flag, int fam)
1639 {
1640         struct netmsg_ifroute msg;
1641
1642         ASSERT_CANDOMSG_NETISR0(curthread);
1643
1644         netmsg_init(&msg.base, NULL, &curthread->td_msgport, 0,
1645             if_route_dispatch);
1646         msg.ifp = ifp;
1647         msg.flag = flag;
1648         msg.fam = fam;
1649         lwkt_domsg(netisr_cpuport(0), &msg.base.lmsg, 0);
1650 }
1651
1652 /*
1653  * Mark an interface down and notify protocols of the transition.  An
1654  * interface going down is also considered to be a synchronizing event.
1655  * We must ensure that all packet processing related to the interface
1656  * has completed before we return so e.g. the caller can free the ifnet
1657  * structure that the mbufs may be referencing.
1658  *
1659  * NOTE: must be called at splnet or eqivalent.
1660  */
1661 void
1662 if_down(struct ifnet *ifp)
1663 {
1664         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1665         netmsg_service_sync();
1666 }
1667
1668 /*
1669  * Mark an interface up and notify protocols of
1670  * the transition.
1671  * NOTE: must be called at splnet or eqivalent.
1672  */
1673 void
1674 if_up(struct ifnet *ifp)
1675 {
1676         if_route(ifp, IFF_UP, AF_UNSPEC);
1677 }
1678
1679 /*
1680  * Process a link state change.
1681  * NOTE: must be called at splsoftnet or equivalent.
1682  */
1683 void
1684 if_link_state_change(struct ifnet *ifp)
1685 {
1686         int link_state = ifp->if_link_state;
1687
1688         rt_ifmsg(ifp);
1689         devctl_notify("IFNET", ifp->if_xname,
1690             (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1691 }
1692
1693 /*
1694  * Handle interface watchdog timer routines.  Called
1695  * from softclock, we decrement timers (if set) and
1696  * call the appropriate interface routine on expiration.
1697  */
1698 static void
1699 if_slowtimo_dispatch(netmsg_t nmsg)
1700 {
1701         struct globaldata *gd = mycpu;
1702         const struct ifnet_array *arr;
1703         int i;
1704
1705         ASSERT_IN_NETISR(0);
1706
1707         crit_enter_gd(gd);
1708         lwkt_replymsg(&nmsg->lmsg, 0);  /* reply ASAP */
1709         crit_exit_gd(gd);
1710
1711         arr = ifnet_array_get();
1712         for (i = 0; i < arr->ifnet_count; ++i) {
1713                 struct ifnet *ifp = arr->ifnet_arr[i];
1714
1715                 crit_enter_gd(gd);
1716
1717                 if (if_stats_compat) {
1718                         IFNET_STAT_GET(ifp, ipackets, ifp->if_ipackets);
1719                         IFNET_STAT_GET(ifp, ierrors, ifp->if_ierrors);
1720                         IFNET_STAT_GET(ifp, opackets, ifp->if_opackets);
1721                         IFNET_STAT_GET(ifp, oerrors, ifp->if_oerrors);
1722                         IFNET_STAT_GET(ifp, collisions, ifp->if_collisions);
1723                         IFNET_STAT_GET(ifp, ibytes, ifp->if_ibytes);
1724                         IFNET_STAT_GET(ifp, obytes, ifp->if_obytes);
1725                         IFNET_STAT_GET(ifp, imcasts, ifp->if_imcasts);
1726                         IFNET_STAT_GET(ifp, omcasts, ifp->if_omcasts);
1727                         IFNET_STAT_GET(ifp, iqdrops, ifp->if_iqdrops);
1728                         IFNET_STAT_GET(ifp, noproto, ifp->if_noproto);
1729                         IFNET_STAT_GET(ifp, oqdrops, ifp->if_oqdrops);
1730                 }
1731
1732                 if (ifp->if_timer == 0 || --ifp->if_timer) {
1733                         crit_exit_gd(gd);
1734                         continue;
1735                 }
1736                 if (ifp->if_watchdog) {
1737                         if (ifnet_tryserialize_all(ifp)) {
1738                                 (*ifp->if_watchdog)(ifp);
1739                                 ifnet_deserialize_all(ifp);
1740                         } else {
1741                                 /* try again next timeout */
1742                                 ++ifp->if_timer;
1743                         }
1744                 }
1745
1746                 crit_exit_gd(gd);
1747         }
1748
1749         callout_reset(&if_slowtimo_timer, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1750 }
1751
1752 static void
1753 if_slowtimo(void *arg __unused)
1754 {
1755         struct lwkt_msg *lmsg = &if_slowtimo_netmsg.lmsg;
1756
1757         KASSERT(mycpuid == 0, ("not on cpu0"));
1758         crit_enter();
1759         if (lmsg->ms_flags & MSGF_DONE)
1760                 lwkt_sendmsg_oncpu(netisr_cpuport(0), lmsg);
1761         crit_exit();
1762 }
1763
1764 /*
1765  * Map interface name to
1766  * interface structure pointer.
1767  */
1768 struct ifnet *
1769 ifunit(const char *name)
1770 {
1771         struct ifnet *ifp;
1772
1773         /*
1774          * Search all the interfaces for this name/number
1775          */
1776         KASSERT(mtx_owned(&ifnet_mtx), ("ifnet is not locked"));
1777
1778         TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
1779                 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1780                         break;
1781         }
1782         return (ifp);
1783 }
1784
1785 struct ifnet *
1786 ifunit_netisr(const char *name)
1787 {
1788         const struct ifnet_array *arr;
1789         int i;
1790
1791         /*
1792          * Search all the interfaces for this name/number
1793          */
1794
1795         arr = ifnet_array_get();
1796         for (i = 0; i < arr->ifnet_count; ++i) {
1797                 struct ifnet *ifp = arr->ifnet_arr[i];
1798
1799                 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1800                         return ifp;
1801         }
1802         return NULL;
1803 }
1804
1805 /*
1806  * Interface ioctls.
1807  */
1808 int
1809 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct ucred *cred)
1810 {
1811         struct ifnet *ifp;
1812         struct ifreq *ifr;
1813         struct ifstat *ifs;
1814         int error, do_ifup = 0;
1815         short oif_flags;
1816         int new_flags;
1817         size_t namelen, onamelen;
1818         char new_name[IFNAMSIZ];
1819         struct ifaddr *ifa;
1820         struct sockaddr_dl *sdl;
1821
1822         switch (cmd) {
1823         case SIOCGIFCONF:
1824         case OSIOCGIFCONF:
1825                 return (ifconf(cmd, data, cred));
1826         default:
1827                 break;
1828         }
1829
1830         ifr = (struct ifreq *)data;
1831
1832         switch (cmd) {
1833         case SIOCIFCREATE:
1834         case SIOCIFCREATE2:
1835                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1836                         return (error);
1837                 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1838                         cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1839         case SIOCIFDESTROY:
1840                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1841                         return (error);
1842                 return (if_clone_destroy(ifr->ifr_name));
1843         case SIOCIFGCLONERS:
1844                 return (if_clone_list((struct if_clonereq *)data));
1845         default:
1846                 break;
1847         }
1848
1849         /*
1850          * Nominal ioctl through interface, lookup the ifp and obtain a
1851          * lock to serialize the ifconfig ioctl operation.
1852          */
1853         ifnet_lock();
1854
1855         ifp = ifunit(ifr->ifr_name);
1856         if (ifp == NULL) {
1857                 ifnet_unlock();
1858                 return (ENXIO);
1859         }
1860         error = 0;
1861
1862         switch (cmd) {
1863         case SIOCGIFINDEX:
1864                 ifr->ifr_index = ifp->if_index;
1865                 break;
1866
1867         case SIOCGIFFLAGS:
1868                 ifr->ifr_flags = ifp->if_flags;
1869                 ifr->ifr_flagshigh = ifp->if_flags >> 16;
1870                 break;
1871
1872         case SIOCGIFCAP:
1873                 ifr->ifr_reqcap = ifp->if_capabilities;
1874                 ifr->ifr_curcap = ifp->if_capenable;
1875                 break;
1876
1877         case SIOCGIFMETRIC:
1878                 ifr->ifr_metric = ifp->if_metric;
1879                 break;
1880
1881         case SIOCGIFMTU:
1882                 ifr->ifr_mtu = ifp->if_mtu;
1883                 break;
1884
1885         case SIOCGIFTSOLEN:
1886                 ifr->ifr_tsolen = ifp->if_tsolen;
1887                 break;
1888
1889         case SIOCGIFDATA:
1890                 error = copyout((caddr_t)&ifp->if_data, ifr->ifr_data,
1891                                 sizeof(ifp->if_data));
1892                 break;
1893
1894         case SIOCGIFPHYS:
1895                 ifr->ifr_phys = ifp->if_physical;
1896                 break;
1897
1898         case SIOCGIFPOLLCPU:
1899                 ifr->ifr_pollcpu = -1;
1900                 break;
1901
1902         case SIOCSIFPOLLCPU:
1903                 break;
1904
1905         case SIOCSIFFLAGS:
1906                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1907                 if (error)
1908                         break;
1909                 new_flags = (ifr->ifr_flags & 0xffff) |
1910                     (ifr->ifr_flagshigh << 16);
1911                 if (ifp->if_flags & IFF_SMART) {
1912                         /* Smart drivers twiddle their own routes */
1913                 } else if (ifp->if_flags & IFF_UP &&
1914                     (new_flags & IFF_UP) == 0) {
1915                         if_down(ifp);
1916                 } else if (new_flags & IFF_UP &&
1917                     (ifp->if_flags & IFF_UP) == 0) {
1918                         do_ifup = 1;
1919                 }
1920
1921 #ifdef IFPOLL_ENABLE
1922                 if ((new_flags ^ ifp->if_flags) & IFF_NPOLLING) {
1923                         if (new_flags & IFF_NPOLLING)
1924                                 ifpoll_register(ifp);
1925                         else
1926                                 ifpoll_deregister(ifp);
1927                 }
1928 #endif
1929
1930                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1931                         (new_flags &~ IFF_CANTCHANGE);
1932                 if (new_flags & IFF_PPROMISC) {
1933                         /* Permanently promiscuous mode requested */
1934                         ifp->if_flags |= IFF_PROMISC;
1935                 } else if (ifp->if_pcount == 0) {
1936                         ifp->if_flags &= ~IFF_PROMISC;
1937                 }
1938                 if (ifp->if_ioctl) {
1939                         ifnet_serialize_all(ifp);
1940                         ifp->if_ioctl(ifp, cmd, data, cred);
1941                         ifnet_deserialize_all(ifp);
1942                 }
1943                 if (do_ifup)
1944                         if_up(ifp);
1945                 getmicrotime(&ifp->if_lastchange);
1946                 break;
1947
1948         case SIOCSIFCAP:
1949                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1950                 if (error)
1951                         break;
1952                 if (ifr->ifr_reqcap & ~ifp->if_capabilities) {
1953                         error = EINVAL;
1954                         break;
1955                 }
1956                 ifnet_serialize_all(ifp);
1957                 ifp->if_ioctl(ifp, cmd, data, cred);
1958                 ifnet_deserialize_all(ifp);
1959                 break;
1960
1961         case SIOCSIFNAME:
1962                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1963                 if (error)
1964                         break;
1965                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1966                 if (error)
1967                         break;
1968                 if (new_name[0] == '\0') {
1969                         error = EINVAL;
1970                         break;
1971                 }
1972                 if (ifunit(new_name) != NULL) {
1973                         error = EEXIST;
1974                         break;
1975                 }
1976
1977                 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
1978
1979                 /* Announce the departure of the interface. */
1980                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1981
1982                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1983                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
1984                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1985                 namelen = strlen(new_name);
1986                 onamelen = sdl->sdl_nlen;
1987                 /*
1988                  * Move the address if needed.  This is safe because we
1989                  * allocate space for a name of length IFNAMSIZ when we
1990                  * create this in if_attach().
1991                  */
1992                 if (namelen != onamelen) {
1993                         bcopy(sdl->sdl_data + onamelen,
1994                             sdl->sdl_data + namelen, sdl->sdl_alen);
1995                 }
1996                 bcopy(new_name, sdl->sdl_data, namelen);
1997                 sdl->sdl_nlen = namelen;
1998                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1999                 bzero(sdl->sdl_data, onamelen);
2000                 while (namelen != 0)
2001                         sdl->sdl_data[--namelen] = 0xff;
2002
2003                 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
2004
2005                 /* Announce the return of the interface. */
2006                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2007                 break;
2008
2009         case SIOCSIFMETRIC:
2010                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2011                 if (error)
2012                         break;
2013                 ifp->if_metric = ifr->ifr_metric;
2014                 getmicrotime(&ifp->if_lastchange);
2015                 break;
2016
2017         case SIOCSIFPHYS:
2018                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2019                 if (error)
2020                         break;
2021                 if (ifp->if_ioctl == NULL) {
2022                         error = EOPNOTSUPP;
2023                         break;
2024                 }
2025                 ifnet_serialize_all(ifp);
2026                 error = ifp->if_ioctl(ifp, cmd, data, cred);
2027                 ifnet_deserialize_all(ifp);
2028                 if (error == 0)
2029                         getmicrotime(&ifp->if_lastchange);
2030                 break;
2031
2032         case SIOCSIFMTU:
2033         {
2034                 u_long oldmtu = ifp->if_mtu;
2035
2036                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2037                 if (error)
2038                         break;
2039                 if (ifp->if_ioctl == NULL) {
2040                         error = EOPNOTSUPP;
2041                         break;
2042                 }
2043                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU) {
2044                         error = EINVAL;
2045                         break;
2046                 }
2047                 ifnet_serialize_all(ifp);
2048                 error = ifp->if_ioctl(ifp, cmd, data, cred);
2049                 ifnet_deserialize_all(ifp);
2050                 if (error == 0) {
2051                         getmicrotime(&ifp->if_lastchange);
2052                         rt_ifmsg(ifp);
2053                 }
2054                 /*
2055                  * If the link MTU changed, do network layer specific procedure.
2056                  */
2057                 if (ifp->if_mtu != oldmtu) {
2058 #ifdef INET6
2059                         nd6_setmtu(ifp);
2060 #endif
2061                 }
2062                 break;
2063         }
2064
2065         case SIOCSIFTSOLEN:
2066                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2067                 if (error)
2068                         break;
2069
2070                 /* XXX need driver supplied upper limit */
2071                 if (ifr->ifr_tsolen <= 0) {
2072                         error = EINVAL;
2073                         break;
2074                 }
2075                 ifp->if_tsolen = ifr->ifr_tsolen;
2076                 break;
2077
2078         case SIOCADDMULTI:
2079         case SIOCDELMULTI:
2080                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2081                 if (error)
2082                         break;
2083
2084                 /* Don't allow group membership on non-multicast interfaces. */
2085                 if ((ifp->if_flags & IFF_MULTICAST) == 0) {
2086                         error = EOPNOTSUPP;
2087                         break;
2088                 }
2089
2090                 /* Don't let users screw up protocols' entries. */
2091                 if (ifr->ifr_addr.sa_family != AF_LINK) {
2092                         error = EINVAL;
2093                         break;
2094                 }
2095
2096                 if (cmd == SIOCADDMULTI) {
2097                         struct ifmultiaddr *ifma;
2098                         error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2099                 } else {
2100                         error = if_delmulti(ifp, &ifr->ifr_addr);
2101                 }
2102                 if (error == 0)
2103                         getmicrotime(&ifp->if_lastchange);
2104                 break;
2105
2106         case SIOCSIFPHYADDR:
2107         case SIOCDIFPHYADDR:
2108 #ifdef INET6
2109         case SIOCSIFPHYADDR_IN6:
2110 #endif
2111         case SIOCSLIFPHYADDR:
2112         case SIOCSIFMEDIA:
2113         case SIOCSIFGENERIC:
2114                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2115                 if (error)
2116                         break;
2117                 if (ifp->if_ioctl == 0) {
2118                         error = EOPNOTSUPP;
2119                         break;
2120                 }
2121                 ifnet_serialize_all(ifp);
2122                 error = ifp->if_ioctl(ifp, cmd, data, cred);
2123                 ifnet_deserialize_all(ifp);
2124                 if (error == 0)
2125                         getmicrotime(&ifp->if_lastchange);
2126                 break;
2127
2128         case SIOCGIFSTATUS:
2129                 ifs = (struct ifstat *)data;
2130                 ifs->ascii[0] = '\0';
2131                 /* fall through */
2132         case SIOCGIFPSRCADDR:
2133         case SIOCGIFPDSTADDR:
2134         case SIOCGLIFPHYADDR:
2135         case SIOCGIFMEDIA:
2136         case SIOCGIFGENERIC:
2137                 if (ifp->if_ioctl == NULL) {
2138                         error = EOPNOTSUPP;
2139                         break;
2140                 }
2141                 ifnet_serialize_all(ifp);
2142                 error = ifp->if_ioctl(ifp, cmd, data, cred);
2143                 ifnet_deserialize_all(ifp);
2144                 break;
2145
2146         case SIOCSIFLLADDR:
2147                 error = priv_check_cred(cred, PRIV_ROOT, 0);
2148                 if (error)
2149                         break;
2150                 error = if_setlladdr(ifp, ifr->ifr_addr.sa_data,
2151                                      ifr->ifr_addr.sa_len);
2152                 EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2153                 break;
2154
2155         default:
2156                 oif_flags = ifp->if_flags;
2157                 if (so->so_proto == 0) {
2158                         error = EOPNOTSUPP;
2159                         break;
2160                 }
2161                 error = so_pru_control_direct(so, cmd, data, ifp);
2162
2163                 if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2164 #ifdef INET6
2165                         DELAY(100);/* XXX: temporary workaround for fxp issue*/
2166                         if (ifp->if_flags & IFF_UP) {
2167                                 crit_enter();
2168                                 in6_if_up(ifp);
2169                                 crit_exit();
2170                         }
2171 #endif
2172                 }
2173                 break;
2174         }
2175
2176         ifnet_unlock();
2177         return (error);
2178 }
2179
2180 /*
2181  * Set/clear promiscuous mode on interface ifp based on the truth value
2182  * of pswitch.  The calls are reference counted so that only the first
2183  * "on" request actually has an effect, as does the final "off" request.
2184  * Results are undefined if the "off" and "on" requests are not matched.
2185  */
2186 int
2187 ifpromisc(struct ifnet *ifp, int pswitch)
2188 {
2189         struct ifreq ifr;
2190         int error;
2191         int oldflags;
2192
2193         oldflags = ifp->if_flags;
2194         if (ifp->if_flags & IFF_PPROMISC) {
2195                 /* Do nothing if device is in permanently promiscuous mode */
2196                 ifp->if_pcount += pswitch ? 1 : -1;
2197                 return (0);
2198         }
2199         if (pswitch) {
2200                 /*
2201                  * If the device is not configured up, we cannot put it in
2202                  * promiscuous mode.
2203                  */
2204                 if ((ifp->if_flags & IFF_UP) == 0)
2205                         return (ENETDOWN);
2206                 if (ifp->if_pcount++ != 0)
2207                         return (0);
2208                 ifp->if_flags |= IFF_PROMISC;
2209                 log(LOG_INFO, "%s: promiscuous mode enabled\n",
2210                     ifp->if_xname);
2211         } else {
2212                 if (--ifp->if_pcount > 0)
2213                         return (0);
2214                 ifp->if_flags &= ~IFF_PROMISC;
2215                 log(LOG_INFO, "%s: promiscuous mode disabled\n",
2216                     ifp->if_xname);
2217         }
2218         ifr.ifr_flags = ifp->if_flags;
2219         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2220         ifnet_serialize_all(ifp);
2221         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
2222         ifnet_deserialize_all(ifp);
2223         if (error == 0)
2224                 rt_ifmsg(ifp);
2225         else
2226                 ifp->if_flags = oldflags;
2227         return error;
2228 }
2229
2230 /*
2231  * Return interface configuration
2232  * of system.  List may be used
2233  * in later ioctl's (above) to get
2234  * other information.
2235  */
2236 static int
2237 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
2238 {
2239         struct ifconf *ifc = (struct ifconf *)data;
2240         struct ifnet *ifp;
2241         struct sockaddr *sa;
2242         struct ifreq ifr, *ifrp;
2243         int space = ifc->ifc_len, error = 0;
2244
2245         ifrp = ifc->ifc_req;
2246
2247         ifnet_lock();
2248         TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2249                 struct ifaddr_container *ifac, *ifac_mark;
2250                 struct ifaddr_marker mark;
2251                 struct ifaddrhead *head;
2252                 int addrs;
2253
2254                 if (space <= sizeof ifr)
2255                         break;
2256
2257                 /*
2258                  * Zero the stack declared structure first to prevent
2259                  * memory disclosure.
2260                  */
2261                 bzero(&ifr, sizeof(ifr));
2262                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2263                     >= sizeof(ifr.ifr_name)) {
2264                         error = ENAMETOOLONG;
2265                         break;
2266                 }
2267
2268                 /*
2269                  * Add a marker, since copyout() could block and during that
2270                  * period the list could be changed.  Inserting the marker to
2271                  * the header of the list will not cause trouble for the code
2272                  * assuming that the first element of the list is AF_LINK; the
2273                  * marker will be moved to the next position w/o blocking.
2274                  */
2275                 ifa_marker_init(&mark, ifp);
2276                 ifac_mark = &mark.ifac;
2277                 head = &ifp->if_addrheads[mycpuid];
2278
2279                 addrs = 0;
2280                 TAILQ_INSERT_HEAD(head, ifac_mark, ifa_link);
2281                 while ((ifac = TAILQ_NEXT(ifac_mark, ifa_link)) != NULL) {
2282                         struct ifaddr *ifa = ifac->ifa;
2283
2284                         TAILQ_REMOVE(head, ifac_mark, ifa_link);
2285                         TAILQ_INSERT_AFTER(head, ifac, ifac_mark, ifa_link);
2286
2287                         /* Ignore marker */
2288                         if (ifa->ifa_addr->sa_family == AF_UNSPEC)
2289                                 continue;
2290
2291                         if (space <= sizeof ifr)
2292                                 break;
2293                         sa = ifa->ifa_addr;
2294                         if (cred->cr_prison &&
2295                             prison_if(cred, sa))
2296                                 continue;
2297                         addrs++;
2298                         /*
2299                          * Keep a reference on this ifaddr, so that it will
2300                          * not be destroyed when its address is copied to
2301                          * the userland, which could block.
2302                          */
2303                         IFAREF(ifa);
2304                         if (sa->sa_len <= sizeof(*sa)) {
2305                                 ifr.ifr_addr = *sa;
2306                                 error = copyout(&ifr, ifrp, sizeof ifr);
2307                                 ifrp++;
2308                         } else {
2309                                 if (space < (sizeof ifr) + sa->sa_len -
2310                                             sizeof(*sa)) {
2311                                         IFAFREE(ifa);
2312                                         break;
2313                                 }
2314                                 space -= sa->sa_len - sizeof(*sa);
2315                                 error = copyout(&ifr, ifrp,
2316                                                 sizeof ifr.ifr_name);
2317                                 if (error == 0)
2318                                         error = copyout(sa, &ifrp->ifr_addr,
2319                                                         sa->sa_len);
2320                                 ifrp = (struct ifreq *)
2321                                         (sa->sa_len + (caddr_t)&ifrp->ifr_addr);
2322                         }
2323                         IFAFREE(ifa);
2324                         if (error)
2325                                 break;
2326                         space -= sizeof ifr;
2327                 }
2328                 TAILQ_REMOVE(head, ifac_mark, ifa_link);
2329                 if (error)
2330                         break;
2331                 if (!addrs) {
2332                         bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
2333                         error = copyout(&ifr, ifrp, sizeof ifr);
2334                         if (error)
2335                                 break;
2336                         space -= sizeof ifr;
2337                         ifrp++;
2338                 }
2339         }
2340         ifnet_unlock();
2341
2342         ifc->ifc_len -= space;
2343         return (error);
2344 }
2345
2346 /*
2347  * Just like if_promisc(), but for all-multicast-reception mode.
2348  */
2349 int
2350 if_allmulti(struct ifnet *ifp, int onswitch)
2351 {
2352         int error = 0;
2353         struct ifreq ifr;
2354
2355         crit_enter();
2356
2357         if (onswitch) {
2358                 if (ifp->if_amcount++ == 0) {
2359                         ifp->if_flags |= IFF_ALLMULTI;
2360                         ifr.ifr_flags = ifp->if_flags;
2361                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2362                         ifnet_serialize_all(ifp);
2363                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2364                                               NULL);
2365                         ifnet_deserialize_all(ifp);
2366                 }
2367         } else {
2368                 if (ifp->if_amcount > 1) {
2369                         ifp->if_amcount--;
2370                 } else {
2371                         ifp->if_amcount = 0;
2372                         ifp->if_flags &= ~IFF_ALLMULTI;
2373                         ifr.ifr_flags = ifp->if_flags;
2374                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2375                         ifnet_serialize_all(ifp);
2376                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2377                                               NULL);
2378                         ifnet_deserialize_all(ifp);
2379                 }
2380         }
2381
2382         crit_exit();
2383
2384         if (error == 0)
2385                 rt_ifmsg(ifp);
2386         return error;
2387 }
2388
2389 /*
2390  * Add a multicast listenership to the interface in question.
2391  * The link layer provides a routine which converts
2392  */
2393 int
2394 if_addmulti_serialized(struct ifnet *ifp, struct sockaddr *sa,
2395     struct ifmultiaddr **retifma)
2396 {
2397         struct sockaddr *llsa, *dupsa;
2398         int error;
2399         struct ifmultiaddr *ifma;
2400
2401         ASSERT_IFNET_SERIALIZED_ALL(ifp);
2402
2403         /*
2404          * If the matching multicast address already exists
2405          * then don't add a new one, just add a reference
2406          */
2407         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2408                 if (sa_equal(sa, ifma->ifma_addr)) {
2409                         ifma->ifma_refcount++;
2410                         if (retifma)
2411                                 *retifma = ifma;
2412                         return 0;
2413                 }
2414         }
2415
2416         /*
2417          * Give the link layer a chance to accept/reject it, and also
2418          * find out which AF_LINK address this maps to, if it isn't one
2419          * already.
2420          */
2421         if (ifp->if_resolvemulti) {
2422                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2423                 if (error)
2424                         return error;
2425         } else {
2426                 llsa = NULL;
2427         }
2428
2429         ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2430         dupsa = kmalloc(sa->sa_len, M_IFMADDR, M_INTWAIT);
2431         bcopy(sa, dupsa, sa->sa_len);
2432
2433         ifma->ifma_addr = dupsa;
2434         ifma->ifma_lladdr = llsa;
2435         ifma->ifma_ifp = ifp;
2436         ifma->ifma_refcount = 1;
2437         ifma->ifma_protospec = NULL;
2438         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2439
2440         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2441         if (retifma)
2442                 *retifma = ifma;
2443
2444         if (llsa != NULL) {
2445                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2446                         if (sa_equal(ifma->ifma_addr, llsa))
2447                                 break;
2448                 }
2449                 if (ifma) {
2450                         ifma->ifma_refcount++;
2451                 } else {
2452                         ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_INTWAIT);
2453                         dupsa = kmalloc(llsa->sa_len, M_IFMADDR, M_INTWAIT);
2454                         bcopy(llsa, dupsa, llsa->sa_len);
2455                         ifma->ifma_addr = dupsa;
2456                         ifma->ifma_ifp = ifp;
2457                         ifma->ifma_refcount = 1;
2458                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2459                 }
2460         }
2461         /*
2462          * We are certain we have added something, so call down to the
2463          * interface to let them know about it.
2464          */
2465         if (ifp->if_ioctl)
2466                 ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2467
2468         return 0;
2469 }
2470
2471 int
2472 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2473     struct ifmultiaddr **retifma)
2474 {
2475         int error;
2476
2477         ifnet_serialize_all(ifp);
2478         error = if_addmulti_serialized(ifp, sa, retifma);
2479         ifnet_deserialize_all(ifp);
2480
2481         return error;
2482 }
2483
2484 /*
2485  * Remove a reference to a multicast address on this interface.  Yell
2486  * if the request does not match an existing membership.
2487  */
2488 static int
2489 if_delmulti_serialized(struct ifnet *ifp, struct sockaddr *sa)
2490 {
2491         struct ifmultiaddr *ifma;
2492
2493         ASSERT_IFNET_SERIALIZED_ALL(ifp);
2494
2495         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2496                 if (sa_equal(sa, ifma->ifma_addr))
2497                         break;
2498         if (ifma == NULL)
2499                 return ENOENT;
2500
2501         if (ifma->ifma_refcount > 1) {
2502                 ifma->ifma_refcount--;
2503                 return 0;
2504         }
2505
2506         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2507         sa = ifma->ifma_lladdr;
2508         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2509         /*
2510          * Make sure the interface driver is notified
2511          * in the case of a link layer mcast group being left.
2512          */
2513         if (ifma->ifma_addr->sa_family == AF_LINK && sa == NULL)
2514                 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2515         kfree(ifma->ifma_addr, M_IFMADDR);
2516         kfree(ifma, M_IFMADDR);
2517         if (sa == NULL)
2518                 return 0;
2519
2520         /*
2521          * Now look for the link-layer address which corresponds to
2522          * this network address.  It had been squirreled away in
2523          * ifma->ifma_lladdr for this purpose (so we don't have
2524          * to call ifp->if_resolvemulti() again), and we saved that
2525          * value in sa above.  If some nasty deleted the
2526          * link-layer address out from underneath us, we can deal because
2527          * the address we stored was is not the same as the one which was
2528          * in the record for the link-layer address.  (So we don't complain
2529          * in that case.)
2530          */
2531         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2532                 if (sa_equal(sa, ifma->ifma_addr))
2533                         break;
2534         if (ifma == NULL)
2535                 return 0;
2536
2537         if (ifma->ifma_refcount > 1) {
2538                 ifma->ifma_refcount--;
2539                 return 0;
2540         }
2541
2542         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2543         ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2544         kfree(ifma->ifma_addr, M_IFMADDR);
2545         kfree(sa, M_IFMADDR);
2546         kfree(ifma, M_IFMADDR);
2547
2548         return 0;
2549 }
2550
2551 int
2552 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2553 {
2554         int error;
2555
2556         ifnet_serialize_all(ifp);
2557         error = if_delmulti_serialized(ifp, sa);
2558         ifnet_deserialize_all(ifp);
2559
2560         return error;
2561 }
2562
2563 /*
2564  * Delete all multicast group membership for an interface.
2565  * Should be used to quickly flush all multicast filters.
2566  */
2567 void
2568 if_delallmulti_serialized(struct ifnet *ifp)
2569 {
2570         struct ifmultiaddr *ifma, mark;
2571         struct sockaddr sa;
2572
2573         ASSERT_IFNET_SERIALIZED_ALL(ifp);
2574
2575         bzero(&sa, sizeof(sa));
2576         sa.sa_family = AF_UNSPEC;
2577         sa.sa_len = sizeof(sa);
2578
2579         bzero(&mark, sizeof(mark));
2580         mark.ifma_addr = &sa;
2581
2582         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, &mark, ifma_link);
2583         while ((ifma = TAILQ_NEXT(&mark, ifma_link)) != NULL) {
2584                 TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2585                 TAILQ_INSERT_AFTER(&ifp->if_multiaddrs, ifma, &mark,
2586                     ifma_link);
2587
2588                 if (ifma->ifma_addr->sa_family == AF_UNSPEC)
2589                         continue;
2590
2591                 if_delmulti_serialized(ifp, ifma->ifma_addr);
2592         }
2593         TAILQ_REMOVE(&ifp->if_multiaddrs, &mark, ifma_link);
2594 }
2595
2596
2597 /*
2598  * Set the link layer address on an interface.
2599  *
2600  * At this time we only support certain types of interfaces,
2601  * and we don't allow the length of the address to change.
2602  */
2603 int
2604 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2605 {
2606         struct sockaddr_dl *sdl;
2607         struct ifreq ifr;
2608
2609         sdl = IF_LLSOCKADDR(ifp);
2610         if (sdl == NULL)
2611                 return (EINVAL);
2612         if (len != sdl->sdl_alen)       /* don't allow length to change */
2613                 return (EINVAL);
2614         switch (ifp->if_type) {
2615         case IFT_ETHER:                 /* these types use struct arpcom */
2616         case IFT_XETHER:
2617         case IFT_L2VLAN:
2618         case IFT_IEEE8023ADLAG:
2619                 bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2620                 bcopy(lladdr, LLADDR(sdl), len);
2621                 break;
2622         default:
2623                 return (ENODEV);
2624         }
2625         /*
2626          * If the interface is already up, we need
2627          * to re-init it in order to reprogram its
2628          * address filter.
2629          */
2630         ifnet_serialize_all(ifp);
2631         if ((ifp->if_flags & IFF_UP) != 0) {
2632 #ifdef INET
2633                 struct ifaddr_container *ifac;
2634 #endif
2635
2636                 ifp->if_flags &= ~IFF_UP;
2637                 ifr.ifr_flags = ifp->if_flags;
2638                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2639                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2640                               NULL);
2641                 ifp->if_flags |= IFF_UP;
2642                 ifr.ifr_flags = ifp->if_flags;
2643                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2644                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2645                                  NULL);
2646 #ifdef INET
2647                 /*
2648                  * Also send gratuitous ARPs to notify other nodes about
2649                  * the address change.
2650                  */
2651                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2652                         struct ifaddr *ifa = ifac->ifa;
2653
2654                         if (ifa->ifa_addr != NULL &&
2655                             ifa->ifa_addr->sa_family == AF_INET)
2656                                 arp_gratuitous(ifp, ifa);
2657                 }
2658 #endif
2659         }
2660         ifnet_deserialize_all(ifp);
2661         return (0);
2662 }
2663
2664 struct ifmultiaddr *
2665 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2666 {
2667         struct ifmultiaddr *ifma;
2668
2669         /* TODO: need ifnet_serialize_main */
2670         ifnet_serialize_all(ifp);
2671         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2672                 if (sa_equal(ifma->ifma_addr, sa))
2673                         break;
2674         ifnet_deserialize_all(ifp);
2675
2676         return ifma;
2677 }
2678
2679 /*
2680  * This function locates the first real ethernet MAC from a network
2681  * card and loads it into node, returning 0 on success or ENOENT if
2682  * no suitable interfaces were found.  It is used by the uuid code to
2683  * generate a unique 6-byte number.
2684  */
2685 int
2686 if_getanyethermac(uint16_t *node, int minlen)
2687 {
2688         struct ifnet *ifp;
2689         struct sockaddr_dl *sdl;
2690
2691         ifnet_lock();
2692         TAILQ_FOREACH(ifp, &ifnetlist, if_link) {
2693                 if (ifp->if_type != IFT_ETHER)
2694                         continue;
2695                 sdl = IF_LLSOCKADDR(ifp);
2696                 if (sdl->sdl_alen < minlen)
2697                         continue;
2698                 bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2699                       minlen);
2700                 ifnet_unlock();
2701                 return(0);
2702         }
2703         ifnet_unlock();
2704         return (ENOENT);
2705 }
2706
2707 /*
2708  * The name argument must be a pointer to storage which will last as
2709  * long as the interface does.  For physical devices, the result of
2710  * device_get_name(dev) is a good choice and for pseudo-devices a
2711  * static string works well.
2712  */
2713 void
2714 if_initname(struct ifnet *ifp, const char *name, int unit)
2715 {
2716         ifp->if_dname = name;
2717         ifp->if_dunit = unit;
2718         if (unit != IF_DUNIT_NONE)
2719                 ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2720         else
2721                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2722 }
2723
2724 int
2725 if_printf(struct ifnet *ifp, const char *fmt, ...)
2726 {
2727         __va_list ap;
2728         int retval;
2729
2730         retval = kprintf("%s: ", ifp->if_xname);
2731         __va_start(ap, fmt);
2732         retval += kvprintf(fmt, ap);
2733         __va_end(ap);
2734         return (retval);
2735 }
2736
2737 struct ifnet *
2738 if_alloc(uint8_t type)
2739 {
2740         struct ifnet *ifp;
2741         size_t size;
2742
2743         /*
2744          * XXX temporary hack until arpcom is setup in if_l2com
2745          */
2746         if (type == IFT_ETHER)
2747                 size = sizeof(struct arpcom);
2748         else
2749                 size = sizeof(struct ifnet);
2750
2751         ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2752
2753         ifp->if_type = type;
2754
2755         if (if_com_alloc[type] != NULL) {
2756                 ifp->if_l2com = if_com_alloc[type](type, ifp);
2757                 if (ifp->if_l2com == NULL) {
2758                         kfree(ifp, M_IFNET);
2759                         return (NULL);
2760                 }
2761         }
2762         return (ifp);
2763 }
2764
2765 void
2766 if_free(struct ifnet *ifp)
2767 {
2768         kfree(ifp, M_IFNET);
2769 }
2770
2771 void
2772 ifq_set_classic(struct ifaltq *ifq)
2773 {
2774         ifq_set_methods(ifq, ifq->altq_ifp->if_mapsubq,
2775             ifsq_classic_enqueue, ifsq_classic_dequeue, ifsq_classic_request);
2776 }
2777
2778 void
2779 ifq_set_methods(struct ifaltq *ifq, altq_mapsubq_t mapsubq,
2780     ifsq_enqueue_t enqueue, ifsq_dequeue_t dequeue, ifsq_request_t request)
2781 {
2782         int q;
2783
2784         KASSERT(mapsubq != NULL, ("mapsubq is not specified"));
2785         KASSERT(enqueue != NULL, ("enqueue is not specified"));
2786         KASSERT(dequeue != NULL, ("dequeue is not specified"));
2787         KASSERT(request != NULL, ("request is not specified"));
2788
2789         ifq->altq_mapsubq = mapsubq;
2790         for (q = 0; q < ifq->altq_subq_cnt; ++q) {
2791                 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
2792
2793                 ifsq->ifsq_enqueue = enqueue;
2794                 ifsq->ifsq_dequeue = dequeue;
2795                 ifsq->ifsq_request = request;
2796         }
2797 }
2798
2799 static void
2800 ifsq_norm_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2801 {
2802
2803         classq_add(&ifsq->ifsq_norm, m);
2804         ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2805 }
2806
2807 static void
2808 ifsq_prio_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m)
2809 {
2810
2811         classq_add(&ifsq->ifsq_prio, m);
2812         ALTQ_SQ_CNTR_INC(ifsq, m->m_pkthdr.len);
2813         ALTQ_SQ_PRIO_CNTR_INC(ifsq, m->m_pkthdr.len);
2814 }
2815
2816 static struct mbuf *
2817 ifsq_norm_dequeue(struct ifaltq_subque *ifsq)
2818 {
2819         struct mbuf *m;
2820
2821         m = classq_get(&ifsq->ifsq_norm);
2822         if (m != NULL)
2823                 ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2824         return (m);
2825 }
2826
2827 static struct mbuf *
2828 ifsq_prio_dequeue(struct ifaltq_subque *ifsq)
2829 {
2830         struct mbuf *m;
2831
2832         m = classq_get(&ifsq->ifsq_prio);
2833         if (m != NULL) {
2834                 ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
2835                 ALTQ_SQ_PRIO_CNTR_DEC(ifsq, m->m_pkthdr.len);
2836         }
2837         return (m);
2838 }
2839
2840 int
2841 ifsq_classic_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m,
2842     struct altq_pktattr *pa __unused)
2843 {
2844
2845         M_ASSERTPKTHDR(m);
2846 again:
2847         if (ifsq->ifsq_len >= ifsq->ifsq_maxlen ||
2848             ifsq->ifsq_bcnt >= ifsq->ifsq_maxbcnt) {
2849                 struct mbuf *m_drop;
2850
2851                 if (m->m_flags & M_PRIO) {
2852                         m_drop = NULL;
2853                         if (ifsq->ifsq_prio_len < (ifsq->ifsq_maxlen >> 1) &&
2854                             ifsq->ifsq_prio_bcnt < (ifsq->ifsq_maxbcnt >> 1)) {
2855                                 /* Try dropping some from normal queue. */
2856                                 m_drop = ifsq_norm_dequeue(ifsq);
2857                         }
2858                         if (m_drop == NULL)
2859                                 m_drop = ifsq_prio_dequeue(ifsq);
2860                 } else {
2861                         m_drop = ifsq_norm_dequeue(ifsq);
2862                 }
2863                 if (m_drop != NULL) {
2864                         IFNET_STAT_INC(ifsq->ifsq_ifp, oqdrops, 1);
2865                         m_freem(m_drop);
2866                         goto again;
2867                 }
2868                 /*
2869                  * No old packets could be dropped!
2870                  * NOTE: Caller increases oqdrops.
2871                  */
2872                 m_freem(m);
2873                 return (ENOBUFS);
2874         } else {
2875                 if (m->m_flags & M_PRIO)
2876                         ifsq_prio_enqueue(ifsq, m);
2877                 else
2878                         ifsq_norm_enqueue(ifsq, m);
2879                 return (0);
2880         }
2881 }
2882
2883 struct mbuf *
2884 ifsq_classic_dequeue(struct ifaltq_subque *ifsq, int op)
2885 {
2886         struct mbuf *m;
2887
2888         switch (op) {
2889         case ALTDQ_POLL:
2890                 m = classq_head(&ifsq->ifsq_prio);
2891                 if (m == NULL)
2892                         m = classq_head(&ifsq->ifsq_norm);
2893                 break;
2894
2895         case ALTDQ_REMOVE:
2896                 m = ifsq_prio_dequeue(ifsq);
2897                 if (m == NULL)
2898                         m = ifsq_norm_dequeue(ifsq);
2899                 break;
2900
2901         default:
2902                 panic("unsupported ALTQ dequeue op: %d", op);
2903         }
2904         return m;
2905 }
2906
2907 int
2908 ifsq_classic_request(struct ifaltq_subque *ifsq, int req, void *arg)
2909 {
2910         switch (req) {
2911         case ALTRQ_PURGE:
2912                 for (;;) {
2913                         struct mbuf *m;
2914
2915                         m = ifsq_classic_dequeue(ifsq, ALTDQ_REMOVE);
2916                         if (m == NULL)
2917                                 break;
2918                         m_freem(m);
2919                 }
2920                 break;
2921
2922         default:
2923                 panic("unsupported ALTQ request: %d", req);
2924         }
2925         return 0;
2926 }
2927
2928 static void
2929 ifsq_ifstart_try(struct ifaltq_subque *ifsq, int force_sched)
2930 {
2931         struct ifnet *ifp = ifsq_get_ifp(ifsq);
2932         int running = 0, need_sched;
2933
2934         /*
2935          * Try to do direct ifnet.if_start on the subqueue first, if there is
2936          * contention on the subqueue hardware serializer, ifnet.if_start on
2937          * the subqueue will be scheduled on the subqueue owner CPU.
2938          */
2939         if (!ifsq_tryserialize_hw(ifsq)) {
2940                 /*
2941                  * Subqueue hardware serializer contention happened,
2942                  * ifnet.if_start on the subqueue is scheduled on
2943                  * the subqueue owner CPU, and we keep going.
2944                  */
2945                 ifsq_ifstart_schedule(ifsq, 1);
2946                 return;
2947         }
2948
2949         if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
2950                 ifp->if_start(ifp, ifsq);
2951                 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
2952                         running = 1;
2953         }
2954         need_sched = ifsq_ifstart_need_schedule(ifsq, running);
2955
2956         ifsq_deserialize_hw(ifsq);
2957
2958         if (need_sched) {
2959                 /*
2960                  * More data need to be transmitted, ifnet.if_start on the
2961                  * subqueue is scheduled on the subqueue owner CPU, and we
2962                  * keep going.
2963                  * NOTE: ifnet.if_start subqueue interlock is not released.
2964                  */
2965                 ifsq_ifstart_schedule(ifsq, force_sched);
2966         }
2967 }
2968
2969 /*
2970  * Subqeue packets staging mechanism:
2971  *
2972  * The packets enqueued into the subqueue are staged to a certain amount
2973  * before the ifnet.if_start on the subqueue is called.  In this way, the
2974  * driver could avoid writing to hardware registers upon every packet,
2975  * instead, hardware registers could be written when certain amount of
2976  * packets are put onto hardware TX ring.  The measurement on several modern
2977  * NICs (emx(4), igb(4), bnx(4), bge(4), jme(4)) shows that the hardware
2978  * registers writing aggregation could save ~20% CPU time when 18bytes UDP
2979  * datagrams are transmitted at 1.48Mpps.  The performance improvement by
2980  * hardware registers writing aggeregation is also mentioned by Luigi Rizzo's
2981  * netmap paper (http://info.iet.unipi.it/~luigi/netmap/).
2982  *
2983  * Subqueue packets staging is performed for two entry points into drivers'
2984  * transmission function:
2985  * - Direct ifnet.if_start calling on the subqueue, i.e. ifsq_ifstart_try()
2986  * - ifnet.if_start scheduling on the subqueue, i.e. ifsq_ifstart_schedule()
2987  *
2988  * Subqueue packets staging will be stopped upon any of the following
2989  * conditions:
2990  * - If the count of packets enqueued on the current CPU is great than or
2991  *   equal to ifsq_stage_cntmax. (XXX this should be per-interface)
2992  * - If the total length of packets enqueued on the current CPU is great
2993  *   than or equal to the hardware's MTU - max_protohdr.  max_protohdr is
2994  *   cut from the hardware's MTU mainly bacause a full TCP segment's size
2995  *   is usually less than hardware's MTU.
2996  * - ifsq_ifstart_schedule() is not pending on the current CPU and
2997  *   ifnet.if_start subqueue interlock (ifaltq_subq.ifsq_started) is not
2998  *   released.
2999  * - The if_start_rollup(), which is registered as low priority netisr
3000  *   rollup function, is called; probably because no more work is pending
3001  *   for netisr.
3002  *
3003  * NOTE:
3004  * Currently subqueue packet staging is only performed in netisr threads.
3005  */
3006 int
3007 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
3008 {
3009         struct ifaltq *ifq = &ifp->if_snd;
3010         struct ifaltq_subque *ifsq;
3011         int error, start = 0, len, mcast = 0, avoid_start = 0;
3012         struct ifsubq_stage_head *head = NULL;
3013         struct ifsubq_stage *stage = NULL;
3014         struct globaldata *gd = mycpu;
3015         struct thread *td = gd->gd_curthread;
3016
3017         crit_enter_quick(td);
3018
3019         ifsq = ifq_map_subq(ifq, gd->gd_cpuid);
3020         ASSERT_ALTQ_SQ_NOT_SERIALIZED_HW(ifsq);
3021
3022         len = m->m_pkthdr.len;
3023         if (m->m_flags & M_MCAST)
3024                 mcast = 1;
3025
3026         if (td->td_type == TD_TYPE_NETISR) {
3027                 head = &ifsubq_stage_heads[mycpuid];
3028                 stage = ifsq_get_stage(ifsq, mycpuid);
3029
3030                 stage->stg_cnt++;
3031                 stage->stg_len += len;
3032                 if (stage->stg_cnt < ifsq_stage_cntmax &&
3033                     stage->stg_len < (ifp->if_mtu - max_protohdr))
3034                         avoid_start = 1;
3035         }
3036
3037         ALTQ_SQ_LOCK(ifsq);
3038         error = ifsq_enqueue_locked(ifsq, m, pa);
3039         if (error) {
3040                 IFNET_STAT_INC(ifp, oqdrops, 1);
3041                 if (!ifsq_data_ready(ifsq)) {
3042                         ALTQ_SQ_UNLOCK(ifsq);
3043                         crit_exit_quick(td);
3044                         return error;
3045                 }
3046                 avoid_start = 0;
3047         }
3048         if (!ifsq_is_started(ifsq)) {
3049                 if (avoid_start) {
3050                         ALTQ_SQ_UNLOCK(ifsq);
3051
3052                         KKASSERT(!error);
3053                         if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
3054                                 ifsq_stage_insert(head, stage);
3055
3056                         IFNET_STAT_INC(ifp, obytes, len);
3057                         if (mcast)
3058                                 IFNET_STAT_INC(ifp, omcasts, 1);
3059                         crit_exit_quick(td);
3060                         return error;
3061                 }
3062
3063                 /*
3064                  * Hold the subqueue interlock of ifnet.if_start
3065                  */
3066                 ifsq_set_started(ifsq);
3067                 start = 1;
3068         }
3069         ALTQ_SQ_UNLOCK(ifsq);
3070
3071         if (!error) {
3072                 IFNET_STAT_INC(ifp, obytes, len);
3073                 if (mcast)
3074                         IFNET_STAT_INC(ifp, omcasts, 1);
3075         }
3076
3077         if (stage != NULL) {
3078                 if (!start && (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)) {
3079                         KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
3080                         if (!avoid_start) {
3081                                 ifsq_stage_remove(head, stage);
3082                                 ifsq_ifstart_schedule(ifsq, 1);
3083                         }
3084                         crit_exit_quick(td);
3085                         return error;
3086                 }
3087
3088                 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED) {
3089                         ifsq_stage_remove(head, stage);
3090                 } else {
3091                         stage->stg_cnt = 0;
3092                         stage->stg_len = 0;
3093                 }
3094         }
3095
3096         if (!start) {
3097                 crit_exit_quick(td);
3098                 return error;
3099         }
3100
3101         ifsq_ifstart_try(ifsq, 0);
3102
3103         crit_exit_quick(td);
3104         return error;
3105 }
3106
3107 void *
3108 ifa_create(int size)
3109 {
3110         struct ifaddr *ifa;
3111         int i;
3112
3113         KASSERT(size >= sizeof(*ifa), ("ifaddr size too small"));
3114
3115         ifa = kmalloc(size, M_IFADDR, M_INTWAIT | M_ZERO);
3116         ifa->ifa_containers =
3117             kmalloc_cachealign(ncpus * sizeof(struct ifaddr_container),
3118                 M_IFADDR, M_INTWAIT | M_ZERO);
3119
3120         ifa->ifa_ncnt = ncpus;
3121         for (i = 0; i < ncpus; ++i) {
3122                 struct ifaddr_container *ifac = &ifa->ifa_containers[i];
3123
3124                 ifac->ifa_magic = IFA_CONTAINER_MAGIC;
3125                 ifac->ifa = ifa;
3126                 ifac->ifa_refcnt = 1;
3127         }
3128 #ifdef IFADDR_DEBUG
3129         kprintf("alloc ifa %p %d\n", ifa, size);
3130 #endif
3131         return ifa;
3132 }
3133
3134 void
3135 ifac_free(struct ifaddr_container *ifac, int cpu_id)
3136 {
3137         struct ifaddr *ifa = ifac->ifa;
3138
3139         KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
3140         KKASSERT(ifac->ifa_refcnt == 0);
3141         KASSERT(ifac->ifa_listmask == 0,
3142                 ("ifa is still on %#x lists", ifac->ifa_listmask));
3143
3144         ifac->ifa_magic = IFA_CONTAINER_DEAD;
3145
3146 #ifdef IFADDR_DEBUG_VERBOSE
3147         kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
3148 #endif
3149
3150         KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
3151                 ("invalid # of ifac, %d", ifa->ifa_ncnt));
3152         if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
3153 #ifdef IFADDR_DEBUG
3154                 kprintf("free ifa %p\n", ifa);
3155 #endif
3156                 kfree(ifa->ifa_containers, M_IFADDR);
3157                 kfree(ifa, M_IFADDR);
3158         }
3159 }
3160
3161 static void
3162 ifa_iflink_dispatch(netmsg_t nmsg)
3163 {
3164         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3165         struct ifaddr *ifa = msg->ifa;
3166         struct ifnet *ifp = msg->ifp;
3167         int cpu = mycpuid;
3168         struct ifaddr_container *ifac;
3169
3170         crit_enter();
3171
3172         ifac = &ifa->ifa_containers[cpu];
3173         ASSERT_IFAC_VALID(ifac);
3174         KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
3175                 ("ifaddr is on if_addrheads"));
3176
3177         ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
3178         if (msg->tail)
3179                 TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
3180         else
3181                 TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
3182
3183         crit_exit();
3184
3185         netisr_forwardmsg(&nmsg->base, cpu + 1);
3186 }
3187
3188 void
3189 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
3190 {
3191         struct netmsg_ifaddr msg;
3192
3193         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3194                     0, ifa_iflink_dispatch);
3195         msg.ifa = ifa;
3196         msg.ifp = ifp;
3197         msg.tail = tail;
3198
3199         netisr_domsg(&msg.base, 0);
3200 }
3201
3202 static void
3203 ifa_ifunlink_dispatch(netmsg_t nmsg)
3204 {
3205         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3206         struct ifaddr *ifa = msg->ifa;
3207         struct ifnet *ifp = msg->ifp;
3208         int cpu = mycpuid;
3209         struct ifaddr_container *ifac;
3210
3211         crit_enter();
3212
3213         ifac = &ifa->ifa_containers[cpu];
3214         ASSERT_IFAC_VALID(ifac);
3215         KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
3216                 ("ifaddr is not on if_addrhead"));
3217
3218         TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
3219         ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
3220
3221         crit_exit();
3222
3223         netisr_forwardmsg(&nmsg->base, cpu + 1);
3224 }
3225
3226 void
3227 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
3228 {
3229         struct netmsg_ifaddr msg;
3230
3231         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3232                     0, ifa_ifunlink_dispatch);
3233         msg.ifa = ifa;
3234         msg.ifp = ifp;
3235
3236         netisr_domsg(&msg.base, 0);
3237 }
3238
3239 static void
3240 ifa_destroy_dispatch(netmsg_t nmsg)
3241 {
3242         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
3243
3244         IFAFREE(msg->ifa);
3245         netisr_forwardmsg(&nmsg->base, mycpuid + 1);
3246 }
3247
3248 void
3249 ifa_destroy(struct ifaddr *ifa)
3250 {
3251         struct netmsg_ifaddr msg;
3252
3253         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
3254                     0, ifa_destroy_dispatch);
3255         msg.ifa = ifa;
3256
3257         netisr_domsg(&msg.base, 0);
3258 }
3259
3260 static void
3261 if_start_rollup(void)
3262 {
3263         struct ifsubq_stage_head *head = &ifsubq_stage_heads[mycpuid];
3264         struct ifsubq_stage *stage;
3265
3266         crit_enter();
3267
3268         while ((stage = TAILQ_FIRST(&head->stg_head)) != NULL) {
3269                 struct ifaltq_subque *ifsq = stage->stg_subq;
3270                 int is_sched = 0;
3271
3272                 if (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)
3273                         is_sched = 1;
3274                 ifsq_stage_remove(head, stage);
3275
3276                 if (is_sched) {
3277                         ifsq_ifstart_schedule(ifsq, 1);
3278                 } else {
3279                         int start = 0;
3280
3281                         ALTQ_SQ_LOCK(ifsq);
3282                         if (!ifsq_is_started(ifsq)) {
3283                                 /*
3284                                  * Hold the subqueue interlock of
3285                                  * ifnet.if_start
3286                                  */
3287                                 ifsq_set_started(ifsq);
3288                                 start = 1;
3289                         }
3290                         ALTQ_SQ_UNLOCK(ifsq);
3291
3292                         if (start)
3293                                 ifsq_ifstart_try(ifsq, 1);
3294                 }
3295                 KKASSERT((stage->stg_flags &
3296                     (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
3297         }
3298
3299         crit_exit();
3300 }
3301
3302 static void
3303 ifnetinit(void *dummy __unused)
3304 {
3305         int i;
3306
3307         for (i = 0; i < ncpus; ++i)
3308                 TAILQ_INIT(&ifsubq_stage_heads[i].stg_head);
3309         netisr_register_rollup(if_start_rollup, NETISR_ROLLUP_PRIO_IFSTART);
3310 }
3311
3312 void
3313 if_register_com_alloc(u_char type,
3314     if_com_alloc_t *a, if_com_free_t *f)
3315 {
3316
3317         KASSERT(if_com_alloc[type] == NULL,
3318             ("if_register_com_alloc: %d already registered", type));
3319         KASSERT(if_com_free[type] == NULL,
3320             ("if_register_com_alloc: %d free already registered", type));
3321
3322         if_com_alloc[type] = a;
3323         if_com_free[type] = f;
3324 }
3325
3326 void
3327 if_deregister_com_alloc(u_char type)
3328 {
3329
3330         KASSERT(if_com_alloc[type] != NULL,
3331             ("if_deregister_com_alloc: %d not registered", type));
3332         KASSERT(if_com_free[type] != NULL,
3333             ("if_deregister_com_alloc: %d free not registered", type));
3334         if_com_alloc[type] = NULL;
3335         if_com_free[type] = NULL;
3336 }
3337
3338 void
3339 ifq_set_maxlen(struct ifaltq *ifq, int len)
3340 {
3341         ifq->altq_maxlen = len + (ncpus * ifsq_stage_cntmax);
3342 }
3343
3344 int
3345 ifq_mapsubq_default(struct ifaltq *ifq __unused, int cpuid __unused)
3346 {
3347         return ALTQ_SUBQ_INDEX_DEFAULT;
3348 }
3349
3350 int
3351 ifq_mapsubq_modulo(struct ifaltq *ifq, int cpuid)
3352 {
3353
3354         return (cpuid % ifq->altq_subq_mappriv);
3355 }
3356
3357 static void
3358 ifsq_watchdog(void *arg)
3359 {
3360         struct ifsubq_watchdog *wd = arg;
3361         struct ifnet *ifp;
3362
3363         if (__predict_true(wd->wd_timer == 0 || --wd->wd_timer))
3364                 goto done;
3365
3366         ifp = ifsq_get_ifp(wd->wd_subq);
3367         if (ifnet_tryserialize_all(ifp)) {
3368                 wd->wd_watchdog(wd->wd_subq);
3369                 ifnet_deserialize_all(ifp);
3370         } else {
3371                 /* try again next timeout */
3372                 wd->wd_timer = 1;
3373         }
3374 done:
3375         ifsq_watchdog_reset(wd);
3376 }
3377
3378 static void
3379 ifsq_watchdog_reset(struct ifsubq_watchdog *wd)
3380 {
3381         callout_reset_bycpu(&wd->wd_callout, hz, ifsq_watchdog, wd,
3382             ifsq_get_cpuid(wd->wd_subq));
3383 }
3384
3385 void
3386 ifsq_watchdog_init(struct ifsubq_watchdog *wd, struct ifaltq_subque *ifsq,
3387     ifsq_watchdog_t watchdog)
3388 {
3389         callout_init_mp(&wd->wd_callout);
3390         wd->wd_timer = 0;
3391         wd->wd_subq = ifsq;
3392         wd->wd_watchdog = watchdog;
3393 }
3394
3395 void
3396 ifsq_watchdog_start(struct ifsubq_watchdog *wd)
3397 {
3398         wd->wd_timer = 0;
3399         ifsq_watchdog_reset(wd);
3400 }
3401
3402 void
3403 ifsq_watchdog_stop(struct ifsubq_watchdog *wd)
3404 {
3405         wd->wd_timer = 0;
3406         callout_stop(&wd->wd_callout);
3407 }
3408
3409 void
3410 ifnet_lock(void)
3411 {
3412         KASSERT(curthread->td_type != TD_TYPE_NETISR,
3413             ("try holding ifnet lock in netisr"));
3414         mtx_lock(&ifnet_mtx);
3415 }
3416
3417 void
3418 ifnet_unlock(void)
3419 {
3420         KASSERT(curthread->td_type != TD_TYPE_NETISR,
3421             ("try holding ifnet lock in netisr"));
3422         mtx_unlock(&ifnet_mtx);
3423 }
3424
3425 static struct ifnet_array *
3426 ifnet_array_alloc(int count)
3427 {
3428         struct ifnet_array *arr;
3429
3430         arr = kmalloc(__offsetof(struct ifnet_array, ifnet_arr[count]),
3431             M_IFNET, M_WAITOK);
3432         arr->ifnet_count = count;
3433
3434         return arr;
3435 }
3436
3437 static void
3438 ifnet_array_free(struct ifnet_array *arr)
3439 {
3440         if (arr == &ifnet_array0)
3441                 return;
3442         kfree(arr, M_IFNET);
3443 }
3444
3445 static struct ifnet_array *
3446 ifnet_array_add(struct ifnet *ifp, const struct ifnet_array *old_arr)
3447 {
3448         struct ifnet_array *arr;
3449         int count, i;
3450
3451         KASSERT(old_arr->ifnet_count >= 0,
3452             ("invalid ifnet array count %d", old_arr->ifnet_count));
3453         count = old_arr->ifnet_count + 1;
3454         arr = ifnet_array_alloc(count);
3455
3456         /*
3457          * Save the old ifnet array and append this ifp to the end of
3458          * the new ifnet array.
3459          */
3460         for (i = 0; i < old_arr->ifnet_count; ++i) {
3461                 KASSERT(old_arr->ifnet_arr[i] != ifp,
3462                     ("%s is already in ifnet array", ifp->if_xname));
3463                 arr->ifnet_arr[i] = old_arr->ifnet_arr[i];
3464         }
3465         KASSERT(i == count - 1,
3466             ("add %s, ifnet array index mismatch, should be %d, but got %d",
3467              ifp->if_xname, count - 1, i));
3468         arr->ifnet_arr[i] = ifp;
3469
3470         return arr;
3471 }
3472
3473 static struct ifnet_array *
3474 ifnet_array_del(struct ifnet *ifp, const struct ifnet_array *old_arr)
3475 {
3476         struct ifnet_array *arr;
3477         int count, i, idx, found = 0;
3478
3479         KASSERT(old_arr->ifnet_count > 0,
3480             ("invalid ifnet array count %d", old_arr->ifnet_count));
3481         count = old_arr->ifnet_count - 1;
3482         arr = ifnet_array_alloc(count);
3483
3484         /*
3485          * Save the old ifnet array, but skip this ifp.
3486          */
3487         idx = 0;
3488         for (i = 0; i < old_arr->ifnet_count; ++i) {
3489                 if (old_arr->ifnet_arr[i] == ifp) {
3490                         KASSERT(!found,
3491                             ("dup %s is in ifnet array", ifp->if_xname));
3492                         found = 1;
3493                         continue;
3494                 }
3495                 KASSERT(idx < count,
3496                     ("invalid ifnet array index %d, count %d", idx, count));
3497                 arr->ifnet_arr[idx] = old_arr->ifnet_arr[i];
3498                 ++idx;
3499         }
3500         KASSERT(found, ("%s is not in ifnet array", ifp->if_xname));
3501         KASSERT(idx == count,
3502             ("del %s, ifnet array count mismatch, should be %d, but got %d ",
3503              ifp->if_xname, count, idx));
3504
3505         return arr;
3506 }
3507
3508 const struct ifnet_array *
3509 ifnet_array_get(void)
3510 {
3511         const struct ifnet_array *ret;
3512
3513         KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3514         ret = ifnet_array;
3515         /* Make sure 'ret' is really used. */
3516         cpu_ccfence();
3517         return (ret);
3518 }
3519
3520 int
3521 ifnet_array_isempty(void)
3522 {
3523         KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
3524         if (ifnet_array->ifnet_count == 0)
3525                 return 1;
3526         else
3527                 return 0;
3528 }
3529
3530 void
3531 ifa_marker_init(struct ifaddr_marker *mark, struct ifnet *ifp)
3532 {
3533         struct ifaddr *ifa;
3534
3535         memset(mark, 0, sizeof(*mark));
3536         ifa = &mark->ifa;
3537
3538         mark->ifac.ifa = ifa;
3539
3540         ifa->ifa_addr = &mark->addr;
3541         ifa->ifa_dstaddr = &mark->dstaddr;
3542         ifa->ifa_netmask = &mark->netmask;
3543         ifa->ifa_ifp = ifp;
3544 }
3545
3546 static int
3547 if_ringcnt_fixup(int ring_cnt, int ring_cntmax)
3548 {
3549
3550         KASSERT(ring_cntmax > 0, ("invalid ring count max %d", ring_cntmax));
3551
3552         if (ring_cnt <= 0 || ring_cnt > ring_cntmax)
3553                 ring_cnt = ring_cntmax;
3554         if (ring_cnt > netisr_ncpus)
3555                 ring_cnt = netisr_ncpus;
3556         return (ring_cnt);
3557 }
3558
3559 static void
3560 if_ringmap_set_grid(device_t dev, struct if_ringmap *rm, int grid)
3561 {
3562         int i, offset;
3563
3564         KASSERT(grid > 0, ("invalid if_ringmap grid %d", grid));
3565         KASSERT(grid >= rm->rm_cnt, ("invalid if_ringmap grid %d, count %d",
3566             grid, rm->rm_cnt));
3567         rm->rm_grid = grid;
3568
3569         offset = (rm->rm_grid * device_get_unit(dev)) % netisr_ncpus;
3570         for (i = 0; i < rm->rm_cnt; ++i) {
3571                 rm->rm_cpumap[i] = offset + i;
3572                 KASSERT(rm->rm_cpumap[i] < netisr_ncpus,
3573                     ("invalid cpumap[%d] = %d, offset %d", i,
3574                      rm->rm_cpumap[i], offset));
3575         }
3576 }
3577
3578 static struct if_ringmap *
3579 if_ringmap_alloc_flags(device_t dev, int ring_cnt, int ring_cntmax,
3580     uint32_t flags)
3581 {
3582         struct if_ringmap *rm;
3583         int i, grid = 0, prev_grid;
3584
3585         ring_cnt = if_ringcnt_fixup(ring_cnt, ring_cntmax);
3586         rm = kmalloc(__offsetof(struct if_ringmap, rm_cpumap[ring_cnt]),
3587             M_DEVBUF, M_WAITOK | M_ZERO);
3588
3589         rm->rm_cnt = ring_cnt;
3590         if (flags & RINGMAP_FLAG_POWEROF2)
3591                 rm->rm_cnt = 1 << (fls(rm->rm_cnt) - 1);
3592
3593         prev_grid = netisr_ncpus;
3594         for (i = 0; i < netisr_ncpus; ++i) {
3595                 if (netisr_ncpus % (i + 1) != 0)
3596                         continue;
3597
3598                 grid = netisr_ncpus / (i + 1);
3599                 if (rm->rm_cnt > grid) {
3600                         grid = prev_grid;
3601                         break;
3602                 }
3603
3604                 if (rm->rm_cnt > netisr_ncpus / (i + 2))
3605                         break;
3606                 prev_grid = grid;
3607         }
3608         if_ringmap_set_grid(dev, rm, grid);
3609
3610         return (rm);
3611 }
3612
3613 struct if_ringmap *
3614 if_ringmap_alloc(device_t dev, int ring_cnt, int ring_cntmax)
3615 {
3616
3617         return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3618             RINGMAP_FLAG_NONE));
3619 }
3620
3621 struct if_ringmap *
3622 if_ringmap_alloc2(device_t dev, int ring_cnt, int ring_cntmax)
3623 {
3624
3625         return (if_ringmap_alloc_flags(dev, ring_cnt, ring_cntmax,
3626             RINGMAP_FLAG_POWEROF2));
3627 }
3628
3629 void
3630 if_ringmap_free(struct if_ringmap *rm)
3631 {
3632
3633         kfree(rm, M_DEVBUF);
3634 }
3635
3636 /*
3637  * Align the two ringmaps.
3638  *
3639  * e.g. 8 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3640  *
3641  * Before:
3642  *
3643  * CPU      0  1  2  3   4  5  6  7
3644  * NIC_RX               n0 n1 n2 n3
3645  * NIC_TX        N0 N1
3646  *
3647  * After:
3648  *
3649  * CPU      0  1  2  3   4  5  6  7
3650  * NIC_RX               n0 n1 n2 n3
3651  * NIC_TX               N0 N1
3652  */
3653 void
3654 if_ringmap_align(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3655 {
3656
3657         if (rm0->rm_grid > rm1->rm_grid)
3658                 if_ringmap_set_grid(dev, rm1, rm0->rm_grid);
3659         else if (rm0->rm_grid < rm1->rm_grid)
3660                 if_ringmap_set_grid(dev, rm0, rm1->rm_grid);
3661 }
3662
3663 void
3664 if_ringmap_match(device_t dev, struct if_ringmap *rm0, struct if_ringmap *rm1)
3665 {
3666         int subset_grid, cnt, divisor, mod, offset, i;
3667         struct if_ringmap *subset_rm, *rm;
3668         int old_rm0_grid, old_rm1_grid;
3669
3670         if (rm0->rm_grid == rm1->rm_grid)
3671                 return;
3672
3673         /* Save grid for later use */
3674         old_rm0_grid = rm0->rm_grid;
3675         old_rm1_grid = rm1->rm_grid;
3676
3677         if_ringmap_align(dev, rm0, rm1);
3678
3679         /*
3680          * Re-shuffle rings to get more even distribution.
3681          *
3682          * e.g. 12 netisrs, rm0 contains 4 rings, rm1 contains 2 rings.
3683          *
3684          * CPU       0  1  2  3   4  5  6  7   8  9 10 11
3685          *
3686          * NIC_RX   a0 a1 a2 a3  b0 b1 b2 b3  c0 c1 c2 c3
3687          * NIC_TX   A0 A1        B0 B1        C0 C1
3688          *
3689          * NIC_RX   d0 d1 d2 d3  e0 e1 e2 e3  f0 f1 f2 f3
3690          * NIC_TX         D0 D1        E0 E1        F0 F1
3691          */
3692
3693         if (rm0->rm_cnt >= (2 * old_rm1_grid)) {
3694                 cnt = rm0->rm_cnt;
3695                 subset_grid = old_rm1_grid;
3696                 subset_rm = rm1;
3697                 rm = rm0;
3698         } else if (rm1->rm_cnt > (2 * old_rm0_grid)) {
3699                 cnt = rm1->rm_cnt;
3700                 subset_grid = old_rm0_grid;
3701                 subset_rm = rm0;
3702                 rm = rm1;
3703         } else {
3704                 /* No space to shuffle. */
3705                 return;
3706         }
3707
3708         mod = cnt / subset_grid;
3709         KKASSERT(mod >= 2);
3710         divisor = netisr_ncpus / rm->rm_grid;
3711         offset = ((device_get_unit(dev) / divisor) % mod) * subset_grid;
3712
3713         for (i = 0; i < subset_rm->rm_cnt; ++i) {
3714                 subset_rm->rm_cpumap[i] += offset;
3715                 KASSERT(subset_rm->rm_cpumap[i] < netisr_ncpus,
3716                     ("match: invalid cpumap[%d] = %d, offset %d",
3717                      i, subset_rm->rm_cpumap[i], offset));
3718         }
3719 #ifdef INVARIANTS
3720         for (i = 0; i < subset_rm->rm_cnt; ++i) {
3721                 int j;
3722
3723                 for (j = 0; j < rm->rm_cnt; ++j) {
3724                         if (rm->rm_cpumap[j] == subset_rm->rm_cpumap[i])
3725                                 break;
3726                 }
3727                 KASSERT(j < rm->rm_cnt,
3728                     ("subset cpumap[%d] = %d not found in superset",
3729                      i, subset_rm->rm_cpumap[i]));
3730         }
3731 #endif
3732 }
3733
3734 int
3735 if_ringmap_count(const struct if_ringmap *rm)
3736 {
3737
3738         return (rm->rm_cnt);
3739 }
3740
3741 int
3742 if_ringmap_cpumap(const struct if_ringmap *rm, int ring)
3743 {
3744
3745         KASSERT(ring >= 0 && ring < rm->rm_cnt, ("invalid ring %d", ring));
3746         return (rm->rm_cpumap[ring]);
3747 }
3748
3749 void
3750 if_ringmap_rdrtable(const struct if_ringmap *rm, int table[], int table_nent)
3751 {
3752         int i, grid_idx, grid_cnt, patch_off, patch_cnt, ncopy;
3753
3754         KASSERT(table_nent > 0 && (table_nent & NETISR_CPUMASK) == 0,
3755             ("invalid redirect table entries %d", table_nent));
3756
3757         grid_idx = 0;
3758         for (i = 0; i < NETISR_CPUMAX; ++i) {
3759                 table[i] = grid_idx++ % rm->rm_cnt;
3760
3761                 if (grid_idx == rm->rm_grid)
3762                         grid_idx = 0;
3763         }
3764
3765         /*
3766          * Make the ring distributed more evenly for the remainder
3767          * of each grid.
3768          *
3769          * e.g. 12 netisrs, rm contains 8 rings.
3770          *
3771          * Redirect table before:
3772          *
3773          *  0  1  2  3  4  5  6  7  0  1  2  3  0  1  2  3
3774          *  4  5  6  7  0  1  2  3  0  1  2  3  4  5  6  7
3775          *  0  1  2  3  0  1  2  3  4  5  6  7  0  1  2  3
3776          *  ....
3777          *
3778          * Redirect table after being patched (pX, patched entries):
3779          *
3780          *  0  1  2  3  4  5  6  7 p0 p1 p2 p3  0  1  2  3
3781          *  4  5  6  7 p4 p5 p6 p7  0  1  2  3  4  5  6  7
3782          * p0 p1 p2 p3  0  1  2  3  4  5  6  7 p4 p5 p6 p7
3783          *  ....
3784          */
3785         patch_cnt = rm->rm_grid % rm->rm_cnt;
3786         if (patch_cnt == 0)
3787                 goto done;
3788         patch_off = rm->rm_grid - (rm->rm_grid % rm->rm_cnt);
3789
3790         grid_cnt = roundup(NETISR_CPUMAX, rm->rm_grid) / rm->rm_grid;
3791         grid_idx = 0;
3792         for (i = 0; i < grid_cnt; ++i) {
3793                 int j;
3794
3795                 for (j = 0; j < patch_cnt; ++j) {
3796                         int fix_idx;
3797
3798                         fix_idx = (i * rm->rm_grid) + patch_off + j;
3799                         if (fix_idx >= NETISR_CPUMAX)
3800                                 goto done;
3801                         table[fix_idx] = grid_idx++ % rm->rm_cnt;
3802                 }
3803         }
3804 done:
3805         /*
3806          * If the device supports larger redirect table, duplicate
3807          * the first NETISR_CPUMAX entries to the rest of the table,
3808          * so that it matches upper layer's expectation:
3809          * (hash & NETISR_CPUMASK) % netisr_ncpus
3810          */
3811         ncopy = table_nent / NETISR_CPUMAX;
3812         for (i = 1; i < ncopy; ++i) {
3813                 memcpy(&table[i * NETISR_CPUMAX], table,
3814                     NETISR_CPUMAX * sizeof(table[0]));
3815         }
3816         if (if_ringmap_dumprdr) {
3817                 for (i = 0; i < table_nent; ++i) {
3818                         if (i != 0 && i % 16 == 0)
3819                                 kprintf("\n");
3820                         kprintf("%03d ", table[i]);
3821                 }
3822                 kprintf("\n");
3823         }
3824 }
3825
3826 int
3827 if_ringmap_cpumap_sysctl(SYSCTL_HANDLER_ARGS)
3828 {
3829         struct if_ringmap *rm = arg1;
3830         int i, error = 0;
3831
3832         for (i = 0; i < rm->rm_cnt; ++i) {
3833                 int cpu = rm->rm_cpumap[i];
3834
3835                 error = SYSCTL_OUT(req, &cpu, sizeof(cpu));
3836                 if (error)
3837                         break;
3838         }
3839         return (error);
3840 }