Writing Device Drivers


A thread of control, or thread, is a sequence of instructions executed within a program. A thread can share data and code with other threads and can run concurrently with other threads. There are two kinds of threads: user threads and kernel threads. See Multithreaded Programming Guide for more information on threads.

User Threads

Each process in the SunOS operating system has an address space that contains one or more lightweight processes (LWPs), each of which in turn runs one or more user threads. Figure 4-1 shows the relationship between threads, LWPs, and processes. An LWP schedules its user threads and runs one user thread at a time, though multiple LWPs may run concurrently. User threads are handled in user space.

The LWP is the interface between user threads and the kernel. The LWP can be thought of as a virtual CPU that schedules user thread execution. When a user thread issues a system call, the LWP running the thread calls into the kernel and remains bound to the thread at least until the system call is complete. When an LWP is running in the kernel, executing a system call on behalf of a user thread, it runs one kernel thread. Each LWP is therefore associated with exactly one kernel thread.

Kernel Threads

There are two types of kernel threads: those bound to an LWP and those not associated with an LWP. Threads not associated with LWPs are system threads, such as those created to handle hardware interrupts. For those threads bound to an LWP, there is one and only one kernel thread per LWP. On a multiprocessor system, several kernel threads can run simultaneously. Even on uniprocessors, running kernel threads can be preempted at any time to run other threads. Drivers are mainly concerned with kernel threads as most device driver routines run as kernel threads. Figure 4-1 illustrates the relationship between threads and lightweight processes.

Figure 4-1 Threads and Lightweight Processes


A multithreaded kernel requires consideration of locking primitives and thread synchronization.