if.c revision 1.475 1 /* $NetBSD: if.c,v 1.475 2020/05/05 08:05:03 jdolecek Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2000, 2001, 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by William Studenmund and Jason R. Thorpe.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the project nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 */
60
61 /*
62 * Copyright (c) 1980, 1986, 1993
63 * The Regents of the University of California. All rights reserved.
64 *
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
67 * are met:
68 * 1. Redistributions of source code must retain the above copyright
69 * notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 * notice, this list of conditions and the following disclaimer in the
72 * documentation and/or other materials provided with the distribution.
73 * 3. Neither the name of the University nor the names of its contributors
74 * may be used to endorse or promote products derived from this software
75 * without specific prior written permission.
76 *
77 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
78 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
81 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87 * SUCH DAMAGE.
88 *
89 * @(#)if.c 8.5 (Berkeley) 1/9/95
90 */
91
92 #include <sys/cdefs.h>
93 __KERNEL_RCSID(0, "$NetBSD: if.c,v 1.475 2020/05/05 08:05:03 jdolecek Exp $");
94
95 #if defined(_KERNEL_OPT)
96 #include "opt_inet.h"
97 #include "opt_ipsec.h"
98 #include "opt_atalk.h"
99 #include "opt_wlan.h"
100 #include "opt_net_mpsafe.h"
101 #include "opt_mrouting.h"
102 #endif
103
104 #include <sys/param.h>
105 #include <sys/mbuf.h>
106 #include <sys/systm.h>
107 #include <sys/callout.h>
108 #include <sys/proc.h>
109 #include <sys/socket.h>
110 #include <sys/socketvar.h>
111 #include <sys/domain.h>
112 #include <sys/protosw.h>
113 #include <sys/kernel.h>
114 #include <sys/ioctl.h>
115 #include <sys/sysctl.h>
116 #include <sys/syslog.h>
117 #include <sys/kauth.h>
118 #include <sys/kmem.h>
119 #include <sys/xcall.h>
120 #include <sys/cpu.h>
121 #include <sys/intr.h>
122 #include <sys/module_hook.h>
123 #include <sys/compat_stub.h>
124 #include <sys/msan.h>
125
126 #include <net/if.h>
127 #include <net/if_dl.h>
128 #include <net/if_ether.h>
129 #include <net/if_media.h>
130 #include <net80211/ieee80211.h>
131 #include <net80211/ieee80211_ioctl.h>
132 #include <net/if_types.h>
133 #include <net/route.h>
134 #include <net/netisr.h>
135 #include <sys/module.h>
136 #ifdef NETATALK
137 #include <netatalk/at_extern.h>
138 #include <netatalk/at.h>
139 #endif
140 #include <net/pfil.h>
141 #include <netinet/in.h>
142 #include <netinet/in_var.h>
143 #include <netinet/ip_encap.h>
144 #include <net/bpf.h>
145
146 #ifdef INET6
147 #include <netinet6/in6_var.h>
148 #include <netinet6/nd6.h>
149 #endif
150
151 #include "ether.h"
152
153 #include "bridge.h"
154 #if NBRIDGE > 0
155 #include <net/if_bridgevar.h>
156 #endif
157
158 #include "carp.h"
159 #if NCARP > 0
160 #include <netinet/ip_carp.h>
161 #endif
162
163 #include <compat/sys/sockio.h>
164
165 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
166 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
167
168 /*
169 * Global list of interfaces.
170 */
171 /* DEPRECATED. Remove it once kvm(3) users disappeared */
172 struct ifnet_head ifnet_list;
173
174 struct pslist_head ifnet_pslist;
175 static ifnet_t ** ifindex2ifnet = NULL;
176 static u_int if_index = 1;
177 static size_t if_indexlim = 0;
178 static uint64_t index_gen;
179 /* Mutex to protect the above objects. */
180 kmutex_t ifnet_mtx __cacheline_aligned;
181 static struct psref_class *ifnet_psref_class __read_mostly;
182 static pserialize_t ifnet_psz;
183 static struct workqueue *ifnet_link_state_wq __read_mostly;
184
185 static kmutex_t if_clone_mtx;
186
187 struct ifnet *lo0ifp;
188 int ifqmaxlen = IFQ_MAXLEN;
189
190 struct psref_class *ifa_psref_class __read_mostly;
191
192 static int if_delroute_matcher(struct rtentry *, void *);
193
194 static bool if_is_unit(const char *);
195 static struct if_clone *if_clone_lookup(const char *, int *);
196
197 static LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
198 static int if_cloners_count;
199
200 /* Packet filtering hook for interfaces. */
201 pfil_head_t * if_pfil __read_mostly;
202
203 static kauth_listener_t if_listener;
204
205 static int doifioctl(struct socket *, u_long, void *, struct lwp *);
206 static void if_detach_queues(struct ifnet *, struct ifqueue *);
207 static void sysctl_sndq_setup(struct sysctllog **, const char *,
208 struct ifaltq *);
209 static void if_slowtimo(void *);
210 static void if_attachdomain1(struct ifnet *);
211 static int ifconf(u_long, void *);
212 static int if_transmit(struct ifnet *, struct mbuf *);
213 static int if_clone_create(const char *);
214 static int if_clone_destroy(const char *);
215 static void if_link_state_change_work(struct work *, void *);
216 static void if_up_locked(struct ifnet *);
217 static void _if_down(struct ifnet *);
218 static void if_down_deactivated(struct ifnet *);
219
220 struct if_percpuq {
221 struct ifnet *ipq_ifp;
222 void *ipq_si;
223 struct percpu *ipq_ifqs; /* struct ifqueue */
224 };
225
226 static struct mbuf *if_percpuq_dequeue(struct if_percpuq *);
227
228 static void if_percpuq_drops(void *, void *, struct cpu_info *);
229 static int sysctl_percpuq_drops_handler(SYSCTLFN_PROTO);
230 static void sysctl_percpuq_setup(struct sysctllog **, const char *,
231 struct if_percpuq *);
232
233 struct if_deferred_start {
234 struct ifnet *ids_ifp;
235 void (*ids_if_start)(struct ifnet *);
236 void *ids_si;
237 };
238
239 static void if_deferred_start_softint(void *);
240 static void if_deferred_start_common(struct ifnet *);
241 static void if_deferred_start_destroy(struct ifnet *);
242
243 #if defined(INET) || defined(INET6)
244 static void sysctl_net_pktq_setup(struct sysctllog **, int);
245 #endif
246
247 /*
248 * Hook for if_vlan - needed by if_agr
249 */
250 struct if_vlan_vlan_input_hook_t if_vlan_vlan_input_hook;
251
252 static void if_sysctl_setup(struct sysctllog **);
253
254 static int
255 if_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
256 void *arg0, void *arg1, void *arg2, void *arg3)
257 {
258 int result;
259 enum kauth_network_req req;
260
261 result = KAUTH_RESULT_DEFER;
262 req = (enum kauth_network_req)(uintptr_t)arg1;
263
264 if (action != KAUTH_NETWORK_INTERFACE)
265 return result;
266
267 if ((req == KAUTH_REQ_NETWORK_INTERFACE_GET) ||
268 (req == KAUTH_REQ_NETWORK_INTERFACE_SET))
269 result = KAUTH_RESULT_ALLOW;
270
271 return result;
272 }
273
274 /*
275 * Network interface utility routines.
276 *
277 * Routines with ifa_ifwith* names take sockaddr *'s as
278 * parameters.
279 */
280 void
281 ifinit(void)
282 {
283
284 #if (defined(INET) || defined(INET6))
285 encapinit();
286 #endif
287
288 if_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
289 if_listener_cb, NULL);
290
291 /* interfaces are available, inform socket code */
292 ifioctl = doifioctl;
293 }
294
295 /*
296 * XXX Initialization before configure().
297 * XXX hack to get pfil_add_hook working in autoconf.
298 */
299 void
300 ifinit1(void)
301 {
302 int error __diagused;
303
304 #ifdef NET_MPSAFE
305 printf("NET_MPSAFE enabled\n");
306 #endif
307
308 mutex_init(&if_clone_mtx, MUTEX_DEFAULT, IPL_NONE);
309
310 TAILQ_INIT(&ifnet_list);
311 mutex_init(&ifnet_mtx, MUTEX_DEFAULT, IPL_NONE);
312 ifnet_psz = pserialize_create();
313 ifnet_psref_class = psref_class_create("ifnet", IPL_SOFTNET);
314 ifa_psref_class = psref_class_create("ifa", IPL_SOFTNET);
315 error = workqueue_create(&ifnet_link_state_wq, "iflnkst",
316 if_link_state_change_work, NULL, PRI_SOFTNET, IPL_NET,
317 WQ_MPSAFE);
318 KASSERT(error == 0);
319 PSLIST_INIT(&ifnet_pslist);
320
321 if_indexlim = 8;
322
323 if_pfil = pfil_head_create(PFIL_TYPE_IFNET, NULL);
324 KASSERT(if_pfil != NULL);
325
326 #if NETHER > 0 || defined(NETATALK) || defined(WLAN)
327 etherinit();
328 #endif
329 }
330
331 /* XXX must be after domaininit() */
332 void
333 ifinit_post(void)
334 {
335
336 if_sysctl_setup(NULL);
337 }
338
339 ifnet_t *
340 if_alloc(u_char type)
341 {
342 return kmem_zalloc(sizeof(ifnet_t), KM_SLEEP);
343 }
344
345 void
346 if_free(ifnet_t *ifp)
347 {
348 kmem_free(ifp, sizeof(ifnet_t));
349 }
350
351 void
352 if_initname(struct ifnet *ifp, const char *name, int unit)
353 {
354 (void)snprintf(ifp->if_xname, sizeof(ifp->if_xname),
355 "%s%d", name, unit);
356 }
357
358 /*
359 * Null routines used while an interface is going away. These routines
360 * just return an error.
361 */
362
363 int
364 if_nulloutput(struct ifnet *ifp, struct mbuf *m,
365 const struct sockaddr *so, const struct rtentry *rt)
366 {
367
368 return ENXIO;
369 }
370
371 void
372 if_nullinput(struct ifnet *ifp, struct mbuf *m)
373 {
374
375 /* Nothing. */
376 }
377
378 void
379 if_nullstart(struct ifnet *ifp)
380 {
381
382 /* Nothing. */
383 }
384
385 int
386 if_nulltransmit(struct ifnet *ifp, struct mbuf *m)
387 {
388
389 m_freem(m);
390 return ENXIO;
391 }
392
393 int
394 if_nullioctl(struct ifnet *ifp, u_long cmd, void *data)
395 {
396
397 return ENXIO;
398 }
399
400 int
401 if_nullinit(struct ifnet *ifp)
402 {
403
404 return ENXIO;
405 }
406
407 void
408 if_nullstop(struct ifnet *ifp, int disable)
409 {
410
411 /* Nothing. */
412 }
413
414 void
415 if_nullslowtimo(struct ifnet *ifp)
416 {
417
418 /* Nothing. */
419 }
420
421 void
422 if_nulldrain(struct ifnet *ifp)
423 {
424
425 /* Nothing. */
426 }
427
428 void
429 if_set_sadl(struct ifnet *ifp, const void *lla, u_char addrlen, bool factory)
430 {
431 struct ifaddr *ifa;
432 struct sockaddr_dl *sdl;
433
434 ifp->if_addrlen = addrlen;
435 if_alloc_sadl(ifp);
436 ifa = ifp->if_dl;
437 sdl = satosdl(ifa->ifa_addr);
438
439 (void)sockaddr_dl_setaddr(sdl, sdl->sdl_len, lla, ifp->if_addrlen);
440 if (factory) {
441 KASSERT(ifp->if_hwdl == NULL);
442 ifp->if_hwdl = ifp->if_dl;
443 ifaref(ifp->if_hwdl);
444 }
445 /* TBD routing socket */
446 }
447
448 struct ifaddr *
449 if_dl_create(const struct ifnet *ifp, const struct sockaddr_dl **sdlp)
450 {
451 unsigned socksize, ifasize;
452 int addrlen, namelen;
453 struct sockaddr_dl *mask, *sdl;
454 struct ifaddr *ifa;
455
456 namelen = strlen(ifp->if_xname);
457 addrlen = ifp->if_addrlen;
458 socksize = roundup(sockaddr_dl_measure(namelen, addrlen), sizeof(long));
459 ifasize = sizeof(*ifa) + 2 * socksize;
460 ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
461
462 sdl = (struct sockaddr_dl *)(ifa + 1);
463 mask = (struct sockaddr_dl *)(socksize + (char *)sdl);
464
465 sockaddr_dl_init(sdl, socksize, ifp->if_index, ifp->if_type,
466 ifp->if_xname, namelen, NULL, addrlen);
467 mask->sdl_family = AF_LINK;
468 mask->sdl_len = sockaddr_dl_measure(namelen, 0);
469 memset(&mask->sdl_data[0], 0xff, namelen);
470 ifa->ifa_rtrequest = link_rtrequest;
471 ifa->ifa_addr = (struct sockaddr *)sdl;
472 ifa->ifa_netmask = (struct sockaddr *)mask;
473 ifa_psref_init(ifa);
474
475 *sdlp = sdl;
476
477 return ifa;
478 }
479
480 static void
481 if_sadl_setrefs(struct ifnet *ifp, struct ifaddr *ifa)
482 {
483 const struct sockaddr_dl *sdl;
484
485 ifp->if_dl = ifa;
486 ifaref(ifa);
487 sdl = satosdl(ifa->ifa_addr);
488 ifp->if_sadl = sdl;
489 }
490
491 /*
492 * Allocate the link level name for the specified interface. This
493 * is an attachment helper. It must be called after ifp->if_addrlen
494 * is initialized, which may not be the case when if_attach() is
495 * called.
496 */
497 void
498 if_alloc_sadl(struct ifnet *ifp)
499 {
500 struct ifaddr *ifa;
501 const struct sockaddr_dl *sdl;
502
503 /*
504 * If the interface already has a link name, release it
505 * now. This is useful for interfaces that can change
506 * link types, and thus switch link names often.
507 */
508 if (ifp->if_sadl != NULL)
509 if_free_sadl(ifp, 0);
510
511 ifa = if_dl_create(ifp, &sdl);
512
513 ifa_insert(ifp, ifa);
514 if_sadl_setrefs(ifp, ifa);
515 }
516
517 static void
518 if_deactivate_sadl(struct ifnet *ifp)
519 {
520 struct ifaddr *ifa;
521
522 KASSERT(ifp->if_dl != NULL);
523
524 ifa = ifp->if_dl;
525
526 ifp->if_sadl = NULL;
527
528 ifp->if_dl = NULL;
529 ifafree(ifa);
530 }
531
532 static void
533 if_replace_sadl(struct ifnet *ifp, struct ifaddr *ifa)
534 {
535 struct ifaddr *old;
536
537 KASSERT(ifp->if_dl != NULL);
538
539 old = ifp->if_dl;
540
541 ifaref(ifa);
542 /* XXX Update if_dl and if_sadl atomically */
543 ifp->if_dl = ifa;
544 ifp->if_sadl = satosdl(ifa->ifa_addr);
545
546 ifafree(old);
547 }
548
549 void
550 if_activate_sadl(struct ifnet *ifp, struct ifaddr *ifa0,
551 const struct sockaddr_dl *sdl)
552 {
553 int s, ss;
554 struct ifaddr *ifa;
555 int bound = curlwp_bind();
556
557 KASSERT(ifa_held(ifa0));
558
559 s = splsoftnet();
560
561 if_replace_sadl(ifp, ifa0);
562
563 ss = pserialize_read_enter();
564 IFADDR_READER_FOREACH(ifa, ifp) {
565 struct psref psref;
566 ifa_acquire(ifa, &psref);
567 pserialize_read_exit(ss);
568
569 rtinit(ifa, RTM_LLINFO_UPD, 0);
570
571 ss = pserialize_read_enter();
572 ifa_release(ifa, &psref);
573 }
574 pserialize_read_exit(ss);
575
576 splx(s);
577 curlwp_bindx(bound);
578 }
579
580 /*
581 * Free the link level name for the specified interface. This is
582 * a detach helper. This is called from if_detach().
583 */
584 void
585 if_free_sadl(struct ifnet *ifp, int factory)
586 {
587 struct ifaddr *ifa;
588 int s;
589
590 if (factory && ifp->if_hwdl != NULL) {
591 ifa = ifp->if_hwdl;
592 ifp->if_hwdl = NULL;
593 ifafree(ifa);
594 }
595
596 ifa = ifp->if_dl;
597 if (ifa == NULL) {
598 KASSERT(ifp->if_sadl == NULL);
599 return;
600 }
601
602 KASSERT(ifp->if_sadl != NULL);
603
604 s = splsoftnet();
605 KASSERT(ifa->ifa_addr->sa_family == AF_LINK);
606 ifa_remove(ifp, ifa);
607 if_deactivate_sadl(ifp);
608 splx(s);
609 }
610
611 static void
612 if_getindex(ifnet_t *ifp)
613 {
614 bool hitlimit = false;
615
616 ifp->if_index_gen = index_gen++;
617
618 ifp->if_index = if_index;
619 if (ifindex2ifnet == NULL) {
620 if_index++;
621 goto skip;
622 }
623 while (if_byindex(ifp->if_index)) {
624 /*
625 * If we hit USHRT_MAX, we skip back to 0 since
626 * there are a number of places where the value
627 * of if_index or if_index itself is compared
628 * to or stored in an unsigned short. By
629 * jumping back, we won't botch those assignments
630 * or comparisons.
631 */
632 if (++if_index == 0) {
633 if_index = 1;
634 } else if (if_index == USHRT_MAX) {
635 /*
636 * However, if we have to jump back to
637 * zero *twice* without finding an empty
638 * slot in ifindex2ifnet[], then there
639 * there are too many (>65535) interfaces.
640 */
641 if (hitlimit) {
642 panic("too many interfaces");
643 }
644 hitlimit = true;
645 if_index = 1;
646 }
647 ifp->if_index = if_index;
648 }
649 skip:
650 /*
651 * ifindex2ifnet is indexed by if_index. Since if_index will
652 * grow dynamically, it should grow too.
653 */
654 if (ifindex2ifnet == NULL || ifp->if_index >= if_indexlim) {
655 size_t m, n, oldlim;
656 void *q;
657
658 oldlim = if_indexlim;
659 while (ifp->if_index >= if_indexlim)
660 if_indexlim <<= 1;
661
662 /* grow ifindex2ifnet */
663 m = oldlim * sizeof(struct ifnet *);
664 n = if_indexlim * sizeof(struct ifnet *);
665 q = malloc(n, M_IFADDR, M_WAITOK | M_ZERO);
666 if (ifindex2ifnet != NULL) {
667 memcpy(q, ifindex2ifnet, m);
668 free(ifindex2ifnet, M_IFADDR);
669 }
670 ifindex2ifnet = (struct ifnet **)q;
671 }
672 ifindex2ifnet[ifp->if_index] = ifp;
673 }
674
675 /*
676 * Initialize an interface and assign an index for it.
677 *
678 * It must be called prior to a device specific attach routine
679 * (e.g., ether_ifattach and ieee80211_ifattach) or if_alloc_sadl,
680 * and be followed by if_register:
681 *
682 * if_initialize(ifp);
683 * ether_ifattach(ifp, enaddr);
684 * if_register(ifp);
685 */
686 int
687 if_initialize(ifnet_t *ifp)
688 {
689 int rv = 0;
690
691 KASSERT(if_indexlim > 0);
692 TAILQ_INIT(&ifp->if_addrlist);
693
694 /*
695 * Link level name is allocated later by a separate call to
696 * if_alloc_sadl().
697 */
698
699 if (ifp->if_snd.ifq_maxlen == 0)
700 ifp->if_snd.ifq_maxlen = ifqmaxlen;
701
702 ifp->if_broadcastaddr = 0; /* reliably crash if used uninitialized */
703
704 ifp->if_link_state = LINK_STATE_UNKNOWN;
705 ifp->if_link_queue = -1; /* all bits set, see link_state_change() */
706
707 ifp->if_capenable = 0;
708 ifp->if_csum_flags_tx = 0;
709 ifp->if_csum_flags_rx = 0;
710
711 #ifdef ALTQ
712 ifp->if_snd.altq_type = 0;
713 ifp->if_snd.altq_disc = NULL;
714 ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
715 ifp->if_snd.altq_tbr = NULL;
716 ifp->if_snd.altq_ifp = ifp;
717 #endif
718
719 IFQ_LOCK_INIT(&ifp->if_snd);
720
721 ifp->if_pfil = pfil_head_create(PFIL_TYPE_IFNET, ifp);
722 pfil_run_ifhooks(if_pfil, PFIL_IFNET_ATTACH, ifp);
723
724 IF_AFDATA_LOCK_INIT(ifp);
725
726 PSLIST_ENTRY_INIT(ifp, if_pslist_entry);
727 PSLIST_INIT(&ifp->if_addr_pslist);
728 psref_target_init(&ifp->if_psref, ifnet_psref_class);
729 ifp->if_ioctl_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
730 LIST_INIT(&ifp->if_multiaddrs);
731 if ((rv = if_stats_init(ifp)) != 0) {
732 goto fail;
733 }
734
735 IFNET_GLOBAL_LOCK();
736 if_getindex(ifp);
737 IFNET_GLOBAL_UNLOCK();
738
739 return 0;
740
741 fail:
742 IF_AFDATA_LOCK_DESTROY(ifp);
743
744 pfil_run_ifhooks(if_pfil, PFIL_IFNET_DETACH, ifp);
745 (void)pfil_head_destroy(ifp->if_pfil);
746
747 IFQ_LOCK_DESTROY(&ifp->if_snd);
748
749 return rv;
750 }
751
752 /*
753 * Register an interface to the list of "active" interfaces.
754 */
755 void
756 if_register(ifnet_t *ifp)
757 {
758 /*
759 * If the driver has not supplied its own if_ioctl, then
760 * supply the default.
761 */
762 if (ifp->if_ioctl == NULL)
763 ifp->if_ioctl = ifioctl_common;
764
765 sysctl_sndq_setup(&ifp->if_sysctl_log, ifp->if_xname, &ifp->if_snd);
766
767 if (!STAILQ_EMPTY(&domains))
768 if_attachdomain1(ifp);
769
770 /* Announce the interface. */
771 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
772
773 if (ifp->if_slowtimo != NULL) {
774 ifp->if_slowtimo_ch =
775 kmem_zalloc(sizeof(*ifp->if_slowtimo_ch), KM_SLEEP);
776 callout_init(ifp->if_slowtimo_ch, 0);
777 callout_setfunc(ifp->if_slowtimo_ch, if_slowtimo, ifp);
778 if_slowtimo(ifp);
779 }
780
781 if (ifp->if_transmit == NULL || ifp->if_transmit == if_nulltransmit)
782 ifp->if_transmit = if_transmit;
783
784 IFNET_GLOBAL_LOCK();
785 TAILQ_INSERT_TAIL(&ifnet_list, ifp, if_list);
786 IFNET_WRITER_INSERT_TAIL(ifp);
787 IFNET_GLOBAL_UNLOCK();
788 }
789
790 /*
791 * The if_percpuq framework
792 *
793 * It allows network device drivers to execute the network stack
794 * in softint (so called softint-based if_input). It utilizes
795 * softint and percpu ifqueue. It doesn't distribute any packets
796 * between CPUs, unlike pktqueue(9).
797 *
798 * Currently we support two options for device drivers to apply the framework:
799 * - Use it implicitly with less changes
800 * - If you use if_attach in driver's _attach function and if_input in
801 * driver's Rx interrupt handler, a packet is queued and a softint handles
802 * the packet implicitly
803 * - Use it explicitly in each driver (recommended)
804 * - You can use if_percpuq_* directly in your driver
805 * - In this case, you need to allocate struct if_percpuq in driver's softc
806 * - See wm(4) as a reference implementation
807 */
808
809 static void
810 if_percpuq_softint(void *arg)
811 {
812 struct if_percpuq *ipq = arg;
813 struct ifnet *ifp = ipq->ipq_ifp;
814 struct mbuf *m;
815
816 while ((m = if_percpuq_dequeue(ipq)) != NULL) {
817 if_statinc(ifp, if_ipackets);
818 bpf_mtap(ifp, m, BPF_D_IN);
819
820 ifp->_if_input(ifp, m);
821 }
822 }
823
824 static void
825 if_percpuq_init_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
826 {
827 struct ifqueue *const ifq = p;
828
829 memset(ifq, 0, sizeof(*ifq));
830 ifq->ifq_maxlen = IFQ_MAXLEN;
831 }
832
833 struct if_percpuq *
834 if_percpuq_create(struct ifnet *ifp)
835 {
836 struct if_percpuq *ipq;
837 u_int flags = SOFTINT_NET;
838
839 flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
840
841 ipq = kmem_zalloc(sizeof(*ipq), KM_SLEEP);
842 ipq->ipq_ifp = ifp;
843 ipq->ipq_si = softint_establish(flags, if_percpuq_softint, ipq);
844 ipq->ipq_ifqs = percpu_alloc(sizeof(struct ifqueue));
845 percpu_foreach(ipq->ipq_ifqs, &if_percpuq_init_ifq, NULL);
846
847 sysctl_percpuq_setup(&ifp->if_sysctl_log, ifp->if_xname, ipq);
848
849 return ipq;
850 }
851
852 static struct mbuf *
853 if_percpuq_dequeue(struct if_percpuq *ipq)
854 {
855 struct mbuf *m;
856 struct ifqueue *ifq;
857 int s;
858
859 s = splnet();
860 ifq = percpu_getref(ipq->ipq_ifqs);
861 IF_DEQUEUE(ifq, m);
862 percpu_putref(ipq->ipq_ifqs);
863 splx(s);
864
865 return m;
866 }
867
868 static void
869 if_percpuq_purge_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
870 {
871 struct ifqueue *const ifq = p;
872
873 IF_PURGE(ifq);
874 }
875
876 void
877 if_percpuq_destroy(struct if_percpuq *ipq)
878 {
879
880 /* if_detach may already destroy it */
881 if (ipq == NULL)
882 return;
883
884 softint_disestablish(ipq->ipq_si);
885 percpu_foreach(ipq->ipq_ifqs, &if_percpuq_purge_ifq, NULL);
886 percpu_free(ipq->ipq_ifqs, sizeof(struct ifqueue));
887 kmem_free(ipq, sizeof(*ipq));
888 }
889
890 void
891 if_percpuq_enqueue(struct if_percpuq *ipq, struct mbuf *m)
892 {
893 struct ifqueue *ifq;
894 int s;
895
896 KASSERT(ipq != NULL);
897
898 s = splnet();
899 ifq = percpu_getref(ipq->ipq_ifqs);
900 if (IF_QFULL(ifq)) {
901 IF_DROP(ifq);
902 percpu_putref(ipq->ipq_ifqs);
903 m_freem(m);
904 goto out;
905 }
906 IF_ENQUEUE(ifq, m);
907 percpu_putref(ipq->ipq_ifqs);
908
909 softint_schedule(ipq->ipq_si);
910 out:
911 splx(s);
912 }
913
914 static void
915 if_percpuq_drops(void *p, void *arg, struct cpu_info *ci __unused)
916 {
917 struct ifqueue *const ifq = p;
918 int *sum = arg;
919
920 *sum += ifq->ifq_drops;
921 }
922
923 static int
924 sysctl_percpuq_drops_handler(SYSCTLFN_ARGS)
925 {
926 struct sysctlnode node;
927 struct if_percpuq *ipq;
928 int sum = 0;
929 int error;
930
931 node = *rnode;
932 ipq = node.sysctl_data;
933
934 percpu_foreach(ipq->ipq_ifqs, if_percpuq_drops, &sum);
935
936 node.sysctl_data = ∑
937 error = sysctl_lookup(SYSCTLFN_CALL(&node));
938 if (error != 0 || newp == NULL)
939 return error;
940
941 return 0;
942 }
943
944 static void
945 sysctl_percpuq_setup(struct sysctllog **clog, const char* ifname,
946 struct if_percpuq *ipq)
947 {
948 const struct sysctlnode *cnode, *rnode;
949
950 if (sysctl_createv(clog, 0, NULL, &rnode,
951 CTLFLAG_PERMANENT,
952 CTLTYPE_NODE, "interfaces",
953 SYSCTL_DESCR("Per-interface controls"),
954 NULL, 0, NULL, 0,
955 CTL_NET, CTL_CREATE, CTL_EOL) != 0)
956 goto bad;
957
958 if (sysctl_createv(clog, 0, &rnode, &rnode,
959 CTLFLAG_PERMANENT,
960 CTLTYPE_NODE, ifname,
961 SYSCTL_DESCR("Interface controls"),
962 NULL, 0, NULL, 0,
963 CTL_CREATE, CTL_EOL) != 0)
964 goto bad;
965
966 if (sysctl_createv(clog, 0, &rnode, &rnode,
967 CTLFLAG_PERMANENT,
968 CTLTYPE_NODE, "rcvq",
969 SYSCTL_DESCR("Interface input queue controls"),
970 NULL, 0, NULL, 0,
971 CTL_CREATE, CTL_EOL) != 0)
972 goto bad;
973
974 #ifdef NOTYET
975 /* XXX Should show each per-CPU queue length? */
976 if (sysctl_createv(clog, 0, &rnode, &rnode,
977 CTLFLAG_PERMANENT,
978 CTLTYPE_INT, "len",
979 SYSCTL_DESCR("Current input queue length"),
980 sysctl_percpuq_len, 0, NULL, 0,
981 CTL_CREATE, CTL_EOL) != 0)
982 goto bad;
983
984 if (sysctl_createv(clog, 0, &rnode, &cnode,
985 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
986 CTLTYPE_INT, "maxlen",
987 SYSCTL_DESCR("Maximum allowed input queue length"),
988 sysctl_percpuq_maxlen_handler, 0, (void *)ipq, 0,
989 CTL_CREATE, CTL_EOL) != 0)
990 goto bad;
991 #endif
992
993 if (sysctl_createv(clog, 0, &rnode, &cnode,
994 CTLFLAG_PERMANENT,
995 CTLTYPE_INT, "drops",
996 SYSCTL_DESCR("Total packets dropped due to full input queue"),
997 sysctl_percpuq_drops_handler, 0, (void *)ipq, 0,
998 CTL_CREATE, CTL_EOL) != 0)
999 goto bad;
1000
1001 return;
1002 bad:
1003 printf("%s: could not attach sysctl nodes\n", ifname);
1004 return;
1005 }
1006
1007 /*
1008 * The deferred if_start framework
1009 *
1010 * The common APIs to defer if_start to softint when if_start is requested
1011 * from a device driver running in hardware interrupt context.
1012 */
1013 /*
1014 * Call ifp->if_start (or equivalent) in a dedicated softint for
1015 * deferred if_start.
1016 */
1017 static void
1018 if_deferred_start_softint(void *arg)
1019 {
1020 struct if_deferred_start *ids = arg;
1021 struct ifnet *ifp = ids->ids_ifp;
1022
1023 ids->ids_if_start(ifp);
1024 }
1025
1026 /*
1027 * The default callback function for deferred if_start.
1028 */
1029 static void
1030 if_deferred_start_common(struct ifnet *ifp)
1031 {
1032 int s;
1033
1034 s = splnet();
1035 if_start_lock(ifp);
1036 splx(s);
1037 }
1038
1039 static inline bool
1040 if_snd_is_used(struct ifnet *ifp)
1041 {
1042
1043 return ALTQ_IS_ENABLED(&ifp->if_snd) ||
1044 ifp->if_transmit == if_transmit ||
1045 ifp->if_transmit == NULL || ifp->if_transmit == if_nulltransmit;
1046 }
1047
1048 /*
1049 * Schedule deferred if_start.
1050 */
1051 void
1052 if_schedule_deferred_start(struct ifnet *ifp)
1053 {
1054
1055 KASSERT(ifp->if_deferred_start != NULL);
1056
1057 if (if_snd_is_used(ifp) && IFQ_IS_EMPTY(&ifp->if_snd))
1058 return;
1059
1060 softint_schedule(ifp->if_deferred_start->ids_si);
1061 }
1062
1063 /*
1064 * Create an instance of deferred if_start. A driver should call the function
1065 * only if the driver needs deferred if_start. Drivers can setup their own
1066 * deferred if_start function via 2nd argument.
1067 */
1068 void
1069 if_deferred_start_init(struct ifnet *ifp, void (*func)(struct ifnet *))
1070 {
1071 struct if_deferred_start *ids;
1072 u_int flags = SOFTINT_NET;
1073
1074 flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
1075
1076 ids = kmem_zalloc(sizeof(*ids), KM_SLEEP);
1077 ids->ids_ifp = ifp;
1078 ids->ids_si = softint_establish(flags, if_deferred_start_softint, ids);
1079 if (func != NULL)
1080 ids->ids_if_start = func;
1081 else
1082 ids->ids_if_start = if_deferred_start_common;
1083
1084 ifp->if_deferred_start = ids;
1085 }
1086
1087 static void
1088 if_deferred_start_destroy(struct ifnet *ifp)
1089 {
1090
1091 if (ifp->if_deferred_start == NULL)
1092 return;
1093
1094 softint_disestablish(ifp->if_deferred_start->ids_si);
1095 kmem_free(ifp->if_deferred_start, sizeof(*ifp->if_deferred_start));
1096 ifp->if_deferred_start = NULL;
1097 }
1098
1099 /*
1100 * The common interface input routine that is called by device drivers,
1101 * which should be used only when the driver's rx handler already runs
1102 * in softint.
1103 */
1104 void
1105 if_input(struct ifnet *ifp, struct mbuf *m)
1106 {
1107
1108 KASSERT(ifp->if_percpuq == NULL);
1109 KASSERT(!cpu_intr_p());
1110
1111 if_statinc(ifp, if_ipackets);
1112 bpf_mtap(ifp, m, BPF_D_IN);
1113
1114 ifp->_if_input(ifp, m);
1115 }
1116
1117 /*
1118 * DEPRECATED. Use if_initialize and if_register instead.
1119 * See the above comment of if_initialize.
1120 *
1121 * Note that it implicitly enables if_percpuq to make drivers easy to
1122 * migrate softint-based if_input without much changes. If you don't
1123 * want to enable it, use if_initialize instead.
1124 */
1125 int
1126 if_attach(ifnet_t *ifp)
1127 {
1128 int rv;
1129
1130 rv = if_initialize(ifp);
1131 if (rv != 0)
1132 return rv;
1133
1134 ifp->if_percpuq = if_percpuq_create(ifp);
1135 if_register(ifp);
1136
1137 return 0;
1138 }
1139
1140 void
1141 if_attachdomain(void)
1142 {
1143 struct ifnet *ifp;
1144 int s;
1145 int bound = curlwp_bind();
1146
1147 s = pserialize_read_enter();
1148 IFNET_READER_FOREACH(ifp) {
1149 struct psref psref;
1150 psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
1151 pserialize_read_exit(s);
1152 if_attachdomain1(ifp);
1153 s = pserialize_read_enter();
1154 psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
1155 }
1156 pserialize_read_exit(s);
1157 curlwp_bindx(bound);
1158 }
1159
1160 static void
1161 if_attachdomain1(struct ifnet *ifp)
1162 {
1163 struct domain *dp;
1164 int s;
1165
1166 s = splsoftnet();
1167
1168 /* address family dependent data region */
1169 memset(ifp->if_afdata, 0, sizeof(ifp->if_afdata));
1170 DOMAIN_FOREACH(dp) {
1171 if (dp->dom_ifattach != NULL)
1172 ifp->if_afdata[dp->dom_family] =
1173 (*dp->dom_ifattach)(ifp);
1174 }
1175
1176 splx(s);
1177 }
1178
1179 /*
1180 * Deactivate an interface. This points all of the procedure
1181 * handles at error stubs. May be called from interrupt context.
1182 */
1183 void
1184 if_deactivate(struct ifnet *ifp)
1185 {
1186 int s;
1187
1188 s = splsoftnet();
1189
1190 ifp->if_output = if_nulloutput;
1191 ifp->_if_input = if_nullinput;
1192 ifp->if_start = if_nullstart;
1193 ifp->if_transmit = if_nulltransmit;
1194 ifp->if_ioctl = if_nullioctl;
1195 ifp->if_init = if_nullinit;
1196 ifp->if_stop = if_nullstop;
1197 ifp->if_slowtimo = if_nullslowtimo;
1198 ifp->if_drain = if_nulldrain;
1199
1200 /* No more packets may be enqueued. */
1201 ifp->if_snd.ifq_maxlen = 0;
1202
1203 splx(s);
1204 }
1205
1206 bool
1207 if_is_deactivated(const struct ifnet *ifp)
1208 {
1209
1210 return ifp->if_output == if_nulloutput;
1211 }
1212
1213 void
1214 if_purgeaddrs(struct ifnet *ifp, int family, void (*purgeaddr)(struct ifaddr *))
1215 {
1216 struct ifaddr *ifa, *nifa;
1217 int s;
1218
1219 s = pserialize_read_enter();
1220 for (ifa = IFADDR_READER_FIRST(ifp); ifa; ifa = nifa) {
1221 nifa = IFADDR_READER_NEXT(ifa);
1222 if (ifa->ifa_addr->sa_family != family)
1223 continue;
1224 pserialize_read_exit(s);
1225
1226 (*purgeaddr)(ifa);
1227
1228 s = pserialize_read_enter();
1229 }
1230 pserialize_read_exit(s);
1231 }
1232
1233 #ifdef IFAREF_DEBUG
1234 static struct ifaddr **ifa_list;
1235 static int ifa_list_size;
1236
1237 /* Depends on only one if_attach runs at once */
1238 static void
1239 if_build_ifa_list(struct ifnet *ifp)
1240 {
1241 struct ifaddr *ifa;
1242 int i;
1243
1244 KASSERT(ifa_list == NULL);
1245 KASSERT(ifa_list_size == 0);
1246
1247 IFADDR_READER_FOREACH(ifa, ifp)
1248 ifa_list_size++;
1249
1250 ifa_list = kmem_alloc(sizeof(*ifa) * ifa_list_size, KM_SLEEP);
1251 i = 0;
1252 IFADDR_READER_FOREACH(ifa, ifp) {
1253 ifa_list[i++] = ifa;
1254 ifaref(ifa);
1255 }
1256 }
1257
1258 static void
1259 if_check_and_free_ifa_list(struct ifnet *ifp)
1260 {
1261 int i;
1262 struct ifaddr *ifa;
1263
1264 if (ifa_list == NULL)
1265 return;
1266
1267 for (i = 0; i < ifa_list_size; i++) {
1268 char buf[64];
1269
1270 ifa = ifa_list[i];
1271 sockaddr_format(ifa->ifa_addr, buf, sizeof(buf));
1272 if (ifa->ifa_refcnt > 1) {
1273 log(LOG_WARNING,
1274 "ifa(%s) still referenced (refcnt=%d)\n",
1275 buf, ifa->ifa_refcnt - 1);
1276 } else
1277 log(LOG_DEBUG,
1278 "ifa(%s) not referenced (refcnt=%d)\n",
1279 buf, ifa->ifa_refcnt - 1);
1280 ifafree(ifa);
1281 }
1282
1283 kmem_free(ifa_list, sizeof(*ifa) * ifa_list_size);
1284 ifa_list = NULL;
1285 ifa_list_size = 0;
1286 }
1287 #endif
1288
1289 /*
1290 * Detach an interface from the list of "active" interfaces,
1291 * freeing any resources as we go along.
1292 *
1293 * NOTE: This routine must be called with a valid thread context,
1294 * as it may block.
1295 */
1296 void
1297 if_detach(struct ifnet *ifp)
1298 {
1299 struct socket so;
1300 struct ifaddr *ifa;
1301 #ifdef IFAREF_DEBUG
1302 struct ifaddr *last_ifa = NULL;
1303 #endif
1304 struct domain *dp;
1305 const struct protosw *pr;
1306 int s, i, family, purged;
1307
1308 #ifdef IFAREF_DEBUG
1309 if_build_ifa_list(ifp);
1310 #endif
1311 /*
1312 * XXX It's kind of lame that we have to have the
1313 * XXX socket structure...
1314 */
1315 memset(&so, 0, sizeof(so));
1316
1317 s = splnet();
1318
1319 sysctl_teardown(&ifp->if_sysctl_log);
1320 IFNET_LOCK(ifp);
1321 if_deactivate(ifp);
1322 IFNET_UNLOCK(ifp);
1323
1324 /*
1325 * Unlink from the list and wait for all readers to leave
1326 * from pserialize read sections. Note that we can't do
1327 * psref_target_destroy here. See below.
1328 */
1329 IFNET_GLOBAL_LOCK();
1330 ifindex2ifnet[ifp->if_index] = NULL;
1331 TAILQ_REMOVE(&ifnet_list, ifp, if_list);
1332 IFNET_WRITER_REMOVE(ifp);
1333 pserialize_perform(ifnet_psz);
1334 IFNET_GLOBAL_UNLOCK();
1335
1336 if (ifp->if_slowtimo != NULL && ifp->if_slowtimo_ch != NULL) {
1337 ifp->if_slowtimo = NULL;
1338 callout_halt(ifp->if_slowtimo_ch, NULL);
1339 callout_destroy(ifp->if_slowtimo_ch);
1340 kmem_free(ifp->if_slowtimo_ch, sizeof(*ifp->if_slowtimo_ch));
1341 }
1342 if_deferred_start_destroy(ifp);
1343
1344 /*
1345 * Do an if_down() to give protocols a chance to do something.
1346 */
1347 if_down_deactivated(ifp);
1348
1349 #ifdef ALTQ
1350 if (ALTQ_IS_ENABLED(&ifp->if_snd))
1351 altq_disable(&ifp->if_snd);
1352 if (ALTQ_IS_ATTACHED(&ifp->if_snd))
1353 altq_detach(&ifp->if_snd);
1354 #endif
1355
1356 #if NCARP > 0
1357 /* Remove the interface from any carp group it is a part of. */
1358 if (ifp->if_carp != NULL && ifp->if_type != IFT_CARP)
1359 carp_ifdetach(ifp);
1360 #endif
1361
1362 /*
1363 * Rip all the addresses off the interface. This should make
1364 * all of the routes go away.
1365 *
1366 * pr_usrreq calls can remove an arbitrary number of ifaddrs
1367 * from the list, including our "cursor", ifa. For safety,
1368 * and to honor the TAILQ abstraction, I just restart the
1369 * loop after each removal. Note that the loop will exit
1370 * when all of the remaining ifaddrs belong to the AF_LINK
1371 * family. I am counting on the historical fact that at
1372 * least one pr_usrreq in each address domain removes at
1373 * least one ifaddr.
1374 */
1375 again:
1376 /*
1377 * At this point, no other one tries to remove ifa in the list,
1378 * so we don't need to take a lock or psref. Avoid using
1379 * IFADDR_READER_FOREACH to pass over an inspection of contract
1380 * violations of pserialize.
1381 */
1382 IFADDR_WRITER_FOREACH(ifa, ifp) {
1383 family = ifa->ifa_addr->sa_family;
1384 #ifdef IFAREF_DEBUG
1385 printf("if_detach: ifaddr %p, family %d, refcnt %d\n",
1386 ifa, family, ifa->ifa_refcnt);
1387 if (last_ifa != NULL && ifa == last_ifa)
1388 panic("if_detach: loop detected");
1389 last_ifa = ifa;
1390 #endif
1391 if (family == AF_LINK)
1392 continue;
1393 dp = pffinddomain(family);
1394 KASSERTMSG(dp != NULL, "no domain for AF %d", family);
1395 /*
1396 * XXX These PURGEIF calls are redundant with the
1397 * purge-all-families calls below, but are left in for
1398 * now both to make a smaller change, and to avoid
1399 * unplanned interactions with clearing of
1400 * ifp->if_addrlist.
1401 */
1402 purged = 0;
1403 for (pr = dp->dom_protosw;
1404 pr < dp->dom_protoswNPROTOSW; pr++) {
1405 so.so_proto = pr;
1406 if (pr->pr_usrreqs) {
1407 (void) (*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
1408 purged = 1;
1409 }
1410 }
1411 if (purged == 0) {
1412 /*
1413 * XXX What's really the best thing to do
1414 * XXX here? --thorpej (at) NetBSD.org
1415 */
1416 printf("if_detach: WARNING: AF %d not purged\n",
1417 family);
1418 ifa_remove(ifp, ifa);
1419 }
1420 goto again;
1421 }
1422
1423 if_free_sadl(ifp, 1);
1424
1425 restart:
1426 IFADDR_WRITER_FOREACH(ifa, ifp) {
1427 family = ifa->ifa_addr->sa_family;
1428 KASSERT(family == AF_LINK);
1429 ifa_remove(ifp, ifa);
1430 goto restart;
1431 }
1432
1433 /* Delete stray routes from the routing table. */
1434 for (i = 0; i <= AF_MAX; i++)
1435 rt_delete_matched_entries(i, if_delroute_matcher, ifp);
1436
1437 DOMAIN_FOREACH(dp) {
1438 if (dp->dom_ifdetach != NULL && ifp->if_afdata[dp->dom_family])
1439 {
1440 void *p = ifp->if_afdata[dp->dom_family];
1441 if (p) {
1442 ifp->if_afdata[dp->dom_family] = NULL;
1443 (*dp->dom_ifdetach)(ifp, p);
1444 }
1445 }
1446
1447 /*
1448 * One would expect multicast memberships (INET and
1449 * INET6) on UDP sockets to be purged by the PURGEIF
1450 * calls above, but if all addresses were removed from
1451 * the interface prior to destruction, the calls will
1452 * not be made (e.g. ppp, for which pppd(8) generally
1453 * removes addresses before destroying the interface).
1454 * Because there is no invariant that multicast
1455 * memberships only exist for interfaces with IPv4
1456 * addresses, we must call PURGEIF regardless of
1457 * addresses. (Protocols which might store ifnet
1458 * pointers are marked with PR_PURGEIF.)
1459 */
1460 for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
1461 so.so_proto = pr;
1462 if (pr->pr_usrreqs && pr->pr_flags & PR_PURGEIF)
1463 (void)(*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
1464 }
1465 }
1466
1467 /*
1468 * Must be done after the above pr_purgeif because if_psref may be
1469 * still used in pr_purgeif.
1470 */
1471 psref_target_destroy(&ifp->if_psref, ifnet_psref_class);
1472 PSLIST_ENTRY_DESTROY(ifp, if_pslist_entry);
1473
1474 pfil_run_ifhooks(if_pfil, PFIL_IFNET_DETACH, ifp);
1475 (void)pfil_head_destroy(ifp->if_pfil);
1476
1477 /* Announce that the interface is gone. */
1478 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1479
1480 IF_AFDATA_LOCK_DESTROY(ifp);
1481
1482 /*
1483 * remove packets that came from ifp, from software interrupt queues.
1484 */
1485 DOMAIN_FOREACH(dp) {
1486 for (i = 0; i < __arraycount(dp->dom_ifqueues); i++) {
1487 struct ifqueue *iq = dp->dom_ifqueues[i];
1488 if (iq == NULL)
1489 break;
1490 dp->dom_ifqueues[i] = NULL;
1491 if_detach_queues(ifp, iq);
1492 }
1493 }
1494
1495 /*
1496 * IP queues have to be processed separately: net-queue barrier
1497 * ensures that the packets are dequeued while a cross-call will
1498 * ensure that the interrupts have completed. FIXME: not quite..
1499 */
1500 #ifdef INET
1501 pktq_barrier(ip_pktq);
1502 #endif
1503 #ifdef INET6
1504 if (in6_present)
1505 pktq_barrier(ip6_pktq);
1506 #endif
1507 xc_barrier(0);
1508
1509 if (ifp->if_percpuq != NULL) {
1510 if_percpuq_destroy(ifp->if_percpuq);
1511 ifp->if_percpuq = NULL;
1512 }
1513
1514 mutex_obj_free(ifp->if_ioctl_lock);
1515 ifp->if_ioctl_lock = NULL;
1516 mutex_obj_free(ifp->if_snd.ifq_lock);
1517 if_stats_fini(ifp);
1518
1519 splx(s);
1520
1521 #ifdef IFAREF_DEBUG
1522 if_check_and_free_ifa_list(ifp);
1523 #endif
1524 }
1525
1526 static void
1527 if_detach_queues(struct ifnet *ifp, struct ifqueue *q)
1528 {
1529 struct mbuf *m, *prev, *next;
1530
1531 prev = NULL;
1532 for (m = q->ifq_head; m != NULL; m = next) {
1533 KASSERT((m->m_flags & M_PKTHDR) != 0);
1534
1535 next = m->m_nextpkt;
1536 if (m->m_pkthdr.rcvif_index != ifp->if_index) {
1537 prev = m;
1538 continue;
1539 }
1540
1541 if (prev != NULL)
1542 prev->m_nextpkt = m->m_nextpkt;
1543 else
1544 q->ifq_head = m->m_nextpkt;
1545 if (q->ifq_tail == m)
1546 q->ifq_tail = prev;
1547 q->ifq_len--;
1548
1549 m->m_nextpkt = NULL;
1550 m_freem(m);
1551 IF_DROP(q);
1552 }
1553 }
1554
1555 /*
1556 * Callback for a radix tree walk to delete all references to an
1557 * ifnet.
1558 */
1559 static int
1560 if_delroute_matcher(struct rtentry *rt, void *v)
1561 {
1562 struct ifnet *ifp = (struct ifnet *)v;
1563
1564 if (rt->rt_ifp == ifp)
1565 return 1;
1566 else
1567 return 0;
1568 }
1569
1570 /*
1571 * Create a clone network interface.
1572 */
1573 static int
1574 if_clone_create(const char *name)
1575 {
1576 struct if_clone *ifc;
1577 int unit;
1578 struct ifnet *ifp;
1579 struct psref psref;
1580
1581 KASSERT(mutex_owned(&if_clone_mtx));
1582
1583 ifc = if_clone_lookup(name, &unit);
1584 if (ifc == NULL)
1585 return EINVAL;
1586
1587 ifp = if_get(name, &psref);
1588 if (ifp != NULL) {
1589 if_put(ifp, &psref);
1590 return EEXIST;
1591 }
1592
1593 return (*ifc->ifc_create)(ifc, unit);
1594 }
1595
1596 /*
1597 * Destroy a clone network interface.
1598 */
1599 static int
1600 if_clone_destroy(const char *name)
1601 {
1602 struct if_clone *ifc;
1603 struct ifnet *ifp;
1604 struct psref psref;
1605 int error;
1606 int (*if_ioctl)(struct ifnet *, u_long, void *);
1607
1608 KASSERT(mutex_owned(&if_clone_mtx));
1609
1610 ifc = if_clone_lookup(name, NULL);
1611 if (ifc == NULL)
1612 return EINVAL;
1613
1614 if (ifc->ifc_destroy == NULL)
1615 return EOPNOTSUPP;
1616
1617 ifp = if_get(name, &psref);
1618 if (ifp == NULL)
1619 return ENXIO;
1620
1621 /* We have to disable ioctls here */
1622 IFNET_LOCK(ifp);
1623 if_ioctl = ifp->if_ioctl;
1624 ifp->if_ioctl = if_nullioctl;
1625 IFNET_UNLOCK(ifp);
1626
1627 /*
1628 * We cannot call ifc_destroy with holding ifp.
1629 * Releasing ifp here is safe thanks to if_clone_mtx.
1630 */
1631 if_put(ifp, &psref);
1632
1633 error = (*ifc->ifc_destroy)(ifp);
1634
1635 if (error != 0) {
1636 /* We have to restore if_ioctl on error */
1637 IFNET_LOCK(ifp);
1638 ifp->if_ioctl = if_ioctl;
1639 IFNET_UNLOCK(ifp);
1640 }
1641
1642 return error;
1643 }
1644
1645 static bool
1646 if_is_unit(const char *name)
1647 {
1648
1649 while (*name != '\0') {
1650 if (*name < '0' || *name > '9')
1651 return false;
1652 name++;
1653 }
1654
1655 return true;
1656 }
1657
1658 /*
1659 * Look up a network interface cloner.
1660 */
1661 static struct if_clone *
1662 if_clone_lookup(const char *name, int *unitp)
1663 {
1664 struct if_clone *ifc;
1665 const char *cp;
1666 char *dp, ifname[IFNAMSIZ + 3];
1667 int unit;
1668
1669 KASSERT(mutex_owned(&if_clone_mtx));
1670
1671 strcpy(ifname, "if_");
1672 /* separate interface name from unit */
1673 /* TODO: search unit number from backward */
1674 for (dp = ifname + 3, cp = name; cp - name < IFNAMSIZ &&
1675 *cp && !if_is_unit(cp);)
1676 *dp++ = *cp++;
1677
1678 if (cp == name || cp - name == IFNAMSIZ || !*cp)
1679 return NULL; /* No name or unit number */
1680 *dp++ = '\0';
1681
1682 again:
1683 LIST_FOREACH(ifc, &if_cloners, ifc_list) {
1684 if (strcmp(ifname + 3, ifc->ifc_name) == 0)
1685 break;
1686 }
1687
1688 if (ifc == NULL) {
1689 int error;
1690 if (*ifname == '\0')
1691 return NULL;
1692 mutex_exit(&if_clone_mtx);
1693 error = module_autoload(ifname, MODULE_CLASS_DRIVER);
1694 mutex_enter(&if_clone_mtx);
1695 if (error)
1696 return NULL;
1697 *ifname = '\0';
1698 goto again;
1699 }
1700
1701 unit = 0;
1702 while (cp - name < IFNAMSIZ && *cp) {
1703 if (*cp < '0' || *cp > '9' || unit >= INT_MAX / 10) {
1704 /* Bogus unit number. */
1705 return NULL;
1706 }
1707 unit = (unit * 10) + (*cp++ - '0');
1708 }
1709
1710 if (unitp != NULL)
1711 *unitp = unit;
1712 return ifc;
1713 }
1714
1715 /*
1716 * Register a network interface cloner.
1717 */
1718 void
1719 if_clone_attach(struct if_clone *ifc)
1720 {
1721
1722 mutex_enter(&if_clone_mtx);
1723 LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
1724 if_cloners_count++;
1725 mutex_exit(&if_clone_mtx);
1726 }
1727
1728 /*
1729 * Unregister a network interface cloner.
1730 */
1731 void
1732 if_clone_detach(struct if_clone *ifc)
1733 {
1734
1735 mutex_enter(&if_clone_mtx);
1736 LIST_REMOVE(ifc, ifc_list);
1737 if_cloners_count--;
1738 mutex_exit(&if_clone_mtx);
1739 }
1740
1741 /*
1742 * Provide list of interface cloners to userspace.
1743 */
1744 int
1745 if_clone_list(int buf_count, char *buffer, int *total)
1746 {
1747 char outbuf[IFNAMSIZ], *dst;
1748 struct if_clone *ifc;
1749 int count, error = 0;
1750
1751 mutex_enter(&if_clone_mtx);
1752 *total = if_cloners_count;
1753 if ((dst = buffer) == NULL) {
1754 /* Just asking how many there are. */
1755 goto out;
1756 }
1757
1758 if (buf_count < 0) {
1759 error = EINVAL;
1760 goto out;
1761 }
1762
1763 count = (if_cloners_count < buf_count) ?
1764 if_cloners_count : buf_count;
1765
1766 for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
1767 ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
1768 (void)strncpy(outbuf, ifc->ifc_name, sizeof(outbuf));
1769 if (outbuf[sizeof(outbuf) - 1] != '\0') {
1770 error = ENAMETOOLONG;
1771 goto out;
1772 }
1773 error = copyout(outbuf, dst, sizeof(outbuf));
1774 if (error != 0)
1775 break;
1776 }
1777
1778 out:
1779 mutex_exit(&if_clone_mtx);
1780 return error;
1781 }
1782
1783 void
1784 ifa_psref_init(struct ifaddr *ifa)
1785 {
1786
1787 psref_target_init(&ifa->ifa_psref, ifa_psref_class);
1788 }
1789
1790 void
1791 ifaref(struct ifaddr *ifa)
1792 {
1793
1794 atomic_inc_uint(&ifa->ifa_refcnt);
1795 }
1796
1797 void
1798 ifafree(struct ifaddr *ifa)
1799 {
1800 KASSERT(ifa != NULL);
1801 KASSERTMSG(ifa->ifa_refcnt > 0, "ifa_refcnt=%d", ifa->ifa_refcnt);
1802
1803 if (atomic_dec_uint_nv(&ifa->ifa_refcnt) == 0) {
1804 free(ifa, M_IFADDR);
1805 }
1806 }
1807
1808 bool
1809 ifa_is_destroying(struct ifaddr *ifa)
1810 {
1811
1812 return ISSET(ifa->ifa_flags, IFA_DESTROYING);
1813 }
1814
1815 void
1816 ifa_insert(struct ifnet *ifp, struct ifaddr *ifa)
1817 {
1818
1819 ifa->ifa_ifp = ifp;
1820
1821 /*
1822 * Check MP-safety for IFEF_MPSAFE drivers.
1823 * Check !IFF_RUNNING for initialization routines that normally don't
1824 * take IFNET_LOCK but it's safe because there is no competitor.
1825 * XXX there are false positive cases because IFF_RUNNING can be off on
1826 * if_stop.
1827 */
1828 KASSERT(!if_is_mpsafe(ifp) || !ISSET(ifp->if_flags, IFF_RUNNING) ||
1829 IFNET_LOCKED(ifp));
1830
1831 TAILQ_INSERT_TAIL(&ifp->if_addrlist, ifa, ifa_list);
1832 IFADDR_ENTRY_INIT(ifa);
1833 IFADDR_WRITER_INSERT_TAIL(ifp, ifa);
1834
1835 ifaref(ifa);
1836 }
1837
1838 void
1839 ifa_remove(struct ifnet *ifp, struct ifaddr *ifa)
1840 {
1841
1842 KASSERT(ifa->ifa_ifp == ifp);
1843 /*
1844 * Check MP-safety for IFEF_MPSAFE drivers.
1845 * if_is_deactivated indicates ifa_remove is called form if_detach
1846 * where is safe even if IFNET_LOCK isn't held.
1847 */
1848 KASSERT(!if_is_mpsafe(ifp) || if_is_deactivated(ifp) || IFNET_LOCKED(ifp));
1849
1850 TAILQ_REMOVE(&ifp->if_addrlist, ifa, ifa_list);
1851 IFADDR_WRITER_REMOVE(ifa);
1852 #ifdef NET_MPSAFE
1853 IFNET_GLOBAL_LOCK();
1854 pserialize_perform(ifnet_psz);
1855 IFNET_GLOBAL_UNLOCK();
1856 #endif
1857
1858 #ifdef NET_MPSAFE
1859 psref_target_destroy(&ifa->ifa_psref, ifa_psref_class);
1860 #endif
1861 IFADDR_ENTRY_DESTROY(ifa);
1862 ifafree(ifa);
1863 }
1864
1865 void
1866 ifa_acquire(struct ifaddr *ifa, struct psref *psref)
1867 {
1868
1869 PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
1870 psref_acquire(psref, &ifa->ifa_psref, ifa_psref_class);
1871 }
1872
1873 void
1874 ifa_release(struct ifaddr *ifa, struct psref *psref)
1875 {
1876
1877 if (ifa == NULL)
1878 return;
1879
1880 psref_release(psref, &ifa->ifa_psref, ifa_psref_class);
1881 }
1882
1883 bool
1884 ifa_held(struct ifaddr *ifa)
1885 {
1886
1887 return psref_held(&ifa->ifa_psref, ifa_psref_class);
1888 }
1889
1890 static inline int
1891 equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
1892 {
1893 return sockaddr_cmp(sa1, sa2) == 0;
1894 }
1895
1896 /*
1897 * Locate an interface based on a complete address.
1898 */
1899 /*ARGSUSED*/
1900 struct ifaddr *
1901 ifa_ifwithaddr(const struct sockaddr *addr)
1902 {
1903 struct ifnet *ifp;
1904 struct ifaddr *ifa;
1905
1906 IFNET_READER_FOREACH(ifp) {
1907 if (if_is_deactivated(ifp))
1908 continue;
1909 IFADDR_READER_FOREACH(ifa, ifp) {
1910 if (ifa->ifa_addr->sa_family != addr->sa_family)
1911 continue;
1912 if (equal(addr, ifa->ifa_addr))
1913 return ifa;
1914 if ((ifp->if_flags & IFF_BROADCAST) &&
1915 ifa->ifa_broadaddr &&
1916 /* IP6 doesn't have broadcast */
1917 ifa->ifa_broadaddr->sa_len != 0 &&
1918 equal(ifa->ifa_broadaddr, addr))
1919 return ifa;
1920 }
1921 }
1922 return NULL;
1923 }
1924
1925 struct ifaddr *
1926 ifa_ifwithaddr_psref(const struct sockaddr *addr, struct psref *psref)
1927 {
1928 struct ifaddr *ifa;
1929 int s = pserialize_read_enter();
1930
1931 ifa = ifa_ifwithaddr(addr);
1932 if (ifa != NULL)
1933 ifa_acquire(ifa, psref);
1934 pserialize_read_exit(s);
1935
1936 return ifa;
1937 }
1938
1939 /*
1940 * Locate the point to point interface with a given destination address.
1941 */
1942 /*ARGSUSED*/
1943 struct ifaddr *
1944 ifa_ifwithdstaddr(const struct sockaddr *addr)
1945 {
1946 struct ifnet *ifp;
1947 struct ifaddr *ifa;
1948
1949 IFNET_READER_FOREACH(ifp) {
1950 if (if_is_deactivated(ifp))
1951 continue;
1952 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1953 continue;
1954 IFADDR_READER_FOREACH(ifa, ifp) {
1955 if (ifa->ifa_addr->sa_family != addr->sa_family ||
1956 ifa->ifa_dstaddr == NULL)
1957 continue;
1958 if (equal(addr, ifa->ifa_dstaddr))
1959 return ifa;
1960 }
1961 }
1962
1963 return NULL;
1964 }
1965
1966 struct ifaddr *
1967 ifa_ifwithdstaddr_psref(const struct sockaddr *addr, struct psref *psref)
1968 {
1969 struct ifaddr *ifa;
1970 int s;
1971
1972 s = pserialize_read_enter();
1973 ifa = ifa_ifwithdstaddr(addr);
1974 if (ifa != NULL)
1975 ifa_acquire(ifa, psref);
1976 pserialize_read_exit(s);
1977
1978 return ifa;
1979 }
1980
1981 /*
1982 * Find an interface on a specific network. If many, choice
1983 * is most specific found.
1984 */
1985 struct ifaddr *
1986 ifa_ifwithnet(const struct sockaddr *addr)
1987 {
1988 struct ifnet *ifp;
1989 struct ifaddr *ifa, *ifa_maybe = NULL;
1990 const struct sockaddr_dl *sdl;
1991 u_int af = addr->sa_family;
1992 const char *addr_data = addr->sa_data, *cplim;
1993
1994 if (af == AF_LINK) {
1995 sdl = satocsdl(addr);
1996 if (sdl->sdl_index && sdl->sdl_index < if_indexlim &&
1997 ifindex2ifnet[sdl->sdl_index] &&
1998 !if_is_deactivated(ifindex2ifnet[sdl->sdl_index])) {
1999 return ifindex2ifnet[sdl->sdl_index]->if_dl;
2000 }
2001 }
2002 #ifdef NETATALK
2003 if (af == AF_APPLETALK) {
2004 const struct sockaddr_at *sat, *sat2;
2005 sat = (const struct sockaddr_at *)addr;
2006 IFNET_READER_FOREACH(ifp) {
2007 if (if_is_deactivated(ifp))
2008 continue;
2009 ifa = at_ifawithnet((const struct sockaddr_at *)addr, ifp);
2010 if (ifa == NULL)
2011 continue;
2012 sat2 = (struct sockaddr_at *)ifa->ifa_addr;
2013 if (sat2->sat_addr.s_net == sat->sat_addr.s_net)
2014 return ifa; /* exact match */
2015 if (ifa_maybe == NULL) {
2016 /* else keep the if with the right range */
2017 ifa_maybe = ifa;
2018 }
2019 }
2020 return ifa_maybe;
2021 }
2022 #endif
2023 IFNET_READER_FOREACH(ifp) {
2024 if (if_is_deactivated(ifp))
2025 continue;
2026 IFADDR_READER_FOREACH(ifa, ifp) {
2027 const char *cp, *cp2, *cp3;
2028
2029 if (ifa->ifa_addr->sa_family != af ||
2030 ifa->ifa_netmask == NULL)
2031 next: continue;
2032 cp = addr_data;
2033 cp2 = ifa->ifa_addr->sa_data;
2034 cp3 = ifa->ifa_netmask->sa_data;
2035 cplim = (const char *)ifa->ifa_netmask +
2036 ifa->ifa_netmask->sa_len;
2037 while (cp3 < cplim) {
2038 if ((*cp++ ^ *cp2++) & *cp3++) {
2039 /* want to continue for() loop */
2040 goto next;
2041 }
2042 }
2043 if (ifa_maybe == NULL ||
2044 rt_refines(ifa->ifa_netmask,
2045 ifa_maybe->ifa_netmask))
2046 ifa_maybe = ifa;
2047 }
2048 }
2049 return ifa_maybe;
2050 }
2051
2052 struct ifaddr *
2053 ifa_ifwithnet_psref(const struct sockaddr *addr, struct psref *psref)
2054 {
2055 struct ifaddr *ifa;
2056 int s;
2057
2058 s = pserialize_read_enter();
2059 ifa = ifa_ifwithnet(addr);
2060 if (ifa != NULL)
2061 ifa_acquire(ifa, psref);
2062 pserialize_read_exit(s);
2063
2064 return ifa;
2065 }
2066
2067 /*
2068 * Find the interface of the addresss.
2069 */
2070 struct ifaddr *
2071 ifa_ifwithladdr(const struct sockaddr *addr)
2072 {
2073 struct ifaddr *ia;
2074
2075 if ((ia = ifa_ifwithaddr(addr)) || (ia = ifa_ifwithdstaddr(addr)) ||
2076 (ia = ifa_ifwithnet(addr)))
2077 return ia;
2078 return NULL;
2079 }
2080
2081 struct ifaddr *
2082 ifa_ifwithladdr_psref(const struct sockaddr *addr, struct psref *psref)
2083 {
2084 struct ifaddr *ifa;
2085 int s;
2086
2087 s = pserialize_read_enter();
2088 ifa = ifa_ifwithladdr(addr);
2089 if (ifa != NULL)
2090 ifa_acquire(ifa, psref);
2091 pserialize_read_exit(s);
2092
2093 return ifa;
2094 }
2095
2096 /*
2097 * Find an interface using a specific address family
2098 */
2099 struct ifaddr *
2100 ifa_ifwithaf(int af)
2101 {
2102 struct ifnet *ifp;
2103 struct ifaddr *ifa = NULL;
2104 int s;
2105
2106 s = pserialize_read_enter();
2107 IFNET_READER_FOREACH(ifp) {
2108 if (if_is_deactivated(ifp))
2109 continue;
2110 IFADDR_READER_FOREACH(ifa, ifp) {
2111 if (ifa->ifa_addr->sa_family == af)
2112 goto out;
2113 }
2114 }
2115 out:
2116 pserialize_read_exit(s);
2117 return ifa;
2118 }
2119
2120 /*
2121 * Find an interface address specific to an interface best matching
2122 * a given address.
2123 */
2124 struct ifaddr *
2125 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
2126 {
2127 struct ifaddr *ifa;
2128 const char *cp, *cp2, *cp3;
2129 const char *cplim;
2130 struct ifaddr *ifa_maybe = 0;
2131 u_int af = addr->sa_family;
2132
2133 if (if_is_deactivated(ifp))
2134 return NULL;
2135
2136 if (af >= AF_MAX)
2137 return NULL;
2138
2139 IFADDR_READER_FOREACH(ifa, ifp) {
2140 if (ifa->ifa_addr->sa_family != af)
2141 continue;
2142 ifa_maybe = ifa;
2143 if (ifa->ifa_netmask == NULL) {
2144 if (equal(addr, ifa->ifa_addr) ||
2145 (ifa->ifa_dstaddr &&
2146 equal(addr, ifa->ifa_dstaddr)))
2147 return ifa;
2148 continue;
2149 }
2150 cp = addr->sa_data;
2151 cp2 = ifa->ifa_addr->sa_data;
2152 cp3 = ifa->ifa_netmask->sa_data;
2153 cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
2154 for (; cp3 < cplim; cp3++) {
2155 if ((*cp++ ^ *cp2++) & *cp3)
2156 break;
2157 }
2158 if (cp3 == cplim)
2159 return ifa;
2160 }
2161 return ifa_maybe;
2162 }
2163
2164 struct ifaddr *
2165 ifaof_ifpforaddr_psref(const struct sockaddr *addr, struct ifnet *ifp,
2166 struct psref *psref)
2167 {
2168 struct ifaddr *ifa;
2169 int s;
2170
2171 s = pserialize_read_enter();
2172 ifa = ifaof_ifpforaddr(addr, ifp);
2173 if (ifa != NULL)
2174 ifa_acquire(ifa, psref);
2175 pserialize_read_exit(s);
2176
2177 return ifa;
2178 }
2179
2180 /*
2181 * Default action when installing a route with a Link Level gateway.
2182 * Lookup an appropriate real ifa to point to.
2183 * This should be moved to /sys/net/link.c eventually.
2184 */
2185 void
2186 link_rtrequest(int cmd, struct rtentry *rt, const struct rt_addrinfo *info)
2187 {
2188 struct ifaddr *ifa;
2189 const struct sockaddr *dst;
2190 struct ifnet *ifp;
2191 struct psref psref;
2192
2193 if (cmd != RTM_ADD || ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
2194 return;
2195 ifp = rt->rt_ifa->ifa_ifp;
2196 dst = rt_getkey(rt);
2197 if ((ifa = ifaof_ifpforaddr_psref(dst, ifp, &psref)) != NULL) {
2198 rt_replace_ifa(rt, ifa);
2199 if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
2200 ifa->ifa_rtrequest(cmd, rt, info);
2201 ifa_release(ifa, &psref);
2202 }
2203 }
2204
2205 /*
2206 * bitmask macros to manage a densely packed link_state change queue.
2207 * Because we need to store LINK_STATE_UNKNOWN(0), LINK_STATE_DOWN(1) and
2208 * LINK_STATE_UP(2) we need 2 bits for each state change.
2209 * As a state change to store is 0, treat all bits set as an unset item.
2210 */
2211 #define LQ_ITEM_BITS 2
2212 #define LQ_ITEM_MASK ((1 << LQ_ITEM_BITS) - 1)
2213 #define LQ_MASK(i) (LQ_ITEM_MASK << (i) * LQ_ITEM_BITS)
2214 #define LINK_STATE_UNSET LQ_ITEM_MASK
2215 #define LQ_ITEM(q, i) (((q) & LQ_MASK((i))) >> (i) * LQ_ITEM_BITS)
2216 #define LQ_STORE(q, i, v) \
2217 do { \
2218 (q) &= ~LQ_MASK((i)); \
2219 (q) |= (v) << (i) * LQ_ITEM_BITS; \
2220 } while (0 /* CONSTCOND */)
2221 #define LQ_MAX(q) ((sizeof((q)) * NBBY) / LQ_ITEM_BITS)
2222 #define LQ_POP(q, v) \
2223 do { \
2224 (v) = LQ_ITEM((q), 0); \
2225 (q) >>= LQ_ITEM_BITS; \
2226 (q) |= LINK_STATE_UNSET << (LQ_MAX((q)) - 1) * LQ_ITEM_BITS; \
2227 } while (0 /* CONSTCOND */)
2228 #define LQ_PUSH(q, v) \
2229 do { \
2230 (q) >>= LQ_ITEM_BITS; \
2231 (q) |= (v) << (LQ_MAX((q)) - 1) * LQ_ITEM_BITS; \
2232 } while (0 /* CONSTCOND */)
2233 #define LQ_FIND_UNSET(q, i) \
2234 for ((i) = 0; i < LQ_MAX((q)); (i)++) { \
2235 if (LQ_ITEM((q), (i)) == LINK_STATE_UNSET) \
2236 break; \
2237 }
2238
2239 /*
2240 * XXX reusing (ifp)->if_snd->ifq_lock rather than having another spin mutex
2241 * for each ifnet. It doesn't matter because:
2242 * - if IFEF_MPSAFE is enabled, if_snd isn't used and lock contentions on
2243 * ifq_lock don't happen
2244 * - if IFEF_MPSAFE is disabled, there is no lock contention on ifq_lock
2245 * because if_snd, if_link_state_change and if_link_state_change_process
2246 * are all called with KERNEL_LOCK
2247 */
2248 #define IF_LINK_STATE_CHANGE_LOCK(ifp) \
2249 mutex_enter((ifp)->if_snd.ifq_lock)
2250 #define IF_LINK_STATE_CHANGE_UNLOCK(ifp) \
2251 mutex_exit((ifp)->if_snd.ifq_lock)
2252
2253 static void
2254 if_link_state_change_work_schedule(struct ifnet *ifp)
2255 {
2256 if (ifp->if_link_cansched && !ifp->if_link_scheduled) {
2257 ifp->if_link_scheduled = true;
2258 workqueue_enqueue(ifnet_link_state_wq, &ifp->if_link_work,
2259 NULL);
2260 }
2261 }
2262
2263 /*
2264 * Handle a change in the interface link state and
2265 * queue notifications.
2266 */
2267 void
2268 if_link_state_change(struct ifnet *ifp, int link_state)
2269 {
2270 int idx;
2271
2272 KASSERTMSG(if_is_link_state_changeable(ifp),
2273 "%s: IFEF_NO_LINK_STATE_CHANGE must not be set, but if_extflags=0x%x",
2274 ifp->if_xname, ifp->if_extflags);
2275
2276 /* Ensure change is to a valid state */
2277 switch (link_state) {
2278 case LINK_STATE_UNKNOWN: /* FALLTHROUGH */
2279 case LINK_STATE_DOWN: /* FALLTHROUGH */
2280 case LINK_STATE_UP:
2281 break;
2282 default:
2283 #ifdef DEBUG
2284 printf("%s: invalid link state %d\n",
2285 ifp->if_xname, link_state);
2286 #endif
2287 return;
2288 }
2289
2290 IF_LINK_STATE_CHANGE_LOCK(ifp);
2291
2292 /* Find the last unset event in the queue. */
2293 LQ_FIND_UNSET(ifp->if_link_queue, idx);
2294
2295 /*
2296 * Ensure link_state doesn't match the last event in the queue.
2297 * ifp->if_link_state is not checked and set here because
2298 * that would present an inconsistent picture to the system.
2299 */
2300 if (idx != 0 &&
2301 LQ_ITEM(ifp->if_link_queue, idx - 1) == (uint8_t)link_state)
2302 goto out;
2303
2304 /* Handle queue overflow. */
2305 if (idx == LQ_MAX(ifp->if_link_queue)) {
2306 uint8_t lost;
2307
2308 /*
2309 * The DOWN state must be protected from being pushed off
2310 * the queue to ensure that userland will always be
2311 * in a sane state.
2312 * Because DOWN is protected, there is no need to protect
2313 * UNKNOWN.
2314 * It should be invalid to change from any other state to
2315 * UNKNOWN anyway ...
2316 */
2317 lost = LQ_ITEM(ifp->if_link_queue, 0);
2318 LQ_PUSH(ifp->if_link_queue, (uint8_t)link_state);
2319 if (lost == LINK_STATE_DOWN) {
2320 lost = LQ_ITEM(ifp->if_link_queue, 0);
2321 LQ_STORE(ifp->if_link_queue, 0, LINK_STATE_DOWN);
2322 }
2323 printf("%s: lost link state change %s\n",
2324 ifp->if_xname,
2325 lost == LINK_STATE_UP ? "UP" :
2326 lost == LINK_STATE_DOWN ? "DOWN" :
2327 "UNKNOWN");
2328 } else
2329 LQ_STORE(ifp->if_link_queue, idx, (uint8_t)link_state);
2330
2331 if_link_state_change_work_schedule(ifp);
2332
2333 out:
2334 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2335 }
2336
2337 /*
2338 * Handle interface link state change notifications.
2339 */
2340 static void
2341 if_link_state_change_process(struct ifnet *ifp, int link_state)
2342 {
2343 struct domain *dp;
2344 int s = splnet();
2345 bool notify;
2346
2347 KASSERT(!cpu_intr_p());
2348
2349 IF_LINK_STATE_CHANGE_LOCK(ifp);
2350
2351 /* Ensure the change is still valid. */
2352 if (ifp->if_link_state == link_state) {
2353 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2354 splx(s);
2355 return;
2356 }
2357
2358 #ifdef DEBUG
2359 log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
2360 link_state == LINK_STATE_UP ? "UP" :
2361 link_state == LINK_STATE_DOWN ? "DOWN" :
2362 "UNKNOWN",
2363 ifp->if_link_state == LINK_STATE_UP ? "UP" :
2364 ifp->if_link_state == LINK_STATE_DOWN ? "DOWN" :
2365 "UNKNOWN");
2366 #endif
2367
2368 /*
2369 * When going from UNKNOWN to UP, we need to mark existing
2370 * addresses as tentative and restart DAD as we may have
2371 * erroneously not found a duplicate.
2372 *
2373 * This needs to happen before rt_ifmsg to avoid a race where
2374 * listeners would have an address and expect it to work right
2375 * away.
2376 */
2377 notify = (link_state == LINK_STATE_UP &&
2378 ifp->if_link_state == LINK_STATE_UNKNOWN);
2379 ifp->if_link_state = link_state;
2380 /* The following routines may sleep so release the spin mutex */
2381 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2382
2383 KERNEL_LOCK_UNLESS_NET_MPSAFE();
2384 if (notify) {
2385 DOMAIN_FOREACH(dp) {
2386 if (dp->dom_if_link_state_change != NULL)
2387 dp->dom_if_link_state_change(ifp,
2388 LINK_STATE_DOWN);
2389 }
2390 }
2391
2392 /* Notify that the link state has changed. */
2393 rt_ifmsg(ifp);
2394
2395 #if NCARP > 0
2396 if (ifp->if_carp)
2397 carp_carpdev_state(ifp);
2398 #endif
2399
2400 DOMAIN_FOREACH(dp) {
2401 if (dp->dom_if_link_state_change != NULL)
2402 dp->dom_if_link_state_change(ifp, link_state);
2403 }
2404 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
2405 splx(s);
2406 }
2407
2408 /*
2409 * Process the interface link state change queue.
2410 */
2411 static void
2412 if_link_state_change_work(struct work *work, void *arg)
2413 {
2414 struct ifnet *ifp = container_of(work, struct ifnet, if_link_work);
2415 int s;
2416 uint8_t state;
2417 bool schedule;
2418
2419 KERNEL_LOCK_UNLESS_NET_MPSAFE();
2420 s = splnet();
2421
2422 /* Pop a link state change from the queue and process it. */
2423 IF_LINK_STATE_CHANGE_LOCK(ifp);
2424 ifp->if_link_scheduled = false;
2425 LQ_POP(ifp->if_link_queue, state);
2426 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2427
2428 if_link_state_change_process(ifp, state);
2429
2430 /* If there is a link state change to come, schedule it. */
2431 IF_LINK_STATE_CHANGE_LOCK(ifp);
2432 schedule = (LQ_ITEM(ifp->if_link_queue, 0) != LINK_STATE_UNSET);
2433 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2434
2435 if (schedule)
2436 if_link_state_change_work_schedule(ifp);
2437
2438 splx(s);
2439 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
2440 }
2441
2442 /*
2443 * Default action when installing a local route on a point-to-point
2444 * interface.
2445 */
2446 void
2447 p2p_rtrequest(int req, struct rtentry *rt,
2448 __unused const struct rt_addrinfo *info)
2449 {
2450 struct ifnet *ifp = rt->rt_ifp;
2451 struct ifaddr *ifa, *lo0ifa;
2452 int s = pserialize_read_enter();
2453
2454 switch (req) {
2455 case RTM_ADD:
2456 if ((rt->rt_flags & RTF_LOCAL) == 0)
2457 break;
2458
2459 rt->rt_ifp = lo0ifp;
2460
2461 if (ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
2462 break;
2463
2464 IFADDR_READER_FOREACH(ifa, ifp) {
2465 if (equal(rt_getkey(rt), ifa->ifa_addr))
2466 break;
2467 }
2468 if (ifa == NULL)
2469 break;
2470
2471 /*
2472 * Ensure lo0 has an address of the same family.
2473 */
2474 IFADDR_READER_FOREACH(lo0ifa, lo0ifp) {
2475 if (lo0ifa->ifa_addr->sa_family ==
2476 ifa->ifa_addr->sa_family)
2477 break;
2478 }
2479 if (lo0ifa == NULL)
2480 break;
2481
2482 /*
2483 * Make sure to set rt->rt_ifa to the interface
2484 * address we are using, otherwise we will have trouble
2485 * with source address selection.
2486 */
2487 if (ifa != rt->rt_ifa)
2488 rt_replace_ifa(rt, ifa);
2489 break;
2490 case RTM_DELETE:
2491 default:
2492 break;
2493 }
2494 pserialize_read_exit(s);
2495 }
2496
2497 static void
2498 _if_down(struct ifnet *ifp)
2499 {
2500 struct ifaddr *ifa;
2501 struct domain *dp;
2502 int s, bound;
2503 struct psref psref;
2504
2505 ifp->if_flags &= ~IFF_UP;
2506 nanotime(&ifp->if_lastchange);
2507
2508 bound = curlwp_bind();
2509 s = pserialize_read_enter();
2510 IFADDR_READER_FOREACH(ifa, ifp) {
2511 ifa_acquire(ifa, &psref);
2512 pserialize_read_exit(s);
2513
2514 pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
2515
2516 s = pserialize_read_enter();
2517 ifa_release(ifa, &psref);
2518 }
2519 pserialize_read_exit(s);
2520 curlwp_bindx(bound);
2521
2522 /*
2523 * Modification of if_link_cansched is serialized with the
2524 * ifnet ioctl lock.
2525 *
2526 * The link state change lock is taken to synchronize with the
2527 * read in if_link_state_change_work_schedule(). Once we set
2528 * this to false, our if_link_work won't be scheduled. But
2529 * we need to wait for our if_link_work to drain in case we
2530 * lost that race.
2531 */
2532 IF_LINK_STATE_CHANGE_LOCK(ifp);
2533 ifp->if_link_cansched = false;
2534 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2535
2536 workqueue_wait(ifnet_link_state_wq, &ifp->if_link_work);
2537
2538 IFQ_PURGE(&ifp->if_snd);
2539 #if NCARP > 0
2540 if (ifp->if_carp)
2541 carp_carpdev_state(ifp);
2542 #endif
2543 rt_ifmsg(ifp);
2544 DOMAIN_FOREACH(dp) {
2545 if (dp->dom_if_down)
2546 dp->dom_if_down(ifp);
2547 }
2548 }
2549
2550 static void
2551 if_down_deactivated(struct ifnet *ifp)
2552 {
2553
2554 KASSERT(if_is_deactivated(ifp));
2555 _if_down(ifp);
2556 }
2557
2558 void
2559 if_down_locked(struct ifnet *ifp)
2560 {
2561
2562 KASSERT(IFNET_LOCKED(ifp));
2563 _if_down(ifp);
2564 }
2565
2566 /*
2567 * Mark an interface down and notify protocols of
2568 * the transition.
2569 * NOTE: must be called at splsoftnet or equivalent.
2570 */
2571 void
2572 if_down(struct ifnet *ifp)
2573 {
2574
2575 IFNET_LOCK(ifp);
2576 if_down_locked(ifp);
2577 IFNET_UNLOCK(ifp);
2578 }
2579
2580 /*
2581 * Must be called with holding if_ioctl_lock.
2582 */
2583 static void
2584 if_up_locked(struct ifnet *ifp)
2585 {
2586 #ifdef notyet
2587 struct ifaddr *ifa;
2588 #endif
2589 struct domain *dp;
2590
2591 KASSERT(IFNET_LOCKED(ifp));
2592
2593 KASSERT(!if_is_deactivated(ifp));
2594 ifp->if_flags |= IFF_UP;
2595 nanotime(&ifp->if_lastchange);
2596 #ifdef notyet
2597 /* this has no effect on IP, and will kill all ISO connections XXX */
2598 IFADDR_READER_FOREACH(ifa, ifp)
2599 pfctlinput(PRC_IFUP, ifa->ifa_addr);
2600 #endif
2601 #if NCARP > 0
2602 if (ifp->if_carp)
2603 carp_carpdev_state(ifp);
2604 #endif
2605 rt_ifmsg(ifp);
2606 DOMAIN_FOREACH(dp) {
2607 if (dp->dom_if_up)
2608 dp->dom_if_up(ifp);
2609 }
2610
2611 IF_LINK_STATE_CHANGE_LOCK(ifp);
2612 ifp->if_link_cansched = true;
2613 IF_LINK_STATE_CHANGE_UNLOCK(ifp);
2614 }
2615
2616 /*
2617 * Handle interface slowtimo timer routine. Called
2618 * from softclock, we decrement timer (if set) and
2619 * call the appropriate interface routine on expiration.
2620 */
2621 static void
2622 if_slowtimo(void *arg)
2623 {
2624 void (*slowtimo)(struct ifnet *);
2625 struct ifnet *ifp = arg;
2626 int s;
2627
2628 slowtimo = ifp->if_slowtimo;
2629 if (__predict_false(slowtimo == NULL))
2630 return;
2631
2632 s = splnet();
2633 if (ifp->if_timer != 0 && --ifp->if_timer == 0)
2634 (*slowtimo)(ifp);
2635
2636 splx(s);
2637
2638 if (__predict_true(ifp->if_slowtimo != NULL))
2639 callout_schedule(ifp->if_slowtimo_ch, hz / IFNET_SLOWHZ);
2640 }
2641
2642 /*
2643 * Mark an interface up and notify protocols of
2644 * the transition.
2645 * NOTE: must be called at splsoftnet or equivalent.
2646 */
2647 void
2648 if_up(struct ifnet *ifp)
2649 {
2650
2651 IFNET_LOCK(ifp);
2652 if_up_locked(ifp);
2653 IFNET_UNLOCK(ifp);
2654 }
2655
2656 /*
2657 * Set/clear promiscuous mode on interface ifp based on the truth value
2658 * of pswitch. The calls are reference counted so that only the first
2659 * "on" request actually has an effect, as does the final "off" request.
2660 * Results are undefined if the "off" and "on" requests are not matched.
2661 */
2662 int
2663 ifpromisc_locked(struct ifnet *ifp, int pswitch)
2664 {
2665 int pcount, ret = 0;
2666 u_short nflags;
2667
2668 KASSERT(IFNET_LOCKED(ifp));
2669
2670 pcount = ifp->if_pcount;
2671 if (pswitch) {
2672 /*
2673 * Allow the device to be "placed" into promiscuous
2674 * mode even if it is not configured up. It will
2675 * consult IFF_PROMISC when it is brought up.
2676 */
2677 if (ifp->if_pcount++ != 0)
2678 goto out;
2679 nflags = ifp->if_flags | IFF_PROMISC;
2680 } else {
2681 if (--ifp->if_pcount > 0)
2682 goto out;
2683 nflags = ifp->if_flags & ~IFF_PROMISC;
2684 }
2685 ret = if_flags_set(ifp, nflags);
2686 /* Restore interface state if not successful. */
2687 if (ret != 0) {
2688 ifp->if_pcount = pcount;
2689 }
2690 out:
2691 return ret;
2692 }
2693
2694 int
2695 ifpromisc(struct ifnet *ifp, int pswitch)
2696 {
2697 int e;
2698
2699 IFNET_LOCK(ifp);
2700 e = ifpromisc_locked(ifp, pswitch);
2701 IFNET_UNLOCK(ifp);
2702
2703 return e;
2704 }
2705
2706 /*
2707 * Map interface name to
2708 * interface structure pointer.
2709 */
2710 struct ifnet *
2711 ifunit(const char *name)
2712 {
2713 struct ifnet *ifp;
2714 const char *cp = name;
2715 u_int unit = 0;
2716 u_int i;
2717 int s;
2718
2719 /*
2720 * If the entire name is a number, treat it as an ifindex.
2721 */
2722 for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
2723 unit = unit * 10 + (*cp - '0');
2724 }
2725
2726 /*
2727 * If the number took all of the name, then it's a valid ifindex.
2728 */
2729 if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
2730 return if_byindex(unit);
2731
2732 ifp = NULL;
2733 s = pserialize_read_enter();
2734 IFNET_READER_FOREACH(ifp) {
2735 if (if_is_deactivated(ifp))
2736 continue;
2737 if (strcmp(ifp->if_xname, name) == 0)
2738 goto out;
2739 }
2740 out:
2741 pserialize_read_exit(s);
2742 return ifp;
2743 }
2744
2745 /*
2746 * Get a reference of an ifnet object by an interface name.
2747 * The returned reference is protected by psref(9). The caller
2748 * must release a returned reference by if_put after use.
2749 */
2750 struct ifnet *
2751 if_get(const char *name, struct psref *psref)
2752 {
2753 struct ifnet *ifp;
2754 const char *cp = name;
2755 u_int unit = 0;
2756 u_int i;
2757 int s;
2758
2759 /*
2760 * If the entire name is a number, treat it as an ifindex.
2761 */
2762 for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
2763 unit = unit * 10 + (*cp - '0');
2764 }
2765
2766 /*
2767 * If the number took all of the name, then it's a valid ifindex.
2768 */
2769 if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
2770 return if_get_byindex(unit, psref);
2771
2772 ifp = NULL;
2773 s = pserialize_read_enter();
2774 IFNET_READER_FOREACH(ifp) {
2775 if (if_is_deactivated(ifp))
2776 continue;
2777 if (strcmp(ifp->if_xname, name) == 0) {
2778 PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
2779 psref_acquire(psref, &ifp->if_psref,
2780 ifnet_psref_class);
2781 goto out;
2782 }
2783 }
2784 out:
2785 pserialize_read_exit(s);
2786 return ifp;
2787 }
2788
2789 /*
2790 * Release a reference of an ifnet object given by if_get, if_get_byindex
2791 * or if_get_bylla.
2792 */
2793 void
2794 if_put(const struct ifnet *ifp, struct psref *psref)
2795 {
2796
2797 if (ifp == NULL)
2798 return;
2799
2800 psref_release(psref, &ifp->if_psref, ifnet_psref_class);
2801 }
2802
2803 /*
2804 * Return ifp having idx. Return NULL if not found. Normally if_byindex
2805 * should be used.
2806 */
2807 ifnet_t *
2808 _if_byindex(u_int idx)
2809 {
2810
2811 return (__predict_true(idx < if_indexlim)) ? ifindex2ifnet[idx] : NULL;
2812 }
2813
2814 /*
2815 * Return ifp having idx. Return NULL if not found or the found ifp is
2816 * already deactivated.
2817 */
2818 ifnet_t *
2819 if_byindex(u_int idx)
2820 {
2821 ifnet_t *ifp;
2822
2823 ifp = _if_byindex(idx);
2824 if (ifp != NULL && if_is_deactivated(ifp))
2825 ifp = NULL;
2826 return ifp;
2827 }
2828
2829 /*
2830 * Get a reference of an ifnet object by an interface index.
2831 * The returned reference is protected by psref(9). The caller
2832 * must release a returned reference by if_put after use.
2833 */
2834 ifnet_t *
2835 if_get_byindex(u_int idx, struct psref *psref)
2836 {
2837 ifnet_t *ifp;
2838 int s;
2839
2840 s = pserialize_read_enter();
2841 ifp = if_byindex(idx);
2842 if (__predict_true(ifp != NULL)) {
2843 PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
2844 psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
2845 }
2846 pserialize_read_exit(s);
2847
2848 return ifp;
2849 }
2850
2851 ifnet_t *
2852 if_get_bylla(const void *lla, unsigned char lla_len, struct psref *psref)
2853 {
2854 ifnet_t *ifp;
2855 int s;
2856
2857 s = pserialize_read_enter();
2858 IFNET_READER_FOREACH(ifp) {
2859 if (if_is_deactivated(ifp))
2860 continue;
2861 if (ifp->if_addrlen != lla_len)
2862 continue;
2863 if (memcmp(lla, CLLADDR(ifp->if_sadl), lla_len) == 0) {
2864 psref_acquire(psref, &ifp->if_psref,
2865 ifnet_psref_class);
2866 break;
2867 }
2868 }
2869 pserialize_read_exit(s);
2870
2871 return ifp;
2872 }
2873
2874 /*
2875 * Note that it's safe only if the passed ifp is guaranteed to not be freed,
2876 * for example using pserialize or the ifp is already held or some other
2877 * object is held which guarantes the ifp to not be freed indirectly.
2878 */
2879 void
2880 if_acquire(struct ifnet *ifp, struct psref *psref)
2881 {
2882
2883 KASSERT(ifp->if_index != 0);
2884 psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
2885 }
2886
2887 bool
2888 if_held(struct ifnet *ifp)
2889 {
2890
2891 return psref_held(&ifp->if_psref, ifnet_psref_class);
2892 }
2893
2894 /*
2895 * Some tunnel interfaces can nest, e.g. IPv4 over IPv4 gif(4) tunnel over IPv4.
2896 * Check the tunnel nesting count.
2897 * Return > 0, if tunnel nesting count is more than limit.
2898 * Return 0, if tunnel nesting count is equal or less than limit.
2899 */
2900 int
2901 if_tunnel_check_nesting(struct ifnet *ifp, struct mbuf *m, int limit)
2902 {
2903 struct m_tag *mtag;
2904 int *count;
2905
2906 mtag = m_tag_find(m, PACKET_TAG_TUNNEL_INFO);
2907 if (mtag != NULL) {
2908 count = (int *)(mtag + 1);
2909 if (++(*count) > limit) {
2910 log(LOG_NOTICE,
2911 "%s: recursively called too many times(%d)\n",
2912 ifp->if_xname, *count);
2913 return EIO;
2914 }
2915 } else {
2916 mtag = m_tag_get(PACKET_TAG_TUNNEL_INFO, sizeof(*count),
2917 M_NOWAIT);
2918 if (mtag != NULL) {
2919 m_tag_prepend(m, mtag);
2920 count = (int *)(mtag + 1);
2921 *count = 0;
2922 } else {
2923 log(LOG_DEBUG,
2924 "%s: m_tag_get() failed, recursion calls are not prevented.\n",
2925 ifp->if_xname);
2926 }
2927 }
2928
2929 return 0;
2930 }
2931
2932 static void
2933 if_tunnel_ro_init_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2934 {
2935 struct tunnel_ro *tro = p;
2936
2937 tro->tr_ro = kmem_zalloc(sizeof(*tro->tr_ro), KM_SLEEP);
2938 tro->tr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
2939 }
2940
2941 static void
2942 if_tunnel_ro_fini_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2943 {
2944 struct tunnel_ro *tro = p;
2945
2946 rtcache_free(tro->tr_ro);
2947 kmem_free(tro->tr_ro, sizeof(*tro->tr_ro));
2948
2949 mutex_obj_free(tro->tr_lock);
2950 }
2951
2952 percpu_t *
2953 if_tunnel_alloc_ro_percpu(void)
2954 {
2955
2956 return percpu_create(sizeof(struct tunnel_ro),
2957 if_tunnel_ro_init_pc, if_tunnel_ro_fini_pc, NULL);
2958 }
2959
2960 void
2961 if_tunnel_free_ro_percpu(percpu_t *ro_percpu)
2962 {
2963
2964 percpu_free(ro_percpu, sizeof(struct tunnel_ro));
2965 }
2966
2967
2968 static void
2969 if_tunnel_rtcache_free_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
2970 {
2971 struct tunnel_ro *tro = p;
2972
2973 mutex_enter(tro->tr_lock);
2974 rtcache_free(tro->tr_ro);
2975 mutex_exit(tro->tr_lock);
2976 }
2977
2978 void if_tunnel_ro_percpu_rtcache_free(percpu_t *ro_percpu)
2979 {
2980
2981 percpu_foreach(ro_percpu, if_tunnel_rtcache_free_pc, NULL);
2982 }
2983
2984 void
2985 if_export_if_data(ifnet_t * const ifp, struct if_data *ifi, bool zero_stats)
2986 {
2987
2988 /* Collet the volatile stats first; this zeros *ifi. */
2989 if_stats_to_if_data(ifp, ifi, zero_stats);
2990
2991 ifi->ifi_type = ifp->if_type;
2992 ifi->ifi_addrlen = ifp->if_addrlen;
2993 ifi->ifi_hdrlen = ifp->if_hdrlen;
2994 ifi->ifi_link_state = ifp->if_link_state;
2995 ifi->ifi_mtu = ifp->if_mtu;
2996 ifi->ifi_metric = ifp->if_metric;
2997 ifi->ifi_baudrate = ifp->if_baudrate;
2998 ifi->ifi_lastchange = ifp->if_lastchange;
2999 }
3000
3001 /* common */
3002 int
3003 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
3004 {
3005 int s;
3006 struct ifreq *ifr;
3007 struct ifcapreq *ifcr;
3008 struct ifdatareq *ifdr;
3009 unsigned short flags;
3010 char *descr;
3011 int error;
3012
3013 switch (cmd) {
3014 case SIOCSIFCAP:
3015 ifcr = data;
3016 if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
3017 return EINVAL;
3018
3019 if (ifcr->ifcr_capenable == ifp->if_capenable)
3020 return 0;
3021
3022 ifp->if_capenable = ifcr->ifcr_capenable;
3023
3024 /* Pre-compute the checksum flags mask. */
3025 ifp->if_csum_flags_tx = 0;
3026 ifp->if_csum_flags_rx = 0;
3027 if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx)
3028 ifp->if_csum_flags_tx |= M_CSUM_IPv4;
3029 if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx)
3030 ifp->if_csum_flags_rx |= M_CSUM_IPv4;
3031
3032 if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx)
3033 ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
3034 if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx)
3035 ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
3036
3037 if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx)
3038 ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
3039 if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx)
3040 ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
3041
3042 if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx)
3043 ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
3044 if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx)
3045 ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
3046
3047 if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx)
3048 ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
3049 if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx)
3050 ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
3051
3052 if (ifp->if_capenable & IFCAP_TSOv4)
3053 ifp->if_csum_flags_tx |= M_CSUM_TSOv4;
3054 if (ifp->if_capenable & IFCAP_TSOv6)
3055 ifp->if_csum_flags_tx |= M_CSUM_TSOv6;
3056
3057 #if NBRIDGE > 0
3058 if (ifp->if_bridge != NULL)
3059 bridge_calc_csum_flags(ifp->if_bridge);
3060 #endif
3061
3062 if (ifp->if_flags & IFF_UP)
3063 return ENETRESET;
3064 return 0;
3065 case SIOCSIFFLAGS:
3066 ifr = data;
3067 /*
3068 * If if_is_mpsafe(ifp), KERNEL_LOCK isn't held here, but if_up
3069 * and if_down aren't MP-safe yet, so we must hold the lock.
3070 */
3071 KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
3072 if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
3073 s = splsoftnet();
3074 if_down_locked(ifp);
3075 splx(s);
3076 }
3077 if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
3078 s = splsoftnet();
3079 if_up_locked(ifp);
3080 splx(s);
3081 }
3082 KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
3083 flags = (ifp->if_flags & IFF_CANTCHANGE) |
3084 (ifr->ifr_flags &~ IFF_CANTCHANGE);
3085 if (ifp->if_flags != flags) {
3086 ifp->if_flags = flags;
3087 /* Notify that the flags have changed. */
3088 rt_ifmsg(ifp);
3089 }
3090 break;
3091 case SIOCGIFFLAGS:
3092 ifr = data;
3093 ifr->ifr_flags = ifp->if_flags;
3094 break;
3095
3096 case SIOCGIFMETRIC:
3097 ifr = data;
3098 ifr->ifr_metric = ifp->if_metric;
3099 break;
3100
3101 case SIOCGIFMTU:
3102 ifr = data;
3103 ifr->ifr_mtu = ifp->if_mtu;
3104 break;
3105
3106 case SIOCGIFDLT:
3107 ifr = data;
3108 ifr->ifr_dlt = ifp->if_dlt;
3109 break;
3110
3111 case SIOCGIFCAP:
3112 ifcr = data;
3113 ifcr->ifcr_capabilities = ifp->if_capabilities;
3114 ifcr->ifcr_capenable = ifp->if_capenable;
3115 break;
3116
3117 case SIOCSIFMETRIC:
3118 ifr = data;
3119 ifp->if_metric = ifr->ifr_metric;
3120 break;
3121
3122 case SIOCGIFDATA:
3123 ifdr = data;
3124 if_export_if_data(ifp, &ifdr->ifdr_data, false);
3125 break;
3126
3127 case SIOCGIFINDEX:
3128 ifr = data;
3129 ifr->ifr_index = ifp->if_index;
3130 break;
3131
3132 case SIOCZIFDATA:
3133 ifdr = data;
3134 if_export_if_data(ifp, &ifdr->ifdr_data, true);
3135 getnanotime(&ifp->if_lastchange);
3136 break;
3137 case SIOCSIFMTU:
3138 ifr = data;
3139 if (ifp->if_mtu == ifr->ifr_mtu)
3140 break;
3141 ifp->if_mtu = ifr->ifr_mtu;
3142 /*
3143 * If the link MTU changed, do network layer specific procedure.
3144 */
3145 #ifdef INET6
3146 KERNEL_LOCK_UNLESS_NET_MPSAFE();
3147 if (in6_present)
3148 nd6_setmtu(ifp);
3149 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
3150 #endif
3151 return ENETRESET;
3152 case SIOCSIFDESCR:
3153 error = kauth_authorize_network(curlwp->l_cred,
3154 KAUTH_NETWORK_INTERFACE,
3155 KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
3156 NULL);
3157 if (error)
3158 return error;
3159
3160 ifr = data;
3161
3162 if (ifr->ifr_buflen > IFDESCRSIZE)
3163 return ENAMETOOLONG;
3164
3165 if (ifr->ifr_buf == NULL || ifr->ifr_buflen == 0) {
3166 /* unset description */
3167 descr = NULL;
3168 } else {
3169 descr = kmem_zalloc(IFDESCRSIZE, KM_SLEEP);
3170 /*
3171 * copy (IFDESCRSIZE - 1) bytes to ensure
3172 * terminating nul
3173 */
3174 error = copyin(ifr->ifr_buf, descr, IFDESCRSIZE - 1);
3175 if (error) {
3176 kmem_free(descr, IFDESCRSIZE);
3177 return error;
3178 }
3179 }
3180
3181 if (ifp->if_description != NULL)
3182 kmem_free(ifp->if_description, IFDESCRSIZE);
3183
3184 ifp->if_description = descr;
3185 break;
3186
3187 case SIOCGIFDESCR:
3188 ifr = data;
3189 descr = ifp->if_description;
3190
3191 if (descr == NULL)
3192 return ENOMSG;
3193
3194 if (ifr->ifr_buflen < IFDESCRSIZE)
3195 return EINVAL;
3196
3197 error = copyout(descr, ifr->ifr_buf, IFDESCRSIZE);
3198 if (error)
3199 return error;
3200 break;
3201
3202 default:
3203 return ENOTTY;
3204 }
3205 return 0;
3206 }
3207
3208 int
3209 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
3210 {
3211 struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
3212 struct ifaddr *ifa;
3213 const struct sockaddr *any, *sa;
3214 union {
3215 struct sockaddr sa;
3216 struct sockaddr_storage ss;
3217 } u, v;
3218 int s, error = 0;
3219
3220 switch (cmd) {
3221 case SIOCSIFADDRPREF:
3222 error = kauth_authorize_network(curlwp->l_cred,
3223 KAUTH_NETWORK_INTERFACE,
3224 KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
3225 NULL);
3226 if (error)
3227 return error;
3228 break;
3229 case SIOCGIFADDRPREF:
3230 break;
3231 default:
3232 return EOPNOTSUPP;
3233 }
3234
3235 /* sanity checks */
3236 if (data == NULL || ifp == NULL) {
3237 panic("invalid argument to %s", __func__);
3238 /*NOTREACHED*/
3239 }
3240
3241 /* address must be specified on ADD and DELETE */
3242 sa = sstocsa(&ifap->ifap_addr);
3243 if (sa->sa_family != sofamily(so))
3244 return EINVAL;
3245 if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
3246 return EINVAL;
3247
3248 sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
3249
3250 s = pserialize_read_enter();
3251 IFADDR_READER_FOREACH(ifa, ifp) {
3252 if (ifa->ifa_addr->sa_family != sa->sa_family)
3253 continue;
3254 sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
3255 if (sockaddr_cmp(&u.sa, &v.sa) == 0)
3256 break;
3257 }
3258 if (ifa == NULL) {
3259 error = EADDRNOTAVAIL;
3260 goto out;
3261 }
3262
3263 switch (cmd) {
3264 case SIOCSIFADDRPREF:
3265 ifa->ifa_preference = ifap->ifap_preference;
3266 goto out;
3267 case SIOCGIFADDRPREF:
3268 /* fill in the if_laddrreq structure */
3269 (void)sockaddr_copy(sstosa(&ifap->ifap_addr),
3270 sizeof(ifap->ifap_addr), ifa->ifa_addr);
3271 ifap->ifap_preference = ifa->ifa_preference;
3272 goto out;
3273 default:
3274 error = EOPNOTSUPP;
3275 }
3276 out:
3277 pserialize_read_exit(s);
3278 return error;
3279 }
3280
3281 /*
3282 * Interface ioctls.
3283 */
3284 static int
3285 doifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
3286 {
3287 struct ifnet *ifp;
3288 struct ifreq *ifr;
3289 int error = 0;
3290 u_long ocmd = cmd;
3291 u_short oif_flags;
3292 struct ifreq ifrb;
3293 struct oifreq *oifr = NULL;
3294 int r;
3295 struct psref psref;
3296 int bound;
3297 bool do_if43_post = false;
3298 bool do_ifm80_post = false;
3299
3300 switch (cmd) {
3301 case SIOCGIFCONF:
3302 return ifconf(cmd, data);
3303 case SIOCINITIFADDR:
3304 return EPERM;
3305 default:
3306 MODULE_HOOK_CALL(uipc_syscalls_40_hook, (cmd, data), enosys(),
3307 error);
3308 if (error != ENOSYS)
3309 return error;
3310 MODULE_HOOK_CALL(uipc_syscalls_50_hook, (l, cmd, data),
3311 enosys(), error);
3312 if (error != ENOSYS)
3313 return error;
3314 error = 0;
3315 break;
3316 }
3317
3318 ifr = data;
3319 /* Pre-conversion */
3320 MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), error);
3321 if (cmd != ocmd) {
3322 oifr = data;
3323 data = ifr = &ifrb;
3324 IFREQO2N_43(oifr, ifr);
3325 do_if43_post = true;
3326 }
3327 MODULE_HOOK_CALL(ifmedia_80_pre_hook, (ifr, &cmd, &do_ifm80_post),
3328 enosys(), error);
3329
3330 switch (cmd) {
3331 case SIOCIFCREATE:
3332 case SIOCIFDESTROY:
3333 bound = curlwp_bind();
3334 if (l != NULL) {
3335 ifp = if_get(ifr->ifr_name, &psref);
3336 error = kauth_authorize_network(l->l_cred,
3337 KAUTH_NETWORK_INTERFACE,
3338 KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
3339 KAUTH_ARG(cmd), NULL);
3340 if (ifp != NULL)
3341 if_put(ifp, &psref);
3342 if (error != 0) {
3343 curlwp_bindx(bound);
3344 return error;
3345 }
3346 }
3347 KERNEL_LOCK_UNLESS_NET_MPSAFE();
3348 mutex_enter(&if_clone_mtx);
3349 r = (cmd == SIOCIFCREATE) ?
3350 if_clone_create(ifr->ifr_name) :
3351 if_clone_destroy(ifr->ifr_name);
3352 mutex_exit(&if_clone_mtx);
3353 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
3354 curlwp_bindx(bound);
3355 return r;
3356
3357 case SIOCIFGCLONERS:
3358 {
3359 struct if_clonereq *req = (struct if_clonereq *)data;
3360 return if_clone_list(req->ifcr_count, req->ifcr_buffer,
3361 &req->ifcr_total);
3362 }
3363 }
3364
3365 bound = curlwp_bind();
3366 ifp = if_get(ifr->ifr_name, &psref);
3367 if (ifp == NULL) {
3368 curlwp_bindx(bound);
3369 return ENXIO;
3370 }
3371
3372 switch (cmd) {
3373 case SIOCALIFADDR:
3374 case SIOCDLIFADDR:
3375 case SIOCSIFADDRPREF:
3376 case SIOCSIFFLAGS:
3377 case SIOCSIFCAP:
3378 case SIOCSIFMETRIC:
3379 case SIOCZIFDATA:
3380 case SIOCSIFMTU:
3381 case SIOCSIFPHYADDR:
3382 case SIOCDIFPHYADDR:
3383 #ifdef INET6
3384 case SIOCSIFPHYADDR_IN6:
3385 #endif
3386 case SIOCSLIFPHYADDR:
3387 case SIOCADDMULTI:
3388 case SIOCDELMULTI:
3389 case SIOCSETHERCAP:
3390 case SIOCSIFMEDIA:
3391 case SIOCSDRVSPEC:
3392 case SIOCG80211:
3393 case SIOCS80211:
3394 case SIOCS80211NWID:
3395 case SIOCS80211NWKEY:
3396 case SIOCS80211POWER:
3397 case SIOCS80211BSSID:
3398 case SIOCS80211CHANNEL:
3399 case SIOCSLINKSTR:
3400 if (l != NULL) {
3401 error = kauth_authorize_network(l->l_cred,
3402 KAUTH_NETWORK_INTERFACE,
3403 KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
3404 KAUTH_ARG(cmd), NULL);
3405 if (error != 0)
3406 goto out;
3407 }
3408 }
3409
3410 oif_flags = ifp->if_flags;
3411
3412 KERNEL_LOCK_UNLESS_IFP_MPSAFE(ifp);
3413 IFNET_LOCK(ifp);
3414
3415 error = (*ifp->if_ioctl)(ifp, cmd, data);
3416 if (error != ENOTTY)
3417 ;
3418 else if (so->so_proto == NULL)
3419 error = EOPNOTSUPP;
3420 else {
3421 KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
3422 MODULE_HOOK_CALL(if_ifioctl_43_hook,
3423 (so, ocmd, cmd, data, l), enosys(), error);
3424 if (error == ENOSYS)
3425 error = (*so->so_proto->pr_usrreqs->pr_ioctl)(so,
3426 cmd, data, ifp);
3427 KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
3428 }
3429
3430 if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
3431 if ((ifp->if_flags & IFF_UP) != 0) {
3432 int s = splsoftnet();
3433 if_up_locked(ifp);
3434 splx(s);
3435 }
3436 }
3437
3438 /* Post-conversion */
3439 if (do_ifm80_post && (error == 0))
3440 MODULE_HOOK_CALL(ifmedia_80_post_hook, (ifr, cmd),
3441 enosys(), error);
3442 if (do_if43_post)
3443 IFREQN2O_43(oifr, ifr);
3444
3445 IFNET_UNLOCK(ifp);
3446 KERNEL_UNLOCK_UNLESS_IFP_MPSAFE(ifp);
3447 out:
3448 if_put(ifp, &psref);
3449 curlwp_bindx(bound);
3450 return error;
3451 }
3452
3453 /*
3454 * Return interface configuration
3455 * of system. List may be used
3456 * in later ioctl's (above) to get
3457 * other information.
3458 *
3459 * Each record is a struct ifreq. Before the addition of
3460 * sockaddr_storage, the API rule was that sockaddr flavors that did
3461 * not fit would extend beyond the struct ifreq, with the next struct
3462 * ifreq starting sa_len beyond the struct sockaddr. Because the
3463 * union in struct ifreq includes struct sockaddr_storage, every kind
3464 * of sockaddr must fit. Thus, there are no longer any overlength
3465 * records.
3466 *
3467 * Records are added to the user buffer if they fit, and ifc_len is
3468 * adjusted to the length that was written. Thus, the user is only
3469 * assured of getting the complete list if ifc_len on return is at
3470 * least sizeof(struct ifreq) less than it was on entry.
3471 *
3472 * If the user buffer pointer is NULL, this routine copies no data and
3473 * returns the amount of space that would be needed.
3474 *
3475 * Invariants:
3476 * ifrp points to the next part of the user's buffer to be used. If
3477 * ifrp != NULL, space holds the number of bytes remaining that we may
3478 * write at ifrp. Otherwise, space holds the number of bytes that
3479 * would have been written had there been adequate space.
3480 */
3481 /*ARGSUSED*/
3482 static int
3483 ifconf(u_long cmd, void *data)
3484 {
3485 struct ifconf *ifc = (struct ifconf *)data;
3486 struct ifnet *ifp;
3487 struct ifaddr *ifa;
3488 struct ifreq ifr, *ifrp = NULL;
3489 int space = 0, error = 0;
3490 const int sz = (int)sizeof(struct ifreq);
3491 const bool docopy = ifc->ifc_req != NULL;
3492 int s;
3493 int bound;
3494 struct psref psref;
3495
3496 memset(&ifr, 0, sizeof(ifr));
3497 if (docopy) {
3498 space = ifc->ifc_len;
3499 ifrp = ifc->ifc_req;
3500 }
3501
3502 bound = curlwp_bind();
3503 s = pserialize_read_enter();
3504 IFNET_READER_FOREACH(ifp) {
3505 psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
3506 pserialize_read_exit(s);
3507
3508 (void)strncpy(ifr.ifr_name, ifp->if_xname,
3509 sizeof(ifr.ifr_name));
3510 if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0') {
3511 error = ENAMETOOLONG;
3512 goto release_exit;
3513 }
3514 if (IFADDR_READER_EMPTY(ifp)) {
3515 /* Interface with no addresses - send zero sockaddr. */
3516 memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
3517 if (!docopy) {
3518 space += sz;
3519 goto next;
3520 }
3521 if (space >= sz) {
3522 error = copyout(&ifr, ifrp, sz);
3523 if (error != 0)
3524 goto release_exit;
3525 ifrp++;
3526 space -= sz;
3527 }
3528 }
3529
3530 s = pserialize_read_enter();
3531 IFADDR_READER_FOREACH(ifa, ifp) {
3532 struct sockaddr *sa = ifa->ifa_addr;
3533 /* all sockaddrs must fit in sockaddr_storage */
3534 KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
3535
3536 if (!docopy) {
3537 space += sz;
3538 continue;
3539 }
3540 memcpy(&ifr.ifr_space, sa, sa->sa_len);
3541 pserialize_read_exit(s);
3542
3543 if (space >= sz) {
3544 error = copyout(&ifr, ifrp, sz);
3545 if (error != 0)
3546 goto release_exit;
3547 ifrp++; space -= sz;
3548 }
3549 s = pserialize_read_enter();
3550 }
3551 pserialize_read_exit(s);
3552
3553 next:
3554 s = pserialize_read_enter();
3555 psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
3556 }
3557 pserialize_read_exit(s);
3558 curlwp_bindx(bound);
3559
3560 if (docopy) {
3561 KASSERT(0 <= space && space <= ifc->ifc_len);
3562 ifc->ifc_len -= space;
3563 } else {
3564 KASSERT(space >= 0);
3565 ifc->ifc_len = space;
3566 }
3567 return (0);
3568
3569 release_exit:
3570 psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
3571 curlwp_bindx(bound);
3572 return error;
3573 }
3574
3575 int
3576 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
3577 {
3578 uint8_t len = sizeof(ifr->ifr_ifru.ifru_space);
3579 struct ifreq ifrb;
3580 struct oifreq *oifr = NULL;
3581 u_long ocmd = cmd;
3582 int hook;
3583
3584 MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), hook);
3585 if (hook != ENOSYS) {
3586 if (cmd != ocmd) {
3587 oifr = (struct oifreq *)(void *)ifr;
3588 ifr = &ifrb;
3589 IFREQO2N_43(oifr, ifr);
3590 len = sizeof(oifr->ifr_addr);
3591 }
3592 }
3593
3594 if (len < sa->sa_len)
3595 return EFBIG;
3596
3597 memset(&ifr->ifr_addr, 0, len);
3598 sockaddr_copy(&ifr->ifr_addr, len, sa);
3599
3600 if (cmd != ocmd)
3601 IFREQN2O_43(oifr, ifr);
3602 return 0;
3603 }
3604
3605 /*
3606 * wrapper function for the drivers which doesn't have if_transmit().
3607 */
3608 static int
3609 if_transmit(struct ifnet *ifp, struct mbuf *m)
3610 {
3611 int s, error;
3612 size_t pktlen = m->m_pkthdr.len;
3613 bool mcast = (m->m_flags & M_MCAST) != 0;
3614
3615 s = splnet();
3616
3617 IFQ_ENQUEUE(&ifp->if_snd, m, error);
3618 if (error != 0) {
3619 /* mbuf is already freed */
3620 goto out;
3621 }
3622
3623 net_stat_ref_t nsr = IF_STAT_GETREF(ifp);
3624 if_statadd_ref(nsr, if_obytes, pktlen);
3625 if (mcast)
3626 if_statinc_ref(nsr, if_omcasts);
3627 IF_STAT_PUTREF(ifp);
3628
3629 if ((ifp->if_flags & IFF_OACTIVE) == 0)
3630 if_start_lock(ifp);
3631 out:
3632 splx(s);
3633
3634 return error;
3635 }
3636
3637 int
3638 if_transmit_lock(struct ifnet *ifp, struct mbuf *m)
3639 {
3640 int error;
3641
3642 kmsan_check_mbuf(m);
3643
3644 #ifdef ALTQ
3645 KERNEL_LOCK(1, NULL);
3646 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
3647 error = if_transmit(ifp, m);
3648 KERNEL_UNLOCK_ONE(NULL);
3649 } else {
3650 KERNEL_UNLOCK_ONE(NULL);
3651 error = (*ifp->if_transmit)(ifp, m);
3652 /* mbuf is alredy freed */
3653 }
3654 #else /* !ALTQ */
3655 error = (*ifp->if_transmit)(ifp, m);
3656 /* mbuf is alredy freed */
3657 #endif /* !ALTQ */
3658
3659 return error;
3660 }
3661
3662 /*
3663 * Queue message on interface, and start output if interface
3664 * not yet active.
3665 */
3666 int
3667 ifq_enqueue(struct ifnet *ifp, struct mbuf *m)
3668 {
3669
3670 return if_transmit_lock(ifp, m);
3671 }
3672
3673 /*
3674 * Queue message on interface, possibly using a second fast queue
3675 */
3676 int
3677 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m)
3678 {
3679 int error = 0;
3680
3681 if (ifq != NULL
3682 #ifdef ALTQ
3683 && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
3684 #endif
3685 ) {
3686 if (IF_QFULL(ifq)) {
3687 IF_DROP(&ifp->if_snd);
3688 m_freem(m);
3689 if (error == 0)
3690 error = ENOBUFS;
3691 } else
3692 IF_ENQUEUE(ifq, m);
3693 } else
3694 IFQ_ENQUEUE(&ifp->if_snd, m, error);
3695 if (error != 0) {
3696 if_statinc(ifp, if_oerrors);
3697 return error;
3698 }
3699 return 0;
3700 }
3701
3702 int
3703 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
3704 {
3705 int rc;
3706
3707 KASSERT(IFNET_LOCKED(ifp));
3708 if (ifp->if_initaddr != NULL)
3709 rc = (*ifp->if_initaddr)(ifp, ifa, src);
3710 else if (src ||
3711 (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
3712 rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
3713
3714 return rc;
3715 }
3716
3717 int
3718 if_do_dad(struct ifnet *ifp)
3719 {
3720 if ((ifp->if_flags & IFF_LOOPBACK) != 0)
3721 return 0;
3722
3723 switch (ifp->if_type) {
3724 case IFT_FAITH:
3725 /*
3726 * These interfaces do not have the IFF_LOOPBACK flag,
3727 * but loop packets back. We do not have to do DAD on such
3728 * interfaces. We should even omit it, because loop-backed
3729 * responses would confuse the DAD procedure.
3730 */
3731 return 0;
3732 default:
3733 /*
3734 * Our DAD routine requires the interface up and running.
3735 * However, some interfaces can be up before the RUNNING
3736 * status. Additionaly, users may try to assign addresses
3737 * before the interface becomes up (or running).
3738 * We simply skip DAD in such a case as a work around.
3739 * XXX: we should rather mark "tentative" on such addresses,
3740 * and do DAD after the interface becomes ready.
3741 */
3742 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
3743 (IFF_UP | IFF_RUNNING))
3744 return 0;
3745
3746 return 1;
3747 }
3748 }
3749
3750 int
3751 if_flags_set(ifnet_t *ifp, const u_short flags)
3752 {
3753 int rc;
3754
3755 KASSERT(IFNET_LOCKED(ifp));
3756
3757 if (ifp->if_setflags != NULL)
3758 rc = (*ifp->if_setflags)(ifp, flags);
3759 else {
3760 u_short cantflags, chgdflags;
3761 struct ifreq ifr;
3762
3763 chgdflags = ifp->if_flags ^ flags;
3764 cantflags = chgdflags & IFF_CANTCHANGE;
3765
3766 if (cantflags != 0)
3767 ifp->if_flags ^= cantflags;
3768
3769 /* Traditionally, we do not call if_ioctl after
3770 * setting/clearing only IFF_PROMISC if the interface
3771 * isn't IFF_UP. Uphold that tradition.
3772 */
3773 if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
3774 return 0;
3775
3776 memset(&ifr, 0, sizeof(ifr));
3777
3778 ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
3779 rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
3780
3781 if (rc != 0 && cantflags != 0)
3782 ifp->if_flags ^= cantflags;
3783 }
3784
3785 return rc;
3786 }
3787
3788 int
3789 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
3790 {
3791 int rc;
3792 struct ifreq ifr;
3793
3794 ifreq_setaddr(cmd, &ifr, sa);
3795 rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
3796
3797 return rc;
3798 }
3799
3800 static void
3801 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
3802 struct ifaltq *ifq)
3803 {
3804 const struct sysctlnode *cnode, *rnode;
3805
3806 if (sysctl_createv(clog, 0, NULL, &rnode,
3807 CTLFLAG_PERMANENT,
3808 CTLTYPE_NODE, "interfaces",
3809 SYSCTL_DESCR("Per-interface controls"),
3810 NULL, 0, NULL, 0,
3811 CTL_NET, CTL_CREATE, CTL_EOL) != 0)
3812 goto bad;
3813
3814 if (sysctl_createv(clog, 0, &rnode, &rnode,
3815 CTLFLAG_PERMANENT,
3816 CTLTYPE_NODE, ifname,
3817 SYSCTL_DESCR("Interface controls"),
3818 NULL, 0, NULL, 0,
3819 CTL_CREATE, CTL_EOL) != 0)
3820 goto bad;
3821
3822 if (sysctl_createv(clog, 0, &rnode, &rnode,
3823 CTLFLAG_PERMANENT,
3824 CTLTYPE_NODE, "sndq",
3825 SYSCTL_DESCR("Interface output queue controls"),
3826 NULL, 0, NULL, 0,
3827 CTL_CREATE, CTL_EOL) != 0)
3828 goto bad;
3829
3830 if (sysctl_createv(clog, 0, &rnode, &cnode,
3831 CTLFLAG_PERMANENT,
3832 CTLTYPE_INT, "len",
3833 SYSCTL_DESCR("Current output queue length"),
3834 NULL, 0, &ifq->ifq_len, 0,
3835 CTL_CREATE, CTL_EOL) != 0)
3836 goto bad;
3837
3838 if (sysctl_createv(clog, 0, &rnode, &cnode,
3839 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3840 CTLTYPE_INT, "maxlen",
3841 SYSCTL_DESCR("Maximum allowed output queue length"),
3842 NULL, 0, &ifq->ifq_maxlen, 0,
3843 CTL_CREATE, CTL_EOL) != 0)
3844 goto bad;
3845
3846 if (sysctl_createv(clog, 0, &rnode, &cnode,
3847 CTLFLAG_PERMANENT,
3848 CTLTYPE_INT, "drops",
3849 SYSCTL_DESCR("Packets dropped due to full output queue"),
3850 NULL, 0, &ifq->ifq_drops, 0,
3851 CTL_CREATE, CTL_EOL) != 0)
3852 goto bad;
3853
3854 return;
3855 bad:
3856 printf("%s: could not attach sysctl nodes\n", ifname);
3857 return;
3858 }
3859
3860 #if defined(INET) || defined(INET6)
3861
3862 #define SYSCTL_NET_PKTQ(q, cn, c) \
3863 static int \
3864 sysctl_net_##q##_##cn(SYSCTLFN_ARGS) \
3865 { \
3866 return sysctl_pktq_count(SYSCTLFN_CALL(rnode), q, c); \
3867 }
3868
3869 #if defined(INET)
3870 static int
3871 sysctl_net_ip_pktq_maxlen(SYSCTLFN_ARGS)
3872 {
3873 return sysctl_pktq_maxlen(SYSCTLFN_CALL(rnode), ip_pktq);
3874 }
3875 SYSCTL_NET_PKTQ(ip_pktq, items, PKTQ_NITEMS)
3876 SYSCTL_NET_PKTQ(ip_pktq, drops, PKTQ_DROPS)
3877 #endif
3878
3879 #if defined(INET6)
3880 static int
3881 sysctl_net_ip6_pktq_maxlen(SYSCTLFN_ARGS)
3882 {
3883 return sysctl_pktq_maxlen(SYSCTLFN_CALL(rnode), ip6_pktq);
3884 }
3885 SYSCTL_NET_PKTQ(ip6_pktq, items, PKTQ_NITEMS)
3886 SYSCTL_NET_PKTQ(ip6_pktq, drops, PKTQ_DROPS)
3887 #endif
3888
3889 static void
3890 sysctl_net_pktq_setup(struct sysctllog **clog, int pf)
3891 {
3892 sysctlfn len_func = NULL, maxlen_func = NULL, drops_func = NULL;
3893 const char *pfname = NULL, *ipname = NULL;
3894 int ipn = 0, qid = 0;
3895
3896 switch (pf) {
3897 #if defined(INET)
3898 case PF_INET:
3899 len_func = sysctl_net_ip_pktq_items;
3900 maxlen_func = sysctl_net_ip_pktq_maxlen;
3901 drops_func = sysctl_net_ip_pktq_drops;
3902 pfname = "inet", ipn = IPPROTO_IP;
3903 ipname = "ip", qid = IPCTL_IFQ;
3904 break;
3905 #endif
3906 #if defined(INET6)
3907 case PF_INET6:
3908 len_func = sysctl_net_ip6_pktq_items;
3909 maxlen_func = sysctl_net_ip6_pktq_maxlen;
3910 drops_func = sysctl_net_ip6_pktq_drops;
3911 pfname = "inet6", ipn = IPPROTO_IPV6;
3912 ipname = "ip6", qid = IPV6CTL_IFQ;
3913 break;
3914 #endif
3915 default:
3916 KASSERT(false);
3917 }
3918
3919 sysctl_createv(clog, 0, NULL, NULL,
3920 CTLFLAG_PERMANENT,
3921 CTLTYPE_NODE, pfname, NULL,
3922 NULL, 0, NULL, 0,
3923 CTL_NET, pf, CTL_EOL);
3924 sysctl_createv(clog, 0, NULL, NULL,
3925 CTLFLAG_PERMANENT,
3926 CTLTYPE_NODE, ipname, NULL,
3927 NULL, 0, NULL, 0,
3928 CTL_NET, pf, ipn, CTL_EOL);
3929 sysctl_createv(clog, 0, NULL, NULL,
3930 CTLFLAG_PERMANENT,
3931 CTLTYPE_NODE, "ifq",
3932 SYSCTL_DESCR("Protocol input queue controls"),
3933 NULL, 0, NULL, 0,
3934 CTL_NET, pf, ipn, qid, CTL_EOL);
3935
3936 sysctl_createv(clog, 0, NULL, NULL,
3937 CTLFLAG_PERMANENT,
3938 CTLTYPE_QUAD, "len",
3939 SYSCTL_DESCR("Current input queue length"),
3940 len_func, 0, NULL, 0,
3941 CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
3942 sysctl_createv(clog, 0, NULL, NULL,
3943 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3944 CTLTYPE_INT, "maxlen",
3945 SYSCTL_DESCR("Maximum allowed input queue length"),
3946 maxlen_func, 0, NULL, 0,
3947 CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
3948 sysctl_createv(clog, 0, NULL, NULL,
3949 CTLFLAG_PERMANENT,
3950 CTLTYPE_QUAD, "drops",
3951 SYSCTL_DESCR("Packets dropped due to full input queue"),
3952 drops_func, 0, NULL, 0,
3953 CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
3954 }
3955 #endif /* INET || INET6 */
3956
3957 static int
3958 if_sdl_sysctl(SYSCTLFN_ARGS)
3959 {
3960 struct ifnet *ifp;
3961 const struct sockaddr_dl *sdl;
3962 struct psref psref;
3963 int error = 0;
3964 int bound;
3965
3966 if (namelen != 1)
3967 return EINVAL;
3968
3969 bound = curlwp_bind();
3970 ifp = if_get_byindex(name[0], &psref);
3971 if (ifp == NULL) {
3972 error = ENODEV;
3973 goto out0;
3974 }
3975
3976 sdl = ifp->if_sadl;
3977 if (sdl == NULL) {
3978 *oldlenp = 0;
3979 goto out1;
3980 }
3981
3982 if (oldp == NULL) {
3983 *oldlenp = sdl->sdl_alen;
3984 goto out1;
3985 }
3986
3987 if (*oldlenp >= sdl->sdl_alen)
3988 *oldlenp = sdl->sdl_alen;
3989 error = sysctl_copyout(l, &sdl->sdl_data[sdl->sdl_nlen], oldp, *oldlenp);
3990 out1:
3991 if_put(ifp, &psref);
3992 out0:
3993 curlwp_bindx(bound);
3994 return error;
3995 }
3996
3997 static void
3998 if_sysctl_setup(struct sysctllog **clog)
3999 {
4000 const struct sysctlnode *rnode = NULL;
4001
4002 sysctl_createv(clog, 0, NULL, &rnode,
4003 CTLFLAG_PERMANENT,
4004 CTLTYPE_NODE, "sdl",
4005 SYSCTL_DESCR("Get active link-layer address"),
4006 if_sdl_sysctl, 0, NULL, 0,
4007 CTL_NET, CTL_CREATE, CTL_EOL);
4008
4009 #if defined(INET)
4010 sysctl_net_pktq_setup(NULL, PF_INET);
4011 #endif
4012 #ifdef INET6
4013 if (in6_present)
4014 sysctl_net_pktq_setup(NULL, PF_INET6);
4015 #endif
4016 }
4017