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