Writing Device Drivers

Software State Management

Software State Structure

For each device that the driver handles, the driver must keep some state information. At a minimum, this consists of a pointer to the dev_info node for the device (required by getinfo(9E)). The driver can define a structure that contains all the information needed about a single device:

	struct xxstate {
 		dev_info_t			*dip;

This structure will grow as the device driver evolves. Additional useful fields might be a pointer to each of the device's mapped registers, or flags such as busy or suspended. The initial state structure the examples in this book use is given in Example 3-3.

Example 3-3 Initial State Structure

struct xxstate {
		dev_info_t								*dip;
		struct device_reg								*regp;
		int 								xx_busy;					
		struct xx_saved_device_state									device_state;

Subsequent chapters in this manual may require that new fields be added to the state structure. Each chapter will list any additions.

Software State Management Routines

To assist device driver writers in allocating state structures, the Solaris 7 DDI/DKI provides a set of memory management routines called the software state management routines (also known as the soft state routines). These routines dynamically allocate, retrieve, and destroy memory items of a specified size, and hide all the details of list management in a multithreaded kernel. An item number is used to identify the desired memory item; this number can be (and usually is) the instance number assigned by the system.

The driver must provide a state pointer, which is used by the soft state system to create the list of memory items:

	static void *statep;

Routines are provided to:

When the module is loaded, the driver calls ddi_soft_state_init(9F) to initialize the driver state pointer, passing a hint indicating how many items to pre-allocate. If more items are needed, the driver will allocate them as necessary. The driver must call ddi_soft_state_fini(9F) when the driver is unloaded.

To allocate an instance of the soft state structure, the driver calls ddi_soft_state_zalloc(9F). Once the item is allocated, the driver calls ddi_get_soft_state(9F) to retrieve the pointer to the allocated structure. This is usually done when the device is attached. When the device is detached, the driver calls ddi_soft_state_free(9F) to free the memory.

See "Loadable Driver Interface" for an example use of these routines.