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