Lock of a tty
A tty often interacts with a process group or a session to manage job control and login session. Namely, TIOCGPGRP, TIOCSPGRP, TIOCNOTTY and TIOCSCTTY ioctl(2)s read or modify the states of a process group or a session, thusly calling for locking both a terminal and a process group or a session.
The interaction between a tty and a process group is mostly job control by sending a signal to a process group and switching the foreground process group, initiated by a tty. Hence a tty should be locked prior to a process group.
We often read or modify a tty via a session to reach a foreground process group, to implement iBCS2 ioctl(2)s and so on. On the other hand, loss of carrier is the only one situation to read or modify a session via a tty. We should thus lock a session prior to a tty. Although this method seems somewhat kludge to attach or detach a controlling terminal to or from a session, we have a simple solution; ttioctl() firstly locks the session involved into the invoked ioctl(2) operation, followed by locking a tty.
If a part of the kernel excepts to lock a tty and a process group or a session not in the order discussed above, it may be ecessary to add another lock like p_pgrpmtx to not break the lock order.