ee4f4b09c7b06ea1b96d09336118381c684749a1
[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         ifq = &ifp->if_snd;
570         ifq->altq_type = 0;
571         ifq->altq_disc = NULL;
572         ifq->altq_flags &= ALTQF_CANTCHANGE;
573         ifq->altq_tbr = NULL;
574         ifq->altq_ifp = ifp;
575
576         if (ifq->altq_subq_cnt <= 0)
577                 ifq->altq_subq_cnt = 1;
578         ifq->altq_subq = kmalloc_cachealign(
579             ifq->altq_subq_cnt * sizeof(struct ifaltq_subque),
580             M_DEVBUF, M_WAITOK | M_ZERO);
581
582         if (ifq->altq_maxlen == 0) {
583                 if_printf(ifp, "driver didn't set ifq_maxlen\n");
584                 ifq_set_maxlen(ifq, ifqmaxlen);
585         }
586
587         for (q = 0; q < ifq->altq_subq_cnt; ++q) {
588                 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
589
590                 ALTQ_SQ_LOCK_INIT(ifsq);
591                 ifsq->ifsq_index = q;
592
593                 ifsq->ifsq_altq = ifq;
594                 ifsq->ifsq_ifp = ifp;
595
596                 ifsq->ifq_maxlen = ifq->altq_maxlen;
597                 ifsq->ifsq_prepended = NULL;
598                 ifsq->ifsq_started = 0;
599                 ifsq->ifsq_hw_oactive = 0;
600                 ifsq_set_cpuid(ifsq, 0);
601
602                 ifsq->ifsq_stage =
603                     kmalloc_cachealign(ncpus * sizeof(struct ifsubq_stage),
604                     M_DEVBUF, M_WAITOK | M_ZERO);
605                 for (i = 0; i < ncpus; ++i)
606                         ifsq->ifsq_stage[i].stg_subq = ifsq;
607
608                 ifsq->ifsq_ifstart_nmsg =
609                     kmalloc(ncpus * sizeof(struct netmsg_base),
610                     M_LWKTMSG, M_WAITOK);
611                 for (i = 0; i < ncpus; ++i) {
612                         netmsg_init(&ifsq->ifsq_ifstart_nmsg[i], NULL,
613                             &netisr_adone_rport, 0, ifsq_ifstart_dispatch);
614                         ifsq->ifsq_ifstart_nmsg[i].lmsg.u.ms_resultp = ifsq;
615                 }
616         }
617         ifq_set_classic(ifq);
618
619         if (!SLIST_EMPTY(&domains))
620                 if_attachdomain1(ifp);
621
622         /* Announce the interface. */
623         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
624
625         mtx_unlock(&ifp->if_ioctl_mtx);
626 }
627
628 static void
629 if_attachdomain(void *dummy)
630 {
631         struct ifnet *ifp;
632
633         crit_enter();
634         TAILQ_FOREACH(ifp, &ifnet, if_list)
635                 if_attachdomain1(ifp);
636         crit_exit();
637 }
638 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_FIRST,
639         if_attachdomain, NULL);
640
641 static void
642 if_attachdomain1(struct ifnet *ifp)
643 {
644         struct domain *dp;
645
646         crit_enter();
647
648         /* address family dependent data region */
649         bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
650         SLIST_FOREACH(dp, &domains, dom_next)
651                 if (dp->dom_ifattach)
652                         ifp->if_afdata[dp->dom_family] =
653                                 (*dp->dom_ifattach)(ifp);
654         crit_exit();
655 }
656
657 /*
658  * Purge all addresses whose type is _not_ AF_LINK
659  */
660 void
661 if_purgeaddrs_nolink(struct ifnet *ifp)
662 {
663         struct ifaddr_container *ifac, *next;
664
665         TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
666                               ifa_link, next) {
667                 struct ifaddr *ifa = ifac->ifa;
668
669                 /* Leave link ifaddr as it is */
670                 if (ifa->ifa_addr->sa_family == AF_LINK)
671                         continue;
672 #ifdef INET
673                 /* XXX: Ugly!! ad hoc just for INET */
674                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
675                         struct ifaliasreq ifr;
676 #ifdef IFADDR_DEBUG_VERBOSE
677                         int i;
678
679                         kprintf("purge in4 addr %p: ", ifa);
680                         for (i = 0; i < ncpus; ++i)
681                                 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
682                         kprintf("\n");
683 #endif
684
685                         bzero(&ifr, sizeof ifr);
686                         ifr.ifra_addr = *ifa->ifa_addr;
687                         if (ifa->ifa_dstaddr)
688                                 ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
689                         if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
690                                        NULL) == 0)
691                                 continue;
692                 }
693 #endif /* INET */
694 #ifdef INET6
695                 if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
696 #ifdef IFADDR_DEBUG_VERBOSE
697                         int i;
698
699                         kprintf("purge in6 addr %p: ", ifa);
700                         for (i = 0; i < ncpus; ++i)
701                                 kprintf("%d ", ifa->ifa_containers[i].ifa_refcnt);
702                         kprintf("\n");
703 #endif
704
705                         in6_purgeaddr(ifa);
706                         /* ifp_addrhead is already updated */
707                         continue;
708                 }
709 #endif /* INET6 */
710                 ifa_ifunlink(ifa, ifp);
711                 ifa_destroy(ifa);
712         }
713 }
714
715 static void
716 ifq_stage_detach_handler(netmsg_t nmsg)
717 {
718         struct ifaltq *ifq = nmsg->lmsg.u.ms_resultp;
719         int q;
720
721         for (q = 0; q < ifq->altq_subq_cnt; ++q) {
722                 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
723                 struct ifsubq_stage *stage = ifsq_get_stage(ifsq, mycpuid);
724
725                 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED)
726                         ifsq_stage_remove(&ifsubq_stage_heads[mycpuid], stage);
727         }
728         lwkt_replymsg(&nmsg->lmsg, 0);
729 }
730
731 static void
732 ifq_stage_detach(struct ifaltq *ifq)
733 {
734         struct netmsg_base base;
735         int cpu;
736
737         netmsg_init(&base, NULL, &curthread->td_msgport, 0,
738             ifq_stage_detach_handler);
739         base.lmsg.u.ms_resultp = ifq;
740
741         for (cpu = 0; cpu < ncpus; ++cpu)
742                 lwkt_domsg(netisr_portfn(cpu), &base.lmsg, 0);
743 }
744
745 /*
746  * Detach an interface, removing it from the
747  * list of "active" interfaces.
748  */
749 void
750 if_detach(struct ifnet *ifp)
751 {
752         struct radix_node_head  *rnh;
753         int i, q;
754         int cpu, origcpu;
755         struct domain *dp;
756
757         EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
758
759         /*
760          * Remove routes and flush queues.
761          */
762         crit_enter();
763 #ifdef IFPOLL_ENABLE
764         if (ifp->if_flags & IFF_NPOLLING)
765                 ifpoll_deregister(ifp);
766 #endif
767         if_down(ifp);
768
769 #ifdef ALTQ
770         if (ifq_is_enabled(&ifp->if_snd))
771                 altq_disable(&ifp->if_snd);
772         if (ifq_is_attached(&ifp->if_snd))
773                 altq_detach(&ifp->if_snd);
774 #endif
775
776         /*
777          * Clean up all addresses.
778          */
779         ifp->if_lladdr = NULL;
780
781         if_purgeaddrs_nolink(ifp);
782         if (!TAILQ_EMPTY(&ifp->if_addrheads[mycpuid])) {
783                 struct ifaddr *ifa;
784
785                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
786                 KASSERT(ifa->ifa_addr->sa_family == AF_LINK,
787                         ("non-link ifaddr is left on if_addrheads"));
788
789                 ifa_ifunlink(ifa, ifp);
790                 ifa_destroy(ifa);
791                 KASSERT(TAILQ_EMPTY(&ifp->if_addrheads[mycpuid]),
792                         ("there are still ifaddrs left on if_addrheads"));
793         }
794
795 #ifdef INET
796         /*
797          * Remove all IPv4 kernel structures related to ifp.
798          */
799         in_ifdetach(ifp);
800 #endif
801
802 #ifdef INET6
803         /*
804          * Remove all IPv6 kernel structs related to ifp.  This should be done
805          * before removing routing entries below, since IPv6 interface direct
806          * routes are expected to be removed by the IPv6-specific kernel API.
807          * Otherwise, the kernel will detect some inconsistency and bark it.
808          */
809         in6_ifdetach(ifp);
810 #endif
811
812         /*
813          * Delete all remaining routes using this interface
814          * Unfortuneatly the only way to do this is to slog through
815          * the entire routing table looking for routes which point
816          * to this interface...oh well...
817          */
818         origcpu = mycpuid;
819         for (cpu = 0; cpu < ncpus; cpu++) {
820                 lwkt_migratecpu(cpu);
821                 for (i = 1; i <= AF_MAX; i++) {
822                         if ((rnh = rt_tables[cpu][i]) == NULL)
823                                 continue;
824                         rnh->rnh_walktree(rnh, if_rtdel, ifp);
825                 }
826         }
827         lwkt_migratecpu(origcpu);
828
829         /* Announce that the interface is gone. */
830         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
831         devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
832
833         SLIST_FOREACH(dp, &domains, dom_next)
834                 if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
835                         (*dp->dom_ifdetach)(ifp,
836                                 ifp->if_afdata[dp->dom_family]);
837
838         /*
839          * Remove interface from ifindex2ifp[] and maybe decrement if_index.
840          */
841         ifindex2ifnet[ifp->if_index] = NULL;
842         while (if_index > 0 && ifindex2ifnet[if_index] == NULL)
843                 if_index--;
844
845         TAILQ_REMOVE(&ifnet, ifp, if_link);
846         kfree(ifp->if_addrheads, M_IFADDR);
847
848         lwkt_synchronize_ipiqs("if_detach");
849         ifq_stage_detach(&ifp->if_snd);
850
851         for (q = 0; q < ifp->if_snd.altq_subq_cnt; ++q) {
852                 struct ifaltq_subque *ifsq = &ifp->if_snd.altq_subq[q];
853
854                 kfree(ifsq->ifsq_ifstart_nmsg, M_LWKTMSG);
855                 kfree(ifsq->ifsq_stage, M_DEVBUF);
856         }
857         kfree(ifp->if_snd.altq_subq, M_DEVBUF);
858
859         crit_exit();
860 }
861
862 /*
863  * Create interface group without members
864  */
865 struct ifg_group *
866 if_creategroup(const char *groupname)
867 {
868         struct ifg_group        *ifg = NULL;
869
870         if ((ifg = (struct ifg_group *)kmalloc(sizeof(struct ifg_group),
871             M_TEMP, M_NOWAIT)) == NULL)
872                 return (NULL);
873
874         strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
875         ifg->ifg_refcnt = 0;
876         ifg->ifg_carp_demoted = 0;
877         TAILQ_INIT(&ifg->ifg_members);
878 #if NPF > 0
879         pfi_attach_ifgroup(ifg);
880 #endif
881         TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
882
883         return (ifg);
884 }
885
886 /*
887  * Add a group to an interface
888  */
889 int
890 if_addgroup(struct ifnet *ifp, const char *groupname)
891 {
892         struct ifg_list         *ifgl;
893         struct ifg_group        *ifg = NULL;
894         struct ifg_member       *ifgm;
895
896         if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
897             groupname[strlen(groupname) - 1] <= '9')
898                 return (EINVAL);
899
900         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
901                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
902                         return (EEXIST);
903
904         if ((ifgl = kmalloc(sizeof(*ifgl), M_TEMP, M_NOWAIT)) == NULL)
905                 return (ENOMEM);
906
907         if ((ifgm = kmalloc(sizeof(*ifgm), M_TEMP, M_NOWAIT)) == NULL) {
908                 kfree(ifgl, M_TEMP);
909                 return (ENOMEM);
910         }
911
912         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
913                 if (!strcmp(ifg->ifg_group, groupname))
914                         break;
915
916         if (ifg == NULL && (ifg = if_creategroup(groupname)) == NULL) {
917                 kfree(ifgl, M_TEMP);
918                 kfree(ifgm, M_TEMP);
919                 return (ENOMEM);
920         }
921
922         ifg->ifg_refcnt++;
923         ifgl->ifgl_group = ifg;
924         ifgm->ifgm_ifp = ifp;
925
926         TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
927         TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
928
929 #if NPF > 0
930         pfi_group_change(groupname);
931 #endif
932
933         return (0);
934 }
935
936 /*
937  * Remove a group from an interface
938  */
939 int
940 if_delgroup(struct ifnet *ifp, const char *groupname)
941 {
942         struct ifg_list         *ifgl;
943         struct ifg_member       *ifgm;
944
945         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
946                 if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
947                         break;
948         if (ifgl == NULL)
949                 return (ENOENT);
950
951         TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
952
953         TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
954                 if (ifgm->ifgm_ifp == ifp)
955                         break;
956
957         if (ifgm != NULL) {
958                 TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
959                 kfree(ifgm, M_TEMP);
960         }
961
962         if (--ifgl->ifgl_group->ifg_refcnt == 0) {
963                 TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
964 #if NPF > 0
965                 pfi_detach_ifgroup(ifgl->ifgl_group);
966 #endif
967                 kfree(ifgl->ifgl_group, M_TEMP);
968         }
969
970         kfree(ifgl, M_TEMP);
971
972 #if NPF > 0
973         pfi_group_change(groupname);
974 #endif
975
976         return (0);
977 }
978
979 /*
980  * Stores all groups from an interface in memory pointed
981  * to by data
982  */
983 int
984 if_getgroup(caddr_t data, struct ifnet *ifp)
985 {
986         int                      len, error;
987         struct ifg_list         *ifgl;
988         struct ifg_req           ifgrq, *ifgp;
989         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
990
991         if (ifgr->ifgr_len == 0) {
992                 TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
993                         ifgr->ifgr_len += sizeof(struct ifg_req);
994                 return (0);
995         }
996
997         len = ifgr->ifgr_len;
998         ifgp = ifgr->ifgr_groups;
999         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1000                 if (len < sizeof(ifgrq))
1001                         return (EINVAL);
1002                 bzero(&ifgrq, sizeof ifgrq);
1003                 strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1004                     sizeof(ifgrq.ifgrq_group));
1005                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1006                     sizeof(struct ifg_req))))
1007                         return (error);
1008                 len -= sizeof(ifgrq);
1009                 ifgp++;
1010         }
1011
1012         return (0);
1013 }
1014
1015 /*
1016  * Stores all members of a group in memory pointed to by data
1017  */
1018 int
1019 if_getgroupmembers(caddr_t data)
1020 {
1021         struct ifgroupreq       *ifgr = (struct ifgroupreq *)data;
1022         struct ifg_group        *ifg;
1023         struct ifg_member       *ifgm;
1024         struct ifg_req           ifgrq, *ifgp;
1025         int                      len, error;
1026
1027         TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
1028                 if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1029                         break;
1030         if (ifg == NULL)
1031                 return (ENOENT);
1032
1033         if (ifgr->ifgr_len == 0) {
1034                 TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1035                         ifgr->ifgr_len += sizeof(ifgrq);
1036                 return (0);
1037         }
1038
1039         len = ifgr->ifgr_len;
1040         ifgp = ifgr->ifgr_groups;
1041         TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1042                 if (len < sizeof(ifgrq))
1043                         return (EINVAL);
1044                 bzero(&ifgrq, sizeof ifgrq);
1045                 strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1046                     sizeof(ifgrq.ifgrq_member));
1047                 if ((error = copyout((caddr_t)&ifgrq, (caddr_t)ifgp,
1048                     sizeof(struct ifg_req))))
1049                         return (error);
1050                 len -= sizeof(ifgrq);
1051                 ifgp++;
1052         }
1053
1054         return (0);
1055 }
1056
1057 /*
1058  * Delete Routes for a Network Interface
1059  *
1060  * Called for each routing entry via the rnh->rnh_walktree() call above
1061  * to delete all route entries referencing a detaching network interface.
1062  *
1063  * Arguments:
1064  *      rn      pointer to node in the routing table
1065  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
1066  *
1067  * Returns:
1068  *      0       successful
1069  *      errno   failed - reason indicated
1070  *
1071  */
1072 static int
1073 if_rtdel(struct radix_node *rn, void *arg)
1074 {
1075         struct rtentry  *rt = (struct rtentry *)rn;
1076         struct ifnet    *ifp = arg;
1077         int             err;
1078
1079         if (rt->rt_ifp == ifp) {
1080
1081                 /*
1082                  * Protect (sorta) against walktree recursion problems
1083                  * with cloned routes
1084                  */
1085                 if (!(rt->rt_flags & RTF_UP))
1086                         return (0);
1087
1088                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1089                                 rt_mask(rt), rt->rt_flags,
1090                                 NULL);
1091                 if (err) {
1092                         log(LOG_WARNING, "if_rtdel: error %d\n", err);
1093                 }
1094         }
1095
1096         return (0);
1097 }
1098
1099 /*
1100  * Locate an interface based on a complete address.
1101  */
1102 struct ifaddr *
1103 ifa_ifwithaddr(struct sockaddr *addr)
1104 {
1105         struct ifnet *ifp;
1106
1107         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1108                 struct ifaddr_container *ifac;
1109
1110                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1111                         struct ifaddr *ifa = ifac->ifa;
1112
1113                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1114                                 continue;
1115                         if (sa_equal(addr, ifa->ifa_addr))
1116                                 return (ifa);
1117                         if ((ifp->if_flags & IFF_BROADCAST) &&
1118                             ifa->ifa_broadaddr &&
1119                             /* IPv6 doesn't have broadcast */
1120                             ifa->ifa_broadaddr->sa_len != 0 &&
1121                             sa_equal(ifa->ifa_broadaddr, addr))
1122                                 return (ifa);
1123                 }
1124         }
1125         return (NULL);
1126 }
1127 /*
1128  * Locate the point to point interface with a given destination address.
1129  */
1130 struct ifaddr *
1131 ifa_ifwithdstaddr(struct sockaddr *addr)
1132 {
1133         struct ifnet *ifp;
1134
1135         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1136                 struct ifaddr_container *ifac;
1137
1138                 if (!(ifp->if_flags & IFF_POINTOPOINT))
1139                         continue;
1140
1141                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1142                         struct ifaddr *ifa = ifac->ifa;
1143
1144                         if (ifa->ifa_addr->sa_family != addr->sa_family)
1145                                 continue;
1146                         if (ifa->ifa_dstaddr &&
1147                             sa_equal(addr, ifa->ifa_dstaddr))
1148                                 return (ifa);
1149                 }
1150         }
1151         return (NULL);
1152 }
1153
1154 /*
1155  * Find an interface on a specific network.  If many, choice
1156  * is most specific found.
1157  */
1158 struct ifaddr *
1159 ifa_ifwithnet(struct sockaddr *addr)
1160 {
1161         struct ifnet *ifp;
1162         struct ifaddr *ifa_maybe = NULL;
1163         u_int af = addr->sa_family;
1164         char *addr_data = addr->sa_data, *cplim;
1165
1166         /*
1167          * AF_LINK addresses can be looked up directly by their index number,
1168          * so do that if we can.
1169          */
1170         if (af == AF_LINK) {
1171                 struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1172
1173                 if (sdl->sdl_index && sdl->sdl_index <= if_index)
1174                         return (ifindex2ifnet[sdl->sdl_index]->if_lladdr);
1175         }
1176
1177         /*
1178          * Scan though each interface, looking for ones that have
1179          * addresses in this address family.
1180          */
1181         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1182                 struct ifaddr_container *ifac;
1183
1184                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1185                         struct ifaddr *ifa = ifac->ifa;
1186                         char *cp, *cp2, *cp3;
1187
1188                         if (ifa->ifa_addr->sa_family != af)
1189 next:                           continue;
1190                         if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1191                                 /*
1192                                  * This is a bit broken as it doesn't
1193                                  * take into account that the remote end may
1194                                  * be a single node in the network we are
1195                                  * looking for.
1196                                  * The trouble is that we don't know the
1197                                  * netmask for the remote end.
1198                                  */
1199                                 if (ifa->ifa_dstaddr != NULL &&
1200                                     sa_equal(addr, ifa->ifa_dstaddr))
1201                                         return (ifa);
1202                         } else {
1203                                 /*
1204                                  * if we have a special address handler,
1205                                  * then use it instead of the generic one.
1206                                  */
1207                                 if (ifa->ifa_claim_addr) {
1208                                         if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1209                                                 return (ifa);
1210                                         } else {
1211                                                 continue;
1212                                         }
1213                                 }
1214
1215                                 /*
1216                                  * Scan all the bits in the ifa's address.
1217                                  * If a bit dissagrees with what we are
1218                                  * looking for, mask it with the netmask
1219                                  * to see if it really matters.
1220                                  * (A byte at a time)
1221                                  */
1222                                 if (ifa->ifa_netmask == 0)
1223                                         continue;
1224                                 cp = addr_data;
1225                                 cp2 = ifa->ifa_addr->sa_data;
1226                                 cp3 = ifa->ifa_netmask->sa_data;
1227                                 cplim = ifa->ifa_netmask->sa_len +
1228                                         (char *)ifa->ifa_netmask;
1229                                 while (cp3 < cplim)
1230                                         if ((*cp++ ^ *cp2++) & *cp3++)
1231                                                 goto next; /* next address! */
1232                                 /*
1233                                  * If the netmask of what we just found
1234                                  * is more specific than what we had before
1235                                  * (if we had one) then remember the new one
1236                                  * before continuing to search
1237                                  * for an even better one.
1238                                  */
1239                                 if (ifa_maybe == NULL ||
1240                                     rn_refines((char *)ifa->ifa_netmask,
1241                                                (char *)ifa_maybe->ifa_netmask))
1242                                         ifa_maybe = ifa;
1243                         }
1244                 }
1245         }
1246         return (ifa_maybe);
1247 }
1248
1249 /*
1250  * Find an interface address specific to an interface best matching
1251  * a given address.
1252  */
1253 struct ifaddr *
1254 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1255 {
1256         struct ifaddr_container *ifac;
1257         char *cp, *cp2, *cp3;
1258         char *cplim;
1259         struct ifaddr *ifa_maybe = NULL;
1260         u_int af = addr->sa_family;
1261
1262         if (af >= AF_MAX)
1263                 return (0);
1264         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1265                 struct ifaddr *ifa = ifac->ifa;
1266
1267                 if (ifa->ifa_addr->sa_family != af)
1268                         continue;
1269                 if (ifa_maybe == NULL)
1270                         ifa_maybe = ifa;
1271                 if (ifa->ifa_netmask == NULL) {
1272                         if (sa_equal(addr, ifa->ifa_addr) ||
1273                             (ifa->ifa_dstaddr != NULL &&
1274                              sa_equal(addr, ifa->ifa_dstaddr)))
1275                                 return (ifa);
1276                         continue;
1277                 }
1278                 if (ifp->if_flags & IFF_POINTOPOINT) {
1279                         if (sa_equal(addr, ifa->ifa_dstaddr))
1280                                 return (ifa);
1281                 } else {
1282                         cp = addr->sa_data;
1283                         cp2 = ifa->ifa_addr->sa_data;
1284                         cp3 = ifa->ifa_netmask->sa_data;
1285                         cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1286                         for (; cp3 < cplim; cp3++)
1287                                 if ((*cp++ ^ *cp2++) & *cp3)
1288                                         break;
1289                         if (cp3 == cplim)
1290                                 return (ifa);
1291                 }
1292         }
1293         return (ifa_maybe);
1294 }
1295
1296 /*
1297  * Default action when installing a route with a Link Level gateway.
1298  * Lookup an appropriate real ifa to point to.
1299  * This should be moved to /sys/net/link.c eventually.
1300  */
1301 static void
1302 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1303 {
1304         struct ifaddr *ifa;
1305         struct sockaddr *dst;
1306         struct ifnet *ifp;
1307
1308         if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
1309             (ifp = ifa->ifa_ifp) == NULL || (dst = rt_key(rt)) == NULL)
1310                 return;
1311         ifa = ifaof_ifpforaddr(dst, ifp);
1312         if (ifa != NULL) {
1313                 IFAFREE(rt->rt_ifa);
1314                 IFAREF(ifa);
1315                 rt->rt_ifa = ifa;
1316                 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1317                         ifa->ifa_rtrequest(cmd, rt, info);
1318         }
1319 }
1320
1321 /*
1322  * Mark an interface down and notify protocols of
1323  * the transition.
1324  * NOTE: must be called at splnet or eqivalent.
1325  */
1326 void
1327 if_unroute(struct ifnet *ifp, int flag, int fam)
1328 {
1329         struct ifaddr_container *ifac;
1330
1331         ifp->if_flags &= ~flag;
1332         getmicrotime(&ifp->if_lastchange);
1333         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1334                 struct ifaddr *ifa = ifac->ifa;
1335
1336                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1337                         kpfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1338         }
1339         ifq_purge_all(&ifp->if_snd);
1340         rt_ifmsg(ifp);
1341 }
1342
1343 /*
1344  * Mark an interface up and notify protocols of
1345  * the transition.
1346  * NOTE: must be called at splnet or eqivalent.
1347  */
1348 void
1349 if_route(struct ifnet *ifp, int flag, int fam)
1350 {
1351         struct ifaddr_container *ifac;
1352
1353         ifq_purge_all(&ifp->if_snd);
1354         ifp->if_flags |= flag;
1355         getmicrotime(&ifp->if_lastchange);
1356         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1357                 struct ifaddr *ifa = ifac->ifa;
1358
1359                 if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1360                         kpfctlinput(PRC_IFUP, ifa->ifa_addr);
1361         }
1362         rt_ifmsg(ifp);
1363 #ifdef INET6
1364         in6_if_up(ifp);
1365 #endif
1366 }
1367
1368 /*
1369  * Mark an interface down and notify protocols of the transition.  An
1370  * interface going down is also considered to be a synchronizing event.
1371  * We must ensure that all packet processing related to the interface
1372  * has completed before we return so e.g. the caller can free the ifnet
1373  * structure that the mbufs may be referencing.
1374  *
1375  * NOTE: must be called at splnet or eqivalent.
1376  */
1377 void
1378 if_down(struct ifnet *ifp)
1379 {
1380         if_unroute(ifp, IFF_UP, AF_UNSPEC);
1381         netmsg_service_sync();
1382 }
1383
1384 /*
1385  * Mark an interface up and notify protocols of
1386  * the transition.
1387  * NOTE: must be called at splnet or eqivalent.
1388  */
1389 void
1390 if_up(struct ifnet *ifp)
1391 {
1392         if_route(ifp, IFF_UP, AF_UNSPEC);
1393 }
1394
1395 /*
1396  * Process a link state change.
1397  * NOTE: must be called at splsoftnet or equivalent.
1398  */
1399 void
1400 if_link_state_change(struct ifnet *ifp)
1401 {
1402         int link_state = ifp->if_link_state;
1403
1404         rt_ifmsg(ifp);
1405         devctl_notify("IFNET", ifp->if_xname,
1406             (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1407 }
1408
1409 /*
1410  * Handle interface watchdog timer routines.  Called
1411  * from softclock, we decrement timers (if set) and
1412  * call the appropriate interface routine on expiration.
1413  */
1414 static void
1415 if_slowtimo(void *arg)
1416 {
1417         struct ifnet *ifp;
1418
1419         crit_enter();
1420
1421         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1422                 if (ifp->if_timer == 0 || --ifp->if_timer)
1423                         continue;
1424                 if (ifp->if_watchdog) {
1425                         if (ifnet_tryserialize_all(ifp)) {
1426                                 (*ifp->if_watchdog)(ifp);
1427                                 ifnet_deserialize_all(ifp);
1428                         } else {
1429                                 /* try again next timeout */
1430                                 ++ifp->if_timer;
1431                         }
1432                 }
1433         }
1434
1435         crit_exit();
1436
1437         callout_reset(&if_slowtimo_timer, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
1438 }
1439
1440 /*
1441  * Map interface name to
1442  * interface structure pointer.
1443  */
1444 struct ifnet *
1445 ifunit(const char *name)
1446 {
1447         struct ifnet *ifp;
1448
1449         /*
1450          * Search all the interfaces for this name/number
1451          */
1452
1453         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1454                 if (strncmp(ifp->if_xname, name, IFNAMSIZ) == 0)
1455                         break;
1456         }
1457         return (ifp);
1458 }
1459
1460
1461 /*
1462  * Map interface name in a sockaddr_dl to
1463  * interface structure pointer.
1464  */
1465 struct ifnet *
1466 if_withname(struct sockaddr *sa)
1467 {
1468         char ifname[IFNAMSIZ+1];
1469         struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
1470
1471         if ( (sa->sa_family != AF_LINK) || (sdl->sdl_nlen == 0) ||
1472              (sdl->sdl_nlen > IFNAMSIZ) )
1473                 return NULL;
1474
1475         /*
1476          * ifunit wants a null-terminated name.  It may not be null-terminated
1477          * in the sockaddr.  We don't want to change the caller's sockaddr,
1478          * and there might not be room to put the trailing null anyway, so we
1479          * make a local copy that we know we can null terminate safely.
1480          */
1481
1482         bcopy(sdl->sdl_data, ifname, sdl->sdl_nlen);
1483         ifname[sdl->sdl_nlen] = '\0';
1484         return ifunit(ifname);
1485 }
1486
1487
1488 /*
1489  * Interface ioctls.
1490  */
1491 int
1492 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct ucred *cred)
1493 {
1494         struct ifnet *ifp;
1495         struct ifreq *ifr;
1496         struct ifstat *ifs;
1497         int error;
1498         short oif_flags;
1499         int new_flags;
1500 #ifdef COMPAT_43
1501         int ocmd;
1502 #endif
1503         size_t namelen, onamelen;
1504         char new_name[IFNAMSIZ];
1505         struct ifaddr *ifa;
1506         struct sockaddr_dl *sdl;
1507
1508         switch (cmd) {
1509         case SIOCGIFCONF:
1510         case OSIOCGIFCONF:
1511                 return (ifconf(cmd, data, cred));
1512         default:
1513                 break;
1514         }
1515
1516         ifr = (struct ifreq *)data;
1517
1518         switch (cmd) {
1519         case SIOCIFCREATE:
1520         case SIOCIFCREATE2:
1521                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1522                         return (error);
1523                 return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1524                         cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1525         case SIOCIFDESTROY:
1526                 if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
1527                         return (error);
1528                 return (if_clone_destroy(ifr->ifr_name));
1529         case SIOCIFGCLONERS:
1530                 return (if_clone_list((struct if_clonereq *)data));
1531         default:
1532                 break;
1533         }
1534
1535         /*
1536          * Nominal ioctl through interface, lookup the ifp and obtain a
1537          * lock to serialize the ifconfig ioctl operation.
1538          */
1539         ifp = ifunit(ifr->ifr_name);
1540         if (ifp == NULL)
1541                 return (ENXIO);
1542         error = 0;
1543         mtx_lock(&ifp->if_ioctl_mtx);
1544
1545         switch (cmd) {
1546         case SIOCGIFINDEX:
1547                 ifr->ifr_index = ifp->if_index;
1548                 break;
1549
1550         case SIOCGIFFLAGS:
1551                 ifr->ifr_flags = ifp->if_flags;
1552                 ifr->ifr_flagshigh = ifp->if_flags >> 16;
1553                 break;
1554
1555         case SIOCGIFCAP:
1556                 ifr->ifr_reqcap = ifp->if_capabilities;
1557                 ifr->ifr_curcap = ifp->if_capenable;
1558                 break;
1559
1560         case SIOCGIFMETRIC:
1561                 ifr->ifr_metric = ifp->if_metric;
1562                 break;
1563
1564         case SIOCGIFMTU:
1565                 ifr->ifr_mtu = ifp->if_mtu;
1566                 break;
1567
1568         case SIOCGIFDATA:
1569                 error = copyout((caddr_t)&ifp->if_data, ifr->ifr_data,
1570                                 sizeof(ifp->if_data));
1571                 break;
1572
1573         case SIOCGIFPHYS:
1574                 ifr->ifr_phys = ifp->if_physical;
1575                 break;
1576
1577         case SIOCGIFPOLLCPU:
1578                 ifr->ifr_pollcpu = -1;
1579                 break;
1580
1581         case SIOCSIFPOLLCPU:
1582                 break;
1583
1584         case SIOCSIFFLAGS:
1585                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1586                 if (error)
1587                         break;
1588                 new_flags = (ifr->ifr_flags & 0xffff) |
1589                     (ifr->ifr_flagshigh << 16);
1590                 if (ifp->if_flags & IFF_SMART) {
1591                         /* Smart drivers twiddle their own routes */
1592                 } else if (ifp->if_flags & IFF_UP &&
1593                     (new_flags & IFF_UP) == 0) {
1594                         crit_enter();
1595                         if_down(ifp);
1596                         crit_exit();
1597                 } else if (new_flags & IFF_UP &&
1598                     (ifp->if_flags & IFF_UP) == 0) {
1599                         crit_enter();
1600                         if_up(ifp);
1601                         crit_exit();
1602                 }
1603
1604 #ifdef IFPOLL_ENABLE
1605                 if ((new_flags ^ ifp->if_flags) & IFF_NPOLLING) {
1606                         if (new_flags & IFF_NPOLLING)
1607                                 ifpoll_register(ifp);
1608                         else
1609                                 ifpoll_deregister(ifp);
1610                 }
1611 #endif
1612
1613                 ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1614                         (new_flags &~ IFF_CANTCHANGE);
1615                 if (new_flags & IFF_PPROMISC) {
1616                         /* Permanently promiscuous mode requested */
1617                         ifp->if_flags |= IFF_PROMISC;
1618                 } else if (ifp->if_pcount == 0) {
1619                         ifp->if_flags &= ~IFF_PROMISC;
1620                 }
1621                 if (ifp->if_ioctl) {
1622                         ifnet_serialize_all(ifp);
1623                         ifp->if_ioctl(ifp, cmd, data, cred);
1624                         ifnet_deserialize_all(ifp);
1625                 }
1626                 getmicrotime(&ifp->if_lastchange);
1627                 break;
1628
1629         case SIOCSIFCAP:
1630                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1631                 if (error)
1632                         break;
1633                 if (ifr->ifr_reqcap & ~ifp->if_capabilities) {
1634                         error = EINVAL;
1635                         break;
1636                 }
1637                 ifnet_serialize_all(ifp);
1638                 ifp->if_ioctl(ifp, cmd, data, cred);
1639                 ifnet_deserialize_all(ifp);
1640                 break;
1641
1642         case SIOCSIFNAME:
1643                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1644                 if (error)
1645                         break;
1646                 error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1647                 if (error)
1648                         break;
1649                 if (new_name[0] == '\0') {
1650                         error = EINVAL;
1651                         break;
1652                 }
1653                 if (ifunit(new_name) != NULL) {
1654                         error = EEXIST;
1655                         break;
1656                 }
1657
1658                 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
1659
1660                 /* Announce the departure of the interface. */
1661                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1662
1663                 strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1664                 ifa = TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
1665                 /* XXX IFA_LOCK(ifa); */
1666                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1667                 namelen = strlen(new_name);
1668                 onamelen = sdl->sdl_nlen;
1669                 /*
1670                  * Move the address if needed.  This is safe because we
1671                  * allocate space for a name of length IFNAMSIZ when we
1672                  * create this in if_attach().
1673                  */
1674                 if (namelen != onamelen) {
1675                         bcopy(sdl->sdl_data + onamelen,
1676                             sdl->sdl_data + namelen, sdl->sdl_alen);
1677                 }
1678                 bcopy(new_name, sdl->sdl_data, namelen);
1679                 sdl->sdl_nlen = namelen;
1680                 sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1681                 bzero(sdl->sdl_data, onamelen);
1682                 while (namelen != 0)
1683                         sdl->sdl_data[--namelen] = 0xff;
1684                 /* XXX IFA_UNLOCK(ifa) */
1685
1686                 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
1687
1688                 /* Announce the return of the interface. */
1689                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1690                 break;
1691
1692         case SIOCSIFMETRIC:
1693                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1694                 if (error)
1695                         break;
1696                 ifp->if_metric = ifr->ifr_metric;
1697                 getmicrotime(&ifp->if_lastchange);
1698                 break;
1699
1700         case SIOCSIFPHYS:
1701                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1702                 if (error)
1703                         break;
1704                 if (ifp->if_ioctl == NULL) {
1705                         error = EOPNOTSUPP;
1706                         break;
1707                 }
1708                 ifnet_serialize_all(ifp);
1709                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1710                 ifnet_deserialize_all(ifp);
1711                 if (error == 0)
1712                         getmicrotime(&ifp->if_lastchange);
1713                 break;
1714
1715         case SIOCSIFMTU:
1716         {
1717                 u_long oldmtu = ifp->if_mtu;
1718
1719                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1720                 if (error)
1721                         break;
1722                 if (ifp->if_ioctl == NULL) {
1723                         error = EOPNOTSUPP;
1724                         break;
1725                 }
1726                 if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU) {
1727                         error = EINVAL;
1728                         break;
1729                 }
1730                 ifnet_serialize_all(ifp);
1731                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1732                 ifnet_deserialize_all(ifp);
1733                 if (error == 0) {
1734                         getmicrotime(&ifp->if_lastchange);
1735                         rt_ifmsg(ifp);
1736                 }
1737                 /*
1738                  * If the link MTU changed, do network layer specific procedure.
1739                  */
1740                 if (ifp->if_mtu != oldmtu) {
1741 #ifdef INET6
1742                         nd6_setmtu(ifp);
1743 #endif
1744                 }
1745                 break;
1746         }
1747
1748         case SIOCADDMULTI:
1749         case SIOCDELMULTI:
1750                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1751                 if (error)
1752                         break;
1753
1754                 /* Don't allow group membership on non-multicast interfaces. */
1755                 if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1756                         error = EOPNOTSUPP;
1757                         break;
1758                 }
1759
1760                 /* Don't let users screw up protocols' entries. */
1761                 if (ifr->ifr_addr.sa_family != AF_LINK) {
1762                         error = EINVAL;
1763                         break;
1764                 }
1765
1766                 if (cmd == SIOCADDMULTI) {
1767                         struct ifmultiaddr *ifma;
1768                         error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1769                 } else {
1770                         error = if_delmulti(ifp, &ifr->ifr_addr);
1771                 }
1772                 if (error == 0)
1773                         getmicrotime(&ifp->if_lastchange);
1774                 break;
1775
1776         case SIOCSIFPHYADDR:
1777         case SIOCDIFPHYADDR:
1778 #ifdef INET6
1779         case SIOCSIFPHYADDR_IN6:
1780 #endif
1781         case SIOCSLIFPHYADDR:
1782         case SIOCSIFMEDIA:
1783         case SIOCSIFGENERIC:
1784                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1785                 if (error)
1786                         break;
1787                 if (ifp->if_ioctl == 0) {
1788                         error = EOPNOTSUPP;
1789                         break;
1790                 }
1791                 ifnet_serialize_all(ifp);
1792                 error = ifp->if_ioctl(ifp, cmd, data, cred);
1793                 ifnet_deserialize_all(ifp);
1794                 if (error == 0)
1795                         getmicrotime(&ifp->if_lastchange);
1796                 break;
1797
1798         case SIOCGIFSTATUS:
1799                 ifs = (struct ifstat *)data;
1800                 ifs->ascii[0] = '\0';
1801                 /* fall through */
1802         case SIOCGIFPSRCADDR:
1803         case SIOCGIFPDSTADDR:
1804         case SIOCGLIFPHYADDR:
1805         case SIOCGIFMEDIA:
1806         case SIOCGIFGENERIC:
1807                 if (ifp->if_ioctl == NULL) {
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                 break;
1815
1816         case SIOCSIFLLADDR:
1817                 error = priv_check_cred(cred, PRIV_ROOT, 0);
1818                 if (error)
1819                         break;
1820                 error = if_setlladdr(ifp, ifr->ifr_addr.sa_data,
1821                                      ifr->ifr_addr.sa_len);
1822                 EVENTHANDLER_INVOKE(iflladdr_event, ifp);
1823                 break;
1824
1825         default:
1826                 oif_flags = ifp->if_flags;
1827                 if (so->so_proto == 0) {
1828                         error = EOPNOTSUPP;
1829                         break;
1830                 }
1831 #ifndef COMPAT_43
1832                 error = so_pru_control_direct(so, cmd, data, ifp);
1833 #else
1834                 ocmd = cmd;
1835
1836                 switch (cmd) {
1837                 case SIOCSIFDSTADDR:
1838                 case SIOCSIFADDR:
1839                 case SIOCSIFBRDADDR:
1840                 case SIOCSIFNETMASK:
1841 #if BYTE_ORDER != BIG_ENDIAN
1842                         if (ifr->ifr_addr.sa_family == 0 &&
1843                             ifr->ifr_addr.sa_len < 16) {
1844                                 ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1845                                 ifr->ifr_addr.sa_len = 16;
1846                         }
1847 #else
1848                         if (ifr->ifr_addr.sa_len == 0)
1849                                 ifr->ifr_addr.sa_len = 16;
1850 #endif
1851                         break;
1852                 case OSIOCGIFADDR:
1853                         cmd = SIOCGIFADDR;
1854                         break;
1855                 case OSIOCGIFDSTADDR:
1856                         cmd = SIOCGIFDSTADDR;
1857                         break;
1858                 case OSIOCGIFBRDADDR:
1859                         cmd = SIOCGIFBRDADDR;
1860                         break;
1861                 case OSIOCGIFNETMASK:
1862                         cmd = SIOCGIFNETMASK;
1863                         break;
1864                 default:
1865                         break;
1866                 }
1867
1868                 error = so_pru_control_direct(so, cmd, data, ifp);
1869
1870                 switch (ocmd) {
1871                 case OSIOCGIFADDR:
1872                 case OSIOCGIFDSTADDR:
1873                 case OSIOCGIFBRDADDR:
1874                 case OSIOCGIFNETMASK:
1875                         *(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1876                         break;
1877                 }
1878 #endif /* COMPAT_43 */
1879
1880                 if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1881 #ifdef INET6
1882                         DELAY(100);/* XXX: temporary workaround for fxp issue*/
1883                         if (ifp->if_flags & IFF_UP) {
1884                                 crit_enter();
1885                                 in6_if_up(ifp);
1886                                 crit_exit();
1887                         }
1888 #endif
1889                 }
1890                 break;
1891         }
1892
1893         mtx_unlock(&ifp->if_ioctl_mtx);
1894         return (error);
1895 }
1896
1897 /*
1898  * Set/clear promiscuous mode on interface ifp based on the truth value
1899  * of pswitch.  The calls are reference counted so that only the first
1900  * "on" request actually has an effect, as does the final "off" request.
1901  * Results are undefined if the "off" and "on" requests are not matched.
1902  */
1903 int
1904 ifpromisc(struct ifnet *ifp, int pswitch)
1905 {
1906         struct ifreq ifr;
1907         int error;
1908         int oldflags;
1909
1910         oldflags = ifp->if_flags;
1911         if (ifp->if_flags & IFF_PPROMISC) {
1912                 /* Do nothing if device is in permanently promiscuous mode */
1913                 ifp->if_pcount += pswitch ? 1 : -1;
1914                 return (0);
1915         }
1916         if (pswitch) {
1917                 /*
1918                  * If the device is not configured up, we cannot put it in
1919                  * promiscuous mode.
1920                  */
1921                 if ((ifp->if_flags & IFF_UP) == 0)
1922                         return (ENETDOWN);
1923                 if (ifp->if_pcount++ != 0)
1924                         return (0);
1925                 ifp->if_flags |= IFF_PROMISC;
1926                 log(LOG_INFO, "%s: promiscuous mode enabled\n",
1927                     ifp->if_xname);
1928         } else {
1929                 if (--ifp->if_pcount > 0)
1930                         return (0);
1931                 ifp->if_flags &= ~IFF_PROMISC;
1932                 log(LOG_INFO, "%s: promiscuous mode disabled\n",
1933                     ifp->if_xname);
1934         }
1935         ifr.ifr_flags = ifp->if_flags;
1936         ifr.ifr_flagshigh = ifp->if_flags >> 16;
1937         ifnet_serialize_all(ifp);
1938         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr, NULL);
1939         ifnet_deserialize_all(ifp);
1940         if (error == 0)
1941                 rt_ifmsg(ifp);
1942         else
1943                 ifp->if_flags = oldflags;
1944         return error;
1945 }
1946
1947 /*
1948  * Return interface configuration
1949  * of system.  List may be used
1950  * in later ioctl's (above) to get
1951  * other information.
1952  */
1953 static int
1954 ifconf(u_long cmd, caddr_t data, struct ucred *cred)
1955 {
1956         struct ifconf *ifc = (struct ifconf *)data;
1957         struct ifnet *ifp;
1958         struct sockaddr *sa;
1959         struct ifreq ifr, *ifrp;
1960         int space = ifc->ifc_len, error = 0;
1961
1962         ifrp = ifc->ifc_req;
1963         TAILQ_FOREACH(ifp, &ifnet, if_link) {
1964                 struct ifaddr_container *ifac;
1965                 int addrs;
1966
1967                 if (space <= sizeof ifr)
1968                         break;
1969
1970                 /*
1971                  * Zero the stack declared structure first to prevent
1972                  * memory disclosure.
1973                  */
1974                 bzero(&ifr, sizeof(ifr));
1975                 if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
1976                     >= sizeof(ifr.ifr_name)) {
1977                         error = ENAMETOOLONG;
1978                         break;
1979                 }
1980
1981                 addrs = 0;
1982                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1983                         struct ifaddr *ifa = ifac->ifa;
1984
1985                         if (space <= sizeof ifr)
1986                                 break;
1987                         sa = ifa->ifa_addr;
1988                         if (cred->cr_prison &&
1989                             prison_if(cred, sa))
1990                                 continue;
1991                         addrs++;
1992 #ifdef COMPAT_43
1993                         if (cmd == OSIOCGIFCONF) {
1994                                 struct osockaddr *osa =
1995                                          (struct osockaddr *)&ifr.ifr_addr;
1996                                 ifr.ifr_addr = *sa;
1997                                 osa->sa_family = sa->sa_family;
1998                                 error = copyout(&ifr, ifrp, sizeof ifr);
1999                                 ifrp++;
2000                         } else
2001 #endif
2002                         if (sa->sa_len <= sizeof(*sa)) {
2003                                 ifr.ifr_addr = *sa;
2004                                 error = copyout(&ifr, ifrp, sizeof ifr);
2005                                 ifrp++;
2006                         } else {
2007                                 if (space < (sizeof ifr) + sa->sa_len -
2008                                             sizeof(*sa))
2009                                         break;
2010                                 space -= sa->sa_len - sizeof(*sa);
2011                                 error = copyout(&ifr, ifrp,
2012                                                 sizeof ifr.ifr_name);
2013                                 if (error == 0)
2014                                         error = copyout(sa, &ifrp->ifr_addr,
2015                                                         sa->sa_len);
2016                                 ifrp = (struct ifreq *)
2017                                         (sa->sa_len + (caddr_t)&ifrp->ifr_addr);
2018                         }
2019                         if (error)
2020                                 break;
2021                         space -= sizeof ifr;
2022                 }
2023                 if (error)
2024                         break;
2025                 if (!addrs) {
2026                         bzero(&ifr.ifr_addr, sizeof ifr.ifr_addr);
2027                         error = copyout(&ifr, ifrp, sizeof ifr);
2028                         if (error)
2029                                 break;
2030                         space -= sizeof ifr;
2031                         ifrp++;
2032                 }
2033         }
2034         ifc->ifc_len -= space;
2035         return (error);
2036 }
2037
2038 /*
2039  * Just like if_promisc(), but for all-multicast-reception mode.
2040  */
2041 int
2042 if_allmulti(struct ifnet *ifp, int onswitch)
2043 {
2044         int error = 0;
2045         struct ifreq ifr;
2046
2047         crit_enter();
2048
2049         if (onswitch) {
2050                 if (ifp->if_amcount++ == 0) {
2051                         ifp->if_flags |= IFF_ALLMULTI;
2052                         ifr.ifr_flags = ifp->if_flags;
2053                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2054                         ifnet_serialize_all(ifp);
2055                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2056                                               NULL);
2057                         ifnet_deserialize_all(ifp);
2058                 }
2059         } else {
2060                 if (ifp->if_amcount > 1) {
2061                         ifp->if_amcount--;
2062                 } else {
2063                         ifp->if_amcount = 0;
2064                         ifp->if_flags &= ~IFF_ALLMULTI;
2065                         ifr.ifr_flags = ifp->if_flags;
2066                         ifr.ifr_flagshigh = ifp->if_flags >> 16;
2067                         ifnet_serialize_all(ifp);
2068                         error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2069                                               NULL);
2070                         ifnet_deserialize_all(ifp);
2071                 }
2072         }
2073
2074         crit_exit();
2075
2076         if (error == 0)
2077                 rt_ifmsg(ifp);
2078         return error;
2079 }
2080
2081 /*
2082  * Add a multicast listenership to the interface in question.
2083  * The link layer provides a routine which converts
2084  */
2085 int
2086 if_addmulti(
2087         struct ifnet *ifp,      /* interface to manipulate */
2088         struct sockaddr *sa,    /* address to add */
2089         struct ifmultiaddr **retifma)
2090 {
2091         struct sockaddr *llsa, *dupsa;
2092         int error;
2093         struct ifmultiaddr *ifma;
2094
2095         /*
2096          * If the matching multicast address already exists
2097          * then don't add a new one, just add a reference
2098          */
2099         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2100                 if (sa_equal(sa, ifma->ifma_addr)) {
2101                         ifma->ifma_refcount++;
2102                         if (retifma)
2103                                 *retifma = ifma;
2104                         return 0;
2105                 }
2106         }
2107
2108         /*
2109          * Give the link layer a chance to accept/reject it, and also
2110          * find out which AF_LINK address this maps to, if it isn't one
2111          * already.
2112          */
2113         if (ifp->if_resolvemulti) {
2114                 ifnet_serialize_all(ifp);
2115                 error = ifp->if_resolvemulti(ifp, &llsa, sa);
2116                 ifnet_deserialize_all(ifp);
2117                 if (error) 
2118                         return error;
2119         } else {
2120                 llsa = NULL;
2121         }
2122
2123         ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_WAITOK);
2124         dupsa = kmalloc(sa->sa_len, M_IFMADDR, M_WAITOK);
2125         bcopy(sa, dupsa, sa->sa_len);
2126
2127         ifma->ifma_addr = dupsa;
2128         ifma->ifma_lladdr = llsa;
2129         ifma->ifma_ifp = ifp;
2130         ifma->ifma_refcount = 1;
2131         ifma->ifma_protospec = 0;
2132         rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2133
2134         /*
2135          * Some network interfaces can scan the address list at
2136          * interrupt time; lock them out.
2137          */
2138         crit_enter();
2139         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2140         crit_exit();
2141         if (retifma)
2142                 *retifma = ifma;
2143
2144         if (llsa != NULL) {
2145                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2146                         if (sa_equal(ifma->ifma_addr, llsa))
2147                                 break;
2148                 }
2149                 if (ifma) {
2150                         ifma->ifma_refcount++;
2151                 } else {
2152                         ifma = kmalloc(sizeof *ifma, M_IFMADDR, M_WAITOK);
2153                         dupsa = kmalloc(llsa->sa_len, M_IFMADDR, M_WAITOK);
2154                         bcopy(llsa, dupsa, llsa->sa_len);
2155                         ifma->ifma_addr = dupsa;
2156                         ifma->ifma_ifp = ifp;
2157                         ifma->ifma_refcount = 1;
2158                         crit_enter();
2159                         TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2160                         crit_exit();
2161                 }
2162         }
2163         /*
2164          * We are certain we have added something, so call down to the
2165          * interface to let them know about it.
2166          */
2167         crit_enter();
2168         ifnet_serialize_all(ifp);
2169         if (ifp->if_ioctl)
2170                 ifp->if_ioctl(ifp, SIOCADDMULTI, 0, NULL);
2171         ifnet_deserialize_all(ifp);
2172         crit_exit();
2173
2174         return 0;
2175 }
2176
2177 /*
2178  * Remove a reference to a multicast address on this interface.  Yell
2179  * if the request does not match an existing membership.
2180  */
2181 int
2182 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2183 {
2184         struct ifmultiaddr *ifma;
2185
2186         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2187                 if (sa_equal(sa, ifma->ifma_addr))
2188                         break;
2189         if (ifma == NULL)
2190                 return ENOENT;
2191
2192         if (ifma->ifma_refcount > 1) {
2193                 ifma->ifma_refcount--;
2194                 return 0;
2195         }
2196
2197         rt_newmaddrmsg(RTM_DELMADDR, ifma);
2198         sa = ifma->ifma_lladdr;
2199         crit_enter();
2200         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2201         /*
2202          * Make sure the interface driver is notified
2203          * in the case of a link layer mcast group being left.
2204          */
2205         if (ifma->ifma_addr->sa_family == AF_LINK && sa == NULL) {
2206                 ifnet_serialize_all(ifp);
2207                 ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2208                 ifnet_deserialize_all(ifp);
2209         }
2210         crit_exit();
2211         kfree(ifma->ifma_addr, M_IFMADDR);
2212         kfree(ifma, M_IFMADDR);
2213         if (sa == NULL)
2214                 return 0;
2215
2216         /*
2217          * Now look for the link-layer address which corresponds to
2218          * this network address.  It had been squirreled away in
2219          * ifma->ifma_lladdr for this purpose (so we don't have
2220          * to call ifp->if_resolvemulti() again), and we saved that
2221          * value in sa above.  If some nasty deleted the
2222          * link-layer address out from underneath us, we can deal because
2223          * the address we stored was is not the same as the one which was
2224          * in the record for the link-layer address.  (So we don't complain
2225          * in that case.)
2226          */
2227         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2228                 if (sa_equal(sa, ifma->ifma_addr))
2229                         break;
2230         if (ifma == NULL)
2231                 return 0;
2232
2233         if (ifma->ifma_refcount > 1) {
2234                 ifma->ifma_refcount--;
2235                 return 0;
2236         }
2237
2238         crit_enter();
2239         ifnet_serialize_all(ifp);
2240         TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2241         ifp->if_ioctl(ifp, SIOCDELMULTI, 0, NULL);
2242         ifnet_deserialize_all(ifp);
2243         crit_exit();
2244         kfree(ifma->ifma_addr, M_IFMADDR);
2245         kfree(sa, M_IFMADDR);
2246         kfree(ifma, M_IFMADDR);
2247
2248         return 0;
2249 }
2250
2251 /*
2252  * Delete all multicast group membership for an interface.
2253  * Should be used to quickly flush all multicast filters.
2254  */
2255 void
2256 if_delallmulti(struct ifnet *ifp)
2257 {
2258         struct ifmultiaddr *ifma;
2259         struct ifmultiaddr *next;
2260
2261         TAILQ_FOREACH_MUTABLE(ifma, &ifp->if_multiaddrs, ifma_link, next)
2262                 if_delmulti(ifp, ifma->ifma_addr);
2263 }
2264
2265
2266 /*
2267  * Set the link layer address on an interface.
2268  *
2269  * At this time we only support certain types of interfaces,
2270  * and we don't allow the length of the address to change.
2271  */
2272 int
2273 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2274 {
2275         struct sockaddr_dl *sdl;
2276         struct ifreq ifr;
2277
2278         sdl = IF_LLSOCKADDR(ifp);
2279         if (sdl == NULL)
2280                 return (EINVAL);
2281         if (len != sdl->sdl_alen)       /* don't allow length to change */
2282                 return (EINVAL);
2283         switch (ifp->if_type) {
2284         case IFT_ETHER:                 /* these types use struct arpcom */
2285         case IFT_XETHER:
2286         case IFT_L2VLAN:
2287                 bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
2288                 bcopy(lladdr, LLADDR(sdl), len);
2289                 break;
2290         default:
2291                 return (ENODEV);
2292         }
2293         /*
2294          * If the interface is already up, we need
2295          * to re-init it in order to reprogram its
2296          * address filter.
2297          */
2298         ifnet_serialize_all(ifp);
2299         if ((ifp->if_flags & IFF_UP) != 0) {
2300 #ifdef INET
2301                 struct ifaddr_container *ifac;
2302 #endif
2303
2304                 ifp->if_flags &= ~IFF_UP;
2305                 ifr.ifr_flags = ifp->if_flags;
2306                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2307                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2308                               NULL);
2309                 ifp->if_flags |= IFF_UP;
2310                 ifr.ifr_flags = ifp->if_flags;
2311                 ifr.ifr_flagshigh = ifp->if_flags >> 16;
2312                 ifp->if_ioctl(ifp, SIOCSIFFLAGS, (caddr_t)&ifr,
2313                                  NULL);
2314 #ifdef INET
2315                 /*
2316                  * Also send gratuitous ARPs to notify other nodes about
2317                  * the address change.
2318                  */
2319                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2320                         struct ifaddr *ifa = ifac->ifa;
2321
2322                         if (ifa->ifa_addr != NULL &&
2323                             ifa->ifa_addr->sa_family == AF_INET)
2324                                 arp_gratuitous(ifp, ifa);
2325                 }
2326 #endif
2327         }
2328         ifnet_deserialize_all(ifp);
2329         return (0);
2330 }
2331
2332 struct ifmultiaddr *
2333 ifmaof_ifpforaddr(struct sockaddr *sa, struct ifnet *ifp)
2334 {
2335         struct ifmultiaddr *ifma;
2336
2337         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
2338                 if (sa_equal(ifma->ifma_addr, sa))
2339                         break;
2340
2341         return ifma;
2342 }
2343
2344 /*
2345  * This function locates the first real ethernet MAC from a network
2346  * card and loads it into node, returning 0 on success or ENOENT if
2347  * no suitable interfaces were found.  It is used by the uuid code to
2348  * generate a unique 6-byte number.
2349  */
2350 int
2351 if_getanyethermac(uint16_t *node, int minlen)
2352 {
2353         struct ifnet *ifp;
2354         struct sockaddr_dl *sdl;
2355
2356         TAILQ_FOREACH(ifp, &ifnet, if_link) {
2357                 if (ifp->if_type != IFT_ETHER)
2358                         continue;
2359                 sdl = IF_LLSOCKADDR(ifp);
2360                 if (sdl->sdl_alen < minlen)
2361                         continue;
2362                 bcopy(((struct arpcom *)ifp->if_softc)->ac_enaddr, node,
2363                       minlen);
2364                 return(0);
2365         }
2366         return (ENOENT);
2367 }
2368
2369 /*
2370  * The name argument must be a pointer to storage which will last as
2371  * long as the interface does.  For physical devices, the result of
2372  * device_get_name(dev) is a good choice and for pseudo-devices a
2373  * static string works well.
2374  */
2375 void
2376 if_initname(struct ifnet *ifp, const char *name, int unit)
2377 {
2378         ifp->if_dname = name;
2379         ifp->if_dunit = unit;
2380         if (unit != IF_DUNIT_NONE)
2381                 ksnprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2382         else
2383                 strlcpy(ifp->if_xname, name, IFNAMSIZ);
2384 }
2385
2386 int
2387 if_printf(struct ifnet *ifp, const char *fmt, ...)
2388 {
2389         __va_list ap;
2390         int retval;
2391
2392         retval = kprintf("%s: ", ifp->if_xname);
2393         __va_start(ap, fmt);
2394         retval += kvprintf(fmt, ap);
2395         __va_end(ap);
2396         return (retval);
2397 }
2398
2399 struct ifnet *
2400 if_alloc(uint8_t type)
2401 {
2402         struct ifnet *ifp;
2403         size_t size;
2404
2405         /*
2406          * XXX temporary hack until arpcom is setup in if_l2com
2407          */
2408         if (type == IFT_ETHER)
2409                 size = sizeof(struct arpcom);
2410         else
2411                 size = sizeof(struct ifnet);
2412
2413         ifp = kmalloc(size, M_IFNET, M_WAITOK|M_ZERO);
2414
2415         ifp->if_type = type;
2416
2417         if (if_com_alloc[type] != NULL) {
2418                 ifp->if_l2com = if_com_alloc[type](type, ifp);
2419                 if (ifp->if_l2com == NULL) {
2420                         kfree(ifp, M_IFNET);
2421                         return (NULL);
2422                 }
2423         }
2424         return (ifp);
2425 }
2426
2427 void
2428 if_free(struct ifnet *ifp)
2429 {
2430         kfree(ifp, M_IFNET);
2431 }
2432
2433 void
2434 ifq_set_classic(struct ifaltq *ifq)
2435 {
2436         ifq_set_methods(ifq, ifsq_classic_enqueue, ifsq_classic_dequeue,
2437             ifsq_classic_request);
2438 }
2439
2440 void
2441 ifq_set_methods(struct ifaltq *ifq, ifsq_enqueue_t enqueue,
2442     ifsq_dequeue_t dequeue, ifsq_request_t request)
2443 {
2444         int q;
2445
2446         for (q = 0; q < ifq->altq_subq_cnt; ++q) {
2447                 struct ifaltq_subque *ifsq = &ifq->altq_subq[q];
2448
2449                 ifsq->ifsq_enqueue = enqueue;
2450                 ifsq->ifsq_dequeue = dequeue;
2451                 ifsq->ifsq_request = request;
2452         }
2453 }
2454
2455 int
2456 ifsq_classic_enqueue(struct ifaltq_subque *ifsq, struct mbuf *m,
2457     struct altq_pktattr *pa __unused)
2458 {
2459         if (IF_QFULL(ifsq)) {
2460                 m_freem(m);
2461                 return(ENOBUFS);
2462         } else {
2463                 IF_ENQUEUE(ifsq, m);
2464                 return(0);
2465         }       
2466 }
2467
2468 struct mbuf *
2469 ifsq_classic_dequeue(struct ifaltq_subque *ifsq, struct mbuf *mpolled, int op)
2470 {
2471         struct mbuf *m;
2472
2473         switch (op) {
2474         case ALTDQ_POLL:
2475                 IF_POLL(ifsq, m);
2476                 break;
2477         case ALTDQ_REMOVE:
2478                 IF_DEQUEUE(ifsq, m);
2479                 break;
2480         default:
2481                 panic("unsupported ALTQ dequeue op: %d", op);
2482         }
2483         KKASSERT(mpolled == NULL || mpolled == m);
2484         return(m);
2485 }
2486
2487 int
2488 ifsq_classic_request(struct ifaltq_subque *ifsq, int req, void *arg)
2489 {
2490         switch (req) {
2491         case ALTRQ_PURGE:
2492                 IF_DRAIN(ifsq);
2493                 break;
2494         default:
2495                 panic("unsupported ALTQ request: %d", req);
2496         }
2497         return(0);
2498 }
2499
2500 static void
2501 ifsq_ifstart_try(struct ifaltq_subque *ifsq, int force_sched)
2502 {
2503         struct ifnet *ifp = ifsq_get_ifp(ifsq);
2504         int running = 0, need_sched;
2505
2506         /*
2507          * Try to do direct ifnet.if_start first, if there is
2508          * contention on ifnet's serializer, ifnet.if_start will
2509          * be scheduled on ifnet's CPU.
2510          */
2511         if (!ifnet_tryserialize_tx(ifp, ifsq)) {
2512                 /*
2513                  * ifnet serializer contention happened,
2514                  * ifnet.if_start is scheduled on ifnet's
2515                  * CPU, and we keep going.
2516                  */
2517                 ifsq_ifstart_schedule(ifsq, 1);
2518                 return;
2519         }
2520
2521         if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq)) {
2522                 ifp->if_start(ifp, ifsq);
2523                 if ((ifp->if_flags & IFF_RUNNING) && !ifsq_is_oactive(ifsq))
2524                         running = 1;
2525         }
2526         need_sched = ifsq_ifstart_need_schedule(ifsq, running);
2527
2528         ifnet_deserialize_tx(ifp, ifsq);
2529
2530         if (need_sched) {
2531                 /*
2532                  * More data need to be transmitted, ifnet.if_start is
2533                  * scheduled on ifnet's CPU, and we keep going.
2534                  * NOTE: ifnet.if_start interlock is not released.
2535                  */
2536                 ifsq_ifstart_schedule(ifsq, force_sched);
2537         }
2538 }
2539
2540 /*
2541  * IFSUBQ packets staging mechanism:
2542  *
2543  * The packets enqueued into IFSUBQ are staged to a certain amount before the
2544  * ifnet's if_start is called.  In this way, the driver could avoid writing
2545  * to hardware registers upon every packet, instead, hardware registers
2546  * could be written when certain amount of packets are put onto hardware
2547  * TX ring.  The measurement on several modern NICs (emx(4), igb(4), bnx(4),
2548  * bge(4), jme(4)) shows that the hardware registers writing aggregation
2549  * could save ~20% CPU time when 18bytes UDP datagrams are transmitted at
2550  * 1.48Mpps.  The performance improvement by hardware registers writing
2551  * aggeregation is also mentioned by Luigi Rizzo's netmap paper
2552  * (http://info.iet.unipi.it/~luigi/netmap/).
2553  *
2554  * IFSUBQ packets staging is performed for two entry points into drivers's
2555  * transmission function:
2556  * - Direct ifnet's if_start calling, i.e. ifsq_ifstart_try()
2557  * - ifnet's if_start scheduling, i.e. ifsq_ifstart_schedule()
2558  *
2559  * IFSUBQ packets staging will be stopped upon any of the following conditions:
2560  * - If the count of packets enqueued on the current CPU is great than or
2561  *   equal to ifsq_stage_cntmax. (XXX this should be per-interface)
2562  * - If the total length of packets enqueued on the current CPU is great
2563  *   than or equal to the hardware's MTU - max_protohdr.  max_protohdr is
2564  *   cut from the hardware's MTU mainly bacause a full TCP segment's size
2565  *   is usually less than hardware's MTU.
2566  * - ifsq_ifstart_schedule() is not pending on the current CPU and if_start
2567  *   interlock (if_snd.altq_started) is not released.
2568  * - The if_start_rollup(), which is registered as low priority netisr
2569  *   rollup function, is called; probably because no more work is pending
2570  *   for netisr.
2571  *
2572  * NOTE:
2573  * Currently IFSUBQ packet staging is only performed in netisr threads.
2574  */
2575 int
2576 ifq_dispatch(struct ifnet *ifp, struct mbuf *m, struct altq_pktattr *pa)
2577 {
2578         struct ifaltq *ifq = &ifp->if_snd;
2579         struct ifaltq_subque *ifsq;
2580         int error, start = 0, len, mcast = 0, avoid_start = 0;
2581         struct ifsubq_stage_head *head = NULL;
2582         struct ifsubq_stage *stage = NULL;
2583         int qid = 0; /* XXX */
2584
2585         /* TODO find qid here */
2586         ifsq = &ifq->altq_subq[qid];
2587
2588         ASSERT_IFNET_NOT_SERIALIZED_TX(ifp, ifsq);
2589
2590         len = m->m_pkthdr.len;
2591         if (m->m_flags & M_MCAST)
2592                 mcast = 1;
2593
2594         if (curthread->td_type == TD_TYPE_NETISR) {
2595                 head = &ifsubq_stage_heads[mycpuid];
2596                 stage = ifsq_get_stage(ifsq, mycpuid);
2597
2598                 stage->stg_cnt++;
2599                 stage->stg_len += len;
2600                 if (stage->stg_cnt < ifsq_stage_cntmax &&
2601                     stage->stg_len < (ifp->if_mtu - max_protohdr))
2602                         avoid_start = 1;
2603         }
2604
2605         ALTQ_SQ_LOCK(ifsq);
2606         error = ifsq_enqueue_locked(ifsq, m, pa);
2607         if (error) {
2608                 if (!ifsq_data_ready(ifsq)) {
2609                         ALTQ_SQ_UNLOCK(ifsq);
2610                         return error;
2611                 }
2612                 avoid_start = 0;
2613         }
2614         if (!ifsq_is_started(ifsq)) {
2615                 if (avoid_start) {
2616                         ALTQ_SQ_UNLOCK(ifsq);
2617
2618                         KKASSERT(!error);
2619                         if ((stage->stg_flags & IFSQ_STAGE_FLAG_QUED) == 0)
2620                                 ifsq_stage_insert(head, stage);
2621
2622                         ifp->if_obytes += len;
2623                         if (mcast)
2624                                 ifp->if_omcasts++;
2625                         return error;
2626                 }
2627
2628                 /*
2629                  * Hold the interlock of ifnet.if_start
2630                  */
2631                 ifsq_set_started(ifsq);
2632                 start = 1;
2633         }
2634         ALTQ_SQ_UNLOCK(ifsq);
2635
2636         if (!error) {
2637                 ifp->if_obytes += len;
2638                 if (mcast)
2639                         ifp->if_omcasts++;
2640         }
2641
2642         if (stage != NULL) {
2643                 if (!start && (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)) {
2644                         KKASSERT(stage->stg_flags & IFSQ_STAGE_FLAG_QUED);
2645                         if (!avoid_start) {
2646                                 ifsq_stage_remove(head, stage);
2647                                 ifsq_ifstart_schedule(ifsq, 1);
2648                         }
2649                         return error;
2650                 }
2651
2652                 if (stage->stg_flags & IFSQ_STAGE_FLAG_QUED) {
2653                         ifsq_stage_remove(head, stage);
2654                 } else {
2655                         stage->stg_cnt = 0;
2656                         stage->stg_len = 0;
2657                 }
2658         }
2659
2660         if (!start)
2661                 return error;
2662
2663         ifsq_ifstart_try(ifsq, 0);
2664         return error;
2665 }
2666
2667 void *
2668 ifa_create(int size, int flags)
2669 {
2670         struct ifaddr *ifa;
2671         int i;
2672
2673         KASSERT(size >= sizeof(*ifa), ("ifaddr size too small"));
2674
2675         ifa = kmalloc(size, M_IFADDR, flags | M_ZERO);
2676         if (ifa == NULL)
2677                 return NULL;
2678
2679         ifa->ifa_containers = kmalloc(ncpus * sizeof(struct ifaddr_container),
2680                                       M_IFADDR, M_WAITOK | M_ZERO);
2681         ifa->ifa_ncnt = ncpus;
2682         for (i = 0; i < ncpus; ++i) {
2683                 struct ifaddr_container *ifac = &ifa->ifa_containers[i];
2684
2685                 ifac->ifa_magic = IFA_CONTAINER_MAGIC;
2686                 ifac->ifa = ifa;
2687                 ifac->ifa_refcnt = 1;
2688         }
2689 #ifdef IFADDR_DEBUG
2690         kprintf("alloc ifa %p %d\n", ifa, size);
2691 #endif
2692         return ifa;
2693 }
2694
2695 void
2696 ifac_free(struct ifaddr_container *ifac, int cpu_id)
2697 {
2698         struct ifaddr *ifa = ifac->ifa;
2699
2700         KKASSERT(ifac->ifa_magic == IFA_CONTAINER_MAGIC);
2701         KKASSERT(ifac->ifa_refcnt == 0);
2702         KASSERT(ifac->ifa_listmask == 0,
2703                 ("ifa is still on %#x lists", ifac->ifa_listmask));
2704
2705         ifac->ifa_magic = IFA_CONTAINER_DEAD;
2706
2707 #ifdef IFADDR_DEBUG_VERBOSE
2708         kprintf("try free ifa %p cpu_id %d\n", ifac->ifa, cpu_id);
2709 #endif
2710
2711         KASSERT(ifa->ifa_ncnt > 0 && ifa->ifa_ncnt <= ncpus,
2712                 ("invalid # of ifac, %d", ifa->ifa_ncnt));
2713         if (atomic_fetchadd_int(&ifa->ifa_ncnt, -1) == 1) {
2714 #ifdef IFADDR_DEBUG
2715                 kprintf("free ifa %p\n", ifa);
2716 #endif
2717                 kfree(ifa->ifa_containers, M_IFADDR);
2718                 kfree(ifa, M_IFADDR);
2719         }
2720 }
2721
2722 static void
2723 ifa_iflink_dispatch(netmsg_t nmsg)
2724 {
2725         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2726         struct ifaddr *ifa = msg->ifa;
2727         struct ifnet *ifp = msg->ifp;
2728         int cpu = mycpuid;
2729         struct ifaddr_container *ifac;
2730
2731         crit_enter();
2732
2733         ifac = &ifa->ifa_containers[cpu];
2734         ASSERT_IFAC_VALID(ifac);
2735         KASSERT((ifac->ifa_listmask & IFA_LIST_IFADDRHEAD) == 0,
2736                 ("ifaddr is on if_addrheads"));
2737
2738         ifac->ifa_listmask |= IFA_LIST_IFADDRHEAD;
2739         if (msg->tail)
2740                 TAILQ_INSERT_TAIL(&ifp->if_addrheads[cpu], ifac, ifa_link);
2741         else
2742                 TAILQ_INSERT_HEAD(&ifp->if_addrheads[cpu], ifac, ifa_link);
2743
2744         crit_exit();
2745
2746         ifa_forwardmsg(&nmsg->lmsg, cpu + 1);
2747 }
2748
2749 void
2750 ifa_iflink(struct ifaddr *ifa, struct ifnet *ifp, int tail)
2751 {
2752         struct netmsg_ifaddr msg;
2753
2754         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2755                     0, ifa_iflink_dispatch);
2756         msg.ifa = ifa;
2757         msg.ifp = ifp;
2758         msg.tail = tail;
2759
2760         ifa_domsg(&msg.base.lmsg, 0);
2761 }
2762
2763 static void
2764 ifa_ifunlink_dispatch(netmsg_t nmsg)
2765 {
2766         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2767         struct ifaddr *ifa = msg->ifa;
2768         struct ifnet *ifp = msg->ifp;
2769         int cpu = mycpuid;
2770         struct ifaddr_container *ifac;
2771
2772         crit_enter();
2773
2774         ifac = &ifa->ifa_containers[cpu];
2775         ASSERT_IFAC_VALID(ifac);
2776         KASSERT(ifac->ifa_listmask & IFA_LIST_IFADDRHEAD,
2777                 ("ifaddr is not on if_addrhead"));
2778
2779         TAILQ_REMOVE(&ifp->if_addrheads[cpu], ifac, ifa_link);
2780         ifac->ifa_listmask &= ~IFA_LIST_IFADDRHEAD;
2781
2782         crit_exit();
2783
2784         ifa_forwardmsg(&nmsg->lmsg, cpu + 1);
2785 }
2786
2787 void
2788 ifa_ifunlink(struct ifaddr *ifa, struct ifnet *ifp)
2789 {
2790         struct netmsg_ifaddr msg;
2791
2792         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2793                     0, ifa_ifunlink_dispatch);
2794         msg.ifa = ifa;
2795         msg.ifp = ifp;
2796
2797         ifa_domsg(&msg.base.lmsg, 0);
2798 }
2799
2800 static void
2801 ifa_destroy_dispatch(netmsg_t nmsg)
2802 {
2803         struct netmsg_ifaddr *msg = (struct netmsg_ifaddr *)nmsg;
2804
2805         IFAFREE(msg->ifa);
2806         ifa_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2807 }
2808
2809 void
2810 ifa_destroy(struct ifaddr *ifa)
2811 {
2812         struct netmsg_ifaddr msg;
2813
2814         netmsg_init(&msg.base, NULL, &curthread->td_msgport,
2815                     0, ifa_destroy_dispatch);
2816         msg.ifa = ifa;
2817
2818         ifa_domsg(&msg.base.lmsg, 0);
2819 }
2820
2821 struct lwkt_port *
2822 ifnet_portfn(int cpu)
2823 {
2824         return &ifnet_threads[cpu].td_msgport;
2825 }
2826
2827 void
2828 ifnet_forwardmsg(struct lwkt_msg *lmsg, int next_cpu)
2829 {
2830         KKASSERT(next_cpu > mycpuid && next_cpu <= ncpus);
2831
2832         if (next_cpu < ncpus)
2833                 lwkt_forwardmsg(ifnet_portfn(next_cpu), lmsg);
2834         else
2835                 lwkt_replymsg(lmsg, 0);
2836 }
2837
2838 int
2839 ifnet_domsg(struct lwkt_msg *lmsg, int cpu)
2840 {
2841         KKASSERT(cpu < ncpus);
2842         return lwkt_domsg(ifnet_portfn(cpu), lmsg, 0);
2843 }
2844
2845 void
2846 ifnet_sendmsg(struct lwkt_msg *lmsg, int cpu)
2847 {
2848         KKASSERT(cpu < ncpus);
2849         lwkt_sendmsg(ifnet_portfn(cpu), lmsg);
2850 }
2851
2852 /*
2853  * Generic netmsg service loop.  Some protocols may roll their own but all
2854  * must do the basic command dispatch function call done here.
2855  */
2856 static void
2857 ifnet_service_loop(void *arg __unused)
2858 {
2859         netmsg_t msg;
2860
2861         while ((msg = lwkt_waitport(&curthread->td_msgport, 0))) {
2862                 KASSERT(msg->base.nm_dispatch, ("ifnet_service: badmsg"));
2863                 msg->base.nm_dispatch(msg);
2864         }
2865 }
2866
2867 static void
2868 if_start_rollup(void)
2869 {
2870         struct ifsubq_stage_head *head = &ifsubq_stage_heads[mycpuid];
2871         struct ifsubq_stage *stage;
2872
2873         while ((stage = TAILQ_FIRST(&head->stg_head)) != NULL) {
2874                 struct ifaltq_subque *ifsq = stage->stg_subq;
2875                 int is_sched = 0;
2876
2877                 if (stage->stg_flags & IFSQ_STAGE_FLAG_SCHED)
2878                         is_sched = 1;
2879                 ifsq_stage_remove(head, stage);
2880
2881                 if (is_sched) {
2882                         ifsq_ifstart_schedule(ifsq, 1);
2883                 } else {
2884                         int start = 0;
2885
2886                         ALTQ_SQ_LOCK(ifsq);
2887                         if (!ifsq_is_started(ifsq)) {
2888                                 /*
2889                                  * Hold the interlock of ifnet.if_start
2890                                  */
2891                                 ifsq_set_started(ifsq);
2892                                 start = 1;
2893                         }
2894                         ALTQ_SQ_UNLOCK(ifsq);
2895
2896                         if (start)
2897                                 ifsq_ifstart_try(ifsq, 1);
2898                 }
2899                 KKASSERT((stage->stg_flags &
2900                     (IFSQ_STAGE_FLAG_QUED | IFSQ_STAGE_FLAG_SCHED)) == 0);
2901         }
2902 }
2903
2904 static void
2905 ifnetinit(void *dummy __unused)
2906 {
2907         int i;
2908
2909         for (i = 0; i < ncpus; ++i) {
2910                 struct thread *thr = &ifnet_threads[i];
2911
2912                 lwkt_create(ifnet_service_loop, NULL, NULL,
2913                             thr, TDF_NOSTART|TDF_FORCE_SPINPORT,
2914                             i, "ifnet %d", i);
2915                 netmsg_service_port_init(&thr->td_msgport);
2916                 lwkt_schedule(thr);
2917         }
2918
2919         for (i = 0; i < ncpus; ++i)
2920                 TAILQ_INIT(&ifsubq_stage_heads[i].stg_head);
2921         netisr_register_rollup(if_start_rollup, NETISR_ROLLUP_PRIO_IFSTART);
2922 }
2923
2924 struct ifnet *
2925 ifnet_byindex(unsigned short idx)
2926 {
2927         if (idx > if_index)
2928                 return NULL;
2929         return ifindex2ifnet[idx];
2930 }
2931
2932 struct ifaddr *
2933 ifaddr_byindex(unsigned short idx)
2934 {
2935         struct ifnet *ifp;
2936
2937         ifp = ifnet_byindex(idx);
2938         if (!ifp)
2939                 return NULL;
2940         return TAILQ_FIRST(&ifp->if_addrheads[mycpuid])->ifa;
2941 }
2942
2943 void
2944 if_register_com_alloc(u_char type,
2945     if_com_alloc_t *a, if_com_free_t *f)
2946 {
2947
2948         KASSERT(if_com_alloc[type] == NULL,
2949             ("if_register_com_alloc: %d already registered", type));
2950         KASSERT(if_com_free[type] == NULL,
2951             ("if_register_com_alloc: %d free already registered", type));
2952
2953         if_com_alloc[type] = a;
2954         if_com_free[type] = f;
2955 }
2956
2957 void
2958 if_deregister_com_alloc(u_char type)
2959 {
2960
2961         KASSERT(if_com_alloc[type] != NULL,
2962             ("if_deregister_com_alloc: %d not registered", type));
2963         KASSERT(if_com_free[type] != NULL,
2964             ("if_deregister_com_alloc: %d free not registered", type));
2965         if_com_alloc[type] = NULL;
2966         if_com_free[type] = NULL;
2967 }
2968
2969 int
2970 if_ring_count2(int cnt, int cnt_max)
2971 {
2972         int shift = 0;
2973
2974         KASSERT(cnt_max >= 1 && powerof2(cnt_max),
2975             ("invalid ring count max %d", cnt_max));
2976
2977         if (cnt <= 0)
2978                 cnt = cnt_max;
2979         if (cnt > ncpus2)
2980                 cnt = ncpus2;
2981         if (cnt > cnt_max)
2982                 cnt = cnt_max;
2983
2984         while ((1 << (shift + 1)) <= cnt)
2985                 ++shift;
2986         cnt = 1 << shift;
2987
2988         KASSERT(cnt >= 1 && cnt <= ncpus2 && cnt <= cnt_max,
2989             ("calculate cnt %d, ncpus2 %d, cnt max %d",
2990              cnt, ncpus2, cnt_max));
2991         return cnt;
2992 }
2993
2994 void
2995 ifq_set_maxlen(struct ifaltq *ifq, int len)
2996 {
2997         ifq->altq_maxlen = len + (ncpus * ifsq_stage_cntmax);
2998 }