16735Samurai/*	$NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $	*/
26735Samurai
3139823Simp/*-
46053Samurai * Copyright (c) 1988, Julian Onions <jpo@cs.nott.ac.uk>
56053Samurai * Nottingham University 1987.
66053Samurai *
76053Samurai * This source may be freely distributed, however I would be interested
86053Samurai * in any changes that are made.
96053Samurai *
106053Samurai * This driver takes packets off the IP i/f and hands them up to a
1135256Sdes * user process to have its wicked way with. This driver has it's
126053Samurai * roots in a similar driver written by Phil Cockcroft (formerly) at
1329365Speter * UCL. This driver is based much more on read/write/poll mode of
146053Samurai * operation though.
1551646Sphk *
1651646Sphk * $FreeBSD: stable/11/sys/net/if_tun.c 353157 2019-10-07 01:03:14Z kevans $
176053Samurai */
186053Samurai
1932350Seivind#include "opt_inet.h"
20111999Sjlemon#include "opt_inet6.h"
2132350Seivind
226735Samurai#include <sys/param.h>
23347378Skevans#include <sys/lock.h>
24164033Srwatson#include <sys/priv.h>
256735Samurai#include <sys/proc.h>
266735Samurai#include <sys/systm.h>
27194368Sbz#include <sys/jail.h>
286735Samurai#include <sys/mbuf.h>
2971862Speter#include <sys/module.h>
306735Samurai#include <sys/socket.h>
31139208Sphk#include <sys/fcntl.h>
3224208Sbde#include <sys/filio.h>
3324208Sbde#include <sys/sockio.h>
34347378Skevans#include <sys/sx.h>
35353157Skevans#include <sys/syslog.h>
3624208Sbde#include <sys/ttycom.h>
3729365Speter#include <sys/poll.h>
38139208Sphk#include <sys/selinfo.h>
397090Sbde#include <sys/signalvar.h>
4041086Struckman#include <sys/filedesc.h>
416735Samurai#include <sys/kernel.h>
4212706Sphk#include <sys/sysctl.h>
437747Swollman#include <sys/conf.h>
4431283Sbde#include <sys/uio.h>
4549829Sphk#include <sys/malloc.h>
46111888Sjlemon#include <sys/random.h>
47345286Skp#include <sys/ctype.h>
486053Samurai
496053Samurai#include <net/if.h>
50257176Sglebius#include <net/if_var.h>
51166497Sbms#include <net/if_clone.h>
5263358Sbrian#include <net/if_types.h>
53111888Sjlemon#include <net/netisr.h>
546053Samurai#include <net/route.h>
55196019Srwatson#include <net/vnet.h>
566053Samurai#ifdef INET
576053Samurai#include <netinet/in.h>
586053Samurai#endif
596053Samurai#include <net/bpf.h>
606053Samurai#include <net/if_tun.h>
616053Samurai
62126077Sphk#include <sys/queue.h>
63186391Sqingli#include <sys/condvar.h>
64126077Sphk
65163606Srwatson#include <security/mac/mac_framework.h>
66163606Srwatson
67127591Srwatson/*
68127591Srwatson * tun_list is protected by global tunmtx.  Other mutable fields are
69127591Srwatson * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
70127591Srwatson * static for the duration of a tunnel interface.
71127591Srwatson */
72126077Sphkstruct tun_softc {
73126077Sphk	TAILQ_ENTRY(tun_softc)	tun_list;
74130585Sphk	struct cdev *tun_dev;
75126077Sphk	u_short	tun_flags;		/* misc flags */
76126077Sphk#define	TUN_OPEN	0x0001
77126077Sphk#define	TUN_INITED	0x0002
78126077Sphk#define	TUN_RCOLL	0x0004
79126077Sphk#define	TUN_IASET	0x0008
80126077Sphk#define	TUN_DSTADDR	0x0010
81126077Sphk#define	TUN_LMODE	0x0020
82126077Sphk#define	TUN_RWAIT	0x0040
83126077Sphk#define	TUN_ASYNC	0x0080
84126077Sphk#define	TUN_IFHEAD	0x0100
85347378Skevans#define	TUN_DYING	0x0200
86126077Sphk
87126077Sphk#define TUN_READY       (TUN_OPEN | TUN_INITED)
88126077Sphk
89127099Srwatson	pid_t	tun_pid;		/* owning pid */
90147256Sbrooks	struct	ifnet *tun_ifp;		/* the interface */
91126077Sphk	struct  sigio *tun_sigio;	/* information for async I/O */
92126077Sphk	struct	selinfo	tun_rsel;	/* read select */
93127591Srwatson	struct mtx	tun_mtx;	/* protect mutable softc fields */
94186391Sqingli	struct cv	tun_cv;		/* protect against ref'd dev destroy */
95126077Sphk};
96147256Sbrooks#define TUN2IFP(sc)	((sc)->tun_ifp)
97126077Sphk
98121778Sbrooks#define TUNDEBUG	if (tundebug) if_printf
9949829Sphk
100127580Srwatson/*
101127580Srwatson * All mutable global variables in if_tun are locked using tunmtx, with
102127580Srwatson * the exception of tundebug, which is used unlocked, and tunclones,
103127580Srwatson * which is static after setup.
104127580Srwatson */
105127580Srwatsonstatic struct mtx tunmtx;
106345286Skpstatic eventhandler_tag tag;
107241610Sglebiusstatic const char tunname[] = "tun";
108241610Sglebiusstatic MALLOC_DEFINE(M_TUN, tunname, "Tunnel Interface");
10912706Sphkstatic int tundebug = 0;
110166497Sbmsstatic int tundclone = 1;
111126077Sphkstatic struct clonedevs *tunclones;
112126077Sphkstatic TAILQ_HEAD(,tun_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
11313993SphkSYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
1146053Samurai
115347378Skevansstatic struct sx tun_ioctl_sx;
116347378SkevansSX_SYSINIT(tun_ioctl_sx, &tun_ioctl_sx, "tun_ioctl");
117347378Skevans
118166497SbmsSYSCTL_DECL(_net_link);
119227309Sedstatic SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
120166497Sbms    "IP tunnel software network interface.");
121267992ShselaskySYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tundclone, 0,
122166497Sbms    "Enable legacy devfs interface creation.");
123166497Sbms
124148868Srwatsonstatic void	tunclone(void *arg, struct ucred *cred, char *name,
125148868Srwatson		    int namelen, struct cdev **dev);
126166497Sbmsstatic void	tuncreate(const char *name, struct cdev *dev);
12777589Sbrianstatic int	tunifioctl(struct ifnet *, u_long, caddr_t);
128222651Sjhbstatic void	tuninit(struct ifnet *);
12977589Sbrianstatic int	tunmodevent(module_t, int, void *);
130249925Sglebiusstatic int	tunoutput(struct ifnet *, struct mbuf *,
131249925Sglebius		    const struct sockaddr *, struct route *ro);
13277589Sbrianstatic void	tunstart(struct ifnet *);
1336053Samurai
134345286Skpstatic int	tun_clone_match(struct if_clone *ifc, const char *name);
135345286Skpstatic int	tun_clone_create(struct if_clone *, char *, size_t, caddr_t);
136345286Skpstatic int	tun_clone_destroy(struct if_clone *, struct ifnet *);
137345286Skpstatic struct unrhdr	*tun_unrhdr;
138345313Skpstatic VNET_DEFINE(struct if_clone *, tun_cloner);
139345286Skp#define V_tun_cloner VNET(tun_cloner)
140166497Sbms
14177589Sbrianstatic d_open_t		tunopen;
14277589Sbrianstatic d_close_t	tunclose;
14377589Sbrianstatic d_read_t		tunread;
14477589Sbrianstatic d_write_t	tunwrite;
14577589Sbrianstatic d_ioctl_t	tunioctl;
14677589Sbrianstatic d_poll_t		tunpoll;
147161103Srwatsonstatic d_kqfilter_t	tunkqfilter;
14812675Sjulian
149161103Srwatsonstatic int		tunkqread(struct knote *, long);
150161103Srwatsonstatic int		tunkqwrite(struct knote *, long);
151161103Srwatsonstatic void		tunkqdetach(struct knote *);
152161103Srwatson
153161103Srwatsonstatic struct filterops tun_read_filterops = {
154161103Srwatson	.f_isfd =	1,
155161103Srwatson	.f_attach =	NULL,
156161103Srwatson	.f_detach =	tunkqdetach,
157161103Srwatson	.f_event =	tunkqread,
158161103Srwatson};
159161103Srwatson
160161103Srwatsonstatic struct filterops tun_write_filterops = {
161161103Srwatson	.f_isfd =	1,
162161103Srwatson	.f_attach =	NULL,
163161103Srwatson	.f_detach =	tunkqdetach,
164161103Srwatson	.f_event =	tunkqwrite,
165161103Srwatson};
166161103Srwatson
16712675Sjulianstatic struct cdevsw tun_cdevsw = {
168126080Sphk	.d_version =	D_VERSION,
169226500Sed	.d_flags =	D_NEEDMINOR,
170111815Sphk	.d_open =	tunopen,
171111815Sphk	.d_close =	tunclose,
172111815Sphk	.d_read =	tunread,
173111815Sphk	.d_write =	tunwrite,
174111815Sphk	.d_ioctl =	tunioctl,
175111815Sphk	.d_poll =	tunpoll,
176161103Srwatson	.d_kqfilter =	tunkqfilter,
177241610Sglebius	.d_name =	tunname,
17812118Sbde};
1797747Swollman
180166497Sbmsstatic int
181345286Skptun_clone_match(struct if_clone *ifc, const char *name)
182166497Sbms{
183345286Skp	if (strncmp(tunname, name, 3) == 0 &&
184345286Skp	    (name[3] == '\0' || isdigit(name[3])))
185345286Skp		return (1);
186345286Skp
187345286Skp	return (0);
188345286Skp}
189345286Skp
190345286Skpstatic int
191345286Skptun_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
192345286Skp{
193166497Sbms	struct cdev *dev;
194345286Skp	int err, unit, i;
195166497Sbms
196345286Skp	err = ifc_name2unit(name, &unit);
197345286Skp	if (err != 0)
198345286Skp		return (err);
199345286Skp
200345286Skp	if (unit != -1) {
201345286Skp		/* If this unit number is still available that/s okay. */
202345286Skp		if (alloc_unr_specific(tun_unrhdr, unit) == -1)
203345286Skp			return (EEXIST);
204345286Skp	} else {
205345286Skp		unit = alloc_unr(tun_unrhdr);
206345286Skp	}
207345286Skp
208345286Skp	snprintf(name, IFNAMSIZ, "%s%d", tunname, unit);
209345286Skp
210166497Sbms	/* find any existing device, or allocate new unit number */
211166497Sbms	i = clone_create(&tunclones, &tun_cdevsw, &unit, &dev, 0);
212166497Sbms	if (i) {
213166497Sbms		/* No preexisting struct cdev *, create one */
214183381Sed		dev = make_dev(&tun_cdevsw, unit,
215241610Sglebius		    UID_UUCP, GID_DIALER, 0600, "%s%d", tunname, unit);
216166497Sbms	}
217241610Sglebius	tuncreate(tunname, dev);
218166497Sbms
219166497Sbms	return (0);
220166497Sbms}
221166497Sbms
22210429Sbdestatic void
223148868Srwatsontunclone(void *arg, struct ucred *cred, char *name, int namelen,
224148868Srwatson    struct cdev **dev)
22564880Sphk{
226166497Sbms	char devname[SPECNAMELEN + 1];
227166497Sbms	int u, i, append_unit;
22864880Sphk
229130640Sphk	if (*dev != NULL)
23064880Sphk		return;
23177589Sbrian
232166497Sbms	/*
233166497Sbms	 * If tun cloning is enabled, only the superuser can create an
234166497Sbms	 * interface.
235166497Sbms	 */
236166497Sbms	if (!tundclone || priv_check_cred(cred, PRIV_NET_IFCREATE, 0) != 0)
237166497Sbms		return;
238166497Sbms
239241610Sglebius	if (strcmp(name, tunname) == 0) {
240126077Sphk		u = -1;
241241610Sglebius	} else if (dev_stdclone(name, NULL, tunname, &u) != 1)
24277589Sbrian		return;	/* Don't recognise the name */
243126077Sphk	if (u != -1 && u > IF_MAXUNIT)
244126077Sphk		return;	/* Unit number too high */
24577589Sbrian
246166497Sbms	if (u == -1)
247166497Sbms		append_unit = 1;
248166497Sbms	else
249166497Sbms		append_unit = 0;
250166497Sbms
251194252Sjamie	CURVNET_SET(CRED_TO_VNET(cred));
252126077Sphk	/* find any existing device, or allocate new unit number */
253126077Sphk	i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
254126077Sphk	if (i) {
255166497Sbms		if (append_unit) {
256221552Syongari			namelen = snprintf(devname, sizeof(devname), "%s%d",
257221552Syongari			    name, u);
258166497Sbms			name = devname;
259166497Sbms		}
260130585Sphk		/* No preexisting struct cdev *, create one */
261204464Skib		*dev = make_dev_credf(MAKEDEV_REF, &tun_cdevsw, u, cred,
262166497Sbms		    UID_UUCP, GID_DIALER, 0600, "%s", name);
26377589Sbrian	}
264166497Sbms
265166497Sbms	if_clone_create(name, namelen, NULL);
266183550Szec	CURVNET_RESTORE();
26764880Sphk}
26864880Sphk
269127580Srwatsonstatic void
270127580Srwatsontun_destroy(struct tun_softc *tp)
271127580Srwatson{
272130585Sphk	struct cdev *dev;
273127580Srwatson
274186391Sqingli	mtx_lock(&tp->tun_mtx);
275347378Skevans	tp->tun_flags |= TUN_DYING;
276186497Sqingli	if ((tp->tun_flags & TUN_OPEN) != 0)
277186391Sqingli		cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
278186483Skmacy	else
279186483Skmacy		mtx_unlock(&tp->tun_mtx);
280186497Sqingli
281183550Szec	CURVNET_SET(TUN2IFP(tp)->if_vnet);
282348126Skevans
283348126Skevans	dev = tp->tun_dev;
284348126Skevans	bpfdetach(TUN2IFP(tp));
285348126Skevans	if_detach(TUN2IFP(tp));
286348126Skevans
287347378Skevans	sx_xlock(&tun_ioctl_sx);
288347378Skevans	TUN2IFP(tp)->if_softc = NULL;
289347378Skevans	sx_xunlock(&tun_ioctl_sx);
290347378Skevans
291345286Skp	free_unr(tun_unrhdr, TUN2IFP(tp)->if_dunit);
292147256Sbrooks	if_free(TUN2IFP(tp));
293127580Srwatson	destroy_dev(dev);
294225177Sattilio	seldrain(&tp->tun_rsel);
295256008Sglebius	knlist_clear(&tp->tun_rsel.si_note, 0);
296161103Srwatson	knlist_destroy(&tp->tun_rsel.si_note);
297127591Srwatson	mtx_destroy(&tp->tun_mtx);
298186391Sqingli	cv_destroy(&tp->tun_cv);
299127580Srwatson	free(tp, M_TUN);
300183550Szec	CURVNET_RESTORE();
301127580Srwatson}
302127580Srwatson
303345286Skpstatic int
304345286Skptun_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
305166497Sbms{
306166497Sbms	struct tun_softc *tp = ifp->if_softc;
307166497Sbms
308166497Sbms	mtx_lock(&tunmtx);
309166497Sbms	TAILQ_REMOVE(&tunhead, tp, tun_list);
310166497Sbms	mtx_unlock(&tunmtx);
311166497Sbms	tun_destroy(tp);
312345286Skp
313345286Skp	return (0);
314166497Sbms}
315166497Sbms
316345286Skpstatic void
317345286Skpvnet_tun_init(const void *unused __unused)
318345286Skp{
319345286Skp	V_tun_cloner = if_clone_advanced(tunname, 0, tun_clone_match,
320345286Skp			tun_clone_create, tun_clone_destroy);
321345286Skp}
322345286SkpVNET_SYSINIT(vnet_tun_init, SI_SUB_PROTO_IF, SI_ORDER_ANY,
323345286Skp		vnet_tun_init, NULL);
324345286Skp
325345286Skpstatic void
326345286Skpvnet_tun_uninit(const void *unused __unused)
327345286Skp{
328345286Skp	if_clone_detach(V_tun_cloner);
329345286Skp}
330345286SkpVNET_SYSUNINIT(vnet_tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY,
331345286Skp    vnet_tun_uninit, NULL);
332345286Skp
333345286Skpstatic void
334345286Skptun_uninit(const void *unused __unused)
335345286Skp{
336345286Skp	struct tun_softc *tp;
337345286Skp
338345286Skp	EVENTHANDLER_DEREGISTER(dev_clone, tag);
339345286Skp	drain_dev_clone_events();
340345286Skp
341345286Skp	mtx_lock(&tunmtx);
342345286Skp	while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
343345286Skp		TAILQ_REMOVE(&tunhead, tp, tun_list);
344345286Skp		mtx_unlock(&tunmtx);
345345286Skp		tun_destroy(tp);
346345286Skp		mtx_lock(&tunmtx);
347345286Skp	}
348345286Skp	mtx_unlock(&tunmtx);
349345286Skp	delete_unrhdr(tun_unrhdr);
350345286Skp	clone_cleanup(&tunclones);
351345286Skp	mtx_destroy(&tunmtx);
352345286Skp}
353345286SkpSYSUNINIT(tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY, tun_uninit, NULL);
354345286Skp
35571862Speterstatic int
356111742Sdestunmodevent(module_t mod, int type, void *data)
35775103Sbrian{
35875103Sbrian
359111742Sdes	switch (type) {
360111742Sdes	case MOD_LOAD:
361127580Srwatson		mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
362126845Sphk		clone_setup(&tunclones);
363345286Skp		tun_unrhdr = new_unrhdr(0, IF_MAXUNIT, &tunmtx);
36477589Sbrian		tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
36575103Sbrian		if (tag == NULL)
36675103Sbrian			return (ENOMEM);
367111742Sdes		break;
368111742Sdes	case MOD_UNLOAD:
369345286Skp		/* See tun_uninit, so it's done after the vnet_sysuninit() */
37075103Sbrian		break;
371132199Sphk	default:
372132199Sphk		return EOPNOTSUPP;
373111742Sdes	}
374111742Sdes	return 0;
375111742Sdes}
3766053Samurai
377111742Sdesstatic moduledata_t tun_mod = {
378111742Sdes	"if_tun",
379111742Sdes	tunmodevent,
380241394Skevlo	0
381111742Sdes};
3826053Samurai
38371862SpeterDECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
384254020SmarkjMODULE_VERSION(if_tun, 1);
38571862Speter
38649829Sphkstatic void
38777589Sbriantunstart(struct ifnet *ifp)
38869621Sjlemon{
38969621Sjlemon	struct tun_softc *tp = ifp->if_softc;
390131455Smlaier	struct mbuf *m;
39169621Sjlemon
392161103Srwatson	TUNDEBUG(ifp,"%s starting\n", ifp->if_xname);
393131455Smlaier	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
394131455Smlaier		IFQ_LOCK(&ifp->if_snd);
395131455Smlaier		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
396131455Smlaier		if (m == NULL) {
397131455Smlaier			IFQ_UNLOCK(&ifp->if_snd);
398131455Smlaier			return;
399131455Smlaier		}
400131455Smlaier		IFQ_UNLOCK(&ifp->if_snd);
401131455Smlaier	}
402131455Smlaier
403127591Srwatson	mtx_lock(&tp->tun_mtx);
40469621Sjlemon	if (tp->tun_flags & TUN_RWAIT) {
40569621Sjlemon		tp->tun_flags &= ~TUN_RWAIT;
406111748Sdes		wakeup(tp);
40769621Sjlemon	}
408213028Sjhb	selwakeuppri(&tp->tun_rsel, PZERO + 1);
409213028Sjhb	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
410127591Srwatson	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
411127591Srwatson		mtx_unlock(&tp->tun_mtx);
41295883Salfred		pgsigio(&tp->tun_sigio, SIGIO, 0);
413127591Srwatson	} else
414127591Srwatson		mtx_unlock(&tp->tun_mtx);
41569621Sjlemon}
41669621Sjlemon
417147256Sbrooks/* XXX: should return an error code so it can fail. */
41869621Sjlemonstatic void
419166497Sbmstuncreate(const char *name, struct cdev *dev)
42049829Sphk{
42149829Sphk	struct tun_softc *sc;
42249829Sphk	struct ifnet *ifp;
42349829Sphk
424184205Sdes	sc = malloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
425127591Srwatson	mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
426186391Sqingli	cv_init(&sc->tun_cv, "tun_condvar");
42749829Sphk	sc->tun_flags = TUN_INITED;
428126077Sphk	sc->tun_dev = dev;
429127580Srwatson	mtx_lock(&tunmtx);
430126077Sphk	TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
431127580Srwatson	mtx_unlock(&tunmtx);
43249829Sphk
433147256Sbrooks	ifp = sc->tun_ifp = if_alloc(IFT_PPP);
434147256Sbrooks	if (ifp == NULL)
435147256Sbrooks		panic("%s%d: failed to if_alloc() interface.\n",
436166497Sbms		    name, dev2unit(dev));
437166497Sbms	if_initname(ifp, name, dev2unit(dev));
43849829Sphk	ifp->if_mtu = TUNMTU;
43949829Sphk	ifp->if_ioctl = tunifioctl;
44049829Sphk	ifp->if_output = tunoutput;
44169621Sjlemon	ifp->if_start = tunstart;
44249829Sphk	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
44349829Sphk	ifp->if_softc = sc;
444131455Smlaier	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
445131455Smlaier	ifp->if_snd.ifq_drv_maxlen = 0;
446131455Smlaier	IFQ_SET_READY(&ifp->if_snd);
447213028Sjhb	knlist_init_mtx(&sc->tun_rsel.si_note, &sc->tun_mtx);
448205222Sqingli	ifp->if_capabilities |= IFCAP_LINKSTATE;
449205222Sqingli	ifp->if_capenable |= IFCAP_LINKSTATE;
450131455Smlaier
45149829Sphk	if_attach(ifp);
452147611Sdwmalone	bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
45349829Sphk	dev->si_drv1 = sc;
454161103Srwatson	TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
455183397Sed	    ifp->if_xname, dev2unit(dev));
4566053Samurai}
4576053Samurai
45877589Sbrianstatic int
459130585Sphktunopen(struct cdev *dev, int flag, int mode, struct thread *td)
4606053Samurai{
4616053Samurai	struct ifnet	*ifp;
4626053Samurai	struct tun_softc *tp;
4636053Samurai
464127591Srwatson	/*
465127591Srwatson	 * XXXRW: Non-atomic test and set of dev->si_drv1 requires
466127591Srwatson	 * synchronization.
467127591Srwatson	 */
46849829Sphk	tp = dev->si_drv1;
46949829Sphk	if (!tp) {
470241610Sglebius		tuncreate(tunname, dev);
47149829Sphk		tp = dev->si_drv1;
47249829Sphk	}
473126077Sphk
474127591Srwatson	mtx_lock(&tp->tun_mtx);
475347378Skevans	if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) {
476127591Srwatson		mtx_unlock(&tp->tun_mtx);
477126077Sphk		return (EBUSY);
478127591Srwatson	}
479347378Skevans
480127099Srwatson	tp->tun_pid = td->td_proc->p_pid;
481126077Sphk	tp->tun_flags |= TUN_OPEN;
482147256Sbrooks	ifp = TUN2IFP(tp);
483185963Scsjp	if_link_state_change(ifp, LINK_STATE_UP);
484121778Sbrooks	TUNDEBUG(ifp, "open\n");
485213028Sjhb	mtx_unlock(&tp->tun_mtx);
48677589Sbrian
4876053Samurai	return (0);
4886053Samurai}
4896053Samurai
4906053Samurai/*
4916053Samurai * tunclose - close the device - mark i/f down & delete
4926053Samurai * routing info
4936053Samurai */
49412675Sjulianstatic	int
495130585Sphktunclose(struct cdev *dev, int foo, int bar, struct thread *td)
4966053Samurai{
497353157Skevans	struct proc *p;
49849829Sphk	struct tun_softc *tp;
49977589Sbrian	struct ifnet *ifp;
5006053Samurai
501353157Skevans	p = td->td_proc;
50249829Sphk	tp = dev->si_drv1;
503147256Sbrooks	ifp = TUN2IFP(tp);
50449829Sphk
505127591Srwatson	mtx_lock(&tp->tun_mtx);
506353157Skevans
507347378Skevans	/*
508353157Skevans	 * Realistically, we can't be obstinate here.  This only means that the
509353157Skevans	 * tuntap device was closed out of order, and the last closer wasn't the
510353157Skevans	 * controller.  These are still good to know about, though, as software
511353157Skevans	 * should avoid multiple processes with a tuntap device open and
512353157Skevans	 * ill-defined transfer of control (e.g., handoff, TUNSIFPID, close in
513353157Skevans	 * parent).
514347378Skevans	 */
515353157Skevans	if (p->p_pid != tp->tun_pid) {
516353157Skevans		log(LOG_INFO,
517353157Skevans		    "pid %d (%s), %s: tun/tap protocol violation, non-controlling process closed last.\n",
518353157Skevans		    p->p_pid, p->p_comm, dev->si_name);
519347378Skevans	}
5206053Samurai
5216053Samurai	/*
5226053Samurai	 * junk all pending output
5236053Samurai	 */
524183550Szec	CURVNET_SET(ifp->if_vnet);
525131455Smlaier	IFQ_PURGE(&ifp->if_snd);
5266053Samurai
5276053Samurai	if (ifp->if_flags & IFF_UP) {
528213028Sjhb		mtx_unlock(&tp->tun_mtx);
5296053Samurai		if_down(ifp);
530213028Sjhb		mtx_lock(&tp->tun_mtx);
5316053Samurai	}
53247550Sbrian
533166512Sbms	/* Delete all addresses and routes which reference this interface. */
534148887Srwatson	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
535111742Sdes		struct ifaddr *ifa;
53647550Sbrian
537213028Sjhb		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
538213028Sjhb		mtx_unlock(&tp->tun_mtx);
539166512Sbms		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
540166512Sbms			/* deal w/IPv4 PtP destination; unlocked read */
541166512Sbms			if (ifa->ifa_addr->sa_family == AF_INET) {
54247550Sbrian				rtinit(ifa, (int)RTM_DELETE,
54347550Sbrian				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
544166512Sbms			} else {
545166512Sbms				rtinit(ifa, (int)RTM_DELETE, 0);
546166512Sbms			}
547166512Sbms		}
548166512Sbms		if_purgeaddrs(ifp);
549213028Sjhb		mtx_lock(&tp->tun_mtx);
55047550Sbrian	}
551185963Scsjp	if_link_state_change(ifp, LINK_STATE_DOWN);
552183550Szec	CURVNET_RESTORE();
55347550Sbrian
55496122Salfred	funsetown(&tp->tun_sigio);
555122352Stanimura	selwakeuppri(&tp->tun_rsel, PZERO + 1);
556213028Sjhb	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
557121778Sbrooks	TUNDEBUG (ifp, "closed\n");
558347378Skevans	tp->tun_flags &= ~TUN_OPEN;
559347378Skevans	tp->tun_pid = 0;
560186391Sqingli
561186391Sqingli	cv_broadcast(&tp->tun_cv);
562186391Sqingli	mtx_unlock(&tp->tun_mtx);
5636053Samurai	return (0);
5646053Samurai}
5656053Samurai
566222651Sjhbstatic void
56777589Sbriantuninit(struct ifnet *ifp)
5686053Samurai{
569213328Sbz	struct tun_softc *tp = ifp->if_softc;
570184679Sbz#ifdef INET
571111742Sdes	struct ifaddr *ifa;
572184679Sbz#endif
5736053Samurai
574121778Sbrooks	TUNDEBUG(ifp, "tuninit\n");
5756053Samurai
576213028Sjhb	mtx_lock(&tp->tun_mtx);
577148887Srwatson	ifp->if_flags |= IFF_UP;
578148887Srwatson	ifp->if_drv_flags |= IFF_DRV_RUNNING;
57935067Sphk	getmicrotime(&ifp->if_lastchange);
5806053Samurai
581160038Syar#ifdef INET
582195022Srwatson	if_addr_rlock(ifp);
583160033Syar	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
584160038Syar		if (ifa->ifa_addr->sa_family == AF_INET) {
585160038Syar			struct sockaddr_in *si;
5866053Samurai
587160038Syar			si = (struct sockaddr_in *)ifa->ifa_addr;
588160038Syar			if (si->sin_addr.s_addr)
589160038Syar				tp->tun_flags |= TUN_IASET;
5906053Samurai
591160038Syar			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
592160038Syar			if (si && si->sin_addr.s_addr)
593160038Syar				tp->tun_flags |= TUN_DSTADDR;
5946735Samurai		}
59532350Seivind	}
596195022Srwatson	if_addr_runlock(ifp);
597160038Syar#endif
598213028Sjhb	mtx_unlock(&tp->tun_mtx);
5996053Samurai}
6006053Samurai
6016053Samurai/*
6026053Samurai * Process an ioctl request.
6036053Samurai */
604105556Sphkstatic int
60577589Sbriantunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6066053Samurai{
60748021Sphk	struct ifreq *ifr = (struct ifreq *)data;
608347378Skevans	struct tun_softc *tp;
60948021Sphk	struct ifstat *ifs;
610213028Sjhb	int		error = 0;
6116053Samurai
612347378Skevans	sx_xlock(&tun_ioctl_sx);
613347378Skevans	tp = ifp->if_softc;
614347378Skevans	if (tp == NULL) {
615347378Skevans		error = ENXIO;
616347378Skevans		goto bad;
617347378Skevans	}
6186053Samurai	switch(cmd) {
61948021Sphk	case SIOCGIFSTATUS:
62048021Sphk		ifs = (struct ifstat *)data;
621127591Srwatson		mtx_lock(&tp->tun_mtx);
622127099Srwatson		if (tp->tun_pid)
623260394Smelifaro			snprintf(ifs->ascii, sizeof(ifs->ascii),
624127099Srwatson			    "\tOpened by PID %d\n", tp->tun_pid);
625260394Smelifaro		else
626260394Smelifaro			ifs->ascii[0] = '\0';
627127591Srwatson		mtx_unlock(&tp->tun_mtx);
62868250Sjlemon		break;
6296053Samurai	case SIOCSIFADDR:
630222651Sjhb		tuninit(ifp);
631222651Sjhb		TUNDEBUG(ifp, "address set\n");
6326053Samurai		break;
63320559Sfenner	case SIOCSIFMTU:
63449469Sbrian		ifp->if_mtu = ifr->ifr_mtu;
635121778Sbrooks		TUNDEBUG(ifp, "mtu set\n");
63620559Sfenner		break;
63775095Sbrian	case SIOCSIFFLAGS:
63811004Swollman	case SIOCADDMULTI:
63911004Swollman	case SIOCDELMULTI:
64011004Swollman		break;
6416053Samurai	default:
6426053Samurai		error = EINVAL;
6436053Samurai	}
644347378Skevansbad:
645347378Skevans	sx_xunlock(&tun_ioctl_sx);
6466053Samurai	return (error);
6476053Samurai}
6486053Samurai
6496053Samurai/*
6506053Samurai * tunoutput - queue packets from higher level ready to put out.
6516053Samurai */
652105556Sphkstatic int
653249925Sglebiustunoutput(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
654221552Syongari    struct route *ro)
6556053Samurai{
65649829Sphk	struct tun_softc *tp = ifp->if_softc;
657127591Srwatson	u_short cached_tun_flags;
658101083Srwatson	int error;
659147611Sdwmalone	u_int32_t af;
6606053Samurai
661121778Sbrooks	TUNDEBUG (ifp, "tunoutput\n");
6626053Samurai
663101083Srwatson#ifdef MAC
664172930Srwatson	error = mac_ifnet_check_transmit(ifp, m0);
665101083Srwatson	if (error) {
666101083Srwatson		m_freem(m0);
667101083Srwatson		return (error);
668101083Srwatson	}
669101083Srwatson#endif
670101083Srwatson
671127591Srwatson	/* Could be unlocked read? */
672127591Srwatson	mtx_lock(&tp->tun_mtx);
673127591Srwatson	cached_tun_flags = tp->tun_flags;
674127591Srwatson	mtx_unlock(&tp->tun_mtx);
675127591Srwatson	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
676121778Sbrooks		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
6776053Samurai		m_freem (m0);
67891275Simp		return (EHOSTDOWN);
6796053Samurai	}
6806053Samurai
681105944Ssimokawa	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
682105804Ssimokawa		m_freem (m0);
683105804Ssimokawa		return (EHOSTDOWN);
684105804Ssimokawa	}
685105804Ssimokawa
686147611Sdwmalone	/* BPF writes need to be handled specially. */
687249925Sglebius	if (dst->sa_family == AF_UNSPEC)
688147611Sdwmalone		bcopy(dst->sa_data, &af, sizeof(af));
689249925Sglebius	else
690249925Sglebius		af = dst->sa_family;
69111004Swollman
692249925Sglebius	if (bpf_peers_present(ifp->if_bpf))
693123922Ssam		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
6946053Samurai
69545014Sdes	/* prepend sockaddr? this may abort if the mbuf allocation fails */
696127591Srwatson	if (cached_tun_flags & TUN_LMODE) {
69745014Sdes		/* allocate space for sockaddr */
698243882Sglebius		M_PREPEND(m0, dst->sa_len, M_NOWAIT);
69945014Sdes
70045014Sdes		/* if allocation failed drop packet */
70169152Sjlemon		if (m0 == NULL) {
702271867Sglebius			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
703271867Sglebius			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
70445014Sdes			return (ENOBUFS);
70545014Sdes		} else {
70645014Sdes			bcopy(dst, m0->m_data, dst->sa_len);
70745014Sdes		}
70845014Sdes	}
70945014Sdes
710127591Srwatson	if (cached_tun_flags & TUN_IFHEAD) {
71156410Sbrian		/* Prepend the address family */
712243882Sglebius		M_PREPEND(m0, 4, M_NOWAIT);
71356410Sbrian
71456410Sbrian		/* if allocation failed drop packet */
71569152Sjlemon		if (m0 == NULL) {
716271867Sglebius			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
717271867Sglebius			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
71891275Simp			return (ENOBUFS);
71956410Sbrian		} else
720249925Sglebius			*(u_int32_t *)m0->m_data = htonl(af);
72156410Sbrian	} else {
7226053Samurai#ifdef INET
723249925Sglebius		if (af != AF_INET)
72456410Sbrian#endif
72556410Sbrian		{
7266053Samurai			m_freem(m0);
72791275Simp			return (EAFNOSUPPORT);
7286053Samurai		}
72956410Sbrian	}
73056410Sbrian
731185164Skmacy	error = (ifp->if_transmit)(ifp, m0);
732221548Syongari	if (error)
73391275Simp		return (ENOBUFS);
734271867Sglebius	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
73591275Simp	return (0);
7366053Samurai}
7376053Samurai
7386053Samurai/*
7396053Samurai * the cdevsw interface is now pretty minimal.
7406053Samurai */
74112675Sjulianstatic	int
742221552Syongaritunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
743221552Syongari    struct thread *td)
7446053Samurai{
745350465Skevans	struct ifreq ifr, *ifrp;
74649829Sphk	struct tun_softc *tp = dev->si_drv1;
747111742Sdes	struct tuninfo *tunp;
748341884Shselasky	int error;
7496053Samurai
7506053Samurai	switch (cmd) {
751350465Skevans	case TUNGIFNAME:
752350465Skevans		ifrp = (struct ifreq *)data;
753350465Skevans		strlcpy(ifrp->ifr_name, TUN2IFP(tp)->if_xname, IFNAMSIZ);
754350465Skevans		break;
755111742Sdes	case TUNSIFINFO:
756111742Sdes		tunp = (struct tuninfo *)data;
757341884Shselasky		if (TUN2IFP(tp)->if_type != tunp->type)
758341884Shselasky			return (EPROTOTYPE);
759341884Shselasky		mtx_lock(&tp->tun_mtx);
760164033Srwatson		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
761347376Skevans			strlcpy(ifr.ifr_name, if_name(TUN2IFP(tp)), IFNAMSIZ);
762341884Shselasky			ifr.ifr_mtu = tunp->mtu;
763341884Shselasky			CURVNET_SET(TUN2IFP(tp)->if_vnet);
764341884Shselasky			error = ifhwioctl(SIOCSIFMTU, TUN2IFP(tp),
765341884Shselasky			    (caddr_t)&ifr, td);
766341884Shselasky			CURVNET_RESTORE();
767341884Shselasky			if (error) {
768341884Shselasky				mtx_unlock(&tp->tun_mtx);
769164033Srwatson				return (error);
770341884Shselasky			}
771164033Srwatson		}
772147256Sbrooks		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
773213028Sjhb		mtx_unlock(&tp->tun_mtx);
774111742Sdes		break;
775111742Sdes	case TUNGIFINFO:
776111742Sdes		tunp = (struct tuninfo *)data;
777213028Sjhb		mtx_lock(&tp->tun_mtx);
778147256Sbrooks		tunp->mtu = TUN2IFP(tp)->if_mtu;
779147256Sbrooks		tunp->type = TUN2IFP(tp)->if_type;
780147256Sbrooks		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
781213028Sjhb		mtx_unlock(&tp->tun_mtx);
782111742Sdes		break;
7836053Samurai	case TUNSDEBUG:
7846053Samurai		tundebug = *(int *)data;
7856053Samurai		break;
7866053Samurai	case TUNGDEBUG:
7876053Samurai		*(int *)data = tundebug;
7886053Samurai		break;
78945014Sdes	case TUNSLMODE:
790127591Srwatson		mtx_lock(&tp->tun_mtx);
79156410Sbrian		if (*(int *)data) {
79245014Sdes			tp->tun_flags |= TUN_LMODE;
79356410Sbrian			tp->tun_flags &= ~TUN_IFHEAD;
79456410Sbrian		} else
79545014Sdes			tp->tun_flags &= ~TUN_LMODE;
796127591Srwatson		mtx_unlock(&tp->tun_mtx);
79745014Sdes		break;
79856410Sbrian	case TUNSIFHEAD:
799127591Srwatson		mtx_lock(&tp->tun_mtx);
80056410Sbrian		if (*(int *)data) {
80156410Sbrian			tp->tun_flags |= TUN_IFHEAD;
80256410Sbrian			tp->tun_flags &= ~TUN_LMODE;
803111742Sdes		} else
80456410Sbrian			tp->tun_flags &= ~TUN_IFHEAD;
805127591Srwatson		mtx_unlock(&tp->tun_mtx);
80656410Sbrian		break;
80756410Sbrian	case TUNGIFHEAD:
808127591Srwatson		mtx_lock(&tp->tun_mtx);
80956410Sbrian		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
810127591Srwatson		mtx_unlock(&tp->tun_mtx);
81156410Sbrian		break;
81245014Sdes	case TUNSIFMODE:
81345014Sdes		/* deny this if UP */
814147256Sbrooks		if (TUN2IFP(tp)->if_flags & IFF_UP)
81545014Sdes			return(EBUSY);
81645014Sdes
81782319Sbrian		switch (*(int *)data & ~IFF_MULTICAST) {
81845014Sdes		case IFF_POINTOPOINT:
81945014Sdes		case IFF_BROADCAST:
820213028Sjhb			mtx_lock(&tp->tun_mtx);
821147256Sbrooks			TUN2IFP(tp)->if_flags &=
82282319Sbrian			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
823147256Sbrooks			TUN2IFP(tp)->if_flags |= *(int *)data;
824213028Sjhb			mtx_unlock(&tp->tun_mtx);
82545014Sdes			break;
82645014Sdes		default:
82745014Sdes			return(EINVAL);
82845014Sdes		}
82945014Sdes		break;
83056349Sbrian	case TUNSIFPID:
831127591Srwatson		mtx_lock(&tp->tun_mtx);
832127099Srwatson		tp->tun_pid = curthread->td_proc->p_pid;
833127591Srwatson		mtx_unlock(&tp->tun_mtx);
83456349Sbrian		break;
8356053Samurai	case FIONBIO:
8366053Samurai		break;
8376053Samurai	case FIOASYNC:
838127591Srwatson		mtx_lock(&tp->tun_mtx);
8396053Samurai		if (*(int *)data)
8406053Samurai			tp->tun_flags |= TUN_ASYNC;
8416053Samurai		else
8426053Samurai			tp->tun_flags &= ~TUN_ASYNC;
843127591Srwatson		mtx_unlock(&tp->tun_mtx);
8446053Samurai		break;
8456053Samurai	case FIONREAD:
846147256Sbrooks		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
847131455Smlaier			struct mbuf *mb;
848147256Sbrooks			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
849147256Sbrooks			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
850213028Sjhb			for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
85112773Speter				*(int *)data += mb->m_len;
852147256Sbrooks			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
85312773Speter		} else
8546053Samurai			*(int *)data = 0;
8556053Samurai		break;
85641086Struckman	case FIOSETOWN:
85741086Struckman		return (fsetown(*(int *)data, &tp->tun_sigio));
85841086Struckman
85941086Struckman	case FIOGETOWN:
860104393Struckman		*(int *)data = fgetown(&tp->tun_sigio);
86141086Struckman		return (0);
86241086Struckman
86341086Struckman	/* This is deprecated, FIOSETOWN should be used instead. */
8646053Samurai	case TIOCSPGRP:
86541086Struckman		return (fsetown(-(*(int *)data), &tp->tun_sigio));
86641086Struckman
86741086Struckman	/* This is deprecated, FIOGETOWN should be used instead. */
8686053Samurai	case TIOCGPGRP:
869104393Struckman		*(int *)data = -fgetown(&tp->tun_sigio);
87041086Struckman		return (0);
87141086Struckman
8726053Samurai	default:
8736053Samurai		return (ENOTTY);
8746053Samurai	}
8756053Samurai	return (0);
8766053Samurai}
8776053Samurai
8786053Samurai/*
8796053Samurai * The cdevsw read interface - reads a packet at a time, or at
8806053Samurai * least as much of a packet as can be read.
8816053Samurai */
88212675Sjulianstatic	int
883130585Sphktunread(struct cdev *dev, struct uio *uio, int flag)
8846053Samurai{
88549829Sphk	struct tun_softc *tp = dev->si_drv1;
886147256Sbrooks	struct ifnet	*ifp = TUN2IFP(tp);
88790227Sdillon	struct mbuf	*m;
888213028Sjhb	int		error=0, len;
8896053Samurai
890121778Sbrooks	TUNDEBUG (ifp, "read\n");
891127591Srwatson	mtx_lock(&tp->tun_mtx);
8926053Samurai	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
893127591Srwatson		mtx_unlock(&tp->tun_mtx);
894121778Sbrooks		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
89591275Simp		return (EHOSTDOWN);
8966053Samurai	}
8976053Samurai
8986053Samurai	tp->tun_flags &= ~TUN_RWAIT;
8996053Samurai
9006053Samurai	do {
901131455Smlaier		IFQ_DEQUEUE(&ifp->if_snd, m);
90290227Sdillon		if (m == NULL) {
903139208Sphk			if (flag & O_NONBLOCK) {
904213028Sjhb				mtx_unlock(&tp->tun_mtx);
90591275Simp				return (EWOULDBLOCK);
9066053Samurai			}
9076053Samurai			tp->tun_flags |= TUN_RWAIT;
908213028Sjhb			error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
909213028Sjhb			    "tunread", 0);
910213028Sjhb			if (error != 0) {
911213028Sjhb				mtx_unlock(&tp->tun_mtx);
91291275Simp				return (error);
91320098Sjulian			}
9146053Samurai		}
91590227Sdillon	} while (m == NULL);
916213028Sjhb	mtx_unlock(&tp->tun_mtx);
9176053Samurai
91890227Sdillon	while (m && uio->uio_resid > 0 && error == 0) {
91990227Sdillon		len = min(uio->uio_resid, m->m_len);
92081106Sfenner		if (len != 0)
921111741Sdes			error = uiomove(mtod(m, void *), len, uio);
92290227Sdillon		m = m_free(m);
9236053Samurai	}
9246053Samurai
92590227Sdillon	if (m) {
926121778Sbrooks		TUNDEBUG(ifp, "Dropping mbuf\n");
92790227Sdillon		m_freem(m);
9286053Samurai	}
92991275Simp	return (error);
9306053Samurai}
9316053Samurai
9326053Samurai/*
9336053Samurai * the cdevsw write interface - an atomic write is a packet - or else!
9346053Samurai */
93512675Sjulianstatic	int
936130585Sphktunwrite(struct cdev *dev, struct uio *uio, int flag)
9376053Samurai{
93849829Sphk	struct tun_softc *tp = dev->si_drv1;
939147256Sbrooks	struct ifnet	*ifp = TUN2IFP(tp);
940137101Sglebius	struct mbuf	*m;
941300205Stuexen	uint32_t	family, mru;
942111888Sjlemon	int 		isr;
9436053Samurai
944121778Sbrooks	TUNDEBUG(ifp, "tunwrite\n");
9456053Samurai
946105944Ssimokawa	if ((ifp->if_flags & IFF_UP) != IFF_UP)
947105804Ssimokawa		/* ignore silently */
948105804Ssimokawa		return (0);
949105804Ssimokawa
95049116Sbrian	if (uio->uio_resid == 0)
95191275Simp		return (0);
95249116Sbrian
953300205Stuexen	mru = TUNMRU;
954300205Stuexen	if (tp->tun_flags & TUN_IFHEAD)
955300205Stuexen		mru += sizeof(family);
956300205Stuexen	if (uio->uio_resid < 0 || uio->uio_resid > mru) {
957194990Skib		TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
95891275Simp		return (EIO);
9596053Samurai	}
9606053Samurai
961243882Sglebius	if ((m = m_uiotombuf(uio, M_NOWAIT, 0, 0, M_PKTHDR)) == NULL) {
962271867Sglebius		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
963222651Sjhb		return (ENOBUFS);
9646053Samurai	}
9656053Samurai
966137101Sglebius	m->m_pkthdr.rcvif = ifp;
967101083Srwatson#ifdef MAC
968172930Srwatson	mac_ifnet_create_mbuf(ifp, m);
969101083Srwatson#endif
9706053Samurai
971127591Srwatson	/* Could be unlocked read? */
972127591Srwatson	mtx_lock(&tp->tun_mtx);
97356410Sbrian	if (tp->tun_flags & TUN_IFHEAD) {
974127591Srwatson		mtx_unlock(&tp->tun_mtx);
975137101Sglebius		if (m->m_len < sizeof(family) &&
976137101Sglebius		    (m = m_pullup(m, sizeof(family))) == NULL)
97791275Simp			return (ENOBUFS);
978137101Sglebius		family = ntohl(*mtod(m, u_int32_t *));
979137101Sglebius		m_adj(m, sizeof(family));
980127591Srwatson	} else {
981127591Srwatson		mtx_unlock(&tp->tun_mtx);
98256410Sbrian		family = AF_INET;
983127591Srwatson	}
98456410Sbrian
985137101Sglebius	BPF_MTAP2(ifp, &family, sizeof(family), m);
986123922Ssam
987111888Sjlemon	switch (family) {
988111888Sjlemon#ifdef INET
989111888Sjlemon	case AF_INET:
990111888Sjlemon		isr = NETISR_IP;
991111888Sjlemon		break;
992111888Sjlemon#endif
993111999Sjlemon#ifdef INET6
994111999Sjlemon	case AF_INET6:
995111999Sjlemon		isr = NETISR_IPV6;
996111999Sjlemon		break;
997111999Sjlemon#endif
998111888Sjlemon	default:
999111888Sjlemon		m_freem(m);
1000111888Sjlemon		return (EAFNOSUPPORT);
1001111888Sjlemon	}
1002285422Smarkm	random_harvest_queue(m, sizeof(*m), 2, RANDOM_NET_TUN);
1003271867Sglebius	if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
1004271867Sglebius	if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1005183550Szec	CURVNET_SET(ifp->if_vnet);
1006223741Sbz	M_SETFIB(m, ifp->if_fib);
1007137101Sglebius	netisr_dispatch(isr, m);
1008183550Szec	CURVNET_RESTORE();
1009111888Sjlemon	return (0);
10106053Samurai}
10116053Samurai
10126053Samurai/*
101329365Speter * tunpoll - the poll interface, this is only useful on reads
10146053Samurai * really. The write detect always returns true, write never blocks
10156053Samurai * anyway, it either accepts the packet or drops it.
10166053Samurai */
101712675Sjulianstatic	int
1018130585Sphktunpoll(struct cdev *dev, int events, struct thread *td)
10196053Samurai{
102049829Sphk	struct tun_softc *tp = dev->si_drv1;
1021147256Sbrooks	struct ifnet	*ifp = TUN2IFP(tp);
102229365Speter	int		revents = 0;
1023131455Smlaier	struct mbuf	*m;
10246053Samurai
1025121778Sbrooks	TUNDEBUG(ifp, "tunpoll\n");
10266735Samurai
102746568Speter	if (events & (POLLIN | POLLRDNORM)) {
1028131455Smlaier		IFQ_LOCK(&ifp->if_snd);
1029131455Smlaier		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
1030131455Smlaier		if (m != NULL) {
1031121778Sbrooks			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
103229365Speter			revents |= events & (POLLIN | POLLRDNORM);
103329365Speter		} else {
1034121778Sbrooks			TUNDEBUG(ifp, "tunpoll waiting\n");
103583805Sjhb			selrecord(td, &tp->tun_rsel);
10366053Samurai		}
1037131455Smlaier		IFQ_UNLOCK(&ifp->if_snd);
103846568Speter	}
103929365Speter	if (events & (POLLOUT | POLLWRNORM))
104029365Speter		revents |= events & (POLLOUT | POLLWRNORM);
104129365Speter
104229365Speter	return (revents);
10436053Samurai}
1044161103Srwatson
1045161103Srwatson/*
1046161103Srwatson * tunkqfilter - support for the kevent() system call.
1047161103Srwatson */
1048161103Srwatsonstatic int
1049161103Srwatsontunkqfilter(struct cdev *dev, struct knote *kn)
1050161103Srwatson{
1051161103Srwatson	struct tun_softc	*tp = dev->si_drv1;
1052161103Srwatson	struct ifnet	*ifp = TUN2IFP(tp);
1053161103Srwatson
1054161103Srwatson	switch(kn->kn_filter) {
1055161103Srwatson	case EVFILT_READ:
1056161103Srwatson		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1057183397Sed		    ifp->if_xname, dev2unit(dev));
1058161103Srwatson		kn->kn_fop = &tun_read_filterops;
1059161103Srwatson		break;
1060161103Srwatson
1061161103Srwatson	case EVFILT_WRITE:
1062161103Srwatson		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1063183397Sed		    ifp->if_xname, dev2unit(dev));
1064161103Srwatson		kn->kn_fop = &tun_write_filterops;
1065161103Srwatson		break;
1066221552Syongari
1067161103Srwatson	default:
1068161103Srwatson		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1069183397Sed		    ifp->if_xname, dev2unit(dev));
1070161103Srwatson		return(EINVAL);
1071161103Srwatson	}
1072161103Srwatson
1073213028Sjhb	kn->kn_hook = tp;
1074161103Srwatson	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1075161103Srwatson
1076161103Srwatson	return (0);
1077161103Srwatson}
1078161103Srwatson
1079161103Srwatson/*
1080161103Srwatson * Return true of there is data in the interface queue.
1081161103Srwatson */
1082161103Srwatsonstatic int
1083161103Srwatsontunkqread(struct knote *kn, long hint)
1084161103Srwatson{
1085213028Sjhb	int			ret;
1086213028Sjhb	struct tun_softc	*tp = kn->kn_hook;
1087213028Sjhb	struct cdev		*dev = tp->tun_dev;
1088161103Srwatson	struct ifnet	*ifp = TUN2IFP(tp);
1089161103Srwatson
1090161103Srwatson	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1091161103Srwatson		TUNDEBUG(ifp,
1092161103Srwatson		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1093183397Sed		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1094161103Srwatson		ret = 1;
1095161103Srwatson	} else {
1096161103Srwatson		TUNDEBUG(ifp,
1097161103Srwatson		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1098183397Sed		    dev2unit(dev));
1099161103Srwatson		ret = 0;
1100161103Srwatson	}
1101161103Srwatson
1102161103Srwatson	return (ret);
1103161103Srwatson}
1104161103Srwatson
1105161103Srwatson/*
1106161103Srwatson * Always can write, always return MTU in kn->data.
1107161103Srwatson */
1108161103Srwatsonstatic int
1109161103Srwatsontunkqwrite(struct knote *kn, long hint)
1110161103Srwatson{
1111213028Sjhb	struct tun_softc	*tp = kn->kn_hook;
1112161103Srwatson	struct ifnet	*ifp = TUN2IFP(tp);
1113161103Srwatson
1114161103Srwatson	kn->kn_data = ifp->if_mtu;
1115161103Srwatson
1116161103Srwatson	return (1);
1117161103Srwatson}
1118161103Srwatson
1119161103Srwatsonstatic void
1120161103Srwatsontunkqdetach(struct knote *kn)
1121161103Srwatson{
1122213028Sjhb	struct tun_softc	*tp = kn->kn_hook;
1123161103Srwatson
1124161103Srwatson	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1125161103Srwatson}
1126