Home | History | Annotate | Line # | Download | only in net
if_gre.c revision 1.126
      1 /*	$NetBSD: if_gre.c,v 1.126 2008/03/27 19:06:52 ad Exp $ */
      2 
      3 /*
      4  * Copyright (c) 1998, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Heiko W.Rupp <hwr (at) pilhuhn.de>
      9  *
     10  * IPv6-over-GRE contributed by Gert Doering <gert (at) greenie.muc.de>
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *        This product includes software developed by the NetBSD
     23  *        Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*
     42  * Encapsulate L3 protocols into IP
     43  * See RFC 1701 and 1702 for more details.
     44  * If_gre is compatible with Cisco GRE tunnels, so you can
     45  * have a NetBSD box as the other end of a tunnel interface of a Cisco
     46  * router. See gre(4) for more details.
     47  */
     48 
     49 #include <sys/cdefs.h>
     50 __KERNEL_RCSID(0, "$NetBSD: if_gre.c,v 1.126 2008/03/27 19:06:52 ad Exp $");
     51 
     52 #include "opt_gre.h"
     53 #include "opt_inet.h"
     54 #include "bpfilter.h"
     55 
     56 #ifdef INET
     57 #include <sys/param.h>
     58 #include <sys/file.h>
     59 #include <sys/filedesc.h>
     60 #include <sys/malloc.h>
     61 #include <sys/mallocvar.h>
     62 #include <sys/mbuf.h>
     63 #include <sys/proc.h>
     64 #include <sys/domain.h>
     65 #include <sys/protosw.h>
     66 #include <sys/socket.h>
     67 #include <sys/socketvar.h>
     68 #include <sys/ioctl.h>
     69 #include <sys/queue.h>
     70 #include <sys/intr.h>
     71 #if __NetBSD__
     72 #include <sys/systm.h>
     73 #include <sys/sysctl.h>
     74 #include <sys/kauth.h>
     75 #endif
     76 
     77 #include <sys/kernel.h>
     78 #include <sys/mutex.h>
     79 #include <sys/condvar.h>
     80 #include <sys/kthread.h>
     81 
     82 #include <sys/cpu.h>
     83 
     84 #include <net/ethertypes.h>
     85 #include <net/if.h>
     86 #include <net/if_types.h>
     87 #include <net/netisr.h>
     88 #include <net/route.h>
     89 
     90 #ifdef INET
     91 #include <netinet/in.h>
     92 #include <netinet/in_systm.h>
     93 #include <netinet/in_var.h>
     94 #include <netinet/ip.h>
     95 #include <netinet/ip_var.h>
     96 #else
     97 #error "Huh? if_gre without inet?"
     98 #endif
     99 
    100 
    101 #ifdef NETATALK
    102 #include <netatalk/at.h>
    103 #include <netatalk/at_var.h>
    104 #include <netatalk/at_extern.h>
    105 #endif
    106 
    107 #if NBPFILTER > 0
    108 #include <sys/time.h>
    109 #include <net/bpf.h>
    110 #endif
    111 
    112 #include <net/if_gre.h>
    113 
    114 #include <compat/sys/socket.h>
    115 #include <compat/sys/sockio.h>
    116 /*
    117  * It is not easy to calculate the right value for a GRE MTU.
    118  * We leave this task to the admin and use the same default that
    119  * other vendors use.
    120  */
    121 #define GREMTU 1476
    122 
    123 #ifdef GRE_DEBUG
    124 int gre_debug = 0;
    125 #define	GRE_DPRINTF(__sc, __fmt, ...)				\
    126 	do {							\
    127 		if (__predict_false(gre_debug ||		\
    128 		    ((__sc)->sc_if.if_flags & IFF_DEBUG) != 0))	\
    129 			printf(__fmt, __VA_ARGS__);		\
    130 	} while (/*CONSTCOND*/0)
    131 #else
    132 #define	GRE_DPRINTF(__sc, __fmt, ...)	do { } while (/*CONSTCOND*/0)
    133 #endif /* GRE_DEBUG */
    134 
    135 int ip_gre_ttl = GRE_TTL;
    136 MALLOC_DEFINE(M_GRE_BUFQ, "gre_bufq", "gre mbuf queue");
    137 
    138 static int gre_clone_create(struct if_clone *, int);
    139 static int gre_clone_destroy(struct ifnet *);
    140 
    141 static struct if_clone gre_cloner =
    142     IF_CLONE_INITIALIZER("gre", gre_clone_create, gre_clone_destroy);
    143 
    144 static int gre_input(struct gre_softc *, struct mbuf *, int,
    145     const struct gre_h *);
    146 static bool gre_is_nullconf(const struct gre_soparm *);
    147 static int gre_output(struct ifnet *, struct mbuf *,
    148 			   const struct sockaddr *, struct rtentry *);
    149 static int gre_ioctl(struct ifnet *, u_long, void *);
    150 static void gre_closef(file_t **);
    151 static int gre_getsockname(struct socket *, struct mbuf *, struct lwp *);
    152 static int gre_getpeername(struct socket *, struct mbuf *, struct lwp *);
    153 static int gre_getnames(struct socket *, struct lwp *,
    154     struct sockaddr_storage *, struct sockaddr_storage *);
    155 static void gre_clearconf(struct gre_soparm *, bool);
    156 static int gre_soreceive(struct socket *, struct mbuf **);
    157 static int gre_sosend(struct socket *, struct mbuf *, struct lwp *);
    158 static struct socket *gre_reconf(struct gre_softc *, struct socket *, lwp_t *,
    159     const struct gre_soparm *);
    160 
    161 static int
    162 nearest_pow2(size_t len0)
    163 {
    164 	size_t len, mid;
    165 
    166 	if (len0 == 0)
    167 		return 1;
    168 
    169 	for (len = len0; (len & (len - 1)) != 0; len &= len - 1)
    170 		;
    171 
    172 	mid = len | (len >> 1);
    173 
    174 	/* avoid overflow */
    175 	if ((len << 1) < len)
    176 		return len;
    177 	if (len0 >= mid)
    178 		return len << 1;
    179 	return len;
    180 }
    181 
    182 static struct gre_bufq *
    183 gre_bufq_init(struct gre_bufq *bq, size_t len0)
    184 {
    185 	size_t len;
    186 
    187 	len = nearest_pow2(len0);
    188 
    189 	memset(bq, 0, sizeof(*bq));
    190 	bq->bq_buf = malloc(len * sizeof(struct mbuf *), M_GRE_BUFQ, M_WAITOK);
    191 	bq->bq_len = len;
    192 	bq->bq_lenmask = len - 1;
    193 
    194 	return bq;
    195 }
    196 
    197 static bool
    198 gre_bufq_empty(struct gre_bufq *bq)
    199 {
    200 	return bq->bq_prodidx == bq->bq_considx;
    201 }
    202 
    203 static struct mbuf *
    204 gre_bufq_dequeue(struct gre_bufq *bq)
    205 {
    206 	struct mbuf *m;
    207 
    208 	if (gre_bufq_empty(bq))
    209 		return NULL;
    210 
    211 	m = bq->bq_buf[bq->bq_considx];
    212 	bq->bq_considx = (bq->bq_considx + 1) & bq->bq_lenmask;
    213 
    214 	return m;
    215 }
    216 
    217 static void
    218 gre_bufq_purge(struct gre_bufq *bq)
    219 {
    220 	struct mbuf *m;
    221 
    222 	while ((m = gre_bufq_dequeue(bq)) != NULL)
    223 		m_freem(m);
    224 }
    225 
    226 static int
    227 gre_bufq_enqueue(struct gre_bufq *bq, struct mbuf *m)
    228 {
    229 	int next;
    230 
    231 	next = (bq->bq_prodidx + 1) & bq->bq_lenmask;
    232 
    233 	if (next == bq->bq_considx) {
    234 		bq->bq_drops++;
    235 		return ENOBUFS;
    236 	}
    237 
    238 	bq->bq_buf[bq->bq_prodidx] = m;
    239 	bq->bq_prodidx = next;
    240 	return 0;
    241 }
    242 
    243 static void
    244 greintr(void *arg)
    245 {
    246 	struct gre_softc *sc = (struct gre_softc *)arg;
    247 	struct socket *so = sc->sc_so;
    248 	lwp_t *l = curlwp;
    249 	int rc;
    250 	struct mbuf *m;
    251 
    252 	KASSERT(sc->sc_so != NULL);
    253 
    254 	sc->sc_send_ev.ev_count++;
    255 	GRE_DPRINTF(sc, "%s: enter\n", __func__);
    256 	while ((m = gre_bufq_dequeue(&sc->sc_snd)) != NULL) {
    257 		/* XXX handle ENOBUFS? */
    258 		if ((rc = gre_sosend(so, m, l)) != 0) {
    259 			GRE_DPRINTF(sc, "%s: gre_sosend failed %d\n", __func__,
    260 			    rc);
    261 		}
    262 	}
    263 }
    264 
    265 /* Caller must hold sc->sc_mtx. */
    266 static void
    267 gre_wait(struct gre_softc *sc)
    268 {
    269 	sc->sc_waiters++;
    270 	cv_wait(&sc->sc_condvar, &sc->sc_mtx);
    271 	sc->sc_waiters--;
    272 }
    273 
    274 /* Caller must hold sc->sc_mtx. */
    275 static void
    276 gre_join(struct gre_softc *sc)
    277 {
    278 	while (sc->sc_waiters > 0)
    279 		cv_wait(&sc->sc_condvar, &sc->sc_mtx);
    280 }
    281 
    282 static void
    283 gre_evcnt_detach(struct gre_softc *sc)
    284 {
    285 	evcnt_detach(&sc->sc_unsupp_ev);
    286 	evcnt_detach(&sc->sc_pullup_ev);
    287 	evcnt_detach(&sc->sc_error_ev);
    288 	evcnt_detach(&sc->sc_block_ev);
    289 	evcnt_detach(&sc->sc_recv_ev);
    290 
    291 	evcnt_detach(&sc->sc_oflow_ev);
    292 	evcnt_detach(&sc->sc_send_ev);
    293 }
    294 
    295 static void
    296 gre_evcnt_attach(struct gre_softc *sc)
    297 {
    298 	evcnt_attach_dynamic(&sc->sc_recv_ev, EVCNT_TYPE_MISC,
    299 	    NULL, sc->sc_if.if_xname, "recv");
    300 	evcnt_attach_dynamic(&sc->sc_block_ev, EVCNT_TYPE_MISC,
    301 	    &sc->sc_recv_ev, sc->sc_if.if_xname, "would block");
    302 	evcnt_attach_dynamic(&sc->sc_error_ev, EVCNT_TYPE_MISC,
    303 	    &sc->sc_recv_ev, sc->sc_if.if_xname, "error");
    304 	evcnt_attach_dynamic(&sc->sc_pullup_ev, EVCNT_TYPE_MISC,
    305 	    &sc->sc_recv_ev, sc->sc_if.if_xname, "pullup failed");
    306 	evcnt_attach_dynamic(&sc->sc_unsupp_ev, EVCNT_TYPE_MISC,
    307 	    &sc->sc_recv_ev, sc->sc_if.if_xname, "unsupported");
    308 
    309 	evcnt_attach_dynamic(&sc->sc_send_ev, EVCNT_TYPE_MISC,
    310 	    NULL, sc->sc_if.if_xname, "send");
    311 	evcnt_attach_dynamic(&sc->sc_oflow_ev, EVCNT_TYPE_MISC,
    312 	    &sc->sc_send_ev, sc->sc_if.if_xname, "overflow");
    313 }
    314 
    315 static int
    316 gre_clone_create(struct if_clone *ifc, int unit)
    317 {
    318 	struct gre_soparm sp;
    319 	struct gre_softc *sc;
    320 
    321 	sc = malloc(sizeof(struct gre_softc), M_DEVBUF, M_WAITOK|M_ZERO);
    322 	mutex_init(&sc->sc_mtx, MUTEX_DRIVER, IPL_SOFTNET);
    323 	cv_init(&sc->sc_condvar, "gre wait");
    324 
    325 	snprintf(sc->sc_if.if_xname, sizeof(sc->sc_if.if_xname), "%s%d",
    326 	    ifc->ifc_name, unit);
    327 	sc->sc_if.if_softc = sc;
    328 	sc->sc_if.if_type = IFT_TUNNEL;
    329 	sc->sc_if.if_addrlen = 0;
    330 	sc->sc_if.if_hdrlen = sizeof(struct ip) + sizeof(struct gre_h);
    331 	sc->sc_if.if_dlt = DLT_NULL;
    332 	sc->sc_if.if_mtu = GREMTU;
    333 	sc->sc_if.if_flags = IFF_POINTOPOINT|IFF_MULTICAST;
    334 	sc->sc_if.if_output = gre_output;
    335 	sc->sc_if.if_ioctl = gre_ioctl;
    336 	sockaddr_copy(sstosa(&sp.sp_dst), sizeof(sp.sp_dst), sintocsa(&in_any));
    337 	sockaddr_copy(sstosa(&sp.sp_src), sizeof(sp.sp_src), sintocsa(&in_any));
    338 	sp.sp_proto = IPPROTO_GRE;
    339 	sp.sp_type = SOCK_RAW;
    340 	sp.sp_bysock = 0;
    341 	sp.sp_fd = -1;
    342 	sc->sc_soparm = sp;
    343 
    344 	gre_evcnt_attach(sc);
    345 
    346 	gre_bufq_init(&sc->sc_snd, 17);
    347 	sc->sc_if.if_flags |= IFF_LINK0;
    348 	if_attach(&sc->sc_if);
    349 	if_alloc_sadl(&sc->sc_if);
    350 #if NBPFILTER > 0
    351 	bpfattach(&sc->sc_if, DLT_NULL, sizeof(uint32_t));
    352 #endif
    353 	sc->sc_lwp = &lwp0;
    354 	sc->sc_state = GRE_S_IDLE;
    355 	return 0;
    356 }
    357 
    358 static int
    359 gre_clone_destroy(struct ifnet *ifp)
    360 {
    361 	int s;
    362 	struct gre_softc *sc = ifp->if_softc;
    363 
    364 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    365 
    366 #if NBPFILTER > 0
    367 	bpfdetach(ifp);
    368 #endif
    369 	s = splnet();
    370 	if_detach(ifp);
    371 
    372 	/* Some LWPs may still wait in gre_ioctl_lock(), however,
    373 	 * no new LWP will enter gre_ioctl_lock(), because ifunit()
    374 	 * cannot locate the interface any longer.
    375 	 */
    376 	mutex_enter(&sc->sc_mtx);
    377 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    378 	while (sc->sc_state != GRE_S_IDLE)
    379 		gre_wait(sc);
    380 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    381 	sc->sc_state = GRE_S_DIE;
    382 	cv_broadcast(&sc->sc_condvar);
    383 	gre_join(sc);
    384 	/* At this point, no other LWP will access the gre_softc, so
    385 	 * we can release the mutex.
    386 	 */
    387 	mutex_exit(&sc->sc_mtx);
    388 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    389 	/* Note that we must not hold the mutex while we call gre_reconf(). */
    390 	sc->sc_so = gre_reconf(sc, sc->sc_so, sc->sc_lwp, NULL);
    391 	splx(s);
    392 
    393 	cv_destroy(&sc->sc_condvar);
    394 	mutex_destroy(&sc->sc_mtx);
    395 	gre_evcnt_detach(sc);
    396 	free(sc, M_DEVBUF);
    397 
    398 	return 0;
    399 }
    400 
    401 static void
    402 gre_receive(struct socket *so, void *arg, int waitflag)
    403 {
    404 	struct gre_softc *sc = (struct gre_softc *)arg;
    405 	int rc;
    406 	const struct gre_h *gh;
    407 	struct mbuf *m;
    408 
    409 	GRE_DPRINTF(sc, "%s: enter\n", __func__);
    410 
    411 	sc->sc_recv_ev.ev_count++;
    412 
    413 	rc = gre_soreceive(so, &m);
    414 	/* TBD Back off if ECONNREFUSED (indicates
    415 	 * ICMP Port Unreachable)?
    416 	 */
    417 	if (rc == EWOULDBLOCK) {
    418 		GRE_DPRINTF(sc, "%s: EWOULDBLOCK\n", __func__);
    419 		sc->sc_block_ev.ev_count++;
    420 		return;
    421 	} else if (rc != 0 || m == NULL) {
    422 		GRE_DPRINTF(sc, "%s: rc %d m %p\n",
    423 		    sc->sc_if.if_xname, rc, (void *)m);
    424 		sc->sc_error_ev.ev_count++;
    425 		return;
    426 	}
    427 	if (m->m_len < sizeof(*gh) && (m = m_pullup(m, sizeof(*gh))) == NULL) {
    428 		GRE_DPRINTF(sc, "%s: m_pullup failed\n", __func__);
    429 		sc->sc_pullup_ev.ev_count++;
    430 		return;
    431 	}
    432 	gh = mtod(m, const struct gre_h *);
    433 
    434 	if (gre_input(sc, m, 0, gh) == 0) {
    435 		sc->sc_unsupp_ev.ev_count++;
    436 		GRE_DPRINTF(sc, "%s: dropping unsupported\n", __func__);
    437 		m_freem(m);
    438 	}
    439 }
    440 
    441 static void
    442 gre_upcall_add(struct socket *so, void *arg)
    443 {
    444 	/* XXX What if the kernel already set an upcall? */
    445 	KASSERT((so->so_rcv.sb_flags & SB_UPCALL) == 0);
    446 	so->so_upcallarg = arg;
    447 	so->so_upcall = gre_receive;
    448 	so->so_rcv.sb_flags |= SB_UPCALL;
    449 }
    450 
    451 static void
    452 gre_upcall_remove(struct socket *so)
    453 {
    454 	so->so_rcv.sb_flags &= ~SB_UPCALL;
    455 	so->so_upcallarg = NULL;
    456 	so->so_upcall = NULL;
    457 }
    458 
    459 static int
    460 gre_socreate(struct gre_softc *sc, struct lwp *l,
    461     struct gre_soparm *sp, int *fdout)
    462 {
    463 	const struct protosw *pr;
    464 	int fd, rc;
    465 	struct mbuf *m;
    466 	struct sockaddr *sa;
    467 	sa_family_t af;
    468 	struct socket *so;
    469 
    470 	GRE_DPRINTF(sc, "%s: enter\n", __func__);
    471 
    472 	af = sp->sp_src.ss_family;
    473 	rc = fsocreate(af, &so, sp->sp_type, sp->sp_proto, l, &fd);
    474 	if (rc != 0) {
    475 		GRE_DPRINTF(sc, "%s: fsocreate failed\n", __func__);
    476 		return rc;
    477 	}
    478 	if ((rc = fd_getsock(fd, &so)) == 0) {
    479 		return rc;
    480 	}
    481 	if ((m = getsombuf(so, MT_SONAME)) == NULL) {
    482 		rc = ENOBUFS;
    483 		goto out;
    484 	}
    485 	sa = mtod(m, struct sockaddr *);
    486 	sockaddr_copy(sa, MIN(MLEN, sizeof(sp->sp_src)), sstosa(&sp->sp_src));
    487 	m->m_len = sp->sp_src.ss_len;
    488 
    489 #if 0
    490 	/* XXX */
    491 	GRE_DPRINTF(sc, "%s: bind 0x%08" PRIx32 " port %d\n", __func__,
    492 	    sin->sin_addr.s_addr, ntohs(sin->sin_port));
    493 #endif
    494 	if ((rc = sobind(so, m, l)) != 0) {
    495 		GRE_DPRINTF(sc, "%s: sobind failed\n", __func__);
    496 		goto out;
    497 	}
    498 
    499 	if ((rc = gre_getsockname(so, m, l)) != 0) {
    500 		GRE_DPRINTF(sc, "%s: gre_getsockname\n", __func__);
    501 		goto out;
    502 	}
    503 	sockaddr_copy(sstosa(&sp->sp_src), sizeof(sp->sp_src), sa);
    504 
    505 	sockaddr_copy(sa, MIN(MLEN, sizeof(sp->sp_dst)), sstosa(&sp->sp_dst));
    506 	m->m_len = sp->sp_dst.ss_len;
    507 
    508 	if ((rc = soconnect(so, m, l)) != 0) {
    509 		GRE_DPRINTF(sc, "%s: soconnect failed\n", __func__);
    510 		goto out;
    511 	}
    512 
    513 	/* XXX convert to a (new) SOL_SOCKET call */
    514 	*mtod(m, int *) = ip_gre_ttl;
    515 	m->m_len = sizeof(int);
    516 	pr = so->so_proto;
    517 	KASSERT(pr != NULL);
    518 	rc = sosetopt(so, IPPROTO_IP, IP_TTL, m);
    519 	m = NULL;
    520 	if (rc != 0) {
    521 		GRE_DPRINTF(sc, "%s: sosetopt ttl failed\n", __func__);
    522 		rc = 0;
    523 	}
    524 	rc = sosetopt(so, SOL_SOCKET, SO_NOHEADER, m_intopt(so, 1));
    525 	if (rc != 0) {
    526 		GRE_DPRINTF(sc, "%s: sosetopt SO_NOHEADER failed\n", __func__);
    527 		rc = 0;
    528 	}
    529 out:
    530 	m_freem(m);
    531 
    532 	if (rc != 0)
    533 		fd_close(fd);
    534 	else  {
    535 		fd_putfile(fd);
    536 		*fdout = fd;
    537 	}
    538 
    539 	return rc;
    540 }
    541 
    542 static int
    543 gre_sosend(struct socket *so, struct mbuf *top, struct lwp *l)
    544 {
    545 	struct mbuf	**mp;
    546 	struct proc	*p;
    547 	long		space, resid;
    548 	int		error, s;
    549 
    550 	p = l->l_proc;
    551 
    552 	resid = top->m_pkthdr.len;
    553 	if (p)
    554 		l->l_ru.ru_msgsnd++;
    555 #define	snderr(errno)	{ error = errno; splx(s); goto release; }
    556 
    557 	if ((error = sblock(&so->so_snd, M_NOWAIT)) != 0)
    558 		goto out;
    559 	s = splsoftnet();
    560 	if (so->so_state & SS_CANTSENDMORE)
    561 		snderr(EPIPE);
    562 	if (so->so_error) {
    563 		error = so->so_error;
    564 		so->so_error = 0;
    565 		splx(s);
    566 		goto release;
    567 	}
    568 	if ((so->so_state & SS_ISCONNECTED) == 0) {
    569 		if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
    570 			if ((so->so_state & SS_ISCONFIRMING) == 0)
    571 				snderr(ENOTCONN);
    572 		} else
    573 			snderr(EDESTADDRREQ);
    574 	}
    575 	space = sbspace(&so->so_snd);
    576 	if (resid > so->so_snd.sb_hiwat)
    577 		snderr(EMSGSIZE);
    578 	if (space < resid)
    579 		snderr(EWOULDBLOCK);
    580 	splx(s);
    581 	mp = &top;
    582 	/*
    583 	 * Data is prepackaged in "top".
    584 	 */
    585 	s = splsoftnet();
    586 
    587 	if (so->so_state & SS_CANTSENDMORE)
    588 		snderr(EPIPE);
    589 
    590 	error = (*so->so_proto->pr_usrreq)(so, PRU_SEND, top, NULL, NULL, l);
    591 	splx(s);
    592 
    593 	top = NULL;
    594 	mp = &top;
    595 	if (error != 0)
    596 		goto release;
    597 
    598  release:
    599 	sbunlock(&so->so_snd);
    600  out:
    601 	if (top != NULL)
    602 		m_freem(top);
    603 	return error;
    604 }
    605 
    606 /* This is a stripped-down version of soreceive() that will never
    607  * block.  It will support SOCK_DGRAM sockets.  It may also support
    608  * SOCK_SEQPACKET sockets.
    609  */
    610 static int
    611 gre_soreceive(struct socket *so, struct mbuf **mp0)
    612 {
    613 	struct lwp *l = curlwp;
    614 	struct mbuf *m, **mp;
    615 	int flags, len, error, s, type;
    616 	const struct protosw	*pr;
    617 	struct mbuf *nextrecord;
    618 
    619 	KASSERT(mp0 != NULL);
    620 
    621 	flags = MSG_DONTWAIT;
    622 	pr = so->so_proto;
    623 	mp = mp0;
    624 	type = 0;
    625 
    626 	*mp = NULL;
    627 
    628 	KASSERT(pr->pr_flags & PR_ATOMIC);
    629 
    630 	if (so->so_state & SS_ISCONFIRMING)
    631 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l);
    632 
    633  restart:
    634 	if ((error = sblock(&so->so_rcv, M_NOWAIT)) != 0)
    635 		return error;
    636 	s = splsoftnet();
    637 
    638 	m = so->so_rcv.sb_mb;
    639 	/*
    640 	 * If we have less data than requested, do not block awaiting more.
    641 	 */
    642 	if (m == NULL) {
    643 #ifdef DIAGNOSTIC
    644 		if (so->so_rcv.sb_cc)
    645 			panic("receive 1");
    646 #endif
    647 		if (so->so_error) {
    648 			error = so->so_error;
    649 			so->so_error = 0;
    650 		} else if (so->so_state & SS_CANTRCVMORE)
    651 			;
    652 		else if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0
    653 		      && (so->so_proto->pr_flags & PR_CONNREQUIRED))
    654 			error = ENOTCONN;
    655 		else
    656 			error = EWOULDBLOCK;
    657 		goto release;
    658 	}
    659 	/*
    660 	 * On entry here, m points to the first record of the socket buffer.
    661 	 * While we process the initial mbufs containing address and control
    662 	 * info, we save a copy of m->m_nextpkt into nextrecord.
    663 	 */
    664 	if (l != NULL)
    665 		l->l_ru.ru_msgrcv++;
    666 	KASSERT(m == so->so_rcv.sb_mb);
    667 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
    668 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
    669 	nextrecord = m->m_nextpkt;
    670 	if (pr->pr_flags & PR_ADDR) {
    671 #ifdef DIAGNOSTIC
    672 		if (m->m_type != MT_SONAME)
    673 			panic("receive 1a");
    674 #endif
    675 		sbfree(&so->so_rcv, m);
    676 		MFREE(m, so->so_rcv.sb_mb);
    677 		m = so->so_rcv.sb_mb;
    678 	}
    679 	while (m != NULL && m->m_type == MT_CONTROL && error == 0) {
    680 		sbfree(&so->so_rcv, m);
    681 		/*
    682 		 * Dispose of any SCM_RIGHTS message that went
    683 		 * through the read path rather than recv.
    684 		 */
    685 		if (pr->pr_domain->dom_dispose &&
    686 		    mtod(m, struct cmsghdr *)->cmsg_type == SCM_RIGHTS)
    687 			(*pr->pr_domain->dom_dispose)(m);
    688 		MFREE(m, so->so_rcv.sb_mb);
    689 		m = so->so_rcv.sb_mb;
    690 	}
    691 
    692 	/*
    693 	 * If m is non-NULL, we have some data to read.  From now on,
    694 	 * make sure to keep sb_lastrecord consistent when working on
    695 	 * the last packet on the chain (nextrecord == NULL) and we
    696 	 * change m->m_nextpkt.
    697 	 */
    698 	if (m != NULL) {
    699 		m->m_nextpkt = nextrecord;
    700 		/*
    701 		 * If nextrecord == NULL (this is a single chain),
    702 		 * then sb_lastrecord may not be valid here if m
    703 		 * was changed earlier.
    704 		 */
    705 		if (nextrecord == NULL) {
    706 			KASSERT(so->so_rcv.sb_mb == m);
    707 			so->so_rcv.sb_lastrecord = m;
    708 		}
    709 		type = m->m_type;
    710 		if (type == MT_OOBDATA)
    711 			flags |= MSG_OOB;
    712 	} else {
    713 		KASSERT(so->so_rcv.sb_mb == m);
    714 		so->so_rcv.sb_mb = nextrecord;
    715 		SB_EMPTY_FIXUP(&so->so_rcv);
    716 	}
    717 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
    718 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
    719 
    720 	while (m != NULL) {
    721 		if (m->m_type == MT_OOBDATA) {
    722 			if (type != MT_OOBDATA)
    723 				break;
    724 		} else if (type == MT_OOBDATA)
    725 			break;
    726 #ifdef DIAGNOSTIC
    727 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
    728 			panic("receive 3");
    729 #endif
    730 		so->so_state &= ~SS_RCVATMARK;
    731 		if (so->so_oobmark != 0 && so->so_oobmark < m->m_len)
    732 			break;
    733 		len = m->m_len;
    734 		/*
    735 		 * mp is set, just pass back the mbufs.
    736 		 * Sockbuf must be consistent here (points to current mbuf,
    737 		 * it points to next record) when we drop priority;
    738 		 * we must note any additions to the sockbuf when we
    739 		 * block interrupts again.
    740 		 */
    741 		if (m->m_flags & M_EOR)
    742 			flags |= MSG_EOR;
    743 		nextrecord = m->m_nextpkt;
    744 		sbfree(&so->so_rcv, m);
    745 		*mp = m;
    746 		mp = &m->m_next;
    747 		so->so_rcv.sb_mb = m = m->m_next;
    748 		*mp = NULL;
    749 		/*
    750 		 * If m != NULL, we also know that
    751 		 * so->so_rcv.sb_mb != NULL.
    752 		 */
    753 		KASSERT(so->so_rcv.sb_mb == m);
    754 		if (m) {
    755 			m->m_nextpkt = nextrecord;
    756 			if (nextrecord == NULL)
    757 				so->so_rcv.sb_lastrecord = m;
    758 		} else {
    759 			so->so_rcv.sb_mb = nextrecord;
    760 			SB_EMPTY_FIXUP(&so->so_rcv);
    761 		}
    762 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
    763 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
    764 		if (so->so_oobmark) {
    765 			so->so_oobmark -= len;
    766 			if (so->so_oobmark == 0) {
    767 				so->so_state |= SS_RCVATMARK;
    768 				break;
    769 			}
    770 		}
    771 		if (flags & MSG_EOR)
    772 			break;
    773 	}
    774 
    775 	if (m != NULL) {
    776 		m_freem(*mp);
    777 		*mp = NULL;
    778 		error = ENOMEM;
    779 		(void) sbdroprecord(&so->so_rcv);
    780 	} else {
    781 		/*
    782 		 * First part is an inline SB_EMPTY_FIXUP().  Second
    783 		 * part makes sure sb_lastrecord is up-to-date if
    784 		 * there is still data in the socket buffer.
    785 		 */
    786 		so->so_rcv.sb_mb = nextrecord;
    787 		if (so->so_rcv.sb_mb == NULL) {
    788 			so->so_rcv.sb_mbtail = NULL;
    789 			so->so_rcv.sb_lastrecord = NULL;
    790 		} else if (nextrecord->m_nextpkt == NULL)
    791 			so->so_rcv.sb_lastrecord = nextrecord;
    792 	}
    793 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
    794 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
    795 	if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
    796 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL,
    797 		    (struct mbuf *)(long)flags, NULL, l);
    798 	if (*mp0 == NULL && (flags & MSG_EOR) == 0 &&
    799 	    (so->so_state & SS_CANTRCVMORE) == 0) {
    800 		sbunlock(&so->so_rcv);
    801 		splx(s);
    802 		goto restart;
    803 	}
    804 
    805  release:
    806 	sbunlock(&so->so_rcv);
    807 	splx(s);
    808 	return error;
    809 }
    810 
    811 static struct socket *
    812 gre_reconf(struct gre_softc *sc, struct socket *so, lwp_t *l,
    813     const struct gre_soparm *newsoparm)
    814 {
    815 	int rc;
    816 	file_t *fp;
    817 	struct ifnet *ifp = &sc->sc_if;
    818 
    819 	GRE_DPRINTF(sc, "%s: enter\n", __func__);
    820 
    821 shutdown:
    822 	if (sc->sc_soparm.sp_fd != -1) {
    823 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    824 		gre_upcall_remove(so);
    825 		softint_disestablish(sc->sc_si);
    826 		sc->sc_si = NULL;
    827 		fd_getfile(sc->sc_soparm.sp_fd);
    828 		fd_close(sc->sc_soparm.sp_fd);
    829 		gre_clearconf(&sc->sc_soparm, false);
    830 		sc->sc_soparm.sp_fd = -1;
    831 		so = NULL;
    832 	}
    833 
    834 	if (newsoparm != NULL) {
    835 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    836 		sc->sc_soparm = *newsoparm;
    837 	}
    838 
    839 	if (sc->sc_soparm.sp_fd != -1) {
    840 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    841 		rc = getsock(sc->sc_soparm.sp_fd, &fp);
    842 		if (rc != 0)
    843 			goto shutdown;
    844 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    845 		so = (struct socket *)fp->f_data;
    846 		sc->sc_si = softint_establish(SOFTINT_NET, greintr, sc);
    847 		gre_upcall_add(so, sc);
    848 		fd_putfile(sc->sc_soparm.sp_fd);
    849 		if ((ifp->if_flags & IFF_UP) == 0) {
    850 			GRE_DPRINTF(sc, "%s: down\n", __func__);
    851 			goto shutdown;
    852 		}
    853 	}
    854 
    855 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
    856 	if (so != NULL)
    857 		sc->sc_if.if_flags |= IFF_RUNNING;
    858 	else {
    859 		gre_bufq_purge(&sc->sc_snd);
    860 		sc->sc_if.if_flags &= ~IFF_RUNNING;
    861 	}
    862 	return so;
    863 }
    864 
    865 static int
    866 gre_input(struct gre_softc *sc, struct mbuf *m, int hlen,
    867     const struct gre_h *gh)
    868 {
    869 	uint16_t flags;
    870 	uint32_t af;		/* af passed to BPF tap */
    871 	int isr, s;
    872 	struct ifqueue *ifq;
    873 
    874 	sc->sc_if.if_ipackets++;
    875 	sc->sc_if.if_ibytes += m->m_pkthdr.len;
    876 
    877 	hlen += sizeof(struct gre_h);
    878 
    879 	/* process GRE flags as packet can be of variable len */
    880 	flags = ntohs(gh->flags);
    881 
    882 	/* Checksum & Offset are present */
    883 	if ((flags & GRE_CP) | (flags & GRE_RP))
    884 		hlen += 4;
    885 	/* We don't support routing fields (variable length) */
    886 	if (flags & GRE_RP) {
    887 		sc->sc_if.if_ierrors++;
    888 		return 0;
    889 	}
    890 	if (flags & GRE_KP)
    891 		hlen += 4;
    892 	if (flags & GRE_SP)
    893 		hlen += 4;
    894 
    895 	switch (ntohs(gh->ptype)) { /* ethertypes */
    896 	case ETHERTYPE_IP:
    897 		ifq = &ipintrq;
    898 		isr = NETISR_IP;
    899 		af = AF_INET;
    900 		break;
    901 #ifdef NETATALK
    902 	case ETHERTYPE_ATALK:
    903 		ifq = &atintrq1;
    904 		isr = NETISR_ATALK;
    905 		af = AF_APPLETALK;
    906 		break;
    907 #endif
    908 #ifdef INET6
    909 	case ETHERTYPE_IPV6:
    910 		ifq = &ip6intrq;
    911 		isr = NETISR_IPV6;
    912 		af = AF_INET6;
    913 		break;
    914 #endif
    915 	default:	   /* others not yet supported */
    916 		GRE_DPRINTF(sc, "%s: unhandled ethertype 0x%04x\n", __func__,
    917 		    ntohs(gh->ptype));
    918 		sc->sc_if.if_noproto++;
    919 		return 0;
    920 	}
    921 
    922 	if (hlen > m->m_pkthdr.len) {
    923 		m_freem(m);
    924 		sc->sc_if.if_ierrors++;
    925 		return EINVAL;
    926 	}
    927 	m_adj(m, hlen);
    928 
    929 #if NBPFILTER > 0
    930 	if (sc->sc_if.if_bpf != NULL)
    931 		bpf_mtap_af(sc->sc_if.if_bpf, af, m);
    932 #endif /*NBPFILTER > 0*/
    933 
    934 	m->m_pkthdr.rcvif = &sc->sc_if;
    935 
    936 	s = splnet();
    937 	if (IF_QFULL(ifq)) {
    938 		IF_DROP(ifq);
    939 		m_freem(m);
    940 	} else {
    941 		IF_ENQUEUE(ifq, m);
    942 	}
    943 	/* we need schednetisr since the address family may change */
    944 	schednetisr(isr);
    945 	splx(s);
    946 
    947 	return 1;	/* packet is done, no further processing needed */
    948 }
    949 
    950 /*
    951  * The output routine. Takes a packet and encapsulates it in the protocol
    952  * given by sc->sc_soparm.sp_proto. See also RFC 1701 and RFC 2004
    953  */
    954 static int
    955 gre_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
    956 	   struct rtentry *rt)
    957 {
    958 	int error = 0;
    959 	struct gre_softc *sc = ifp->if_softc;
    960 	struct gre_h *gh;
    961 	struct ip *ip;
    962 	uint8_t ip_tos = 0;
    963 	uint16_t etype = 0;
    964 
    965 	if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING)) {
    966 		m_freem(m);
    967 		error = ENETDOWN;
    968 		goto end;
    969 	}
    970 
    971 #if NBPFILTER > 0
    972 	if (ifp->if_bpf != NULL)
    973 		bpf_mtap_af(ifp->if_bpf, dst->sa_family, m);
    974 #endif
    975 
    976 	m->m_flags &= ~(M_BCAST|M_MCAST);
    977 
    978 	GRE_DPRINTF(sc, "%s: dst->sa_family=%d\n", __func__, dst->sa_family);
    979 	switch (dst->sa_family) {
    980 	case AF_INET:
    981 		ip = mtod(m, struct ip *);
    982 		ip_tos = ip->ip_tos;
    983 		etype = htons(ETHERTYPE_IP);
    984 		break;
    985 #ifdef NETATALK
    986 	case AF_APPLETALK:
    987 		etype = htons(ETHERTYPE_ATALK);
    988 		break;
    989 #endif
    990 #ifdef INET6
    991 	case AF_INET6:
    992 		etype = htons(ETHERTYPE_IPV6);
    993 		break;
    994 #endif
    995 	default:
    996 		IF_DROP(&ifp->if_snd);
    997 		m_freem(m);
    998 		error = EAFNOSUPPORT;
    999 		goto end;
   1000 	}
   1001 
   1002 	M_PREPEND(m, sizeof(*gh), M_DONTWAIT);
   1003 
   1004 	if (m == NULL) {
   1005 		IF_DROP(&ifp->if_snd);
   1006 		error = ENOBUFS;
   1007 		goto end;
   1008 	}
   1009 
   1010 	gh = mtod(m, struct gre_h *);
   1011 	gh->flags = 0;
   1012 	gh->ptype = etype;
   1013 	/* XXX Need to handle IP ToS.  Look at how I handle IP TTL. */
   1014 
   1015 	ifp->if_opackets++;
   1016 	ifp->if_obytes += m->m_pkthdr.len;
   1017 
   1018 	/* send it off */
   1019 	if ((error = gre_bufq_enqueue(&sc->sc_snd, m)) != 0) {
   1020 		sc->sc_oflow_ev.ev_count++;
   1021 		m_freem(m);
   1022 	} else
   1023 		softint_schedule(sc->sc_si);
   1024   end:
   1025 	if (error)
   1026 		ifp->if_oerrors++;
   1027 	return error;
   1028 }
   1029 
   1030 static int
   1031 gre_getname(struct socket *so, int req, struct mbuf *nam, struct lwp *l)
   1032 {
   1033 	return (*so->so_proto->pr_usrreq)(so, req, NULL, nam, NULL, l);
   1034 }
   1035 
   1036 static int
   1037 gre_getsockname(struct socket *so, struct mbuf *nam, struct lwp *l)
   1038 {
   1039 	return gre_getname(so, PRU_SOCKADDR, nam, l);
   1040 }
   1041 
   1042 static int
   1043 gre_getpeername(struct socket *so, struct mbuf *nam, struct lwp *l)
   1044 {
   1045 	return gre_getname(so, PRU_PEERADDR, nam, l);
   1046 }
   1047 
   1048 static int
   1049 gre_getnames(struct socket *so, struct lwp *l, struct sockaddr_storage *src,
   1050     struct sockaddr_storage *dst)
   1051 {
   1052 	struct mbuf *m;
   1053 	struct sockaddr_storage *ss;
   1054 	int rc;
   1055 
   1056 	if ((m = getsombuf(so, MT_SONAME)) == NULL)
   1057 		return ENOBUFS;
   1058 
   1059 	ss = mtod(m, struct sockaddr_storage *);
   1060 
   1061 	if ((rc = gre_getsockname(so, m, l)) != 0)
   1062 		goto out;
   1063 	*src = *ss;
   1064 
   1065 	if ((rc = gre_getpeername(so, m, l)) != 0)
   1066 		goto out;
   1067 	*dst = *ss;
   1068 
   1069 out:
   1070 	m_freem(m);
   1071 	return rc;
   1072 }
   1073 
   1074 static void
   1075 gre_closef(file_t **fpp)
   1076 {
   1077 	file_t *fp = *fpp;
   1078 
   1079 	closef(fp);
   1080 	*fpp = NULL;
   1081 }
   1082 
   1083 static int
   1084 gre_ssock(struct ifnet *ifp, struct gre_soparm *sp, int fd)
   1085 {
   1086 	int error, kfd;
   1087 	const struct protosw *pr;
   1088 	file_t *fp;
   1089 	struct gre_softc *sc = ifp->if_softc;
   1090 	struct lwp *l = curlwp;
   1091 	struct proc *kp;
   1092 	struct socket *so;
   1093 	struct sockaddr_storage dst, src;
   1094 
   1095 	/* getsock() will FILE_USE() and unlock the descriptor for us */
   1096 	if ((fp = fd_getfile(fd)) == NULL) {
   1097 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1098 		return EINVAL;
   1099 	}
   1100 	if (fp->f_type != DTYPE_SOCKET) {
   1101 		fd_putfile(fd);
   1102 		return ENOTSOCK;
   1103 	}
   1104 
   1105 	/* Increase reference count.  Now that our reference to
   1106 	 * the file descriptor is counted, this thread can release
   1107 	 * our "use" of the descriptor, but it will not be destroyed
   1108 	 * by some other thread's action.  This thread needs to
   1109 	 * release its use, too, because one and only one thread
   1110 	 * can have use of the descriptor at once.  The kernel
   1111 	 * thread will pick up the use if it needs it.
   1112 	 */
   1113 	mutex_enter(&fp->f_lock);
   1114 	fp->f_count++;
   1115 	mutex_exit(&fp->f_lock);
   1116 	fd_putfile(fd);
   1117 	GRE_DPRINTF(sc, "%s: l.%d f_count %d\n", __func__, __LINE__,
   1118 	    fp->f_count);
   1119 
   1120 	kp = sc->sc_lwp->l_proc;
   1121 	while ((error = fd_alloc(kp, 0, &kfd)) != 0 && error == ENOSPC)
   1122 		fd_tryexpand(kp);
   1123 	if (error != 0)
   1124 		goto closef;
   1125 	fd_affix(kp, fp, kfd);
   1126 
   1127 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1128 
   1129 	so = (struct socket *)fp->f_data;
   1130 	pr = so->so_proto;
   1131 	if ((pr->pr_flags & PR_ATOMIC) == 0 ||
   1132 	    (sp->sp_type != 0 && pr->pr_type != sp->sp_type) ||
   1133 	    (sp->sp_proto != 0 && pr->pr_protocol != 0 &&
   1134 	     pr->pr_protocol != sp->sp_proto)) {
   1135 		GRE_DPRINTF(sc, "%s: l.%d, type %d, proto %d\n", __func__,
   1136 		    __LINE__, pr->pr_type, pr->pr_protocol);
   1137 		error = EINVAL;
   1138 		goto release;
   1139 	}
   1140 
   1141 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1142 
   1143 	/* check address */
   1144 	if ((error = gre_getnames(so, l, &src, &dst)) != 0)
   1145 		goto release;
   1146 
   1147 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1148 
   1149 	if (error != 0)
   1150 		goto release;
   1151 
   1152 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1153 
   1154 	sp->sp_src = src;
   1155 	sp->sp_dst = dst;
   1156 	/* fp does not any longer belong to this thread. */
   1157 	sp->sp_fd = kfd;
   1158 
   1159 	/* XXX print src & dst */
   1160 
   1161 	return 0;
   1162 release:
   1163 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1164 	fd_abort(kp, fp, kfd);
   1165 	return error;
   1166 closef:
   1167 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1168 	gre_closef(&fp);
   1169 	return error;
   1170 }
   1171 
   1172 static bool
   1173 sockaddr_is_anyaddr(const struct sockaddr *sa)
   1174 {
   1175 	socklen_t anylen, salen;
   1176 	const void *anyaddr, *addr;
   1177 
   1178 	if ((anyaddr = sockaddr_anyaddr(sa, &anylen)) == NULL ||
   1179 	    (addr = sockaddr_const_addr(sa, &salen)) == NULL)
   1180 		return false;
   1181 
   1182 	if (salen > anylen)
   1183 		return false;
   1184 
   1185 	return memcmp(anyaddr, addr, MIN(anylen, salen)) == 0;
   1186 }
   1187 
   1188 static bool
   1189 gre_is_nullconf(const struct gre_soparm *sp)
   1190 {
   1191 	return sockaddr_is_anyaddr(sstocsa(&sp->sp_src)) ||
   1192 	       sockaddr_is_anyaddr(sstocsa(&sp->sp_dst));
   1193 }
   1194 
   1195 static void
   1196 gre_clearconf(struct gre_soparm *sp, bool force)
   1197 {
   1198 	if (sp->sp_bysock || force) {
   1199 		sockaddr_copy(sstosa(&sp->sp_src), sizeof(sp->sp_src),
   1200 		    sockaddr_any(sstosa(&sp->sp_src)));
   1201 		sockaddr_copy(sstosa(&sp->sp_dst), sizeof(sp->sp_dst),
   1202 		    sockaddr_any(sstosa(&sp->sp_dst)));
   1203 		sp->sp_bysock = 0;
   1204 	}
   1205 	sp->sp_fd = -1;
   1206 }
   1207 
   1208 static int
   1209 gre_ioctl_lock(struct gre_softc *sc)
   1210 {
   1211 	mutex_enter(&sc->sc_mtx);
   1212 
   1213 	while (sc->sc_state == GRE_S_IOCTL)
   1214 		gre_wait(sc);
   1215 
   1216 	if (sc->sc_state != GRE_S_IDLE) {
   1217 		cv_signal(&sc->sc_condvar);
   1218 		mutex_exit(&sc->sc_mtx);
   1219 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1220 		return ENXIO;
   1221 	}
   1222 
   1223 	sc->sc_state = GRE_S_IOCTL;
   1224 
   1225 	mutex_exit(&sc->sc_mtx);
   1226 	return 0;
   1227 }
   1228 
   1229 static void
   1230 gre_ioctl_unlock(struct gre_softc *sc)
   1231 {
   1232 	mutex_enter(&sc->sc_mtx);
   1233 
   1234 	KASSERT(sc->sc_state == GRE_S_IOCTL);
   1235 	sc->sc_state = GRE_S_IDLE;
   1236 	cv_signal(&sc->sc_condvar);
   1237 
   1238 	mutex_exit(&sc->sc_mtx);
   1239 }
   1240 
   1241 static int
   1242 gre_ioctl(struct ifnet *ifp, const u_long cmd, void *data)
   1243 {
   1244 	struct lwp *l = curlwp;
   1245 	struct ifreq *ifr;
   1246 	struct if_laddrreq *lifr = (struct if_laddrreq *)data;
   1247 	struct gre_softc *sc = ifp->if_softc;
   1248 	struct gre_soparm *sp;
   1249 	int fd, error = 0, oproto, otype, s;
   1250 	struct gre_soparm sp0;
   1251 
   1252 	ifr = data;
   1253 	fd = 0;
   1254 
   1255 	GRE_DPRINTF(sc, "%s: l.%d, cmd %lu\n", __func__, __LINE__, cmd);
   1256 
   1257 	switch (cmd) {
   1258 	case SIOCSIFFLAGS:
   1259 	case SIOCSIFMTU:
   1260 	case GRESPROTO:
   1261 	case GRESADDRD:
   1262 	case GRESADDRS:
   1263 	case GRESSOCK:
   1264 	case GREDSOCK:
   1265 	case SIOCSLIFPHYADDR:
   1266 	case SIOCDIFPHYADDR:
   1267 		if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
   1268 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
   1269 		    NULL) != 0)
   1270 			return EPERM;
   1271 		break;
   1272 	default:
   1273 		break;
   1274 	}
   1275 
   1276 	if ((error = gre_ioctl_lock(sc)) != 0) {
   1277 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1278 		return error;
   1279 	}
   1280 	s = splnet();
   1281 
   1282 	sp0 = sc->sc_soparm;
   1283 	sp0.sp_fd = -1;
   1284 	sp = &sp0;
   1285 
   1286 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1287 
   1288 	switch (cmd) {
   1289 	case SIOCSIFADDR:
   1290 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1291 		if ((ifp->if_flags & IFF_UP) != 0)
   1292 			break;
   1293 		gre_clearconf(sp, false);
   1294 		ifp->if_flags |= IFF_UP;
   1295 		goto mksocket;
   1296 	case SIOCSIFDSTADDR:
   1297 		break;
   1298 	case SIOCSIFFLAGS:
   1299 		oproto = sp->sp_proto;
   1300 		otype = sp->sp_type;
   1301 		switch (ifr->ifr_flags & (IFF_LINK0|IFF_LINK2)) {
   1302 		case IFF_LINK0|IFF_LINK2:
   1303 			sp->sp_proto = IPPROTO_UDP;
   1304 			sp->sp_type = SOCK_DGRAM;
   1305 			break;
   1306 		case IFF_LINK2:
   1307 			sp->sp_proto = 0;
   1308 			sp->sp_type = 0;
   1309 			break;
   1310 		case IFF_LINK0:
   1311 			sp->sp_proto = IPPROTO_GRE;
   1312 			sp->sp_type = SOCK_RAW;
   1313 			break;
   1314 		default:
   1315 			GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1316 			error = EINVAL;
   1317 			goto out;
   1318 		}
   1319 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1320 		gre_clearconf(sp, false);
   1321 		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) ==
   1322 		    (IFF_UP|IFF_RUNNING) &&
   1323 		    (oproto == sp->sp_proto || sp->sp_proto == 0) &&
   1324 		    (otype == sp->sp_type || sp->sp_type == 0))
   1325 			break;
   1326 		switch (sp->sp_proto) {
   1327 		case IPPROTO_UDP:
   1328 		case IPPROTO_GRE:
   1329 			goto mksocket;
   1330 		default:
   1331 			break;
   1332 		}
   1333 		break;
   1334 	case SIOCSIFMTU:
   1335 		/* XXX determine MTU automatically by probing w/
   1336 		 * XXX do-not-fragment packets?
   1337 		 */
   1338 		if (ifr->ifr_mtu < 576) {
   1339 			error = EINVAL;
   1340 			break;
   1341 		}
   1342 		/*FALLTHROUGH*/
   1343 	case SIOCGIFMTU:
   1344 		if ((error = ifioctl_common(ifp, cmd, data)) == ENETRESET)
   1345 			error = 0;
   1346 		break;
   1347 	case SIOCADDMULTI:
   1348 	case SIOCDELMULTI:
   1349 		if (ifr == NULL) {
   1350 			error = EAFNOSUPPORT;
   1351 			break;
   1352 		}
   1353 		switch (ifreq_getaddr(cmd, ifr)->sa_family) {
   1354 #ifdef INET
   1355 		case AF_INET:
   1356 			break;
   1357 #endif
   1358 #ifdef INET6
   1359 		case AF_INET6:
   1360 			break;
   1361 #endif
   1362 		default:
   1363 			error = EAFNOSUPPORT;
   1364 			break;
   1365 		}
   1366 		break;
   1367 	case GRESPROTO:
   1368 		gre_clearconf(sp, false);
   1369 		oproto = sp->sp_proto;
   1370 		otype = sp->sp_type;
   1371 		sp->sp_proto = ifr->ifr_flags;
   1372 		switch (sp->sp_proto) {
   1373 		case IPPROTO_UDP:
   1374 			ifp->if_flags |= IFF_LINK0|IFF_LINK2;
   1375 			sp->sp_type = SOCK_DGRAM;
   1376 			break;
   1377 		case IPPROTO_GRE:
   1378 			ifp->if_flags |= IFF_LINK0;
   1379 			ifp->if_flags &= ~IFF_LINK2;
   1380 			sp->sp_type = SOCK_RAW;
   1381 			break;
   1382 		case 0:
   1383 			ifp->if_flags &= ~IFF_LINK0;
   1384 			ifp->if_flags |= IFF_LINK2;
   1385 			sp->sp_type = 0;
   1386 			break;
   1387 		default:
   1388 			error = EPROTONOSUPPORT;
   1389 			break;
   1390 		}
   1391 		if ((oproto == sp->sp_proto || sp->sp_proto == 0) &&
   1392 		    (otype == sp->sp_type || sp->sp_type == 0))
   1393 			break;
   1394 		switch (sp->sp_proto) {
   1395 		case IPPROTO_UDP:
   1396 		case IPPROTO_GRE:
   1397 			goto mksocket;
   1398 		default:
   1399 			break;
   1400 		}
   1401 		break;
   1402 	case GREGPROTO:
   1403 		ifr->ifr_flags = sp->sp_proto;
   1404 		break;
   1405 	case GRESADDRS:
   1406 	case GRESADDRD:
   1407 		gre_clearconf(sp, false);
   1408 		/*
   1409 		 * set tunnel endpoints, compute a less specific route
   1410 		 * to the remote end and mark if as up
   1411 		 */
   1412 		switch (cmd) {
   1413 		case GRESADDRS:
   1414 			sockaddr_copy(sstosa(&sp->sp_src),
   1415 			    sizeof(sp->sp_src), ifreq_getaddr(cmd, ifr));
   1416 			break;
   1417 		case GRESADDRD:
   1418 			sockaddr_copy(sstosa(&sp->sp_dst),
   1419 			    sizeof(sp->sp_dst), ifreq_getaddr(cmd, ifr));
   1420 			break;
   1421 		}
   1422 	checkaddr:
   1423 		if (sockaddr_any(sstosa(&sp->sp_src)) == NULL ||
   1424 		    sockaddr_any(sstosa(&sp->sp_dst)) == NULL) {
   1425 			error = EINVAL;
   1426 			break;
   1427 		}
   1428 		/* let gre_socreate() check the rest */
   1429 	mksocket:
   1430 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1431 		/* If we're administratively down, or the configuration
   1432 		 * is empty, there's no use creating a socket.
   1433 		 */
   1434 		if ((ifp->if_flags & IFF_UP) == 0 || gre_is_nullconf(sp))
   1435 			goto sendconf;
   1436 
   1437 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1438 		error = gre_socreate(sc, l, sp, &fd);
   1439 		if (error != 0)
   1440 			break;
   1441 
   1442 	setsock:
   1443 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1444 
   1445 		error = gre_ssock(ifp, sp, fd);
   1446 
   1447 		if (cmd != GRESSOCK) {
   1448 			GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1449 			/* XXX v. dodgy */
   1450 			if (fd_getfile(fd) != NULL)
   1451 				fd_close(fd);
   1452 		}
   1453 
   1454 		if (error == 0) {
   1455 	sendconf:
   1456 			GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1457 			ifp->if_flags &= ~IFF_RUNNING;
   1458 			sc->sc_so = gre_reconf(sc, sc->sc_so, sc->sc_lwp, sp);
   1459 		}
   1460 
   1461 		break;
   1462 	case GREGADDRS:
   1463 		ifreq_setaddr(cmd, ifr, sstosa(&sp->sp_src));
   1464 		break;
   1465 	case GREGADDRD:
   1466 		ifreq_setaddr(cmd, ifr, sstosa(&sp->sp_dst));
   1467 		break;
   1468 	case GREDSOCK:
   1469 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1470 		if (sp->sp_bysock)
   1471 			ifp->if_flags &= ~IFF_UP;
   1472 		gre_clearconf(sp, false);
   1473 		goto mksocket;
   1474 	case GRESSOCK:
   1475 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1476 		gre_clearconf(sp, true);
   1477 		fd = (int)ifr->ifr_value;
   1478 		sp->sp_bysock = 1;
   1479 		ifp->if_flags |= IFF_UP;
   1480 		goto setsock;
   1481 	case SIOCSLIFPHYADDR:
   1482 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1483 		if (lifr->addr.ss_family != lifr->dstaddr.ss_family) {
   1484 			error = EAFNOSUPPORT;
   1485 			break;
   1486 		}
   1487 		sockaddr_copy(sstosa(&sp->sp_src), sizeof(sp->sp_src),
   1488 		    sstosa(&lifr->addr));
   1489 		sockaddr_copy(sstosa(&sp->sp_dst), sizeof(sp->sp_dst),
   1490 		    sstosa(&lifr->dstaddr));
   1491 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1492 		goto checkaddr;
   1493 	case SIOCDIFPHYADDR:
   1494 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1495 		gre_clearconf(sp, true);
   1496 		ifp->if_flags &= ~IFF_UP;
   1497 		goto mksocket;
   1498 	case SIOCGLIFPHYADDR:
   1499 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1500 		if (gre_is_nullconf(sp)) {
   1501 			error = EADDRNOTAVAIL;
   1502 			break;
   1503 		}
   1504 		sockaddr_copy(sstosa(&lifr->addr), sizeof(lifr->addr),
   1505 		    sstosa(&sp->sp_src));
   1506 		sockaddr_copy(sstosa(&lifr->dstaddr), sizeof(lifr->dstaddr),
   1507 		    sstosa(&sp->sp_dst));
   1508 		GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1509 		break;
   1510 	default:
   1511 		error = EINVAL;
   1512 		break;
   1513 	}
   1514 out:
   1515 	GRE_DPRINTF(sc, "%s: l.%d\n", __func__, __LINE__);
   1516 	splx(s);
   1517 	gre_ioctl_unlock(sc);
   1518 	return error;
   1519 }
   1520 
   1521 #endif
   1522 
   1523 void	greattach(int);
   1524 
   1525 /* ARGSUSED */
   1526 void
   1527 greattach(int count)
   1528 {
   1529 #ifdef INET
   1530 	if_clone_attach(&gre_cloner);
   1531 #endif
   1532 }
   1533