--- sys/kern/tty.c.orig
+++ sys/kern/tty.c
@@ -1870,7 +1870,12 @@
 		/* XXX: This looks awful. */
 		tty_unlock(tp);
 		sx_xlock(&proctree_lock);
-		tty_lock(tp);
+		error = ttydev_enter(tp);
+		if (error != 0) {
+			sx_xunlock(&proctree_lock);
+			tty_lock(tp);
+			return (error);
+		}
 
 		if (!SESS_LEADER(p)) {
 			/* Only the session leader may do this. */
@@ -1934,7 +1939,12 @@
 			tty_lock(tp);
 			return (EPERM);
 		}
-		tty_lock(tp);
+		error = ttydev_enter(tp);
+		if (error != 0) {
+			sx_sunlock(&proctree_lock);
+			tty_lock(tp);
+			return (error);
+		}
 
 		/*
 		 * Determine if this TTY is the controlling TTY after
