--- y/drivers/net/tun.c
+++ t/drivers/net/tun.c
@@ -212,6 +212,7 @@ struct tun_struct {
 	/* init args */
 	struct file *file;
 	struct ifreq *ifr;
+	int all_detached;
 };
 
 struct veth {
@@ -701,6 +702,7 @@ static void tun_detach_all(struct net_de
 	struct tun_file *tfile, *tmp;
 	int i, n = tun->numqueues;
 
+	tun->all_detached = 1;
 	for (i = 0; i < n; i++) {
 		tfile = rtnl_dereference(tun->tfiles[i]);
 		BUG_ON(!tfile);
@@ -808,6 +810,10 @@ static int tun_attach(struct tun_struct
 	if (tfile->detached) {
 		tun_enable_queue(tfile);
 	} else {
+		if (tun->all_detached) {
+			err = -EINVAL;
+			goto out;
+		}
 		sock_hold(&tfile->sk);
 		tun_napi_init(tun, tfile, napi, napi_frags);
 	}
@@ -2803,6 +2809,7 @@ static int tun_set_iff(struct net *net,
 
 		tun->ifr = ifr;
 		tun->file = file;
+		tun->all_detached = 0;
 
 		tun_net_initialize(dev);