Device drivers infrastructure¶
The Basic Device Driver-Model Structures¶
- structsubsys_interface¶
interfaces to device functions
Definition:
struct subsys_interface { const char *name; const struct bus_type *subsys; struct list_head node; int (*add_dev)(struct device *dev, struct subsys_interface *sif); void (*remove_dev)(struct device *dev, struct subsys_interface *sif);};Members
namename of the device function
subsyssubsystem of the devices to attach to
nodethe list of functions registered at the subsystem
add_devdevice hookup to device function handler
remove_devdevice hookup to device function handler
Description
Simple interfaces attached to a subsystem. Multiple interfaces canattach to a subsystem and its devices. Unlike drivers, they do notexclusively claim or control devices. Interfaces usually representa specific functionality of a subsystem/class of devices.
- structdevice_attribute¶
Interface for exporting device attributes.
Definition:
struct device_attribute { struct attribute attr; ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf); ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count);};Members
attrsysfs attribute definition.
showShow handler.
storeStore handler.
- structdev_ext_attribute¶
Exported device attribute with extra context.
Definition:
struct dev_ext_attribute { struct device_attribute attr; void *var;};Members
attrExported device attribute.
varPointer to context.
- DEVICE_ATTR¶
DEVICE_ATTR(_name,_mode,_show,_store)
Define a device attribute.
Parameters
_nameAttribute name.
_modeFile mode.
_showShow handler. Optional, but mandatory if attribute is readable.
_storeStore handler. Optional, but mandatory if attribute is writable.
Description
Convenience macro for defining astructdevice_attribute.
For example,DEVICE_ATTR(foo,0644,foo_show,foo_store); expands to:
structdevice_attributedev_attr_foo={.attr={.name="foo",.mode=0644},.show=foo_show,.store=foo_store,};
- DEVICE_ATTR_PREALLOC¶
DEVICE_ATTR_PREALLOC(_name,_mode,_show,_store)
Define a preallocated device attribute.
Parameters
_nameAttribute name.
_modeFile mode.
_showShow handler. Optional, but mandatory if attribute is readable.
_storeStore handler. Optional, but mandatory if attribute is writable.
Description
LikeDEVICE_ATTR(), butSYSFS_PREALLOC is set on_mode.
- DEVICE_ATTR_RW¶
DEVICE_ATTR_RW(_name)
Define a read-write device attribute.
Parameters
_nameAttribute name.
Description
LikeDEVICE_ATTR(), but_mode is 0644,_show is <_name>_show,and_store is <_name>_store.
- DEVICE_ATTR_ADMIN_RW¶
DEVICE_ATTR_ADMIN_RW(_name)
Define an admin-only read-write device attribute.
- DEVICE_ATTR_RO¶
DEVICE_ATTR_RO(_name)
Define a readable device attribute.
Parameters
_nameAttribute name.
Description
LikeDEVICE_ATTR(), but_mode is 0444 and_show is <_name>_show.
- DEVICE_ATTR_ADMIN_RO¶
DEVICE_ATTR_ADMIN_RO(_name)
Define an admin-only readable device attribute.
- DEVICE_ATTR_WO¶
DEVICE_ATTR_WO(_name)
Define an admin-only writable device attribute.
Parameters
_nameAttribute name.
Description
LikeDEVICE_ATTR(), but_mode is 0200 and_store is <_name>_store.
- DEVICE_ULONG_ATTR¶
DEVICE_ULONG_ATTR(_name,_mode,_var)
Define a device attribute backed by an unsigned long.
Parameters
_nameAttribute name.
_modeFile mode.
_varIdentifier of unsigned long.
Description
LikeDEVICE_ATTR(), but_show and_store are automatically providedsuch that reads and writes to the attribute from userspace affect_var.
- DEVICE_INT_ATTR¶
DEVICE_INT_ATTR(_name,_mode,_var)
Define a device attribute backed by an int.
Parameters
_nameAttribute name.
_modeFile mode.
_varIdentifier of int.
Description
LikeDEVICE_ULONG_ATTR(), but_var is an int.
- DEVICE_BOOL_ATTR¶
DEVICE_BOOL_ATTR(_name,_mode,_var)
Define a device attribute backed by a bool.
Parameters
_nameAttribute name.
_modeFile mode.
_varIdentifier of bool.
Description
LikeDEVICE_ULONG_ATTR(), but_var is a bool.
- DEVICE_STRING_ATTR_RO¶
DEVICE_STRING_ATTR_RO(_name,_mode,_var)
Define a device attribute backed by a r/o string.
Parameters
_nameAttribute name.
_modeFile mode.
_varIdentifier of string.
Description
LikeDEVICE_ULONG_ATTR(), but_var is a string. Because the length of thestring allocation is unknown, the attribute must be read-only.
- enumdl_dev_state¶
Device driver presence tracking information.
Constants
DL_DEV_NO_DRIVERThere is no driver attached to the device.
DL_DEV_PROBINGA driver is probing.
DL_DEV_DRIVER_BOUNDThe driver has been bound to the device.
DL_DEV_UNBINDINGThe driver is unbinding from the device.
- enumdevice_removable¶
Whether the device is removable. The criteria for a device to be classified as removable is determined by its subsystem or bus.
Constants
DEVICE_REMOVABLE_NOT_SUPPORTEDThis attribute is not supported for thisdevice (default).
DEVICE_REMOVABLE_UNKNOWNDevice location is Unknown.
DEVICE_FIXEDDevice is not removable by the user.
DEVICE_REMOVABLEDevice is removable by the user.
- structdev_links_info¶
Device data related to device links.
Definition:
struct dev_links_info { struct list_head suppliers; struct list_head consumers; struct list_head defer_sync; enum dl_dev_state status;};Members
suppliersList of links to supplier devices.
consumersList of links to consumer devices.
defer_syncHook to global list of devices that have deferred sync_state.
statusDriver status information.
- structdev_msi_info¶
Device data related to MSI
Definition:
struct dev_msi_info {#ifdef CONFIG_GENERIC_MSI_IRQ; struct irq_domain *domain; struct msi_device_data *data;#endif;};Members
domainThe MSI interrupt domain associated to the device
dataPointer to MSI device data
- enumdevice_physical_location_panel¶
Describes which panel surface of the system’s housing the device connection point resides on.
Constants
DEVICE_PANEL_TOPDevice connection point is on the top panel.
DEVICE_PANEL_BOTTOMDevice connection point is on the bottom panel.
DEVICE_PANEL_LEFTDevice connection point is on the left panel.
DEVICE_PANEL_RIGHTDevice connection point is on the right panel.
DEVICE_PANEL_FRONTDevice connection point is on the front panel.
DEVICE_PANEL_BACKDevice connection point is on the back panel.
DEVICE_PANEL_UNKNOWNThe panel with device connection point is unknown.
- enumdevice_physical_location_vertical_position¶
Describes vertical position of the device connection point on the panel surface.
Constants
DEVICE_VERT_POS_UPPERDevice connection point is at upper part of panel.
DEVICE_VERT_POS_CENTERDevice connection point is at center part of panel.
DEVICE_VERT_POS_LOWERDevice connection point is at lower part of panel.
- enumdevice_physical_location_horizontal_position¶
Describes horizontal position of the device connection point on the panel surface.
Constants
DEVICE_HORI_POS_LEFTDevice connection point is at left part of panel.
DEVICE_HORI_POS_CENTERDevice connection point is at center part of panel.
DEVICE_HORI_POS_RIGHTDevice connection point is at right part of panel.
- structdevice_physical_location¶
Device data related to physical location of the device connection point.
Definition:
struct device_physical_location { enum device_physical_location_panel panel; enum device_physical_location_vertical_position vertical_position; enum device_physical_location_horizontal_position horizontal_position; bool dock; bool lid;};Members
panelPanel surface of the system’s housing that the device connectionpoint resides on.
vertical_positionVertical position of the device connection point withinthe panel.
horizontal_positionHorizontal position of the device connection pointwithin the panel.
dockSet if the device connection point resides in a docking station orport replicator.
lidSet if this device connection point resides on the lid of laptopsystem.
- structdevice¶
The basic device structure
Definition:
struct device { struct kobject kobj; struct device *parent; struct device_private *p; const char *init_name; const struct device_type *type; const struct bus_type *bus; struct device_driver *driver; void *platform_data; void *driver_data; struct mutex mutex; struct dev_links_info links; struct dev_pm_info power; struct dev_pm_domain *pm_domain;#ifdef CONFIG_ENERGY_MODEL; struct em_perf_domain *em_pd;#endif;#ifdef CONFIG_PINCTRL; struct dev_pin_info *pins;#endif; struct dev_msi_info msi;#ifdef CONFIG_ARCH_HAS_DMA_OPS; const struct dma_map_ops *dma_ops;#endif; u64 *dma_mask; u64 coherent_dma_mask; u64 bus_dma_limit; const struct bus_dma_region *dma_range_map; struct device_dma_parameters *dma_parms; struct list_head dma_pools;#ifdef CONFIG_DMA_DECLARE_COHERENT; struct dma_coherent_mem *dma_mem;#endif;#ifdef CONFIG_DMA_CMA; struct cma *cma_area;#endif;#ifdef CONFIG_SWIOTLB; struct io_tlb_mem *dma_io_tlb_mem;#endif;#ifdef CONFIG_SWIOTLB_DYNAMIC; struct list_head dma_io_tlb_pools; spinlock_t dma_io_tlb_lock; bool dma_uses_io_tlb;#endif; struct dev_archdata archdata; struct device_node *of_node; struct fwnode_handle *fwnode;#ifdef CONFIG_NUMA; int numa_node;#endif; dev_t devt; u32 id; spinlock_t devres_lock; struct list_head devres_head; const struct class *class; const struct attribute_group **groups; void (*release)(struct device *dev); struct iommu_group *iommu_group; struct dev_iommu *iommu; struct device_physical_location *physical_location; enum device_removable removable; bool offline_disabled:1; bool offline:1; bool of_node_reused:1; bool state_synced:1; bool can_match:1;#if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) || defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) || defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL); bool dma_coherent:1;#endif;#ifdef CONFIG_DMA_OPS_BYPASS; bool dma_ops_bypass : 1;#endif;#ifdef CONFIG_DMA_NEED_SYNC; bool dma_skip_sync:1;#endif;#ifdef CONFIG_IOMMU_DMA; bool dma_iommu:1;#endif;};Members
kobjA top-level, abstract class from which other classes are derived.
parentThe device’s “parent” device, the device to which it is attached.In most cases, a parent device is some sort of bus or hostcontroller. If parent is NULL, the device, is a top-level device,which is not usually what you want.
pHolds the private data of the driver core portions of the device.See the comment of the
structdevice_privatefor detail.init_nameInitial name of the device.
typeThe type of device.This identifies the device type and carries type-specificinformation.
busType of bus device is on.
driverWhich driver has allocated this
platform_dataPlatform data specific to the device.
driver_dataPrivate pointer for driver specific info.
mutexMutex to synchronize calls to its driver.
linksLinks to suppliers and consumers of this device.
powerFor device power management.SeeDevice Power Management Basics for details.
pm_domainProvide callbacks that are executed during system suspend,hibernation, system resume and during runtime PM transitionsalong with subsystem-level and driver-level callbacks.
em_pddevice’s energy model performance domain
pinsFor device pin management.SeePINCTRL (PIN CONTROL) subsystem for details.
msiMSI related data
dma_opsDMA mapping operations for this device.
dma_maskDma mask (if dma’ble device).
coherent_dma_maskLike dma_mask, but for alloc_coherent mapping as not allhardware supports 64-bit addresses for consistent allocationssuch descriptors.
bus_dma_limitLimit of an upstream bridge or bus which imposes a smallerDMA limit than the device itself supports.
dma_range_mapmap for DMA memory ranges relative to that of RAM
dma_parmsA low level driver may set these to teach IOMMU code aboutsegment limitations.
dma_poolsDma pools (if dma’ble device).
dma_memInternal for coherent mem override.
cma_areaContiguous memory area for dma allocations
dma_io_tlb_memSoftware IO TLB allocator. Not for driver use.
dma_io_tlb_poolsList of transient swiotlb memory pools.
dma_io_tlb_lockProtects changes to the list of active pools.
dma_uses_io_tlbtrueif device has used the software IO TLB.archdataFor arch-specific additions.
of_nodeAssociated device tree node.
fwnodeAssociated device node supplied by platform firmware.
numa_nodeNUMA node this device is close to.
devtFor creating the sysfs “dev”.
iddevice instance
devres_lockSpinlock to protect the resource of the device.
devres_headThe resources list of the device.
classThe class of the device.
groupsOptional attribute groups.
releaseCallback to free the device after all references havegone away. This should be set by the allocator of thedevice (i.e. the bus driver that discovered the device).
iommu_groupIOMMU group the device belongs to.
iommuPer device generic IOMMU runtime data
physical_locationDescribes physical location of the device connectionpoint in the system housing.
removableWhether the device can be removed from the system. Thisshould be set by the subsystem / bus driver that discoveredthe device.
offline_disabledIf set, the device is permanently online.
offlineSet after successful invocation of bus type’s .
offline().of_node_reusedSet if the device-tree node is shared with an ancestordevice.
state_syncedThe hardware state of this device has been synced to matchthe software state of this device by calling the driver/bus
sync_state()callback.can_matchThe device has matched with a driver at least once or it is ina bus (like AMBA) which can’t check for matching drivers untilother devices probe successfully.
dma_coherentthis particular device is dma coherent, even if thearchitecture supports non-coherent devices.
dma_ops_bypassIf set to
truethen the dma_ops are bypassed for thestreaming DMA operations (->map_* / ->unmap_* / ->sync_*),and optionall (if the coherent mask is large enough) alsofor dma allocations. This flag is managed by the dma opsinstance from ->dma_supported.dma_skip_syncDMA sync operations can be skipped for coherent buffers.
dma_iommuDevice is using default IOMMU implementation for DMA anddoesn’t rely on dma_ops structure.
Example
- For devices on custom boards, as typical of embedded
and SOC based hardware, Linux often uses platform_data to pointto board-specific structures describing devices and how theyare wired. That can include what ports are available, chipvariants, which GPIO pins act in what additional roles, and soon. This shrinks the “Board Support Packages” (BSPs) andminimizes board-specific #ifdefs in drivers.
Description
At the lowest level, every device in a Linux system is represented by aninstance ofstructdevice. The device structure contains the informationthat the device model core needs to model the system. Most subsystems,however, track additional information about the devices they host. As aresult, it is rare for devices to be represented by bare device structures;instead, that structure, like kobject structures, is usually embedded withina higher-level representation of the device.
- structdevice_link¶
Device link representation.
Definition:
struct device_link { struct device *supplier; struct list_head s_node; struct device *consumer; struct list_head c_node; struct device link_dev; enum device_link_state status; u32 flags; refcount_t rpm_active; struct kref kref; struct work_struct rm_work; bool supplier_preactivated;};Members
supplierThe device on the supplier end of the link.
s_nodeHook to the supplier device’s list of links to consumers.
consumerThe device on the consumer end of the link.
c_nodeHook to the consumer device’s list of links to suppliers.
link_devdevice used to expose link details in sysfs
statusThe state of the link (with respect to the presence of drivers).
flagsLink flags.
rpm_activeWhether or not the consumer device is runtime-PM-active.
krefCount repeated addition of the same link.
rm_workWork structure used for removing the link.
supplier_preactivatedSupplier has been made active before consumer probe.
- booldevice_iommu_mapped(structdevice*dev)¶
Returns true when the device DMA is translated by an IOMMU
Parameters
structdevice*devDevice to perform the check on
Parameters
conststructdevice*devDevice with name to get.
Return
The kobject name of the device, or its initial name if unavailable.
Parameters
conststructdevice*devstructdeviceto get the bus/class name of
Description
Will return the name of the bus/class the device is attached to. If it isnot attached to a bus/class, an empty string will be returned.
- structdevice*device_find_child_by_name(structdevice*parent,constchar*name)¶
device iterator for locating a child device.
Parameters
structdevice*parentparent
structdeviceconstchar*namename of the child device
Description
This is similar to thedevice_find_child() function above, but itreturns a reference to a device that has the namename.
NOTE
you will need to drop the reference withput_device() after use.
- structdevice*device_find_any_child(structdevice*parent)¶
device iterator for locating a child device, if any.
Parameters
structdevice*parentparent
structdevice
Description
This is similar to thedevice_find_child() function above, but itreturns a reference to a child device, if any.
NOTE
you will need to drop the reference withput_device() after use.
- device_lock_set_class¶
device_lock_set_class(dev,key)
Specify a temporary lock class while a device is attached to a driver
Parameters
devdevice to modify
keylock class key data
Description
This must be called with thedevice_lock() already held, for examplefrom driver ->probe(). Take care to only override the defaultlockdep_no_validate class.
- device_lock_reset_class¶
device_lock_reset_class(dev)
Return a device to the default lockdep novalidate state
Parameters
devdevice to modify
Description
This must be called with thedevice_lock() already held, for examplefrom driver ->remove().
- structbus_type¶
The bus type of the device
Definition:
struct bus_type { const char *name; const char *dev_name; const struct attribute_group **bus_groups; const struct attribute_group **dev_groups; const struct attribute_group **drv_groups; int (*match)(struct device *dev, const struct device_driver *drv); int (*uevent)(const struct device *dev, struct kobj_uevent_env *env); int (*probe)(struct device *dev); void (*sync_state)(struct device *dev); void (*remove)(struct device *dev); void (*shutdown)(struct device *dev); const struct cpumask *(*irq_get_affinity)(struct device *dev, unsigned int irq_vec); int (*online)(struct device *dev); int (*offline)(struct device *dev); int (*suspend)(struct device *dev, pm_message_t state); int (*resume)(struct device *dev); int (*num_vf)(struct device *dev); int (*dma_configure)(struct device *dev); void (*dma_cleanup)(struct device *dev); const struct dev_pm_ops *pm; bool need_parent_lock;};Members
nameThe name of the bus.
dev_nameUsed for subsystems to enumerate devices like (“foo``u``”, dev->id).
bus_groupsDefault attributes of the bus.
dev_groupsDefault attributes of the devices on the bus.
drv_groupsDefault attributes of the device drivers on the bus.
matchCalled, perhaps multiple times, whenever a new device or driveris added for this bus. It should return a positive value if thegiven device can be handled by the given driver and zerootherwise. It may also return error code if determining thatthe driver supports the device is not possible. In case of-EPROBE_DEFER it will queue the device for deferred probing.
ueventCalled when a device is added, removed, or a few other thingsthat generate uevents to add the environment variables.
probeCalled when a new device or driver add to this bus, and callbackthe specific driver’s probe to initial the matched device.
sync_stateCalled to sync device state to software state after all thestate tracking consumers linked to this device (present atthe time of late_initcall) have successfully bound to adriver. If the device has no consumers, this function willbe called at late_initcall_sync level. If the device hasconsumers that are never bound to a driver, this functionwill never get called until they do.
removeCalled when a device removed from this bus.
shutdownCalled at shut-down time to quiesce the device.
irq_get_affinityGet IRQ affinity mask for the device on this bus.
onlineCalled to put the device back online (after offlining it).
offlineCalled to put the device offline for hot-removal. May fail.
suspendCalled when a device on this bus wants to go to sleep mode.
resumeCalled to bring a device on this bus out of sleep mode.
num_vfCalled to find out how many virtual functions a device on thisbus supports.
dma_configureCalled to setup DMA configuration on a device onthis bus.
dma_cleanupCalled to cleanup DMA configuration on a device onthis bus.
pmPower management operations of this bus, callback the specificdevice driver’s pm-ops.
need_parent_lockWhen probing or removing a device on this bus, thedevice core should lock the device’s parent.
Description
A bus is a channel between the processor and one or more devices. For thepurposes of the device model, all devices are connected via a bus, even ifit is an internal, virtual, “platform” bus. Buses can plug into each other.A USB controller is usually a PCI device, for example. The device modelrepresents the actual connections between buses and the devices they control.A bus is represented by the bus_type structure. It contains the name, thedefault attributes, the bus’ methods, PM operations, and the driver core’sprivate data.
- enumbus_notifier_event¶
Bus Notifier events that have happened
Constants
BUS_NOTIFY_ADD_DEVICEdevice is added to this bus
BUS_NOTIFY_DEL_DEVICEdevice is about to be removed from this bus
BUS_NOTIFY_REMOVED_DEVICEdevice is successfully removed from this bus
BUS_NOTIFY_BIND_DRIVERa driver is about to be bound to this device on this bus
BUS_NOTIFY_BOUND_DRIVERa driver is successfully bound to this device on this bus
BUS_NOTIFY_UNBIND_DRIVERa driver is about to be unbound from this device on this bus
BUS_NOTIFY_UNBOUND_DRIVERa driver is successfully unbound from this device on this bus
BUS_NOTIFY_DRIVER_NOT_BOUNDa driver failed to be bound to this device on this bus
Description
These are the value passed to a bus notifier when a specific event happens.
Note that bus notifiers are likely to be called with the device lock alreadyheld by the driver core, so be careful in any notifier callback as to whatyou do with the device structure.
All bus notifiers are called with the targetstructdevice * as an argument.
- structclass¶
device classes
Definition:
struct class { const char *name; const struct attribute_group **class_groups; const struct attribute_group **dev_groups; int (*dev_uevent)(const struct device *dev, struct kobj_uevent_env *env); char *(*devnode)(const struct device *dev, umode_t *mode); void (*class_release)(const struct class *class); void (*dev_release)(struct device *dev); int (*shutdown_pre)(struct device *dev); const struct kobj_ns_type_operations *ns_type; const void *(*namespace)(const struct device *dev); void (*get_ownership)(const struct device *dev, kuid_t *uid, kgid_t *gid); const struct dev_pm_ops *pm;};Members
nameName of the class.
class_groupsDefault attributes of this class.
dev_groupsDefault attributes of the devices that belong to the class.
dev_ueventCalled when a device is added, removed from this class, or afew other things that generate uevents to add the environmentvariables.
devnodeCallback to provide the devtmpfs.
class_releaseCalled to release this class.
dev_releaseCalled to release the device.
shutdown_preCalled at shut-down time before driver shutdown.
ns_typeCallbacks so sysfs can detemine namespaces.
namespaceNamespace of the device belongs to this class.
get_ownershipAllows class to specify uid/gid of the sysfs directoriesfor the devices belonging to the class. Usually tied todevice’s namespace.
pmThe default device power management operations of this class.
Description
A class is a higher-level view of a device that abstracts out low-levelimplementation details. Drivers may see a SCSI disk or an ATA disk, but,at the class level, they are all simply disks. Classes allow user spaceto work with devices based on what they do, rather than how they areconnected or how they work.
- enumprobe_type¶
device driver probe type to try Device drivers may opt in for special handling of their respective probe routines. This tells the core what to expect and prefer.
Constants
PROBE_DEFAULT_STRATEGYUsed by drivers that work equally wellwhether probed synchronously or asynchronously.
PROBE_PREFER_ASYNCHRONOUSDrivers for “slow” devices whichprobing order is not essential for booting the system mayopt into executing their probes asynchronously.
PROBE_FORCE_SYNCHRONOUSUse this to annotate drivers that needtheir probe routines to run synchronously with driver anddevice registration (with the exception of -EPROBE_DEFERhandling - re-probing always ends up being done asynchronously).
Description
Note that the end goal is to switch the kernel to use asynchronousprobing by default, so annotating drivers withPROBE_PREFER_ASYNCHRONOUS is a temporary measure that allows usto speed up boot process while we are validating the rest of thedrivers.
- structdevice_driver¶
The basic device driver structure
Definition:
struct device_driver { const char *name; const struct bus_type *bus; struct module *owner; const char *mod_name; bool suppress_bind_attrs; enum probe_type probe_type; const struct of_device_id *of_match_table; const struct acpi_device_id *acpi_match_table; int (*probe) (struct device *dev); void (*sync_state)(struct device *dev); int (*remove) (struct device *dev); void (*shutdown) (struct device *dev); int (*suspend) (struct device *dev, pm_message_t state); int (*resume) (struct device *dev); const struct attribute_group **groups; const struct attribute_group **dev_groups; const struct dev_pm_ops *pm; void (*coredump) (struct device *dev); struct driver_private *p; struct { void (*post_unbind_rust)(struct device *dev); } p_cb;};Members
nameName of the device driver.
busThe bus which the device of this driver belongs to.
ownerThe module owner.
mod_nameUsed for built-in modules.
suppress_bind_attrsDisables bind/unbind via sysfs.
probe_typeType of the probe (synchronous or asynchronous) to use.
of_match_tableThe open firmware table.
acpi_match_tableThe ACPI match table.
probeCalled to query the existence of a specific device,whether this driver can work with it, and bind the driverto a specific device.
sync_stateCalled to sync device state to software state after all thestate tracking consumers linked to this device (present atthe time of late_initcall) have successfully bound to adriver. If the device has no consumers, this function willbe called at late_initcall_sync level. If the device hasconsumers that are never bound to a driver, this functionwill never get called until they do.
removeCalled when the device is removed from the system tounbind a device from this driver.
shutdownCalled at shut-down time to quiesce the device.
suspendCalled to put the device to sleep mode. Usually to alow power state.
resumeCalled to bring a device from sleep mode.
groupsDefault attributes that get created by the driver coreautomatically.
dev_groupsAdditional attributes attached to device instance onceit is bound to the driver.
pmPower management operations of the device which matchedthis driver.
coredumpCalled when sysfs entry is written to. The device driveris expected to call the dev_coredump API resulting in auevent.
pDriver core’s private data, no one other than the drivercore can touch this.
p_cbCallbacks private to the driver core; no one other than thedriver core is allowed to touch this.
Description
The device driver-model tracks all of the drivers known to the system.The main reason for this tracking is to enable the driver core to matchup drivers with new devices. Once drivers are known objects within thesystem, however, a number of other things become possible. Device driverscan export information and configuration variables that are independentof any specific device.
Device Drivers Base¶
- voiddriver_init(void)¶
initialize driver model.
Parameters
voidno arguments
Description
Call the driver model init functions to initialize theirsubsystems. Called early from init/main.c.
- structdevice*driver_find_device_by_name(conststructdevice_driver*drv,constchar*name)¶
device iterator for locating a particular device of a specific name.
Parameters
conststructdevice_driver*drvthe driver we’re iterating
constchar*namename of the device to match
- structdevice*driver_find_device_by_of_node(conststructdevice_driver*drv,conststructdevice_node*np)¶
device iterator for locating a particular device by of_node pointer.
Parameters
conststructdevice_driver*drvthe driver we’re iterating
conststructdevice_node*npof_node pointer to match.
- structdevice*driver_find_device_by_fwnode(structdevice_driver*drv,conststructfwnode_handle*fwnode)¶
device iterator for locating a particular device by fwnode pointer.
Parameters
structdevice_driver*drvthe driver we’re iterating
conststructfwnode_handle*fwnodefwnode pointer to match.
- structdevice*driver_find_device_by_devt(conststructdevice_driver*drv,dev_tdevt)¶
device iterator for locating a particular device by devt.
Parameters
conststructdevice_driver*drvthe driver we’re iterating
dev_tdevtdevt pointer to match.
- structdevice*driver_find_device_by_acpi_dev(conststructdevice_driver*drv,conststructacpi_device*adev)¶
device iterator for locating a particular device matching the ACPI_COMPANION device.
Parameters
conststructdevice_driver*drvthe driver we’re iterating
conststructacpi_device*adevACPI_COMPANION device to match.
- module_driver¶
module_driver(__driver,__register,__unregister,...)
Helper macro for drivers that don’t do anything special in module init/exit. This eliminates a lot of boilerplate. Each module may only use this macro once, and calling it replaces
module_init()andmodule_exit().
Parameters
__driverdriver name
__registerregister function for this driver type
__unregisterunregister function for this driver type
...Additional arguments to be passed to __register and __unregister.
Description
Use this macro to construct bus specific macros for registeringdrivers, and do not use it on its own.
- builtin_driver¶
builtin_driver(__driver,__register,...)
Helper macro for drivers that don’t do anything special in init and have no exit. This eliminates some boilerplate. Each driver may only use this macro once, and calling it replaces device_initcall (or in some cases, the legacy __initcall). This is meant to be a direct parallel of
module_driver()above but without the __exit stuff that is not used for builtin cases.
Parameters
__driverdriver name
__registerregister function for this driver type
...Additional arguments to be passed to __register
Description
Use this macro to construct bus specific macros for registeringdrivers, and do not use it on its own.
- intdriver_set_override(structdevice*dev,constchar**override,constchar*s,size_tlen)¶
Helper to set or clear driver override.
Parameters
structdevice*devDevice to change
constchar**overrideAddress of string to change (e.g.
device->driver_override);The contents will be freed and hold newly allocated override.constchar*sNUL-terminated string, new driver name to force a match, pass emptystring to clear it (”” or “n”, where the latter is only for sysfsinterface).
size_tlenlength ofs
Description
Helper to set or clear driver override in a device, intended for the caseswhen the driver_override field is allocated by driver/bus code.
Return
0 on success or a negative error code on failure.
- intdriver_for_each_device(structdevice_driver*drv,structdevice*start,void*data,device_iter_tfn)¶
Iterator for devices bound to a driver.
Parameters
structdevice_driver*drvDriver we’re iterating.
structdevice*startDevice to begin with
void*dataData to pass to the callback.
device_iter_tfnFunction to call for each device.
Description
Iterate over thedrv’s list of devices callingfn for each one.
- structdevice*driver_find_device(conststructdevice_driver*drv,structdevice*start,constvoid*data,device_match_tmatch)¶
device iterator for locating a particular device.
Parameters
conststructdevice_driver*drvThe device’s driver
structdevice*startDevice to begin with
constvoid*dataData to pass to match function
device_match_tmatchCallback function to check device
Description
This is similar to thedriver_for_each_device() function above, butit returns a reference to a device that is ‘found’ for later use, asdetermined by thematch callback.
The callback should return 0 if the device doesn’t match and non-zeroif it does. If the callback returns non-zero, this function willreturn to the caller and not iterate over any more devices.
- intdriver_create_file(conststructdevice_driver*drv,conststructdriver_attribute*attr)¶
create sysfs file for driver.
Parameters
conststructdevice_driver*drvdriver.
conststructdriver_attribute*attrdriver attribute descriptor.
- voiddriver_remove_file(conststructdevice_driver*drv,conststructdriver_attribute*attr)¶
remove sysfs file for driver.
Parameters
conststructdevice_driver*drvdriver.
conststructdriver_attribute*attrdriver attribute descriptor.
- intdriver_register(structdevice_driver*drv)¶
register driver with bus
Parameters
structdevice_driver*drvdriver to register
Description
We pass off most of the work to thebus_add_driver() call,since most of the things we have to do deal with the busstructures.
- voiddriver_unregister(structdevice_driver*drv)¶
remove driver from system.
Parameters
structdevice_driver*drvdriver.
Description
Again, we pass off most of the work to the bus-level call.
- voiddevice_link_wait_removal(void)¶
Wait for ongoing devlink removal jobs to terminate
Parameters
voidno arguments
- structdevice_link*device_link_add(structdevice*consumer,structdevice*supplier,u32flags)¶
Create a link between two devices.
Parameters
structdevice*consumerConsumer end of the link.
structdevice*supplierSupplier end of the link.
u32flagsLink flags.
Return
On success, a device_linkstructwill be returned.On error or invalid flag settings, NULL will be returned.
Description
The caller is responsible for the proper synchronization of the link creationwith runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause theruntime PM framework to take the link into account. Second, if theDL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices willbe forced into the active meta state and reference-counted upon the creationof the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will beignored.
If DL_FLAG_STATELESS is set inflags, the caller of this function isexpected to release the link returned by it directly with the help of eitherdevice_link_del() ordevice_link_remove().
If that flag is not set, however, the caller of this function is handing themanagement of the link over to the driver core entirely and its return valuecan only be used to check whether or not the link is present. In that case,the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device linkflags can be used to indicate to the driver core when the link can be safelydeleted. Namely, setting one of them inflags indicates to the driver corethat the link is not going to be used (by the given caller of this function)after unbinding the consumer or supplier driver, respectively, from itsdevice, so the link can be deleted at that point. If none of them is set,the link will be maintained until one of the devices pointed to by it (eitherthe consumer or the supplier) is unregistered.
Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER andDL_FLAG_AUTOREMOVE_SUPPLIER are not set inflags (that is, a persistentmanaged device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag canbe used to request the driver core to automatically probe for a consumerdriver after successfully binding a driver to the supplier device.
The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set inflags atthe same time is invalid and will cause NULL to be returned upfront.However, if a device link between the givenconsumer andsupplier pairexists already when this function is called for them, the existing link willbe returned regardless of its current type and status (the link’s flags maybe modified then). The caller of this function is then expected to treatthe link as though it has just been created, so (in particular) ifDL_FLAG_STATELESS was passed inflags, the link needs to be releasedexplicitly when not needed any more (as stated above).
A side effect of the link creation is re-ordering of dpm_list and thedevices_kset list by moving the consumer device and all devices dependingon it to the ends of these lists (that does not happen to devices that havenot been registered when this function is called).
The supplier device is required to be registered when this function is calledand NULL will be returned if that is not the case. The consumer device neednot be registered, however.
- voiddevice_link_del(structdevice_link*link)¶
Delete a stateless link between two devices.
Parameters
structdevice_link*linkDevice link to delete.
Description
The caller must ensure proper synchronization of this function with runtimePM. If the link was added multiple times, it needs to be deleted as often.Care is required for hotplugged devices: Their links are purged on removaland callingdevice_link_del() is then no longer allowed.
- voiddevice_link_remove(void*consumer,structdevice*supplier)¶
Delete a stateless link between two devices.
Parameters
void*consumerConsumer end of the link.
structdevice*supplierSupplier end of the link.
Description
The caller must ensure proper synchronization of this function with runtimePM.
- constchar*dev_driver_string(conststructdevice*dev)¶
Return a device’s driver name, if at all possible
Parameters
conststructdevice*devstructdeviceto get the name of
Description
Will return the device’s driver’s name if it is bound to a device. Ifthe device is not bound to a driver, it will return the name of the busit is attached to. If it is not attached to a bus either, an emptystring will be returned.
- intdevm_device_add_group(structdevice*dev,conststructattribute_group*grp)¶
given a device, create a managed attribute group
Parameters
structdevice*devThe device to create the group for
conststructattribute_group*grpThe attribute group to create
Description
This function creates a group for the first time. It will explicitlywarn and error if any of the attribute files being created already exist.
Returns 0 on success or error code on failure.
- intdevice_create_file(structdevice*dev,conststructdevice_attribute*attr)¶
create sysfs attribute file for device.
Parameters
structdevice*devdevice.
conststructdevice_attribute*attrdevice attribute descriptor.
- voiddevice_remove_file(structdevice*dev,conststructdevice_attribute*attr)¶
remove sysfs attribute file.
Parameters
structdevice*devdevice.
conststructdevice_attribute*attrdevice attribute descriptor.
- booldevice_remove_file_self(structdevice*dev,conststructdevice_attribute*attr)¶
remove sysfs attribute file from its own method.
Parameters
structdevice*devdevice.
conststructdevice_attribute*attrdevice attribute descriptor.
Description
Seekernfs_remove_self() for details.
- intdevice_create_bin_file(structdevice*dev,conststructbin_attribute*attr)¶
create sysfs binary attribute file for device.
Parameters
structdevice*devdevice.
conststructbin_attribute*attrdevice binary attribute descriptor.
- voiddevice_remove_bin_file(structdevice*dev,conststructbin_attribute*attr)¶
remove sysfs binary attribute file
Parameters
structdevice*devdevice.
conststructbin_attribute*attrdevice binary attribute descriptor.
Parameters
structdevice*devdevice.
Description
This prepares the device for use by other layers by initializingits fields.It is the first half ofdevice_register(), if called bythat function, though it can also be called separately, so onemay usedev’s fields. In particular,get_device()/put_device()may be used for reference counting ofdev after calling thisfunction.
All fields indev must be initialized by the caller to 0, exceptfor those explicitly set to some other value. The simplestapproach is to usekzalloc() to allocate the structure containingdev.
NOTE
Useput_device() to give up your reference instead of freeingdev directly once you have called this function.
Parameters
structdevice*devdevice
constchar*fmtformat string for the device’s name
...variable arguments
Parameters
structdevice*devdevice.
Description
This is part 2 ofdevice_register(), though may be calledseparately _iff_device_initialize() has been called separately.
This addsdev to the kobject hierarchy viakobject_add(), adds itto the global and sibling lists for the device, thenadds it to the other relevant subsystems of the driver model.
Do not call this routine ordevice_register() more than once forany device structure. The driver model core is not designed to workwith devices that get unregistered and then spring back to life.(Among other things, it’s very hard to guarantee that all referencesto the previous incarnation ofdev have been dropped.) Allocateand register a fresh newstructdevice instead.
NOTE
_Never_ directly freedev after calling this function, evenif it returned an error! Always useput_device() to give up yourreference instead.
Rule of thumb is: ifdevice_add() succeeds, you should calldevice_del() when you want to get rid of it. Ifdevice_add() hasnot succeeded, useonlyput_device() to drop the referencecount.
Parameters
structdevice*devpointer to the device structure
Description
This happens in two clean steps - initialize the deviceand add it to the system. The two steps can be calledseparately, but this is the easiest and most common.I.e. you should only call the two helpers separately ifhave a clearly defined need to use and refcount the devicebefore it is added to the hierarchy.
For more information, see the kerneldoc fordevice_initialize()anddevice_add().
NOTE
_Never_ directly freedev after calling this function, evenif it returned an error! Always useput_device() to give up thereference initialized in this function instead.
Parameters
structdevice*devdevice.
Description
This simply forwards the call tokobject_get(), thoughwe do take care to provide for the case that we get a NULLpointer passed in.
Parameters
structdevice*devdevice in question.
Parameters
structdevice*devdevice.
Description
This is the first part of the device unregistrationsequence. This removes the device from the lists we controlfrom here, has it removed from the other driver modelsubsystems it was added to indevice_add(), and removes itfrom the kobject hierarchy.
NOTE
this should be called manually _iff_device_add() wasalso called manually.
Parameters
structdevice*devdevice going away.
Description
We do this in two parts, like we dodevice_register(). First,we remove it from all the subsystems withdevice_del(), thenwe decrement the reference count viaput_device(). If thatis the final reference count, the device will be cleaned upviadevice_release() above. Otherwise, the structure willstick around until the final reference to the device is dropped.
Parameters
structdevice*parentparent
structdevice.void*datadata for the callback.
device_iter_tfnfunction to be called for each device.
Description
Iterate overparent’s child devices, and callfn for each,passing itdata.
We check the return offn each time. If it returns anythingother than 0, we break out and return that value.
- intdevice_for_each_child_reverse(structdevice*parent,void*data,device_iter_tfn)¶
device child iterator in reversed order.
Parameters
structdevice*parentparent
structdevice.void*datadata for the callback.
device_iter_tfnfunction to be called for each device.
Description
Iterate overparent’s child devices, and callfn for each,passing itdata.
We check the return offn each time. If it returns anythingother than 0, we break out and return that value.
- intdevice_for_each_child_reverse_from(structdevice*parent,structdevice*from,void*data,device_iter_tfn)¶
device child iterator in reversed order.
Parameters
structdevice*parentparent
structdevice.structdevice*fromoptional starting point in child list
void*datadata for the callback.
device_iter_tfnfunction to be called for each device.
Description
Iterate overparent’s child devices, starting atfrom, and callfnfor each, passing itdata. This helper is identical todevice_for_each_child_reverse() whenfrom is NULL.
fn is checked each iteration. If it returns anything other than 0,iteration stop and that value is returned to the caller ofdevice_for_each_child_reverse_from();
- structdevice*device_find_child(structdevice*parent,constvoid*data,device_match_tmatch)¶
device iterator for locating a particular device.
Parameters
structdevice*parentparent
structdeviceconstvoid*dataData to pass to match function
device_match_tmatchCallback function to check device
Description
This is similar to thedevice_for_each_child() function above, but itreturns a reference to a device that is ‘found’ for later use, asdetermined by thematch callback.
The callback should return 0 if the device doesn’t match and non-zeroif it does. If the callback returns non-zero and a reference to thecurrent device can be obtained, this function will return to the callerand not iterate over any more devices.
NOTE
you will need to drop the reference withput_device() after use.
- structdevice*__root_device_register(constchar*name,structmodule*owner)¶
allocate and register a root device
Parameters
constchar*nameroot device name
structmodule*ownerowner module of the root device, usually THIS_MODULE
Description
This function allocates a root device and registers itusingdevice_register(). In order to free the returneddevice, useroot_device_unregister().
Root devices are dummy devices which allow other devicesto be grouped under /sys/devices. Use this function toallocate a root device and then use it as the parent ofany device which should appear under /sys/devices/{name}
The /sys/devices/{name} directory will also contain a‘module’ symlink which points to theowner directoryin sysfs.
Returnsstructdevice pointer on success, orERR_PTR() on error.
Note
You probably want to useroot_device_register().
Parameters
structdevice*devdevice going away
Description
This function unregisters and cleans up a device that was created byroot_device_register().
- structdevice*device_create(conststructclass*class,structdevice*parent,dev_tdevt,void*drvdata,constchar*fmt,...)¶
creates a device and registers it with sysfs
Parameters
conststructclass*classpointer to the
structclassthat this device should be registered tostructdevice*parentpointer to the parent
structdeviceof this new device, if anydev_tdevtthe dev_t for the char device to be added
void*drvdatathe data to be added to the device for callbacks
constchar*fmtstring for the device’s name
...variable arguments
Description
This function can be used by char device classes. Astructdevicewill be created in sysfs, registered to the specified class.
A “dev” file will be created, showing the dev_t for the device, ifthe dev_t is not 0,0.If a pointer to a parentstructdevice is passed in, the newly createdstructdevice will be a child of that device in sysfs.The pointer to thestructdevice will be returned from the call.Any further sysfs files that might be required can be created using thispointer.
Returnsstructdevice pointer on success, orERR_PTR() on error.
- structdevice*device_create_with_groups(conststructclass*class,structdevice*parent,dev_tdevt,void*drvdata,conststructattribute_group**groups,constchar*fmt,...)¶
creates a device and registers it with sysfs
Parameters
conststructclass*classpointer to the
structclassthat this device should be registered tostructdevice*parentpointer to the parent
structdeviceof this new device, if anydev_tdevtthe dev_t for the char device to be added
void*drvdatathe data to be added to the device for callbacks
conststructattribute_group**groupsNULL-terminated list of attribute groups to be created
constchar*fmtstring for the device’s name
...variable arguments
Description
This function can be used by char device classes. Astructdevicewill be created in sysfs, registered to the specified class.Additional attributes specified in the groups parameter will alsobe created automatically.
A “dev” file will be created, showing the dev_t for the device, ifthe dev_t is not 0,0.If a pointer to a parentstructdevice is passed in, the newly createdstructdevice will be a child of that device in sysfs.The pointer to thestructdevice will be returned from the call.Any further sysfs files that might be required can be created using thispointer.
Returnsstructdevice pointer on success, orERR_PTR() on error.
- voiddevice_destroy(conststructclass*class,dev_tdevt)¶
removes a device that was created with
device_create()
Parameters
conststructclass*classpointer to the
structclassthat this device was registered withdev_tdevtthe dev_t of the device that was previously registered
Description
This call unregisters and cleans up a device that was created with acall todevice_create().
Parameters
structdevice*devthe pointer to the
structdeviceto be renamedconstchar*new_namethe new name of the device
Description
It is the responsibility of the caller to provide mutualexclusion between two different calls of device_renameon the same device to ensure that new_name is valid andwon’t conflict with other devices.
Note
given that some subsystems (networking and infiniband) use thisfunction, with no immediate plans for this to change, we cannot assume orrequire that this function not be called at all.
However, if you’re writing new code, do not call this function. The followingtext from Kay Sievers offers some insight:
Renaming devices is racy at many levels, symlinks and other stuff are notreplaced atomically, and you get a “move” uevent, but it’s not easy toconnect the event to the old and new device. Device nodes are not renamed atall, there isn’t even support for that in the kernel now.
In the meantime, during renaming, your target name might be taken by anotherdriver, creating conflicts. Or the old name is taken directly after yourenamed it -- then you get events for the same DEVPATH, before you even seethe “move” event. It’s just a mess, and nothing new should ever rely onkernel device renaming. Besides that, it’s not even implemented now forother things than (driver-core wise very simple) network devices.
Make up a “real” name in the driver before you register anything, or addsome other attributes for userspace to find the device, or use udev to addsymlinks -- but never rename kernel devices later, it’s a complete mess. Wedon’t even want to get into that and try to implement the missing pieces inthe core. We really have other pieces to fix in the driver core mess. :)
- intdevice_move(structdevice*dev,structdevice*new_parent,enumdpm_orderdpm_order)¶
moves a device to a new parent
Parameters
structdevice*devthe pointer to the
structdeviceto be movedstructdevice*new_parentthe new parent of the device (can be NULL)
enumdpm_orderdpm_orderhow to reorder the dpm_list
- intdevice_change_owner(structdevice*dev,kuid_tkuid,kgid_tkgid)¶
change the owner of an existing device.
Parameters
structdevice*devdevice.
kuid_tkuidnew owner’s kuid
kgid_tkgidnew owner’s kgid
Description
This changes the owner ofdev and its corresponding sysfs entries tokuid/kgid. This function closely mirrors howdev was added via drivercore.
Returns 0 on success or error code on failure.
Parameters
conststructdevice*devthe pointer to the
structdeviceinterrerror value to test
constchar*fmtprintf-style format string
...arguments as specified in the format string
Description
This helper implements common pattern present in probe functions for errorchecking: print debug or error message depending if the error value is-EPROBE_DEFER and propagate error upwards.In case of -EPROBE_DEFER it sets also defer probe reason, which can bechecked later by reading devices_deferred debugfs attribute.It replaces the following code sequence:
if (err != -EPROBE_DEFER) dev_err(dev, ...);else dev_dbg(dev, ...);return err;
with:
return dev_err_probe(dev, err, ...);
Using this helper in your probe function is totally fine even iferris known to never be -EPROBE_DEFER.The benefit compared to a normaldev_err() is the standardized formatof the error code, which is emitted symbolically (i.e. you get “EAGAIN”instead of “-35”), and having the error code returned allows morecompact error paths.
Returnserr.
Parameters
conststructdevice*devthe pointer to the
structdeviceinterrerror value to test
constchar*fmtprintf-style format string
...arguments as specified in the format string
Description
This helper implements common pattern present in probe functions for errorchecking: print debug or warning message depending if the error value is-EPROBE_DEFER and propagate error upwards.In case of -EPROBE_DEFER it sets also defer probe reason, which can bechecked later by reading devices_deferred debugfs attribute.It replaces the following code sequence:
if (err != -EPROBE_DEFER) dev_warn(dev, ...);else dev_dbg(dev, ...);return err;
with:
return dev_warn_probe(dev, err, ...);
Using this helper in your probe function is totally fine even iferris known to never be -EPROBE_DEFER.The benefit compared to a normaldev_warn() is the standardized formatof the error code, which is emitted symbolically (i.e. you get “EAGAIN”instead of “-35”), and having the error code returned allows morecompact error paths.
Returnserr.
- voidset_primary_fwnode(structdevice*dev,structfwnode_handle*fwnode)¶
Change the primary firmware node of a given device.
Parameters
structdevice*devDevice to handle.
structfwnode_handle*fwnodeNew primary firmware node of the device.
Description
Set the device’s firmware node pointer tofwnode, but if a secondaryfirmware node of the device is present, preserve it.
- Valid fwnode cases are:
primary --> secondary --> -ENODEV
primary --> NULL
secondary --> -ENODEV
NULL
- voidset_secondary_fwnode(structdevice*dev,structfwnode_handle*fwnode)¶
Change the secondary firmware node of a given device.
Parameters
structdevice*devDevice to handle.
structfwnode_handle*fwnodeNew secondary firmware node of the device.
Description
If a primary firmware node of the device is present, set its secondarypointer tofwnode. Otherwise, set the device’s firmware node pointer tofwnode.
Parameters
structdevice*devdevice whose device tree node is being removed
- intdevice_add_of_node(structdevice*dev,structdevice_node*of_node)¶
Add an of_node to an existing device
Parameters
structdevice*devdevice whose device tree node is being added
structdevice_node*of_nodeof_node to add
Return
0 on success or error code on failure.
- voiddevice_set_of_node_from_dev(structdevice*dev,conststructdevice*dev2)¶
reuse device-tree node of another device
Parameters
structdevice*devdevice whose device-tree node is being set
conststructdevice*dev2device whose device-tree node is being reused
Description
Takes another reference to the new device-tree node after first droppingany reference held to the old node.
- structdevice*get_dev_from_fwnode(structfwnode_handle*fwnode)¶
Obtain a reference count of the
structdevicethestructfwnode_handleis associated with.
Parameters
structfwnode_handle*fwnodeThe pointer to the
structfwnode_handleto obtain thestructdevicereference count of.
Description
This function obtains a reference count of the device the device pointerembedded in thestructfwnode_handle points to.
Note that thestructdevice pointer embedded instructfwnode_handle doesnot have a reference count of thestructdevice itself.
Hence, it is a UAF (and thus a bug) to call this function if the caller can’tguarantee that the last reference count of the correspondingstructdevice isnot dropped concurrently.
This is possible sincestructfwnode_handle has its own reference count andhence can out-live thestructdevice it is associated with.
Parameters
structsyscore*syscoreSystem core operations to register.
Parameters
structsyscore*syscoreSystem core operations to unregister.
- intsyscore_suspend(void)¶
Execute all the registered system core suspend callbacks.
Parameters
voidno arguments
Description
This function is executed with one CPU on-line and disabled interrupts.
- voidsyscore_resume(void)¶
Execute all the registered system core resume callbacks.
Parameters
voidno arguments
Description
This function is executed with one CPU on-line and disabled interrupts.
- structdevice*class_find_device_by_name(conststructclass*class,constchar*name)¶
device iterator for locating a particular device of a specific name.
Parameters
conststructclass*classclass type
constchar*namename of the device to match
- structdevice*class_find_device_by_of_node(conststructclass*class,conststructdevice_node*np)¶
device iterator for locating a particular device matching the of_node.
Parameters
conststructclass*classclass type
conststructdevice_node*npof_node of the device to match.
- structdevice*class_find_device_by_fwnode(conststructclass*class,conststructfwnode_handle*fwnode)¶
device iterator for locating a particular device matching the fwnode.
Parameters
conststructclass*classclass type
conststructfwnode_handle*fwnodefwnode of the device to match.
- structdevice*class_find_device_by_devt(conststructclass*class,dev_tdevt)¶
device iterator for locating a particular device matching the device type.
Parameters
conststructclass*classclass type
dev_tdevtdevice type of the device to match.
- structdevice*class_find_device_by_acpi_dev(conststructclass*class,conststructacpi_device*adev)¶
device iterator for locating a particular device matching the ACPI_COMPANION device.
Parameters
conststructclass*classclass type
conststructacpi_device*adevACPI_COMPANION device to match.
- structclass*class_create(constchar*name)¶
create a
structclassstructure
Parameters
constchar*namepointer to a string for the name of this class.
Description
This is used to create astructclass pointer that can then be usedin calls todevice_create().
Returnsstructclass pointer on success, orERR_PTR() on error.
Note, the pointer created here is to be destroyed when finished bymaking a call toclass_destroy().
- voidclass_destroy(conststructclass*cls)¶
destroys a
structclassstructure
Parameters
conststructclass*clspointer to the
structclassthat is to be destroyed
Description
Note, the pointer to be destroyed must have been created with a calltoclass_create().
- voidclass_dev_iter_init(structclass_dev_iter*iter,conststructclass*class,conststructdevice*start,conststructdevice_type*type)¶
initialize class device iterator
Parameters
structclass_dev_iter*iterclass iterator to initialize
conststructclass*classthe class we wanna iterate over
conststructdevice*startthe device to start iterating from, if any
conststructdevice_type*typedevice_type of the devices to iterate over, NULL for all
Description
Initialize class iteratoriter such that it iterates over devicesofclass. Ifstart is set, the list iteration will start there,otherwise if it is NULL, the iteration starts at the beginning ofthe list.
Parameters
structclass_dev_iter*iterclass iterator to proceed
Description
Proceediter to the next device and return it. Returns NULL ifiteration is complete.
The returned device is referenced and won’t be released tilliterator is proceed to the next device or exited. The caller isfree to do whatever it wants to do with the device includingcalling back into class code.
- voidclass_dev_iter_exit(structclass_dev_iter*iter)¶
finish iteration
Parameters
structclass_dev_iter*iterclass iterator to finish
Description
Finish an iteration. Always call this function after iteration iscomplete whether the iteration ran till the end or not.
- intclass_for_each_device(conststructclass*class,conststructdevice*start,void*data,device_iter_tfn)¶
device iterator
Parameters
conststructclass*classthe class we’re iterating
conststructdevice*startthe device to start with in the list, if any.
void*datadata for the callback
device_iter_tfnfunction to be called for each device
Description
Iterate overclass’s list of devices, and callfn for each,passing itdata. Ifstart is set, the list iteration will startthere, otherwise if it is NULL, the iteration starts at thebeginning of the list.
We check the return offn each time. If it returns anythingother than 0, we break out and return that value.
fn is allowed to do anything including calling back into classcode. There’s no locking restriction.
- structdevice*class_find_device(conststructclass*class,conststructdevice*start,constvoid*data,device_match_tmatch)¶
device iterator for locating a particular device
Parameters
conststructclass*classthe class we’re iterating
conststructdevice*startDevice to begin with
constvoid*datadata for the match function
device_match_tmatchfunction to check device
Description
This is similar to theclass_for_each_dev() function above, but itreturns a reference to a device that is ‘found’ for later use, asdetermined by thematch callback.
The callback should return 0 if the device doesn’t match and non-zeroif it does. If the callback returns non-zero, this function willreturn to the caller and not iterate over any more devices.
Note, you will need to drop the reference withput_device() after use.
match is allowed to do anything including calling back into classcode. There’s no locking restriction.
- structclass_compat*class_compat_register(constchar*name)¶
register a compatibility class
Parameters
constchar*namethe name of the class
Description
Compatibility class are meant as a temporary user-space compatibilityworkaround when converting a family of class devices to a bus devices.
- voidclass_compat_unregister(structclass_compat*cls)¶
unregister a compatibility class
Parameters
structclass_compat*clsthe class to unregister
- intclass_compat_create_link(structclass_compat*cls,structdevice*dev)¶
create a compatibility class device link to a bus device
Parameters
structclass_compat*clsthe compatibility class
structdevice*devthe target bus device
- voidclass_compat_remove_link(structclass_compat*cls,structdevice*dev)¶
remove a compatibility class device link to a bus device
Parameters
structclass_compat*clsthe compatibility class
structdevice*devthe target bus device
- boolclass_is_registered(conststructclass*class)¶
determine if at this moment in time, a class is registered in the driver core or not.
Parameters
conststructclass*classthe class to check
Description
Returns a boolean to state if the class is registered in the driver coreor not. Note that the value could switch right after this call is made,so only use this in places where you “know” it is safe to do so (usuallyto determine if the specific class has been registered yet or not).
Be careful in using this.
- structfaux_device¶
a “faux” device
Description
A simple faux device that can be created/destroyed. To be used when adriver only needs to have a device to “hang” something off. This can beused for downloading firmware or other basic tasks. Use this instead ofastructplatform_device if the device has no resources assigned toit at all.
- structfaux_device_ops¶
a set of callbacks for a
structfaux_device
Definition:
struct faux_device_ops { int (*probe)(struct faux_device *faux_dev); void (*remove)(struct faux_device *faux_dev);};Members
probecalled when a faux device is probed by the driver corebefore the device is fully bound to the internal faux buscode. If probe succeeds, return 0, otherwise return anegative error number to stop the probe sequence fromsucceeding.
removecalled when a faux device is removed from the system
Description
Bothprobe andremove are optional, if not needed, set to NULL.
- structfaux_device*faux_device_create_with_groups(constchar*name,structdevice*parent,conststructfaux_device_ops*faux_ops,conststructattribute_group**groups)¶
Create and register with the driver core a faux device and populate the device with an initial set of sysfs attributes.
Parameters
constchar*nameThe name of the device we are adding, must be unique forall faux devices.
structdevice*parentPointer to a potential parent
structdevice. If set toNULL, the device will be created in the “root” of the fauxdevice tree in sysfs.conststructfaux_device_ops*faux_opsstructfaux_device_opsthat the new device will call backinto, can be NULL.conststructattribute_group**groupsThe set of sysfs attributes that will be created for thisdevice when it is registered with the driver core.
Description
Create a new faux device and register it in the driver core properly.If present, callbacks infaux_ops will be called with the device thatfor the caller to do something with at the proper time given thedevice’s lifecycle.
Note, when this function is called, the functions specified instructfaux_ops can be called before the function returns, so be prepared foreverything to be properly initialized before that point in time. If theprobe callback (if one is present) does NOT succeed, the creation of thedevice will fail and NULL will be returned.
Return
NULL if an error happened with creating the device
pointer to a valid
structfaux_devicethat is registered with sysfs
- structfaux_device*faux_device_create(constchar*name,structdevice*parent,conststructfaux_device_ops*faux_ops)¶
create and register with the driver core a faux device
Parameters
constchar*nameThe name of the device we are adding, must be unique for allfaux devices.
structdevice*parentPointer to a potential parent
structdevice. If set toNULL, the device will be created in the “root” of the fauxdevice tree in sysfs.conststructfaux_device_ops*faux_opsstructfaux_device_opsthat the new device will call backinto, can be NULL.
Description
Create a new faux device and register it in the driver core properly.If present, callbacks infaux_ops will be called with the device thatfor the caller to do something with at the proper time given thedevice’s lifecycle.
Note, when this function is called, the functions specified instructfaux_ops can be called before the function returns, so be prepared foreverything to be properly initialized before that point in time.
Return
NULL if an error happened with creating the device
pointer to a valid
structfaux_devicethat is registered with sysfs
- voidfaux_device_destroy(structfaux_device*faux_dev)¶
destroy a faux device
Parameters
structfaux_device*faux_devfaux device to destroy
Description
Unregisters and cleans up a device that was created with a call tofaux_device_create()
- structnode_access_nodes¶
Access class device to hold user visible relationships to other nodes.
Definition:
struct node_access_nodes { struct device dev; struct list_head list_node; unsigned int access;#ifdef CONFIG_HMEM_REPORTING; struct access_coordinate coord;#endif;};Members
devDevice for this memory access class
list_nodeList element in the node’s access list
accessThe access class rank
coordHeterogeneous memory performance coordinates
- structnode_cache_info¶
Internal tracking for memory node caches
Definition:
struct node_cache_info { struct device dev; struct list_head node; struct node_cache_attrs cache_attrs;};Members
devDevice represeting the cache level
nodeList element for tracking in the node
cache_attrsAttributes for this cache level
- voidnode_add_cache(unsignedintnid,structnode_cache_attrs*cache_attrs)¶
add cache attribute to a memory node
Parameters
unsignedintnidNode identifier that has new cache attributes
structnode_cache_attrs*cache_attrsAttributes for the cache being added
- intregister_memory_node_under_compute_node(unsignedintmem_nid,unsignedintcpu_nid,enumaccess_coordinate_classaccess)¶
link memory node to its compute node for a given access class.
Parameters
unsignedintmem_nidMemory node number
unsignedintcpu_nidCpu node number
enumaccess_coordinate_classaccessAccess class to register
Description
For use with platforms that may have separate memory and compute nodes.This function will export node relationships linking which memoryinitiator nodes can access memory targets at a given ranked accessclass.
- intregister_node(intnid)¶
Initialize and register the node device.
Parameters
intnidNode number to use when creating the device.
Return
0 on success, -errno otherwise
- voidunregister_node(intnid)¶
unregister a node device
Parameters
intnidnid of the node going away
Description
Unregisters the node device at node idnid. All the devices on thenode must be unregistered before calling this function.
- inttransport_class_register(structtransport_class*tclass)¶
register an initial transport class
Parameters
structtransport_class*tclassa pointer to the transport class structure to be initialised
Description
The transport class contains an embedded class which is used toidentify it. The caller should initialise this structure withzeros and then generic class must have been initialised with theactual transport class unique name. There’s a macroDECLARE_TRANSPORT_CLASS() to do this (declared classes still mustbe registered).
Returns 0 on success or error on failure.
- voidtransport_class_unregister(structtransport_class*tclass)¶
unregister a previously registered class
Parameters
structtransport_class*tclassThe transport class to unregister
Description
Must be called prior to deallocating the memory for the transportclass.
- intanon_transport_class_register(structanon_transport_class*atc)¶
register an anonymous class
Parameters
structanon_transport_class*atcThe anon transport class to register
Description
The anonymous transport class contains both a transport class and acontainer. The idea of an anonymous class is that it neveractually has any device attributes associated with it (and thussaves on container storage). So it can only be used for triggeringevents. Use prezero and then useDECLARE_ANON_TRANSPORT_CLASS() toinitialise the anon transport class storage.
- voidanon_transport_class_unregister(structanon_transport_class*atc)¶
unregister an anon class
Parameters
structanon_transport_class*atcPointer to the anon transport class to unregister
Description
Must be called prior to deallocating the memory for the anontransport class.
- voidtransport_setup_device(structdevice*dev)¶
declare a new dev for transport class association but don’t make it visible yet.
Parameters
structdevice*devthe generic device representing the entity being added
Description
Usually, dev represents some component in the HBA system (eitherthe HBA itself or a device remote across the HBA bus). Thisroutine is simply a trigger point to see if any set of transportclasses wishes to associate with the added device. This allocatesstorage for the class device and initialises it, but does not yetadd it to the system or add attributes to it (you do this withtransport_add_device). If you have no need for a separate setupand add operations, use transport_register_device (seetransport_class.h).
Parameters
structdevice*devthe generic device representing the entity being added
Description
Usually, dev represents some component in the HBA system (eitherthe HBA itself or a device remote across the HBA bus). Thisroutine is simply a trigger point used to add the device to thesystem and register attributes for it.
Parameters
structdevice*devgeneric device representing device to be configured
Description
The idea of configure is simply to provide a point within the setupprocess to allow the transport class to extract information from adevice after it has been setup. This is used in SCSI because wehave to have a setup device to begin using the HBA, but after wesend the initial inquiry, we use configure to extract the deviceparameters. The device need not have been added to be configured.
Parameters
structdevice*devgeneric device to remove
Description
This call removes the visibility of the device (to the user fromsysfs), but does not destroy it. To eliminate a device entirelyyou must also call transport_destroy_device. If you don’t need todo remove and destroy as separate operations, usetransport_unregister_device() (see transport_class.h) which willperform both calls for you.
Parameters
structdevice*devdevice to eliminate from the transport class.
Description
This call triggers the elimination of storage associated with thetransport classdev. Note: all it really does is relinquish areference to the classdev. The memory will not be freed until thelast reference goes to zero. Note also that the classdev retains areference count on dev, so dev too will remain for as long as thetransport class device remains around.
Parameters
structdevice*devdevice to check
Return
-ENODEV if initcalls have completed and modules are disabled.
-ETIMEDOUT if the deferred probe timeout was set and has expiredand modules are enabled.
-EPROBE_DEFER in other cases.
Description
Drivers or subsystems can opt-in to calling this function instead of directlyreturning -EPROBE_DEFER.
Parameters
structdevice*devdevice to check
Description
Returns true if passed device has already finished probing successfullyagainst a driver.
This function must be called with the device lock held.
Parameters
structdevice*devdevice.
Description
Allow manual attachment of a driver to a device.Caller must have already setdev->driver.
Note that this does not modify the bus reference count.Please verify that is accounted for before calling this.(It is ok to call with no other effort from a driver’sprobe() method.)
This function must be called with the device lock held.
Callers should prefer to usedevice_driver_attach() instead.
- voidwait_for_device_probe(void)¶
Parameters
voidno arguments
Description
Wait for device probing to be completed.
Parameters
structdevice*devdevice.
Description
Walk the list of drivers that the bus has and calldriver_probe_device() for each pair. If a compatiblepair is found, break out and return.
Returns 1 if the device was bound to a driver;0 if no matching driver was found;-ENODEV if the device is not registered.
When called for a USB interface,dev->parent lock must be held.
- intdevice_driver_attach(conststructdevice_driver*drv,structdevice*dev)¶
attach a specific driver to a specific device
Parameters
conststructdevice_driver*drvDriver to attach
structdevice*devDevice to attach it to
Description
Manually attach driver to a device. Will acquire bothdev lock anddev->parent lock if needed. Returns 0 on success, -ERR on failure.
- intdriver_attach(conststructdevice_driver*drv)¶
try to bind driver to devices.
Parameters
conststructdevice_driver*drvdriver.
Description
Walk the list of devices that the bus has on it and try tomatch the driver with each one. Ifdriver_probe_device()returns 0 and thedev->driver is set, we’ve found acompatible pair.
Parameters
structdevice*devdevice.
Description
Manually detach device from driver.When called for a USB interface,dev->parent lock must be held.
If this function is to be called withdev->parent lock held, ensure thatthe device’s consumers are unbound in advance or that their locks can beacquired under thedev->parent lock.
- structplatform_device*platform_device_register_resndata(structdevice*parent,constchar*name,intid,conststructresource*res,unsignedintnum,constvoid*data,size_tsize)¶
add a platform-level device with resources and platform-specific data
Parameters
structdevice*parentparent device for the device we’re adding
constchar*namebase name of the device we’re adding
intidinstance id
conststructresource*resset of resources that needs to be allocated for the device
unsignedintnumnumber of resources
constvoid*dataplatform specific data for this platform device
size_tsizesize of platform specific data
Description
Returnsstructplatform_device pointer on success, orERR_PTR() on error.
- structplatform_device*platform_device_register_simple(constchar*name,intid,conststructresource*res,unsignedintnum)¶
add a platform-level device and its resources
Parameters
constchar*namebase name of the device we’re adding
intidinstance id
conststructresource*resset of resources that needs to be allocated for the device
unsignedintnumnumber of resources
Description
This function creates a simple platform device that requires minimalresource and memory management. Canned release function freeing memoryallocated for the device allows drivers using such devices to beunloaded without waiting for the last reference to the device to bedropped.
This interface is primarily intended for use with legacy drivers whichprobe hardware directly. Because such drivers create sysfs device nodesthemselves, rather than letting system infrastructure handle such deviceenumeration tasks, they don’t fully conform to the Linux driver model.In particular, when such drivers are built as modules, they can’t be“hotplugged”.
Returnsstructplatform_device pointer on success, orERR_PTR() on error.
- structplatform_device*platform_device_register_data(structdevice*parent,constchar*name,intid,constvoid*data,size_tsize)¶
add a platform-level device with platform-specific data
Parameters
structdevice*parentparent device for the device we’re adding
constchar*namebase name of the device we’re adding
intidinstance id
constvoid*dataplatform specific data for this platform device
size_tsizesize of platform specific data
Description
This function creates a simple platform device that requires minimalresource and memory management. Canned release function freeing memoryallocated for the device allows drivers using such devices to beunloaded without waiting for the last reference to the device to bedropped.
Returnsstructplatform_device pointer on success, orERR_PTR() on error.
- structresource*platform_get_resource(structplatform_device*dev,unsignedinttype,unsignedintnum)¶
get a resource for a device
Parameters
structplatform_device*devplatform device
unsignedinttyperesource type
unsignedintnumresource index
Return
a pointer to the resource or NULL on failure.
- void__iomem*devm_platform_get_and_ioremap_resource(structplatform_device*pdev,unsignedintindex,structresource**res)¶
call
devm_ioremap_resource()for a platform device and get resource
Parameters
structplatform_device*pdevplatform device to use both for memory resource lookup as well asresource management
unsignedintindexresource index
structresource**resoptional output parameter to store a pointer to the obtained resource.
Return
a pointer to the remapped memory or anERR_PTR() encoded error codeon failure.
- void__iomem*devm_platform_ioremap_resource(structplatform_device*pdev,unsignedintindex)¶
call
devm_ioremap_resource()for a platform device
Parameters
structplatform_device*pdevplatform device to use both for memory resource lookup as well asresource management
unsignedintindexresource index
Return
a pointer to the remapped memory or anERR_PTR() encoded error codeon failure.
- void__iomem*devm_platform_ioremap_resource_byname(structplatform_device*pdev,constchar*name)¶
call devm_ioremap_resource for a platform device, retrieve the resource by name
Parameters
structplatform_device*pdevplatform device to use both for memory resource lookup as well asresource management
constchar*namename of the resource
Return
a pointer to the remapped memory or anERR_PTR() encoded error codeon failure.
- intplatform_get_irq_affinity(structplatform_device*dev,unsignedintnum,conststructcpumask**affinity)¶
get an optional IRQ and its affinity for a device
Parameters
structplatform_device*devplatform device
unsignedintnuminterrupt number index
conststructcpumask**affinityoptional cpumask pointer to get the affinity of a per-cpu interrupt
Description
Gets an interupt for a platform device. Device drivers should check thereturn value for errors so as to not pass a negative integer value totherequest_irq() APIs. Optional affinity information is provided in theaffinity pointer if available, and NULL otherwise.
Return
non-zero interrupt number on success, negative error number on failure.
- intplatform_get_irq_optional(structplatform_device*dev,unsignedintnum)¶
get an optional interrupt for a device
Parameters
structplatform_device*devplatform device
unsignedintnuminterrupt number index
Description
Gets an interrupt for a platform device. Device drivers should check thereturn value for errors so as to not pass a negative integer value totherequest_irq() APIs. This is the same asplatform_get_irq(), exceptthat it does not print an error message if an interrupt can not beobtained.
For example:
int irq = platform_get_irq_optional(pdev, 0);if (irq < 0) return irq;
Return
non-zero interrupt number on success, negative error number on failure.
- intplatform_get_irq(structplatform_device*dev,unsignedintnum)¶
get an IRQ for a device
Parameters
structplatform_device*devplatform device
unsignedintnumIRQ number index
Description
Gets an IRQ for a platform device and prints an error message if finding theIRQ fails. Device drivers should check the return value for errors so as tonot pass a negative integer value to therequest_irq() APIs.
For example:
int irq = platform_get_irq(pdev, 0);if (irq < 0) return irq;
Return
non-zero IRQ number on success, negative error number on failure.
- intplatform_irq_count(structplatform_device*dev)¶
Count the number of IRQs a platform device uses
Parameters
structplatform_device*devplatform device
Return
Number of IRQs a platform device uses or EPROBE_DEFER
- intdevm_platform_get_irqs_affinity(structplatform_device*dev,structirq_affinity*affd,unsignedintminvec,unsignedintmaxvec,int**irqs)¶
devm method to get a set of IRQs for a device using an interrupt affinity descriptor
Parameters
structplatform_device*devplatform device pointer
structirq_affinity*affdaffinity descriptor
unsignedintminvecminimum count of interrupt vectors
unsignedintmaxvecmaximum count of interrupt vectors
int**irqspointer holder for IRQ numbers
Description
Gets a set of IRQs for a platform device, and updates IRQ afffinty accordingto the passed affinity descriptor
Return
Number of vectors on success, negative error number on failure.
- structresource*platform_get_resource_byname(structplatform_device*dev,unsignedinttype,constchar*name)¶
get a resource for a device by name
Parameters
structplatform_device*devplatform device
unsignedinttyperesource type
constchar*nameresource name
- intplatform_get_irq_byname(structplatform_device*dev,constchar*name)¶
get an IRQ for a device by name
Parameters
structplatform_device*devplatform device
constchar*nameIRQ name
Description
Get an IRQ likeplatform_get_irq(), but then by name rather then by index.
Return
non-zero IRQ number on success, negative error number on failure.
- intplatform_get_irq_byname_optional(structplatform_device*dev,constchar*name)¶
get an optional IRQ for a device by name
Parameters
structplatform_device*devplatform device
constchar*nameIRQ name
Description
Get an optional IRQ by name likeplatform_get_irq_byname(). Except that itdoes not print an error message if an IRQ can not be obtained.
Return
non-zero IRQ number on success, negative error number on failure.
- intplatform_add_devices(structplatform_device**devs,intnum)¶
add a numbers of platform devices
Parameters
structplatform_device**devsarray of platform devices to add
intnumnumber of platform devices in array
Return
0 on success, negative error number on failure.
- voidplatform_device_put(structplatform_device*pdev)¶
destroy a platform device
Parameters
structplatform_device*pdevplatform device to free
Description
Free all memory associated with a platform device. This function must_only_ be externally called in error cases. All other usage is a bug.
- structplatform_device*platform_device_alloc(constchar*name,intid)¶
create a platform device
Parameters
constchar*namebase name of the device we’re adding
intidinstance id
Description
Create a platform device object which can have other objects attachedto it, and which will have attached objects freed when it is released.
- intplatform_device_add_resources(structplatform_device*pdev,conststructresource*res,unsignedintnum)¶
add resources to a platform device
Parameters
structplatform_device*pdevplatform device allocated by platform_device_alloc to add resources to
conststructresource*resset of resources that needs to be allocated for the device
unsignedintnumnumber of resources
Description
Add a copy of the resources to the platform device. The memoryassociated with the resources will be freed when the platform device isreleased.
- intplatform_device_add_data(structplatform_device*pdev,constvoid*data,size_tsize)¶
add platform-specific data to a platform device
Parameters
structplatform_device*pdevplatform device allocated by platform_device_alloc to add resources to
constvoid*dataplatform specific data for this platform device
size_tsizesize of platform specific data
Description
Add a copy of platform specific data to the platform device’splatform_data pointer. The memory associated with the platform datawill be freed when the platform device is released.
- intplatform_device_add(structplatform_device*pdev)¶
add a platform device to device hierarchy
Parameters
structplatform_device*pdevplatform device we’re adding
Description
This is part 2 ofplatform_device_register(), though may be calledseparately _iff_ pdev was allocated byplatform_device_alloc().
- voidplatform_device_del(structplatform_device*pdev)¶
remove a platform-level device
Parameters
structplatform_device*pdevplatform device we’re removing
Description
Note that this function will also release all memory- and port-basedresources owned by the device (dev->resource). This function must_only_ be externally called in error cases. All other usage is a bug.
- intplatform_device_register(structplatform_device*pdev)¶
add a platform-level device
Parameters
structplatform_device*pdevplatform device we’re adding
NOTE
_Never_ directly freepdev after calling this function, even if itreturned an error! Always useplatform_device_put() to give up thereference initialised in this function instead.
- voidplatform_device_unregister(structplatform_device*pdev)¶
unregister a platform-level device
Parameters
structplatform_device*pdevplatform device we’re unregistering
Description
Unregistration is done in 2 steps. First we release all resourcesand remove it from the subsystem, then we drop reference count bycallingplatform_device_put().
- structplatform_device*platform_device_register_full(conststructplatform_device_info*pdevinfo)¶
add a platform-level device with resources and platform-specific data
Parameters
conststructplatform_device_info*pdevinfodata used to create device
Description
Returnsstructplatform_device pointer on success, orERR_PTR() on error.
- int__platform_driver_register(structplatform_driver*drv,structmodule*owner)¶
register a driver for platform-level devices
Parameters
structplatform_driver*drvplatform driver structure
structmodule*ownerowning module/driver
- voidplatform_driver_unregister(structplatform_driver*drv)¶
unregister a driver for platform-level devices
Parameters
structplatform_driver*drvplatform driver structure
- int__platform_driver_probe(structplatform_driver*drv,int(*probe)(structplatform_device*),structmodule*module)¶
register driver for non-hotpluggable device
Parameters
structplatform_driver*drvplatform driver structure
int(*probe)(structplatform_device*)the driver probe routine, probably from an __init section
structmodule*modulemodule which will be the owner of the driver
Description
Use this instead ofplatform_driver_register() when you know the deviceis not hotpluggable and has already been registered, and you want toremove its run-onceprobe() infrastructure from memory after the driverhas bound to the device.
One typical use for this would be with drivers for controllers integratedinto system-on-chip processors, where the controller devices have beenconfigured as part of board setup.
Note that this is incompatible with deferred probing.
Returns zero if the driver registered and bound to a device, else returnsa negative error code and with the driver not registered.
- structplatform_device*__platform_create_bundle(structplatform_driver*driver,int(*probe)(structplatform_device*),structresource*res,unsignedintn_res,constvoid*data,size_tsize,structmodule*module)¶
register driver and create corresponding device
Parameters
structplatform_driver*driverplatform driver structure
int(*probe)(structplatform_device*)the driver probe routine, probably from an __init section
structresource*resset of resources that needs to be allocated for the device
unsignedintn_resnumber of resources
constvoid*dataplatform specific data for this platform device
size_tsizesize of platform specific data
structmodule*modulemodule which will be the owner of the driver
Description
Use this in legacy-style modules that probe hardware directly andregister a single platform device and corresponding platform driver.
Returnsstructplatform_device pointer on success, orERR_PTR() on error.
- int__platform_register_drivers(structplatform_driver*const*drivers,unsignedintcount,structmodule*owner)¶
register an array of platform drivers
Parameters
structplatform_driver*const*driversan array of drivers to register
unsignedintcountthe number of drivers to register
structmodule*ownermodule owning the drivers
Description
Registers platform drivers specified by an array. On failure to register adriver, all previously registered drivers will be unregistered. Callers ofthis API should useplatform_unregister_drivers() to unregister drivers inthe reverse order.
Return
0 on success or a negative error code on failure.
- voidplatform_unregister_drivers(structplatform_driver*const*drivers,unsignedintcount)¶
unregister an array of platform drivers
Parameters
structplatform_driver*const*driversan array of drivers to unregister
unsignedintcountthe number of drivers to unregister
Description
Unregisters platform drivers specified by an array. This is typically usedto complement an earlier call toplatform_register_drivers(). Drivers areunregistered in the reverse order in which they were registered.
- structdevice*platform_find_device_by_driver(structdevice*start,conststructdevice_driver*drv)¶
Find a platform device with a given driver.
Parameters
structdevice*startThe device to start the search from.
conststructdevice_driver*drvThe device driver to look for.
- structdevice*bus_find_device_by_name(conststructbus_type*bus,structdevice*start,constchar*name)¶
device iterator for locating a particular device of a specific name.
Parameters
conststructbus_type*busbus type
structdevice*startDevice to begin with
constchar*namename of the device to match
- structdevice*bus_find_device_by_of_node(conststructbus_type*bus,conststructdevice_node*np)¶
device iterator for locating a particular device matching the of_node.
Parameters
conststructbus_type*busbus type
conststructdevice_node*npof_node of the device to match.
- structdevice*bus_find_device_by_fwnode(conststructbus_type*bus,conststructfwnode_handle*fwnode)¶
device iterator for locating a particular device matching the fwnode.
Parameters
conststructbus_type*busbus type
conststructfwnode_handle*fwnodefwnode of the device to match.
- structdevice*bus_find_device_by_devt(conststructbus_type*bus,dev_tdevt)¶
device iterator for locating a particular device matching the device type.
Parameters
conststructbus_type*busbus type
dev_tdevtdevice type of the device to match.
- structdevice*bus_find_next_device(conststructbus_type*bus,structdevice*cur)¶
Find the next device after a given device in a given bus.
Parameters
conststructbus_type*busbus type
structdevice*curdevice to begin the search with.
- structdevice*bus_find_device_by_acpi_dev(conststructbus_type*bus,conststructacpi_device*adev)¶
device iterator for locating a particular device matching the ACPI COMPANION device.
Parameters
conststructbus_type*busbus type
conststructacpi_device*adevACPI COMPANION device to match.
- intbus_for_each_dev(conststructbus_type*bus,structdevice*start,void*data,device_iter_tfn)¶
device iterator.
Parameters
conststructbus_type*busbus type.
structdevice*startdevice to start iterating from.
void*datadata for the callback.
device_iter_tfnfunction to be called for each device.
Description
Iterate overbus’s list of devices, and callfn for each,passing itdata. Ifstart is not NULL, we use that device tobegin iterating from.
We check the return offn each time. If it returns anythingother than 0, we break out and return that value.
NOTE
The device that returns a non-zero value is not retainedin any way, nor is its refcount incremented. If the caller needsto retain this data, it should do so, and increment the referencecount in the supplied callback.
- structdevice*bus_find_device(conststructbus_type*bus,structdevice*start,constvoid*data,device_match_tmatch)¶
device iterator for locating a particular device.
Parameters
conststructbus_type*busbus type
structdevice*startDevice to begin with
constvoid*dataData to pass to match function
device_match_tmatchCallback function to check device
Description
This is similar to thebus_for_each_dev() function above, but itreturns a reference to a device that is ‘found’ for later use, asdetermined by thematch callback.
The callback should return 0 if the device doesn’t match and non-zeroif it does. If the callback returns non-zero, this function willreturn to the caller and not iterate over any more devices.
- intbus_for_each_drv(conststructbus_type*bus,structdevice_driver*start,void*data,int(*fn)(structdevice_driver*,void*))¶
driver iterator
Parameters
conststructbus_type*busbus we’re dealing with.
structdevice_driver*startdriver to start iterating on.
void*datadata to pass to the callback.
int(*fn)(structdevice_driver*,void*)function to call for each driver.
Description
This is nearly identical to the device iterator above.We iterate over each driver that belongs tobus, and callfn for each. Iffn returns anything but 0, we break outand return it. Ifstart is not NULL, we use it as the headof the list.
NOTE
we don’t return the driver that returns a non-zerovalue, nor do we leave the reference count incremented for thatdriver. If the caller needs to know that info, it must set itin the callback. It must also be sure to increment the refcountso it doesn’t disappear before returning to the caller.
Parameters
conststructbus_type*busthe bus to scan.
Description
This function will look for devices on the bus with no driverattached and rescan it against existing drivers to see if it matchesany by callingdevice_attach() for the unbound devices.
Parameters
structdevice*devthe device to reprobe
Description
This function detaches the attached driver (if any) for the givendevice and restarts the driver probing process. It is intendedto use if probing criteria changed during a devices lifetime anddriver attachment should change accordingly.
Parameters
conststructbus_type*busbus to register
Description
Once we have that, we register the bus with the kobjectinfrastructure, then register the children subsystems it has:the devices and drivers that belong to the subsystem.
Parameters
conststructbus_type*busbus.
Description
Unregister the child subsystems and the bus itself.Finally, we callbus_put() to release the refcount
- intsubsys_system_register(conststructbus_type*subsys,conststructattribute_group**groups)¶
register a subsystem at /sys/devices/system/
Parameters
conststructbus_type*subsyssystem subsystem
conststructattribute_group**groupsdefault attributes for the root device
Description
All ‘system’ subsystems have a /sys/devices/system/<name> root devicewith the name of the subsystem. The root device can carry subsystem-wide attributes. All registered devices are below this single rootdevice and are named after the subsystem with a simple enumerationnumber appended. The registered devices are not explicitly named;only ‘id’ in the device needs to be set.
Do not use this interface for anything new, it exists for compatibilitywith bad ideas only. New subsystems should use plain subsystems; andadd the subsystem-wide attributes should be added to the subsystemdirectory itself and not some create fake root-device placed in/sys/devices/system/<name>.
- intsubsys_virtual_register(conststructbus_type*subsys,conststructattribute_group**groups)¶
register a subsystem at /sys/devices/virtual/
Parameters
conststructbus_type*subsysvirtual subsystem
conststructattribute_group**groupsdefault attributes for the root device
Description
All ‘virtual’ subsystems have a /sys/devices/system/<name> root devicewith the name of the subsystem. The root device can carry subsystem-wideattributes. All registered devices are below this single root device.There’s no restriction on device naming. This is for kernel softwareconstructs which need sysfs interface.
- structdevice_driver*driver_find(constchar*name,conststructbus_type*bus)¶
locate driver on a bus by its name.
Parameters
constchar*namename of the driver.
conststructbus_type*busbus to scan for the driver.
Description
Callkset_find_obj() to iterate over list of drivers ona bus to find driver by name. Return driver if found.
This routine provides no locking to prevent the driver it returnsfrom being unregistered or unloaded while the caller is using it.The caller is responsible for preventing this.
- structdevice*bus_get_dev_root(conststructbus_type*bus)¶
return a pointer to the “device root” of a bus
Parameters
conststructbus_type*busbus to return the device root of.
Description
If a bus has a “device root” structure, return it, WITH THE REFERENCECOUNT INCREMENTED.
Note, when finished with the device, a call toput_device() is required.
If the device root is not present (or bus is not a valid pointer), NULLwill be returned.
Device Drivers DMA Management¶
- voiddmam_free_coherent(structdevice*dev,size_tsize,void*vaddr,dma_addr_tdma_handle)¶
Managed
dma_free_coherent()
Parameters
structdevice*devDevice to free coherent memory for
size_tsizeSize of allocation
void*vaddrVirtual address of the memory to free
dma_addr_tdma_handleDMA handle of the memory to free
Description
Manageddma_free_coherent().
- void*dmam_alloc_attrs(structdevice*dev,size_tsize,dma_addr_t*dma_handle,gfp_tgfp,unsignedlongattrs)¶
Managed
dma_alloc_attrs()
Parameters
structdevice*devDevice to allocate non_coherent memory for
size_tsizeSize of allocation
dma_addr_t*dma_handleOut argument for allocated DMA handle
gfp_tgfpAllocation flags
unsignedlongattrsFlags in the DMA_ATTR_* namespace.
Description
Manageddma_alloc_attrs(). Memory allocated using this function will beautomatically released on driver detach.
Return
Pointer to allocated memory on success, NULL on failure.
- unsignedintdma_map_sg_attrs(structdevice*dev,structscatterlist*sg,intnents,enumdma_data_directiondir,unsignedlongattrs)¶
Map the given buffer for DMA
Parameters
structdevice*devThe device for which to perform the DMA operation
structscatterlist*sgThe sg_table object describing the buffer
intnentsNumber of entries to map
enumdma_data_directiondirDMA direction
unsignedlongattrsOptional DMA attributes for the map operation
Description
Maps a buffer described by a scatterlist passed in the sg argument withnents segments for thedir DMA operation by thedev device.
Returns the number of mapped entries (which can be less than nents)on success. Zero is returned for any error.
dma_unmap_sg_attrs() should be used to unmap the buffer with theoriginal sg and original nents (not the value returned by this funciton).
- intdma_map_sgtable(structdevice*dev,structsg_table*sgt,enumdma_data_directiondir,unsignedlongattrs)¶
Map the given buffer for DMA
Parameters
structdevice*devThe device for which to perform the DMA operation
structsg_table*sgtThe sg_table object describing the buffer
enumdma_data_directiondirDMA direction
unsignedlongattrsOptional DMA attributes for the map operation
Description
Maps a buffer described by a scatterlist stored in the given sg_tableobject for thedir DMA operation by thedev device. After success, theownership for the buffer is transferred to the DMA domain. One has tocalldma_sync_sgtable_for_cpu() ordma_unmap_sgtable() to move theownership of the buffer back to the CPU domain before touching thebuffer by the CPU.
Returns 0 on success or a negative error code on error. The followingerror codes are supported with the given meaning:
- -EINVAL
An invalid argument, unaligned access or other errorin usage. Will not succeed if retried.
- -ENOMEM
Insufficient resources (like memory or IOVA space) tocomplete the mapping. Should succeed if retried later.
- -EIO
Legacy error code with an unknown meaning. eg. this isreturned if a lower level call returnedDMA_MAPPING_ERROR.
- -EREMOTEIO
The DMA device cannot access P2PDMA memory specifiedin the sg_table. This will not succeed if retried.
Parameters
structdevice*devdevice to check
Description
If this function returnsfalse, drivers can skip calling dma_unmap_* afterfinishing an I/O. This function must be called after all mappings that mightneed to be unmapped have been performed.
Parameters
structdevice*devdevice to check
Description
Returnstrue ifdev supportsdma_mmap_coherent() anddma_mmap_attrs() tomap DMA allocations to userspace.
- intdma_mmap_attrs(structdevice*dev,structvm_area_struct*vma,void*cpu_addr,dma_addr_tdma_addr,size_tsize,unsignedlongattrs)¶
map a coherent DMA allocation into user space
Parameters
structdevice*devvalid
structdevicepointer, or NULL for ISA and EISA-like devicesstructvm_area_struct*vmavm_area_struct describing requested user mapping
void*cpu_addrkernel CPU-view address returned from dma_alloc_attrs
dma_addr_tdma_addrdevice-view address returned from dma_alloc_attrs
size_tsizesize of memory originally requested in dma_alloc_attrs
unsignedlongattrsattributes of mapping properties requested in dma_alloc_attrs
Description
Map a coherent DMA buffer previously allocated by dma_alloc_attrs into userspace. The coherent DMA buffer must not be freed by the driver until theuser space mapping has been released.
Parameters
structdevice*devdevice to check
Description
Returntrue if the devices DMA mask is too small to address all memory inthe system, elsefalse. Lack of addressing bits is the prime reason forbounce buffering, but might not be the only one.
Device drivers PnP support¶
- intpnp_register_protocol(structpnp_protocol*protocol)¶
adds a pnp protocol to the pnp layer
Parameters
structpnp_protocol*protocolpointer to the corresponding pnp_protocol structure
Description
Ex protocols: ISAPNP, PNPBIOS, etc
- structpnp_dev*pnp_request_card_device(structpnp_card_link*clink,constchar*id,structpnp_dev*from)¶
Searches for a PnP device under the specified card
Parameters
structpnp_card_link*clinkpointer to the card link, cannot be NULL
constchar*idpointer to a PnP ID structure that explains the rules for finding the device
structpnp_dev*fromStarting place to search from. If NULL it will start from the beginning.
- voidpnp_release_card_device(structpnp_dev*dev)¶
call this when the driver no longer needs the device
Parameters
structpnp_dev*devpointer to the PnP device structure
- intpnp_register_card_driver(structpnp_card_driver*drv)¶
registers a PnP card driver with the PnP Layer
Parameters
structpnp_card_driver*drvpointer to the driver to register
- voidpnp_unregister_card_driver(structpnp_card_driver*drv)¶
unregisters a PnP card driver from the PnP Layer
Parameters
structpnp_card_driver*drvpointer to the driver to unregister
- structpnp_id*pnp_add_id(structpnp_dev*dev,constchar*id)¶
adds an EISA id to the specified device
Parameters
structpnp_dev*devpointer to the desired device
constchar*idpointer to an EISA id string
- intpnp_start_dev(structpnp_dev*dev)¶
low-level start of the PnP device
Parameters
structpnp_dev*devpointer to the desired device
Description
assumes that resources have already been allocated
- intpnp_stop_dev(structpnp_dev*dev)¶
low-level disable of the PnP device
Parameters
structpnp_dev*devpointer to the desired device
Description
does not free resources
- intpnp_activate_dev(structpnp_dev*dev)¶
activates a PnP device for use
Parameters
structpnp_dev*devpointer to the desired device
Description
does not validate or set resources so be careful.
- intpnp_disable_dev(structpnp_dev*dev)¶
disables device
Parameters
structpnp_dev*devpointer to the desired device
Description
inform the correct pnp protocol so that resources can be used by other devices
- intpnp_is_active(structpnp_dev*dev)¶
Determines if a device is active based on its current resources
Parameters
structpnp_dev*devpointer to the desired PnP device
Userspace IO devices¶
Parameters
structuio_info*infoUIO device capabilities
- int__uio_register_device(structmodule*owner,structdevice*parent,structuio_info*info)¶
register a new userspace IO device
Parameters
structmodule*ownermodule that creates the new device
structdevice*parentparent device
structuio_info*infoUIO device capabilities
Description
returns zero on success or a negative error code.
- int__devm_uio_register_device(structmodule*owner,structdevice*parent,structuio_info*info)¶
Resource managed
uio_register_device()
Parameters
structmodule*ownermodule that creates the new device
structdevice*parentparent device
structuio_info*infoUIO device capabilities
Description
returns zero on success or a negative error code.
Parameters
structuio_info*infoUIO device capabilities
- structuio_mem¶
description of a UIO memory region
Definition:
struct uio_mem { const char *name; phys_addr_t addr; dma_addr_t dma_addr; unsigned long offs; resource_size_t size; int memtype; void __iomem *internal_addr; struct device *dma_device; struct uio_map *map;};Members
namename of the memory region for identification
addraddress of the device’s memory rounded to pagesize (phys_addr is used since addr can belogical, virtual, or physical & phys_addr_tshould always be large enough to handle any ofthe address types)
dma_addrDMA handle set by dma_alloc_coherent, used withUIO_MEM_DMA_COHERENT only (addr should be thevoid * returned from the same dma_alloc_coherent call)
offsoffset of device memory within the page
sizesize of IO (multiple of page size)
memtypetype of memory addr points to
internal_addrioremap-ped version of addr, for driver internal use
dma_devicedevice
structthatwas passed to dma_alloc_coherent,used with UIO_MEM_DMA_COHERENT onlymapfor use by the UIO core only.
- structuio_port¶
description of a UIO port region
Definition:
struct uio_port { const char *name; unsigned long start; unsigned long size; int porttype; struct uio_portio *portio;};Members
namename of the port region for identification
startstart of port region
sizesize of port region
porttypetype of port (see UIO_PORT_* below)
portiofor use by the UIO core only.
- structuio_info¶
UIO device capabilities
Definition:
struct uio_info { struct uio_device *uio_dev; const char *name; const char *version; struct uio_mem mem[MAX_UIO_MAPS]; struct uio_port port[MAX_UIO_PORT_REGIONS]; long irq; unsigned long irq_flags; void *priv; irqreturn_t (*handler)(int irq, struct uio_info *dev_info); int (*mmap)(struct uio_info *info, struct vm_area_struct *vma); int (*open)(struct uio_info *info, struct inode *inode); int (*release)(struct uio_info *info, struct inode *inode); int (*irqcontrol)(struct uio_info *info, s32 irq_on);};Members
uio_devthe UIO device this info belongs to
namedevice name
versiondevice driver version
memlist of mappable memory regions, size==0 for end of list
portlist of port regions, size==0 for end of list
irqinterrupt number or UIO_IRQ_CUSTOM
irq_flagsflags for
request_irq()privoptional private data
handlerthe device’s irq handler
mmapmmap operation for this uio device
openopen operation for this uio device
releaserelease operation for this uio device
irqcontroldisable/enable irqs when 0/1 is written to /dev/uioX
- uio_register_device¶
uio_register_device(parent,info)
register a new userspace IO device
Parameters
parentparent device
infoUIO device capabilities
Description
returns zero on success or a negative error code.
- devm_uio_register_device¶
devm_uio_register_device(parent,info)
Resource managed
uio_register_device()
Parameters
parentparent device
infoUIO device capabilities
Description
returns zero on success or a negative error code.