Driver fundamentals
Single-page view · as markdown
Driver development
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Driver development combines common kernel facilities with the interfaces of a particular bus or device subsystem.
Start with the Device and driver model and Driver basics. Then use the guides for Device I/O, DMA engines and Firmware loading as needed.
The remaining shelves collect subsystem APIs, platform services and media interfaces. CXL has its own group covering the programming model, allocation, devices and platform integration.
Use Hardware and drivers for device-family documentation and Kernel development for build and test guidance.
Managing Ownership of the Framebuffer Aperture
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
A graphics device might be supported by different drivers, but only one driver can be active at any given time. Many systems load a generic graphics drivers, such as EFI-GOP or VESA, early during the boot process. During later boot stages, they replace the generic driver with a dedicated, hardware-specific driver. To take over the device, the dedicated driver first has to remove the generic driver. Aperture functions manage ownership of framebuffer memory and hand-over between drivers.
Graphics drivers should call aperture_remove_conflicting_devices()
at the top of their probe function. The function removes any generic
driver that is currently associated with the given framebuffer memory.
An example for a graphics device on the platform bus is shown below.
static int
static const struct platform_driver example_driver = ;
The given example reads the platform device's I/O-memory range from the
device instance. An active framebuffer will be located within this range.
The call to aperture_remove_conflicting_devices() releases drivers that
have previously claimed ownership of the range and are currently driving
output on the framebuffer. If successful, the new driver can take over
the device.
While the given example uses a platform device, the aperture helpers work
with every bus that has an addressable framebuffer. In the case of PCI,
device drivers can also call aperture_remove_conflicting_pci_devices() and
let the function detect the apertures automatically. Device drivers without
knowledge of the framebuffer's location can call
aperture_remove_all_conflicting_devices(), which removes all known devices.
Drivers that are susceptible to being removed by other drivers, such as
generic EFI or VESA drivers, have to register themselves as owners of their
framebuffer apertures. Ownership of the framebuffer memory is achieved
by calling devm_aperture_acquire_for_platform_device(). If successful, the
driver is the owner of the framebuffer range. The function fails if the
framebuffer is already owned by another driver. See below for an example.
static int
static int
static const struct platform_driver generic_driver = ;
The similar to the previous example, the generic driver claims ownership of the framebuffer memory from its probe function. This will fail if the memory range, or parts of it, is already owned by another driver.
If successful, the generic driver is now subject to forced removal by
another driver. This only works for platform drivers that support hot
unplugging. When a driver calls aperture_remove_conflicting_devices()
et al for the registered framebuffer range, the aperture helpers call
platform_device_unregister() and the generic driver unloads itself. The
generic driver also has to provide a remove function to make this work.
Once hot unplugged from hardware, it may not access the device's
registers, framebuffer memory, ROM, etc afterwards.
aperture_remove_all_conflicting_devices() #
int remove all existing framebuffers
Parameters
const char *name: a descriptive name of the requesting driver
Description
This function removes all graphics device drivers. Use this function on systems that can have their framebuffer located anywhere in memory.
Return
0 on success, or a negative errno code otherwise
devm_aperture_acquire_for_platform_device() #
int Acquires ownership of an aperture on behalf of a platform device.
Parameters
struct platform_device *pdev: the platform device to own the apertureresource_size_t base: the aperture's byte offset in physical memoryresource_size_t size: the aperture size in bytes
Description
Installs the given device as the new owner of the aperture. The function expects the aperture to be provided by a platform device. If another driver takes over ownership of the aperture, aperture helpers will then unregister the platform device automatically. All acquired apertures are released automatically when the underlying device goes away.
The function fails if the aperture, or parts of it, is currently
owned by another device. To evict current owners, callers should use
remove_conflicting_devices() et al. before calling this function.
Return
0 on success, or a negative errno value otherwise.
aperture_remove_conflicting_devices() #
int remove devices in the given range
Parameters
resource_size_t base: the aperture's base address in physical memoryresource_size_t size: aperture size in bytesconst char *name: a descriptive name of the requesting driver
Description
This function removes devices that own apertures within base and size.
Return
0 on success, or a negative errno code otherwise
__aperture_remove_legacy_vga_devices() #
int remove legacy VGA devices of a PCI devices
Parameters
struct pci_dev *pdev: PCI device
Description
This function removes VGA devices provided by pdev, such as a VGA framebuffer or a console. This is useful if you have a VGA-compatible PCI graphics device with framebuffers in non-BAR locations. Drivers should acquire ownership of those memory areas and afterwards call this helper to release remaining VGA devices.
If your hardware has its framebuffers accessible via PCI BARS, use
aperture_remove_conflicting_pci_devices() instead. The function will
release any VGA devices automatically.
-
WARNING: Apparently we must remove graphics drivers before calling
this helper. Otherwise the vga fbdev driver falls over if we have vgacon configured.
Return
0 on success, or a negative errno code otherwise
aperture_remove_conflicting_pci_devices() #
int remove existing framebuffers for PCI devices
Parameters
struct pci_dev *pdev: PCI deviceconst char *name: a descriptive name of the requesting driver
Description
This function removes devices that own apertures within any of pdev's memory bars. The function assumes that PCI device with shadowed ROM drives a primary display and therefore kicks out vga16fb as well.
Return
0 on success, or a negative errno code otherwise
Driver Basics
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Peios: The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See Peios kernel behaviour and the VFS callback reference for the Peios integration contracts.
Driver Entry and Exit points #
module_init() #
driver initialization entry point
Parameters
x: function to be run at kernel boot time or module insertion
Description
module_init() will either be called during do_initcalls() (if
builtin) or at module insertion time (if a module). There can only
be one per module.
module_exit() #
driver exit entry point
Parameters
x: function to be run when driver is removed
Description
module_exit() will wrap the driver clean-up code
with cleanup_module() when used with rmmod when
the driver is a module. If the driver is statically
compiled into the kernel, module_exit() has no effect.
There can only be one per module.
struct klp_modinfo #
ELF information preserved from the livepatch module
Definition
;
Members
hdr: ELF headersechdrs: Section header tablesecstrings: String table for the section headerssymndx: The symbol table section index
try_module_get() #
bool take module refcount unless module is being removed
Parameters
struct module *module: the module we should check for
Description
Only try to get a module reference count if the module is not being removed. This call will fail if the module is in the process of being removed.
Care must also be taken to ensure the module exists and is alive prior to usage of this call. This can be gauranteed through two means:
-
Direct protection: you know an earlier caller must have increased the module reference through
__module_get(). This can typically be achieved by having another entity other than the module itself increment the module reference count. -
Implied protection: there is an implied protection against module removal. An example of this is the implied protection used by kernfs / sysfs. The sysfs store / read file operations are guaranteed to exist through the use of kernfs's active reference (see
kernfs_active()) and a sysfs / kernfs file removal cannot happen unless the same file is not active. Therefore, if a sysfs file is being read or written to the module which created it must still exist. It is therefore safe to usetry_module_get()on module sysfs store / read ops.
One of the real values to try_module_get() is the module_is_live() check
which ensures that the caller of try_module_get() can yield to userspace
module removal requests and gracefully fail if the module is on its way out.
Returns true if the reference count was successfully incremented.
module_put() #
void release a reference count to a module
Parameters
struct module *module: the module we should release a reference count for
Description
If you successfully bump a reference count to a module with try_module_get(),
when you are finished you must call module_put() to release that reference
count.
Driver device table #
struct usb_device_id #
identifies USB devices for probing and hotplugging
Definition
;
Members
match_flags: Bit mask controlling which of the other fields are used to match against new devices. Any field except for driver_info may be used, although some only make sense in conjunction with other fields. This is usually set by a USB_DEVICE_*() macro, which sets all other fields in this structure except for driver_info.idVendor: USB vendor ID for a device; numbers are assigned by the USB forum to its members.idProduct: Vendor-assigned product ID.bcdDevice_lo: Low end of range of vendor-assigned product version numbers. This is also used to identify individual product versions, for a range consisting of a single device.bcdDevice_hi: High end of version number range. The range of product versions is inclusive.bDeviceClass: Class of device; numbers are assigned by the USB forum. Products may choose to implement classes, or be vendor-specific. Device classes specify behavior of all the interfaces on a device.bDeviceSubClass: Subclass of device; associated with bDeviceClass.bDeviceProtocol: Protocol of device; associated with bDeviceClass.bInterfaceClass: Class of interface; numbers are assigned by the USB forum. Products may choose to implement classes, or be vendor-specific. Interface classes specify behavior only of a given interface; other interfaces may support other classes.bInterfaceSubClass: Subclass of interface; associated with bInterfaceClass.bInterfaceProtocol: Protocol of interface; associated with bInterfaceClass.bInterfaceNumber: Number of interface; composite devices may use fixed interface numbers to differentiate between vendor-specific interfaces.driver_info: Holds information used by the driver. Usually it holds a pointer to a descriptor understood by the driver, or perhaps device flags.
Description
In most cases, drivers will create a table of device IDs by using
USB_DEVICE(), or similar macros designed for that purpose.
They will then export it to userspace using MODULE_DEVICE_TABLE(),
and provide it to the USB core through their usb_driver structure.
See the usb_match_id() function for information about how matches are
performed. Briefly, you will normally use one of several macros to help
construct these entries. Each entry you provide will either identify
one or more specific products, or will identify a class of products
which have agreed to behave the same. You should put the more specific
matches towards the beginning of your table, so that driver_info can
record quirks of specific products.
ACPI_DEVICE_CLASS() #
macro used to describe an ACPI device with the PCI-defined class-code information
Parameters
_cls: the class, subclass, prog-if triple for this device_msk: the class mask for this device
Description
This macro is used to create a struct acpi_device_id that matches a specific PCI class. The .id and .driver_data fields will be left initialized with the default value.
struct mdio_device_id #
identifies PHY devices on an MDIO/MII bus
Definition
;
Members
phy_id: The result of (mdio_read(MII_PHYSID1) << 16 | mdio_read(MII_PHYSID2)) & phy_id_mask for this PHY typephy_id_mask: Defines the significant bits of phy_id. A value of 0 is used to terminate an array of struct mdio_device_id.
struct amba_id #
identifies a device on an AMBA bus
Definition
;
Members
id: The significant bits if the hardware device IDmask: Bitmask specifying which bits of the id field are significant when matching. A driver binds to a device when ((hardware device ID) & mask) == id.data: Private data used by the driver.
struct mips_cdmm_device_id #
identifies devices in MIPS CDMM bus
Definition
;
Members
type: Device type identifier.
struct mei_cl_device_id #
MEI client device identifier
Definition
;
Members
name: helper nameuuid: client uuidversion: client protocol versiondriver_info: information used by the driver.
Description
identifies mei client device by uuid and name
struct rio_device_id #
RIO device identifier
Definition
;
Members
did: RapidIO device IDvid: RapidIO vendor IDasm_did: RapidIO assembly device IDasm_vid: RapidIO assembly vendor ID
Description
Identifies a RapidIO device based on both the device/vendor IDs and the assembly device/vendor IDs.
struct fsl_mc_device_id #
MC object device identifier
Definition
;
Members
vendor: vendor IDobj_type: MC object type
Description
Type of entries in the "device Id" table for MC object devices supported by a MC object device driver. The last entry of the table has vendor set to 0x0
struct tb_service_id #
Thunderbolt service identifiers
Definition
;
Members
match_flags: Flags used to match the structureprotocol_key: Protocol key the service supportsprotocol_id: Protocol id the service supportsprotocol_version: Version of the protocolprotocol_revision: Revision of the protocol softwaredriver_data: Driver specific data
Description
Thunderbolt XDomain services are exposed as devices where each device carries the protocol information the service supports. Thunderbolt XDomain service drivers match against that information.
struct typec_device_id #
USB Type-C alternate mode identifiers
Definition
;
Members
svid: Standard or Vendor IDmode: Mode indexdriver_data: Driver specific data
struct tee_client_device_id #
tee based device identifier
Definition
;
Members
uuid: For TEE based client devices we use the device uuid as the identifier.
struct wmi_device_id #
WMI device identifier
Definition
;
Members
guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49bacontext: pointer to driver specific data
struct mhi_device_id #
MHI device identification
Definition
;
Members
chan: MHI channel namedriver_data: driver data;
struct dfl_device_id #
dfl device identifier
Definition
;
Members
type: DFL FIU type of the device. See enum dfl_id_type.feature_id: feature identifier local to its DFL FIU type.driver_data: driver specific data.
struct ishtp_device_id #
ISHTP device identifier
Definition
;
Members
guid: GUID of the device.driver_data: pointer to driver specific data
struct cdx_device_id #
CDX device identifier
Definition
;
Members
vendor: Vendor IDdevice: Device IDsubvendor: Subsystem vendor ID (or CDX_ANY_ID)subdevice: Subsystem device ID (or CDX_ANY_ID)class: Device class Most drivers do not need to specify class/class_mask as vendor/device is normally sufficient.class_mask: Limit which sub-fields of the class field are compared.override_only: Match only when dev->driver_override is this driver.
Description
Type of entries in the "device Id" table for CDX devices supported by a CDX device driver.
struct coreboot_device_id #
Identifies a coreboot table entry
Definition
;
Members
tag: tag IDdriver_data: driver specific data
Delaying and scheduling routines #
struct prev_cputime #
snapshot of system and user cputime
Definition
;
Members
utime: time spent in user modestime: time spent in system modelock: protects the above two fields
Description
Stores previous user/system time values such that we can guarantee monotonicity.
__task_lazy_mmu_mode_active() #
bool Test the lazy MMU mode state for a task.
Parameters
struct task_struct *tsk: The task to check.
Description
Test whether tsk has its lazy MMU mode state set to active (i.e. enabled and not paused).
This function only considers the state saved in task_struct; to test whether
current actually is in lazy MMU mode, is_lazy_mmu_mode_active() should be
used instead.
This function is intended for architectures that implement the lazy MMU mode; it must not be called from generic code.
is_lazy_mmu_mode_active() #
bool Test whether we are currently in lazy MMU mode.
Parameters
void: no arguments
Description
Test whether the current context is in lazy MMU mode. This is true if both:
- We are not in interrupt context
- Lazy MMU mode is active for the current task
This function is intended for architectures that implement the lazy MMU mode; it must not be called from generic code.
set_cpus_allowed_ptr() #
int set CPU affinity mask of a task
Parameters
struct task_struct *p: the taskconst struct cpumask *new_mask: CPU affinity mask
Return
zero if successful, or a negative error code
task_nice() #
int return the nice value of a given task.
Parameters
const struct task_struct *p: the task in question.
Return
The nice value [ -20 ... 0 ... 19 ].
is_idle_task() #
bool is the specified task an idle task?
Parameters
const struct task_struct *p: the task in question.
Return
1 if p is an idle task. 0 otherwise.
wake_up_process() #
int Wake up a specific process
Parameters
struct task_struct *p: The process to be woken up.
Description
Attempt to wake up the nominated process and move it to the set of runnable processes.
This function executes a full memory barrier before accessing the task state.
Return
1 if the process was woken up, 0 if it was already running.
preempt_notifier_register() #
void tell me when current is being preempted & rescheduled
Parameters
struct preempt_notifier *notifier: notifier struct to register
preempt_notifier_unregister() #
void no longer interested in preemption notifications
Parameters
struct preempt_notifier *notifier: notifier struct to unregister
Description
This is not safe to call from within a preemption notifier.
preempt_schedule_notrace() #
__visible void notrace preempt_schedule called by tracing
Parameters
void: no arguments
Description
The tracing infrastructure uses preempt_enable_notrace to prevent
recursion and tracing preempt enabling caused by the tracing
infrastructure itself. But as tracing can happen in areas coming
from userspace or just about to enter userspace, a preempt enable
can occur before user_exit() is called. This will cause the scheduler
to be called when the system is still in usermode.
To prevent this, the preempt_enable_notrace will use this function
instead of preempt_schedule() to exit user context if needed before
calling the scheduler.
cpupri_find_fitness() #
int find the best (lowest-pri) CPU in the system
Parameters
struct cpupri *cp: The cpupri contextstruct task_struct *p: The taskstruct cpumask *lowest_mask: A mask to fill in with selected CPUs (or NULL)bool (*fitness_fn)(struct task_struct *p, int cpu): A pointer to a function to do custom checks whether the CPU fits a specific criteria so that we only return those CPUs.
Note
This function returns the recommended CPUs as calculated during the current invocation. By the time the call returns, the CPUs may have in fact changed priorities any number of times. While not ideal, it is not an issue of correctness since the normal rebalancer logic will correct any discrepancies created by racing against the uncertainty of the current priority configuration.
Return
(int)bool - CPUs were found
cpupri_set() #
void update the CPU priority setting
Parameters
struct cpupri *cp: The cpupri contextint cpu: The target CPUint newpri: The priority (INVALID,NORMAL,RT1-RT99,HIGHER) to assign to this CPU
Note
Assumes cpu_rq(cpu)->lock is locked
Return
(void)
cpupri_init() #
int initialize the cpupri structure
Parameters
struct cpupri *cp: The cpupri context
Return
-ENOMEM on memory allocation failure.
cpupri_cleanup() #
void clean up the cpupri structure
Parameters
struct cpupri *cp: The cpupri context
update_tg_load_avg() #
void update the tg's load avg
Parameters
struct cfs_rq *cfs_rq: the cfs_rq whose avg changed
Description
This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. However, because tg->load_avg is a global value there are performance considerations.
In order to avoid having to look at the other cfs_rq's, we use a differential update where we store the last value we propagated. This in turn allows skipping updates if the differential is 'small'.
Updating tg's load_avg is necessary before update_cfs_share().
update_cfs_rq_load_avg() #
int update the cfs_rq's load/util averages
Parameters
u64 now: current time, as percfs_rq_clock_pelt()struct cfs_rq *cfs_rq: cfs_rq to update
Description
The cfs_rq avg is the direct sum of all its entities (blocked and runnable) avg. The immediate corollary is that all (fair) tasks must be attached.
cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
Since both these conditions indicate a changed cfs_rq->avg.load we should
call update_tg_load_avg() when this function returns true.
Return
true if the load decayed or we removed load.
attach_entity_load_avg() #
void attach this entity to its cfs_rq load avg
Parameters
struct cfs_rq *cfs_rq: cfs_rq to attach tostruct sched_entity *se: sched_entity to attach
Description
Must call update_cfs_rq_load_avg() before this, since we rely on
cfs_rq->avg.last_update_time being current.
detach_entity_load_avg() #
void detach this entity from its cfs_rq load avg
Parameters
struct cfs_rq *cfs_rq: cfs_rq to detach fromstruct sched_entity *se: sched_entity to detach
Description
Must call update_cfs_rq_load_avg() before this, since we rely on
cfs_rq->avg.last_update_time being current.
cpu_util() #
unsigned long Estimates the amount of CPU capacity used by CFS tasks.
Parameters
int cpu: the CPU to get the utilization forstruct task_struct *p: task for which the CPU utilization should be predicted or NULLint dst_cpu: CPU p migrates to, -1 if p moves from cpu or p == NULLint boost: 1 to enable boosting, otherwise 0
Description
The unit of the return value must be the same as the one of CPU capacity so that CPU utilization can be compared with CPU capacity.
CPU utilization is the sum of running time of runnable tasks plus the recent utilization of currently non-runnable tasks on that CPU. It represents the amount of CPU capacity currently used by CFS tasks in the range [0..max CPU capacity] with max CPU capacity being the CPU capacity at f_max.
The estimated CPU utilization is defined as the maximum between CPU utilization and sum of the estimated utilization of the currently runnable tasks on that CPU. It preserves a utilization "snapshot" of previously-executed tasks, which helps better deduce how busy a CPU will be when a long-sleeping task wakes up. The contribution to CPU utilization of such a task would be significantly decayed at this point of time.
Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
CPU contention for CFS tasks can be detected by CPU runnable > CPU
utilization. Boosting is implemented in cpu_util() so that internal
users (e.g. EAS) can use it next to external users (e.g. schedutil),
latter via cpu_util_cfs_boost().
CPU utilization can be higher than the current CPU capacity (f_curr/f_max * max CPU capacity) or even the max CPU capacity because of rounding errors as well as task migrations or wakeups of new tasks. CPU utilization has to be capped to fit into the [0..max CPU capacity] range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) could be seen as over-utilized even though CPU1 has 20% of spare CPU capacity. CPU utilization is allowed to overshoot current CPU capacity though since this is useful for predicting the CPU capacity required after task migrations (scheduler-driven DVFS).
Return
(Boosted) (estimated) utilization for the specified CPU.
sched_use_asym_prio() #
bool Check whether asym_packing priority must be used
Parameters
struct sched_domain *sd: The scheduling domain of the load balancingint cpu: A CPU
Description
Always use CPU priority when balancing load between SMT siblings. When balancing load between cores, it is not sufficient that cpu is idle. Only use CPU priority if the whole core is idle.
Return
True if the priority of cpu must be followed. False otherwise.
sched_group_asym() #
bool Check if the destination CPU can do asym_packing balance
Parameters
struct lb_env *env: The load balancing environmentstruct sg_lb_stats *sgs: Load-balancing statistics of the candidate busiest groupstruct sched_group *group: The candidate busiest group
Description
env::dst_cpu can do asym_packing if it has higher priority than the preferred CPU of group.
Return
true if env::dst_cpu can do with asym_packing load balance. False otherwise.
update_sg_lb_stats() #
void Update sched_group's statistics for load balancing.
Parameters
struct lb_env *env: The load balancing environment.struct sd_lb_stats *sds: Load-balancing data with statistics of the local group.struct sched_group *group: sched_group whose statistics are to be updated.struct sg_lb_stats *sgs: variable to hold the statistics for this group.bool *sg_overloaded: sched_group is overloadedbool *sg_overutilized: sched_group is overutilized
update_sd_pick_busiest() #
bool return 1 on busiest group
Parameters
struct lb_env *env: The load balancing environment.struct sd_lb_stats *sds: sched_domain statisticsstruct sched_group *sg: sched_group candidate to be checked for being the busieststruct sg_lb_stats *sgs: sched_group statistics
Description
Determine if sg is a busier group than the previously selected busiest group.
Return
true if sg is a busier group than the previously selected
busiest group. false otherwise.
idle_cpu_without() #
int would a given CPU be idle without p ?
Parameters
int cpu: the processor on which idleness is tested.struct task_struct *p: task which should be ignored.
Return
1 if the CPU would be idle. 0 otherwise.
update_sd_lb_stats() #
void Update sched_domain's statistics for load balancing.
Parameters
struct lb_env *env: The load balancing environment.struct sd_lb_stats *sds: variable to hold the statistics for this sched_domain.
calculate_imbalance() #
void Calculate the amount of imbalance present within the groups of a given sched_domain during load balance.
Parameters
struct lb_env *env: load balance environmentstruct sd_lb_stats *sds: statistics of the sched_domain whose imbalance is to be calculated.
sched_balance_find_src_group() #
struct sched_group * Returns the busiest group within the sched_domain if there is an imbalance.
Parameters
struct lb_env *env: The load balancing environment.
Description
Also calculates the amount of runnable load which should be moved to restore balance.
Return
- The busiest group if imbalance exists.
DECLARE_COMPLETION() #
declare and initialize a completion structure
Parameters
work: identifier for the completion structure
Description
This macro declares and initializes a completion structure. Generally used for static declarations. You should use the _ONSTACK variant for automatic variables.
DECLARE_COMPLETION_ONSTACK() #
declare and initialize a completion structure
Parameters
work: identifier for the completion structure
Description
This macro declares and initializes a completion structure on the kernel stack.
init_completion() #
void Initialize a dynamically allocated completion
Parameters
struct completion *x: pointer to completion structure that is to be initialized
Description
This inline function will initialize a dynamically created completion structure.
reinit_completion() #
void reinitialize a completion structure
Parameters
struct completion *x: pointer to completion structure that is to be reinitialized
Description
This inline function should be used to reinitialize a completion structure so it can
be reused. This is especially important after complete_all() is used.
Time and timer routines #
get_jiffies_64() #
u64 read the 64-bit non-atomic jiffies_64 value
Parameters
void: no arguments
Description
When BITS_PER_LONG < 64, this uses sequence number sampling using jiffies_lock to protect the 64-bit read.
Return
current 64-bit jiffies value
time_after() #
returns true if the time a is after time b.
Parameters
a: first comparable as unsigned longb: second comparable as unsigned long
Description
Do this with "<0" and ">=0" to only test the sign of the result. A good compiler would generate better code (and a really good compiler wouldn't care). Gcc is currently neither.
Return
true is time a is after time b, otherwise false.
time_before() #
returns true if the time a is before time b.
Parameters
a: first comparable as unsigned longb: second comparable as unsigned long
Return
true is time a is before time b, otherwise false.
time_after_eq() #
returns true if the time a is after or the same as time b.
Parameters
a: first comparable as unsigned longb: second comparable as unsigned long
Return
true is time a is after or the same as time b, otherwise false.
time_before_eq() #
returns true if the time a is before or the same as time b.
Parameters
a: first comparable as unsigned longb: second comparable as unsigned long
Return
true is time a is before or the same as time b, otherwise false.
time_in_range() #
Calculate whether a is in the range of [b, c].
Parameters
a: time to testb: beginning of the rangec: end of the range
Return
true is time a is in the range [b, c], otherwise false.
time_in_range_open() #
Calculate whether a is in the range of [b, c).
Parameters
a: time to testb: beginning of the rangec: end of the range
Return
true is time a is in the range [b, c), otherwise false.
time_after64() #
returns true if the time a is after time b.
Parameters
a: first comparable as __u64b: second comparable as __u64
Description
This must be used when utilizing jiffies_64 (i.e. return value of
get_jiffies_64()).
Return
true is time a is after time b, otherwise false.
time_before64() #
returns true if the time a is before time b.
Parameters
a: first comparable as __u64b: second comparable as __u64
Description
This must be used when utilizing jiffies_64 (i.e. return value of
get_jiffies_64()).
Return
true is time a is before time b, otherwise false.
time_after_eq64() #
returns true if the time a is after or the same as time b.
Parameters
a: first comparable as __u64b: second comparable as __u64
Description
This must be used when utilizing jiffies_64 (i.e. return value of
get_jiffies_64()).
Return
true is time a is after or the same as time b, otherwise false.
time_before_eq64() #
returns true if the time a is before or the same as time b.
Parameters
a: first comparable as __u64b: second comparable as __u64
Description
This must be used when utilizing jiffies_64 (i.e. return value of
get_jiffies_64()).
Return
true is time a is before or the same as time b, otherwise false.
time_in_range64() #
Calculate whether a is in the range of [b, c].
Parameters
a: time to testb: beginning of the rangec: end of the range
Return
true is time a is in the range [b, c], otherwise false.
time_is_before_jiffies() #
return true if a is before jiffies
Parameters
a: time (unsigned long) to compare to jiffies
Return
true is time a is before jiffies, otherwise false.
time_is_before_jiffies64() #
return true if a is before jiffies_64
Parameters
a: time (__u64) to compare to jiffies_64
Return
true is time a is before jiffies_64, otherwise false.
time_is_after_jiffies() #
return true if a is after jiffies
Parameters
a: time (unsigned long) to compare to jiffies
Return
true is time a is after jiffies, otherwise false.
time_is_after_jiffies64() #
return true if a is after jiffies_64
Parameters
a: time (__u64) to compare to jiffies_64
Return
true is time a is after jiffies_64, otherwise false.
time_is_before_eq_jiffies() #
return true if a is before or equal to jiffies
Parameters
a: time (unsigned long) to compare to jiffies
Return
true is time a is before or the same as jiffies, otherwise false.
time_is_before_eq_jiffies64() #
return true if a is before or equal to jiffies_64
Parameters
a: time (__u64) to compare to jiffies_64
Return
true is time a is before or the same jiffies_64, otherwise false.
time_is_after_eq_jiffies() #
return true if a is after or equal to jiffies
Parameters
a: time (unsigned long) to compare to jiffies
Return
true is time a is after or the same as jiffies, otherwise false.
time_is_after_eq_jiffies64() #
return true if a is after or equal to jiffies_64
Parameters
a: time (__u64) to compare to jiffies_64
Return
true is time a is after or the same as jiffies_64, otherwise false.
jiffies_to_msecs() #
unsigned int Convert jiffies to milliseconds
Parameters
const unsigned long j: jiffies value
Description
This inline version takes care of HZ in {100,250,1000}.
Return
milliseconds value
jiffies_to_usecs() #
unsigned int Convert jiffies to microseconds
Parameters
const unsigned long j: jiffies value
Return
microseconds value
jiffies_to_nsecs() #
u64 Convert jiffies to nanoseconds
Parameters
const unsigned long j: jiffies value
Return
nanoseconds value
msecs_to_jiffies() #
unsigned long - convert milliseconds to jiffies
Parameters
const unsigned int m: time in milliseconds
Description
conversion is done as follows:
-
negative values mean 'infinite timeout' (MAX_JIFFY_OFFSET)
-
'too large' values [that would result in larger than MAX_JIFFY_OFFSET values] mean 'infinite timeout' too.
-
all other values are converted to jiffies by either multiplying the input value by a factor or dividing it with a factor and handling any 32-bit overflows. for the details see
_msecs_to_jiffies()
msecs_to_jiffies() checks for the passed in value being a constant
via __builtin_constant_p() allowing gcc to eliminate most of the
code. __msecs_to_jiffies() is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The HZ range specific helpers _msecs_to_jiffies() are called both
directly here and from __msecs_to_jiffies() in the case where
constant folding is not possible.
Return
jiffies value
secs_to_jiffies() #
- convert seconds to jiffies
Parameters
_secs: time in seconds
Description
Conversion is done by simple multiplication with HZ
secs_to_jiffies() is defined as a macro rather than a static inline
function so it can be used in static initializers.
Return
jiffies value
usecs_to_jiffies() #
unsigned long - convert microseconds to jiffies
Parameters
const unsigned int u: time in microseconds
Description
conversion is done as follows:
-
'too large' values [that would result in larger than MAX_JIFFY_OFFSET values] mean 'infinite timeout' too.
-
all other values are converted to jiffies by either multiplying the input value by a factor or dividing it with a factor and handling any 32-bit overflows as for msecs_to_jiffies.
usecs_to_jiffies() checks for the passed in value being a constant
via __builtin_constant_p() allowing gcc to eliminate most of the
code. __usecs_to_jiffies() is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The HZ range specific helpers _usecs_to_jiffies() are called both
directly here and from __msecs_to_jiffies() in the case where
constant folding is not possible.
Return
jiffies value
jiffies_to_msecs() #
unsigned int Convert jiffies to milliseconds
Parameters
const unsigned long j: jiffies value
Return
milliseconds value
jiffies_to_usecs() #
unsigned int Convert jiffies to microseconds
Parameters
const unsigned long j: jiffies value
Return
microseconds value
mktime64() #
time64_t Converts date to seconds.
Parameters
const unsigned int year0: year to convertconst unsigned int mon0: month to convertconst unsigned int day: day to convertconst unsigned int hour: hour to convertconst unsigned int min: minute to convertconst unsigned int sec: second to convert
Description
Converts Gregorian date to seconds since 1970-01-01 00:00:00. Assumes input in normal date format, i.e. 1980-12-31 23:59:59 => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
[For the Julian calendar (which was used in Russia before 1917, Britain & colonies before 1752, anywhere else before 1582, and is still in use by some communities) leave out the -year/100+year/400 terms, and add 10.]
This algorithm was first published by Gauss (I think).
A leap second can be indicated by calling this function with sec as 60 (allowable under ISO 8601). The leap second is treated the same as the following second since they don't exist in UNIX time.
An encoding of midnight at the end of the day as 24:00:00 - ie. midnight tomorrow - (allowable under ISO 8601) is supported.
Return
seconds since the epoch time for the given input date
set_normalized_timespec64() #
void set timespec sec and nsec parts and normalize
Parameters
struct timespec64 *ts: pointer to timespec variable to be settime64_t sec: seconds to sets64 nsec: nanoseconds to set
Description
Set seconds and nanoseconds field of a timespec variable and normalize to the timespec storage format
Note
The tv_nsec part is always in the range of 0 <= tv_nsec < NSEC_PER_SEC. For negative values only the tv_sec field is negative !
ns_to_timespec64() #
struct timespec64 Convert nanoseconds to timespec64
Parameters
s64 nsec: the nanoseconds value to be converted
Return
the timespec64 representation of the nsec parameter.
__msecs_to_jiffies() #
unsigned long - convert milliseconds to jiffies
Parameters
const unsigned int m: time in milliseconds
Description
conversion is done as follows:
-
negative values mean 'infinite timeout' (MAX_JIFFY_OFFSET)
-
'too large' values [that would result in larger than MAX_JIFFY_OFFSET values] mean 'infinite timeout' too.
-
all other values are converted to jiffies by either multiplying the input value by a factor or dividing it with a factor and handling any 32-bit overflows. for the details see
_msecs_to_jiffies()
msecs_to_jiffies() checks for the passed in value being a constant
via __builtin_constant_p() allowing gcc to eliminate most of the
code, __msecs_to_jiffies() is called if the value passed does not
allow constant folding and the actual conversion must be done at
runtime.
The _msecs_to_jiffies helpers are the HZ dependent conversion
routines found in include/linux/jiffies.h
Return
jiffies value
__usecs_to_jiffies() #
unsigned long - convert microseconds to jiffies
Parameters
const unsigned int u: time in milliseconds
Return
jiffies value
timespec64_to_jiffies() #
unsigned long convert a timespec64 value to jiffies
Parameters
const struct timespec64 *value: pointer tostruct timespec64
Description
The TICK_NSEC - 1 rounds up the value to the next resolution. Note that a remainder subtract here would not do the right thing as the resolution values don't fall on second boundaries. I.e. the line: nsec -= nsec % TICK_NSEC; is NOT a correct resolution rounding. Note that due to the small error in the multiplier here, this rounding is incorrect for sufficiently large values of tv_nsec, but well formed timespecs should have tv_nsec < NSEC_PER_SEC, so we're OK.
Rather, we just shift the bits off the right.
The >> (NSEC_JIFFIE_SC - SEC_JIFFIE_SC) converts the scaled nsec value to a scaled second value.
Return
jiffies value
jiffies_to_timespec64() #
void convert jiffies value to struct timespec64
Parameters
const unsigned long jiffies: jiffies valuestruct timespec64 *value: pointer tostruct timespec64
jiffies_to_clock_t() #
clock_t Convert jiffies to clock_t
Parameters
unsigned long x: jiffies value
Return
jiffies converted to clock_t (CLOCKS_PER_SEC)
clock_t_to_jiffies() #
unsigned long Convert clock_t to jiffies
Parameters
unsigned long x: clock_t value
Return
clock_t value converted to jiffies
jiffies_64_to_clock_t() #
notrace u64 Convert jiffies_64 to clock_t
Parameters
u64 x: jiffies_64 value
Return
jiffies_64 value converted to 64-bit "clock_t" (CLOCKS_PER_SEC)
jiffies64_to_nsecs() #
u64 Convert jiffies64 to nanoseconds
Parameters
u64 j: jiffies64 value
Return
nanoseconds value
jiffies64_to_msecs() #
u64 Convert jiffies64 to milliseconds
Parameters
const u64 j: jiffies64 value
Return
milliseconds value
nsecs_to_jiffies64() #
u64 Convert nsecs in u64 to jiffies64
Parameters
u64 n: nsecs in u64
Description
Unlike {m,u}secs_to_jiffies, type of input is not unsigned int but u64. And this doesn't return MAX_JIFFY_OFFSET since this function is designed for scheduler, not for use in device drivers to calculate timeout value.
note
NSEC_PER_SEC = 10^9 = (5^9 * 2^9) = (1953125 * 512) ULLONG_MAX ns = 18446744073.709551615 secs = about 584 years
Return
nsecs converted to jiffies64 value
nsecs_to_jiffies() #
unsigned long Convert nsecs in u64 to jiffies
Parameters
u64 n: nsecs in u64
Description
Unlike {m,u}secs_to_jiffies, type of input is not unsigned int but u64. And this doesn't return MAX_JIFFY_OFFSET since this function is designed for scheduler, not for use in device drivers to calculate timeout value.
note
NSEC_PER_SEC = 10^9 = (5^9 * 2^9) = (1953125 * 512) ULLONG_MAX ns = 18446744073.709551615 secs = about 584 years
Return
nsecs converted to jiffies value
timespec64_add_safe() #
struct timespec64 Add two timespec64 values and do a safety check for overflow.
Parameters
const struct timespec64 lhs: first (left) timespec64 to addconst struct timespec64 rhs: second (right) timespec64 to add
Description
It's assumed that both values are valid (>= 0). And, each timespec64 is in normalized form.
Return
sum of lhs + rhs
get_timespec64() #
int get user's time value into kernel space
Parameters
struct timespec64 *ts: destinationstruct timespec64const struct __kernel_timespec __user *uts: user's time value asstruct __kernel_timespec
Description
Handles compat or 32-bit modes.
Return
0 on success or negative errno on error
put_timespec64() #
int convert timespec64 value to __kernel_timespec format and copy the latter to userspace
Parameters
const struct timespec64 *ts: inputstruct timespec64struct __kernel_timespec __user *uts: user'sstruct __kernel_timespec
Return
0 on success or negative errno on error
get_old_timespec32() #
int get user's old-format time value into kernel space
Parameters
struct timespec64 *ts: destinationstruct timespec64const void __user *uts: user's old-format time value (struct old_timespec32)
Description
Handles X86_X32_ABI compatibility conversion.
Return
0 on success or negative errno on error
put_old_timespec32() #
int convert timespec64 value to struct old_timespec32 and copy the latter to userspace
Parameters
const struct timespec64 *ts: inputstruct timespec64void __user *uts: user'sstruct old_timespec32
Description
Handles X86_X32_ABI compatibility conversion.
Return
0 on success or negative errno on error
get_itimerspec64() #
int get user's struct __kernel_itimerspec into kernel space
Parameters
struct itimerspec64 *it: destinationstruct itimerspec64const struct __kernel_itimerspec __user *uit: user'sstruct __kernel_itimerspec
Return
0 on success or negative errno on error
put_itimerspec64() #
int convert struct itimerspec64 to __kernel_itimerspec format and copy the latter to userspace
Parameters
const struct itimerspec64 *it: inputstruct itimerspec64struct __kernel_itimerspec __user *uit: user'sstruct __kernel_itimerspec
Return
0 on success or negative errno on error
get_old_itimerspec32() #
int get user's struct old_itimerspec32 into kernel space
Parameters
struct itimerspec64 *its: destinationstruct itimerspec64const struct old_itimerspec32 __user *uits: user'sstruct old_itimerspec32
Return
0 on success or negative errno on error
put_old_itimerspec32() #
int convert struct itimerspec64 to struct old_itimerspec32 and copy the latter to userspace
Parameters
const struct itimerspec64 *its: inputstruct itimerspec64struct old_itimerspec32 __user *uits: user'sstruct old_itimerspec32
Return
0 on success or negative errno on error
__round_jiffies_relative() #
unsigned long function to round jiffies to a full second
Parameters
unsigned long j: the time in (relative) jiffies that should be roundedint cpu: the processor number on which the timeout will happen
Description
__round_jiffies_relative() rounds a time delta in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.
By rounding these timers to whole seconds, all such timers will fire at the same time, rather than at various times spread out. The goal of this is to have the CPU wake up less, which saves power.
The exact rounding is skewed for each processor to avoid all processors firing at the exact same time, which could lead to lock contention or spurious cache line bouncing.
The return value is the rounded version of the j parameter.
round_jiffies() #
unsigned long function to round jiffies to a full second
Parameters
unsigned long j: the time in (absolute) jiffies that should be rounded
Description
round_jiffies() rounds an absolute time in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.
By rounding these timers to whole seconds, all such timers will fire at the same time, rather than at various times spread out. The goal of this is to have the CPU wake up less, which saves power.
The return value is the rounded version of the j parameter.
round_jiffies_relative() #
unsigned long function to round jiffies to a full second
Parameters
unsigned long j: the time in (relative) jiffies that should be rounded
Description
round_jiffies_relative() rounds a time delta in the future (in jiffies)
up or down to (approximately) full seconds. This is useful for timers
for which the exact time they fire does not matter too much, as long as
they fire approximately every X seconds.
By rounding these timers to whole seconds, all such timers will fire at the same time, rather than at various times spread out. The goal of this is to have the CPU wake up less, which saves power.
The return value is the rounded version of the j parameter.
__round_jiffies_up_relative() #
unsigned long function to round jiffies up to a full second
Parameters
unsigned long j: the time in (relative) jiffies that should be roundedint cpu: the processor number on which the timeout will happen
Description
This is the same as __round_jiffies_relative() except that it will never
round down. This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.
round_jiffies_up() #
unsigned long function to round jiffies up to a full second
Parameters
unsigned long j: the time in (absolute) jiffies that should be rounded
Description
This is the same as round_jiffies() except that it will never
round down. This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.
round_jiffies_up_relative() #
unsigned long function to round jiffies up to a full second
Parameters
unsigned long j: the time in (relative) jiffies that should be rounded
Description
This is the same as round_jiffies_relative() except that it will never
round down. This is useful for timeouts for which the exact time
of firing does not matter too much, as long as they don't fire too
early.
timer_init_key() #
void initialize a timer
Parameters
struct timer_list *timer: the timer to be initializedvoid (*func)(struct timer_list *): timer callback functionunsigned int flags: timer flagsconst char *name: name of the timerstruct lock_class_key *key: lockdep class key of the fake lock used for tracking timer sync lock dependencies
Description
timer_init_key() must be done to a timer prior to calling any of the
other timer functions.
mod_timer_pending() #
int Modify a pending timer's timeout
Parameters
struct timer_list *timer: The pending timer to be modifiedunsigned long expires: New absolute timeout in jiffies
Description
mod_timer_pending() is the same for pending timers as mod_timer(), but
will not activate inactive timers.
If timer->function == NULL then the start operation is silently discarded.
Return
0- The timer was inactive and not modified or was in shutdown state and the operation was discarded1- The timer was active and requeued to expire at expires
mod_timer() #
int Modify a timer's timeout
Parameters
struct timer_list *timer: The timer to be modifiedunsigned long expires: New absolute timeout in jiffies
Description
mod_timer(timer, expires) is equivalent to:
timer_delete(timer); timer->expires = expires; add_timer(timer);
mod_timer() is more efficient than the above open coded sequence. In
case that the timer is inactive, the timer_delete() part is a NOP. The
timer is in any case activated with the new expiry time expires.
Note that if there are multiple unserialized concurrent users of the
same timer, then mod_timer() is the only safe way to modify the timeout,
since add_timer() cannot modify an already running timer.
If timer->function == NULL then the start operation is silently discarded. In this case the return value is 0 and meaningless.
Return
0- The timer was inactive and started or was in shutdown state and the operation was discarded1- The timer was active and requeued to expire at expires or the timer was active and not modified because expires did not change the effective expiry time
timer_reduce() #
int Modify a timer's timeout if it would reduce the timeout
Parameters
struct timer_list *timer: The timer to be modifiedunsigned long expires: New absolute timeout in jiffies
Description
timer_reduce() is very similar to mod_timer(), except that it will only
modify an enqueued timer if that would reduce the expiration time. If
timer is not enqueued it starts the timer.
If timer->function == NULL then the start operation is silently discarded.
Return
0- The timer was inactive and started or was in shutdown state and the operation was discarded1- The timer was active and requeued to expire at expires or the timer was active and not modified because expires did not change the effective expiry time such that the timer would expire earlier than already scheduled
add_timer() #
void Start a timer
Parameters
struct timer_list *timer: The timer to be started
Description
Start timer to expire at timer->expires in the future. timer->expires is the absolute expiry time measured in 'jiffies'. When the timer expires timer->function(timer) will be invoked from soft interrupt context.
The timer->expires and timer->function fields must be set prior to calling this function.
If timer->function == NULL then the start operation is silently discarded.
If timer->expires is already in the past timer will be queued to expire at the next timer tick.
This can only operate on an inactive timer. Attempts to invoke this on an active timer are rejected with a warning.
add_timer_local() #
void Start a timer on the local CPU
Parameters
struct timer_list *timer: The timer to be started
Description
Same as add_timer() except that the timer flag TIMER_PINNED is set.
See add_timer() for further details.
add_timer_global() #
void Start a timer without TIMER_PINNED flag set
Parameters
struct timer_list *timer: The timer to be started
Description
Same as add_timer() except that the timer flag TIMER_PINNED is unset.
See add_timer() for further details.
add_timer_on() #
void Start a timer on a particular CPU
Parameters
struct timer_list *timer: The timer to be startedint cpu: The CPU to start it on
Description
Same as add_timer() except that it starts the timer on the given CPU and
the TIMER_PINNED flag is set. When timer shouldn't be a pinned timer in
the next round, add_timer_global() should be used instead as it unsets
the TIMER_PINNED flag.
See add_timer() for further details.
timer_delete() #
int Deactivate a timer
Parameters
struct timer_list *timer: The timer to be deactivated
Description
The function only deactivates a pending timer, but contrary to
timer_delete_sync() it does not take into account whether the timer's
callback function is concurrently executed on a different CPU or not.
It neither prevents rearming of the timer. If timer can be rearmed
concurrently then the return value of this function is meaningless.
Return
0- The timer was not pending1- The timer was pending and deactivated
timer_shutdown() #
int Deactivate a timer and prevent rearming
Parameters
struct timer_list *timer: The timer to be deactivated
Description
The function does not wait for an eventually running timer callback on a different CPU but it prevents rearming of the timer. Any attempt to arm timer after this function returns will be silently ignored.
This function is useful for teardown code and should only be used when
timer_shutdown_sync() cannot be invoked due to locking or context constraints.
Return
0- The timer was not pending1- The timer was pending
timer_delete_sync_try() #
int Try to deactivate a timer
Parameters
struct timer_list *timer: Timer to deactivate
Description
This function tries to deactivate a timer. On success the timer is not queued and the timer callback function is not running on any CPU.
This function does not guarantee that the timer cannot be rearmed right after dropping the base lock. That needs to be prevented by the calling code if necessary.
Return
0- The timer was not pending1- The timer was pending and deactivated-1- The timer callback function is running on a different CPU
timer_delete_sync() #
int Deactivate a timer and wait for the handler to finish.
Parameters
struct timer_list *timer: The timer to be deactivated
Description
Synchronization rules: Callers must prevent restarting of the timer,
otherwise this function is meaningless. It must not be called from
interrupt contexts unless the timer is an irqsafe one. The caller must
not hold locks which would prevent completion of the timer's callback
function. The timer's handler must not call add_timer_on(). Upon exit
the timer is not queued and the handler is not running on any CPU.
For !irqsafe timers, the caller must not hold locks that are held in interrupt context. Even if the lock has nothing to do with the timer in question. Here's why:
CPU0 CPU1
---- ----
<SOFTIRQ>
call_timer_fn();
base->running_timer = mytimer;
spin_lock_irq(somelock);
<IRQ>
spin_lock(somelock);
timer_delete_sync(mytimer);
while (base->running_timer == mytimer);
Now timer_delete_sync() will never return and never release somelock.
The interrupt on the other CPU is waiting to grab somelock but it has
interrupted the softirq that CPU0 is waiting to finish.
This function cannot guarantee that the timer is not rearmed again by some concurrent or preempting code, right after it dropped the base lock. If there is the possibility of a concurrent rearm then the return value of the function is meaningless.
If such a guarantee is needed, e.g. for teardown situations then use
timer_shutdown_sync() instead.
Return
0- The timer was not pending1- The timer was pending and deactivated
timer_shutdown_sync() #
int Shutdown a timer and prevent rearming
Parameters
struct timer_list *timer: The timer to be shutdown
Description
- When the function returns it is guaranteed that:
- timer is not queued
- The callback function of timer is not running
- timer cannot be enqueued again. Any attempt to rearm timer is silently ignored.
See timer_delete_sync() for synchronization rules.
This function is useful for final teardown of an infrastructure where the timer is subject to a circular dependency problem.
A common pattern for this is a timer and a workqueue where the timer can
schedule work and work can arm the timer. On shutdown the workqueue must
be destroyed and the timer must be prevented from rearming. Unless the
code has conditionals like 'if (mything->in_shutdown)' to prevent that
there is no way to get this correct with timer_delete_sync().
timer_shutdown_sync() is solving the problem. The correct ordering of
calls in this case is:
timer_shutdown_sync(mything->timer);
workqueue_destroy(mything->workqueue);
After this 'mything' can be safely freed.
This obviously implies that the timer is not required to be functional for the rest of the shutdown operation.
Return
0- The timer was not pending1- The timer was pending
High-resolution timers #
ktime_set() #
ktime_t Set a ktime_t variable from a seconds/nanoseconds value
Parameters
const s64 secs: seconds to setconst unsigned long nsecs: nanoseconds to set
Return
The ktime_t representation of the value.
ktime_compare() #
int Compares two ktime_t variables for less, greater or equal
Parameters
const ktime_t cmp1: comparable1const ktime_t cmp2: comparable2
Return
... cmp1 < cmp2: return <0 cmp1 == cmp2: return 0 cmp1 > cmp2: return >0
ktime_after() #
bool Compare if a ktime_t value is bigger than another one.
Parameters
const ktime_t cmp1: comparable1const ktime_t cmp2: comparable2
Return
true if cmp1 happened after cmp2.
ktime_before() #
bool Compare if a ktime_t value is smaller than another one.
Parameters
const ktime_t cmp1: comparable1const ktime_t cmp2: comparable2
Return
true if cmp1 happened before cmp2.
ktime_to_timespec64_cond() #
bool convert a ktime_t variable to timespec64 format only if the variable contains data
Parameters
const ktime_t kt: the ktime_t variable to convertstruct timespec64 *ts: the timespec variable to store the result in
Return
true if there was a successful conversion, false if kt was 0.
struct hrtimer_sleeper #
simple sleeper structure
Definition
;
Members
timer: embedded timer structuretask: task to wake up
Description
task is set to NULL, when the timer expires.
hrtimer_start() #
void (re)start an hrtimer
Parameters
struct hrtimer *timer: the timer to be addedktime_t tim: expiry timeconst enum hrtimer_mode mode: timer mode: absolute (HRTIMER_MODE_ABS) or relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED); softirq based mode is considered for debug purpose only!
hrtimer_get_remaining() #
ktime_t get remaining time for the timer
Parameters
const struct hrtimer *timer: the timer to read
hrtimer_is_queued() #
bool check, whether the timer is on one of the queues
Parameters
struct hrtimer *timer: Timer to check
Return
True if the timer is queued, false otherwise
Description
The function can be used lockless, but it gives only a current snapshot.
hrtimer_update_function() #
void Update the timer's callback function
Parameters
struct hrtimer *timer: Timer to updateenum hrtimer_restart (*function)(struct hrtimer *): New callback function
Description
Only safe to call if the timer is not enqueued. Can be called in the callback function if the timer is not enqueued at the same time (see the comments above HRTIMER_STATE_ENQUEUED).
hrtimer_forward_now() #
u64 forward the timer expiry so it expires after now
Parameters
struct hrtimer *timer: hrtimer to forwardktime_t interval: the interval to forward
Description
It is a variant of hrtimer_forward(). The timer will expire after the current
time of the hrtimer clock base. See hrtimer_forward() for details.
hrtimer_forward() #
u64 forward the timer expiry
Parameters
struct hrtimer *timer: hrtimer to forwardktime_t now: forward past this timektime_t interval: the interval to forward
Description
Forward the timer expiry so it will expire in the future.
There is also a variant of the function hrtimer_forward_now().
Context
Can be safely called from the callback function of timer. If called from other contexts timer must neither be enqueued nor running the callback and the caller needs to take care of serialization.
Return
The number of overruns are returned.
hrtimer_start_range_ns() #
void (re)start an hrtimer
Parameters
struct hrtimer *timer: the timer to be addedktime_t tim: expiry timeu64 delta_ns: "slack" range for the timerconst enum hrtimer_mode mode: timer mode: absolute (HRTIMER_MODE_ABS) or relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED); softirq based mode is considered for debug purpose only!
hrtimer_try_to_cancel() #
int try to deactivate a timer
Parameters
struct hrtimer *timer: hrtimer to stop
Description
- 0 when the timer was not active
- 1 when the timer was active
- -1 when the timer is currently executing the callback function and cannot be stopped
hrtimer_cancel() #
int cancel a timer and wait for the handler to finish.
Parameters
struct hrtimer *timer: the timer to be cancelled
Return
0 when the timer was not active 1 when the timer was active
__hrtimer_get_remaining() #
ktime_t get remaining time for the timer
Parameters
const struct hrtimer *timer: the timer to readbool adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y
hrtimer_setup() #
void initialize a timer to the given clock
Parameters
struct hrtimer *timer: the timer to be initializedenum hrtimer_restart (*function)(struct hrtimer *): the callback functionclockid_t clock_id: the clock to be usedenum hrtimer_mode mode: The modes which are relevant for initialization: HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT, HRTIMER_MODE_REL_SOFT
Description
The PINNED variants of the above can be handed in, but the PINNED bit is ignored as pinning happens when the hrtimer is started
hrtimer_setup_on_stack() #
void initialize a timer on stack memory
Parameters
struct hrtimer *timer: The timer to be initializedenum hrtimer_restart (*function)(struct hrtimer *): the callback functionclockid_t clock_id: The clock to be usedenum hrtimer_mode mode: The timer mode
Description
Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack
memory.
hrtimer_sleeper_start_expires() #
void Start a hrtimer sleeper timer
Parameters
struct hrtimer_sleeper *sl: sleeper to be startedenum hrtimer_mode mode: timer mode abs/rel
Description
Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
hrtimer_setup_sleeper_on_stack() #
void initialize a sleeper in stack memory
Parameters
struct hrtimer_sleeper *sl: sleeper to be initializedclockid_t clock_id: the clock to be usedenum hrtimer_mode mode: timer mode abs/rel
Wait queues and Wake events #
waitqueue_active() #
int - locklessly test for waiters on the queue
Parameters
struct wait_queue_head *wq_head: the waitqueue to test for waiters
Description
returns true if the wait list is not empty
NOTE
this function is lockless and requires care, incorrect usage will lead to sporadic and non-obvious failure.
Use either while holding wait_queue_head::lock or when used for wakeups
with an extra smp_mb() like:
CPU0 - waker CPU1 - waiter
for (;;) {
@cond = true; prepare_to_wait(&wq_head, &wait, state);
smp_mb(); // smp_mb() from set_current_state()
if (waitqueue_active(wq_head)) if (@cond)
wake_up(wq_head); break;
schedule();
}
finish_wait(&wq_head, &wait);
Because without the explicit smp_mb() it's possible for the
waitqueue_active() load to get hoisted over the cond store such that we'll
observe an empty wait list while the waiter might not observe cond.
Also note that this 'optimization' trades a spin_lock() for an smp_mb(),
which (when the lock is uncontended) are of roughly equal cost.
wq_has_single_sleeper() #
bool check if there is only one sleeper
Parameters
struct wait_queue_head *wq_head: wait queue head
Description
Returns true of wq_head has only one sleeper on the list.
Please refer to the comment for waitqueue_active.
wq_has_sleeper() #
bool check if there are any waiting processes
Parameters
struct wait_queue_head *wq_head: wait queue head
Description
Returns true if wq_head has waiting processes
Please refer to the comment for waitqueue_active.
wake_up_pollfree() #
void signal that a polled waitqueue is going away
Parameters
struct wait_queue_head *wq_head: the wait queue head
Description
In the very rare cases where a ->poll() implementation uses a waitqueue whose
lifetime is tied to a task rather than to the 'struct file' being polled,
this function must be called before the waitqueue is freed so that
non-blocking polls (e.g. epoll) are notified that the queue is going away.
The caller must also RCU-delay the freeing of the wait_queue_head, e.g. via
an explicit synchronize_rcu() or call_rcu(), or via SLAB_TYPESAFE_BY_RCU.
wait_event() #
sleep until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
wait_event_freezable() #
sleep (or freeze) until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE -- so as not to contribute to system load) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
wait_event_timeout() #
sleep until a condition gets true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, in jiffies
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
Return
0 if the condition evaluated to false after the timeout elapsed,
1 if the condition evaluated to true after the timeout elapsed,
or the remaining jiffies (at least 1) if the condition evaluated
to true before the timeout elapsed.
wait_event_cmd() #
sleep until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forcmd1: the command will be executed before sleepcmd2: the command will be executed after sleep
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
wait_event_interruptible() #
sleep until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_timeout() #
sleep until a condition gets true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, in jiffies
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
Return
0 if the condition evaluated to false after the timeout elapsed,
1 if the condition evaluated to true after the timeout elapsed,
the remaining jiffies (at least 1) if the condition evaluated
to true before the timeout elapsed, or -ERESTARTSYS if it was
interrupted by a signal.
wait_event_hrtimeout() #
sleep until a condition gets true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, as a ktime_t
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
The function returns 0 if condition became true, or -ETIME if the timeout elapsed.
wait_event_interruptible_hrtimeout() #
sleep until a condition gets true or a timeout elapses
Parameters
wq: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, as a ktime_t
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
The function returns 0 if condition became true, -ERESTARTSYS if it was interrupted by a signal, or -ETIME if the timeout elapsed.
wait_event_idle() #
wait for a condition without contributing to system load
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_IDLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
wait_event_idle_exclusive() #
wait for a condition with contributing to system load
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_IDLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag set thus if other processes wait on the same list, when this process is woken further processes are not considered.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
wait_event_idle_timeout() #
sleep without load until a condition becomes true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, in jiffies
Description
The process is put to sleep (TASK_IDLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
Return
0 if the condition evaluated to false after the timeout elapsed,
1 if the condition evaluated to true after the timeout elapsed,
or the remaining jiffies (at least 1) if the condition evaluated
to true before the timeout elapsed.
wait_event_idle_exclusive_timeout() #
sleep without load until a condition becomes true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, in jiffies
Description
The process is put to sleep (TASK_IDLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag set thus if other processes wait on the same list, when this process is woken further processes are not considered.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
Return
0 if the condition evaluated to false after the timeout elapsed,
1 if the condition evaluated to true after the timeout elapsed,
or the remaining jiffies (at least 1) if the condition evaluated
to true before the timeout elapsed.
wait_event_interruptible_locked() #
sleep until a condition gets true
Parameters
wq: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq is woken up.
It must be called with wq.lock being held. This spinlock is unlocked while sleeping but condition testing is done while lock is held and when this macro exits the lock is held.
The lock is locked/unlocked using spin_lock()/spin_unlock()
functions which must match the way they are locked/unlocked outside
of this macro.
wake_up_locked() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_locked_irq() #
sleep until a condition gets true
Parameters
wq: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq is woken up.
It must be called with wq.lock being held. This spinlock is unlocked while sleeping but condition testing is done while lock is held and when this macro exits the lock is held.
The lock is locked/unlocked using spin_lock_irq()/spin_unlock_irq()
functions which must match the way they are locked/unlocked outside
of this macro.
wake_up_locked() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_exclusive_locked() #
sleep exclusively until a condition gets true
Parameters
wq: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq is woken up.
It must be called with wq.lock being held. This spinlock is unlocked while sleeping but condition testing is done while lock is held and when this macro exits the lock is held.
The lock is locked/unlocked using spin_lock()/spin_unlock()
functions which must match the way they are locked/unlocked outside
of this macro.
The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag set thus when other process waits process on the list if this process is awaken further processes are not considered.
wake_up_locked() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_exclusive_locked_irq() #
sleep until a condition gets true
Parameters
wq: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq is woken up.
It must be called with wq.lock being held. This spinlock is unlocked while sleeping but condition testing is done while lock is held and when this macro exits the lock is held.
The lock is locked/unlocked using spin_lock_irq()/spin_unlock_irq()
functions which must match the way they are locked/unlocked outside
of this macro.
The process is put on the wait queue with an WQ_FLAG_EXCLUSIVE flag set thus when other process waits process on the list if this process is awaken further processes are not considered.
wake_up_locked() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_killable() #
sleep until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait for
Description
The process is put to sleep (TASK_KILLABLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_state() #
sleep until a condition gets true
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forstate: state to sleep in
Description
The process is put to sleep (state) until the condition evaluates to true or a signal is received (when allowed by state). The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
The function will return -ERESTARTSYS if it was interrupted by a signal (when allowed by state) and 0 if condition evaluated to true.
wait_event_killable_timeout() #
sleep until a condition gets true or a timeout elapses
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait fortimeout: timeout, in jiffies
Description
The process is put to sleep (TASK_KILLABLE) until the condition evaluates to true or a kill signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
Only kill signals interrupt this process.
Return
0 if the condition evaluated to false after the timeout elapsed,
1 if the condition evaluated to true after the timeout elapsed,
the remaining jiffies (at least 1) if the condition evaluated
to true before the timeout elapsed, or -ERESTARTSYS if it was
interrupted by a kill signal.
wait_event_lock_irq_cmd() #
sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forlock: a locked spinlock_t, which will be released before cmd andschedule()and reacquired afterwards.cmd: a command which is invoked outside the critical section before sleep
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
This is supposed to be called while holding the lock. The lock is dropped before invoking the cmd and going to sleep and is reacquired afterwards.
wait_event_lock_irq() #
sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forlock: a locked spinlock_t, which will be released beforeschedule()and reacquired afterwards.
Description
The process is put to sleep (TASK_UNINTERRUPTIBLE) until the condition evaluates to true. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
This is supposed to be called while holding the lock. The lock is dropped before going to sleep and is reacquired afterwards.
wait_event_interruptible_lock_irq_cmd() #
sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forlock: a locked spinlock_t, which will be released before cmd andschedule()and reacquired afterwards.cmd: a command which is invoked outside the critical section before sleep
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or a signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
This is supposed to be called while holding the lock. The lock is dropped before invoking the cmd and going to sleep and is reacquired afterwards.
The macro will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_lock_irq() #
sleep until a condition gets true. The condition is checked under the lock. This is expected to be called with the lock taken.
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forlock: a locked spinlock_t, which will be released beforeschedule()and reacquired afterwards.
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
This is supposed to be called while holding the lock. The lock is dropped before going to sleep and is reacquired afterwards.
The macro will return -ERESTARTSYS if it was interrupted by a signal and 0 if condition evaluated to true.
wait_event_interruptible_lock_irq_timeout() #
sleep until a condition gets true or a timeout elapses. The condition is checked under the lock. This is expected to be called with the lock taken.
Parameters
wq_head: the waitqueue to wait oncondition: a C expression for the event to wait forlock: a locked spinlock_t, which will be released beforeschedule()and reacquired afterwards.timeout: timeout, in jiffies
Description
The process is put to sleep (TASK_INTERRUPTIBLE) until the condition evaluates to true or signal is received. The condition is checked each time the waitqueue wq_head is woken up.
wake_up() has to be called after changing any variable that could
change the result of the wait condition.
This is supposed to be called while holding the lock. The lock is dropped before going to sleep and is reacquired afterwards.
The function returns 0 if the timeout elapsed, -ERESTARTSYS if it was interrupted by a signal, and the remaining jiffies otherwise if the condition evaluated to true before the timeout elapsed.
__wake_up() #
int wake up threads blocked on a waitqueue.
Parameters
struct wait_queue_head *wq_head: the waitqueueunsigned int mode: which threadsint nr_exclusive: how many wake-one or wake-many threads to wake upvoid *key: is directly passed to the wakeup function
Description
If this function wakes up a task, it executes a full memory barrier before accessing the task state. Returns the number of exclusive tasks that were awaken.
__wake_up_sync_key() #
void wake up threads blocked on a waitqueue.
Parameters
struct wait_queue_head *wq_head: the waitqueueunsigned int mode: which threadsvoid *key: opaque value to be passed to wakeup targets
Description
The sync wakeup differs that the waker knows that it will schedule away soon, so while the target thread will be woken up, it will not be migrated to another CPU - ie. the two threads are 'synchronized' with each other. This can prevent needless bouncing between CPUs.
On UP it can prevent extra preemption.
If this function wakes up a task, it executes a full memory barrier before accessing the task state.
__wake_up_locked_sync_key() #
void wake up a thread blocked on a locked waitqueue.
Parameters
struct wait_queue_head *wq_head: the waitqueueunsigned int mode: which threadsvoid *key: opaque value to be passed to wakeup targets
Description
The sync wakeup differs in that the waker knows that it will schedule away soon, so while the target thread will be woken up, it will not be migrated to another CPU - ie. the two threads are 'synchronized' with each other. This can prevent needless bouncing between CPUs.
On UP it can prevent extra preemption.
If this function wakes up a task, it executes a full memory barrier before accessing the task state.
finish_wait() #
void clean up after waiting in a queue
Parameters
struct wait_queue_head *wq_head: waitqueue waited onstruct wait_queue_entry *wq_entry: wait descriptor
Description
Sets current thread back to running state and removes the wait descriptor from the given waitqueue if still queued.
Internal Functions #
wait_task_stopped() #
int Wait for TASK_STOPPED or TASK_TRACED
Parameters
struct wait_opts *wo: wait optionsint ptrace: is the wait for ptracestruct task_struct *p: task to wait for
Description
Handle sys_wait4() work for p in state TASK_STOPPED or TASK_TRACED.
Context
read_lock(tasklist_lock), which is released if return value is
non-zero. Also, grabs and releases p->sighand->siglock.
Return
0 if wait condition didn't exist and search for other wait conditions should continue. Non-zero return, -errno on failure and p's pid on success, implies that tasklist_lock is released and wait condition search should terminate.
task_set_jobctl_pending() #
bool set jobctl pending bits
Parameters
struct task_struct *task: target taskunsigned long mask: pending bits to set
Description
Clear mask from task->jobctl. mask must be subset of
JOBCTL_PENDING_MASK | JOBCTL_STOP_CONSUME | JOBCTL_STOP_SIGMASK |
JOBCTL_TRAPPING. If stop signo is being set, the existing signo is
cleared. If task is already being killed or exiting, this function
becomes noop.
Context
Must be called with task->sighand->siglock held.
Return
true if mask is set, false if made noop because task was dying.
task_clear_jobctl_trapping() #
void clear jobctl trapping bit
Parameters
struct task_struct *task: target task
Description
If JOBCTL_TRAPPING is set, a ptracer is waiting for us to enter TRACED. Clear it and wake up the ptracer. Note that we don't need any further locking. task->siglock guarantees that task->parent points to the ptracer.
Context
Must be called with task->sighand->siglock held.
task_clear_jobctl_pending() #
void clear jobctl pending bits
Parameters
struct task_struct *task: target taskunsigned long mask: pending bits to clear
Description
Clear mask from task->jobctl. mask must be subset of
JOBCTL_PENDING_MASK. If JOBCTL_STOP_PENDING is being cleared, other
STOP bits are cleared together.
If clearing of mask leaves no stop or trap pending, this function calls
task_clear_jobctl_trapping().
Context
Must be called with task->sighand->siglock held.
task_participate_group_stop() #
bool participate in a group stop
Parameters
struct task_struct *task: task participating in a group stop
Description
task has JOBCTL_STOP_PENDING set and is participating in a group stop.
Group stop states are cleared and the group stop count is consumed if
JOBCTL_STOP_CONSUME was set. If the consumption completes the group
stop, the appropriate SIGNAL_* flags are set.
Context
Must be called with task->sighand->siglock held.
Return
true if group stop completion should be notified to the parent, false
otherwise.
ptrace_trap_notify() #
void schedule trap to notify ptracer
Parameters
struct task_struct *t: tracee wanting to notify tracer
Description
This function schedules sticky ptrace trap which is cleared on the next TRAP_STOP to notify ptracer of an event. t must have been seized by ptracer.
If t is running, STOP trap will be taken. If trapped for STOP and ptracer is listening for events, tracee is woken up so that it can re-trap for the new event. If trapped otherwise, STOP trap will be eventually taken without returning to userland after the existing traps are finished by PTRACE_CONT.
Context
Must be called with task->sighand->siglock held.
force_sig_seccomp() #
int signals the task to allow in-process syscall emulation
Parameters
int syscall: syscall number to send to userlandint reason: filter-supplied reason code to send to userland (via si_errno)bool force_coredump: true to trigger a coredump
Description
Forces a SIGSYS with a code of SYS_SECCOMP and related sigsys info.
do_notify_parent_cldstop() #
void notify parent of stopped/continued state change
Parameters
struct task_struct *tsk: task reporting the state changebool for_ptracer: the notification is for ptracerint why: CLD_{CONTINUED|STOPPED|TRAPPED} to report
Description
Notify tsk's parent that the stopped/continued state has changed. If
for_ptracer is false, tsk's group leader notifies to its real parent.
If true, tsk reports to tsk->parent which should be the ptracer.
Context
Must be called with tasklist_lock at least read locked.
do_signal_stop() #
bool handle group stop for SIGSTOP and other stop signals
Parameters
int signr: signr causing group stop if initiating
Description
If JOBCTL_STOP_PENDING is not set yet, initiate group stop with signr
and participate in it. If already set, participate in the existing
group stop. If participated in a group stop (and thus slept), true is
returned with siglock released.
If ptraced, this function doesn't handle stop itself. Instead,
JOBCTL_TRAP_STOP is scheduled and false is returned with siglock
untouched. The caller must ensure that INTERRUPT trap handling takes
places afterwards.
Context
Must be called with current->sighand->siglock held, which is released
on true return.
Return
false if group stop is already cancelled or ptrace trap is scheduled.
true if participated in group stop.
do_jobctl_trap() #
void take care of ptrace jobctl traps
Parameters
void: no arguments
Description
When PT_SEIZED, it's used for both group stop and explicit
SEIZE/INTERRUPT traps. Both generate PTRACE_EVENT_STOP trap with
accompanying siginfo. If stopped, lower eight bits of exit_code contain
the stop signal; otherwise, SIGTRAP.
When !PT_SEIZED, it's used only for group stop trap with stop signal number as exit_code and no siginfo.
Context
Must be called with current->sighand->siglock held, which may be released and re-acquired before returning with intervening sleep.
do_freezer_trap() #
void handle the freezer jobctl trap
Parameters
void: no arguments
Description
Puts the task into frozen state, if only the task is not about to quit. In this case it drops JOBCTL_TRAP_FREEZE.
Context
Must be called with current->sighand->siglock held, which is always released before returning.
signal_delivered() #
void called after signal delivery to update blocked signals
Parameters
struct ksignal *ksig: kernel signal structint stepping: nonzero if debugger single-step or block-step in use
Description
This function should be called when a signal has successfully been
delivered. It updates the blocked signals accordingly (ksig->ka.sa.sa_mask
is always blocked), and the signal itself is blocked unless SA_NODEFER
is set in ksig->ka.sa.sa_flags. Tracing is notified.
sys_restart_syscall() #
long restart a system call
Parameters
void: no arguments
set_current_blocked() #
void change current->blocked mask
Parameters
sigset_t *newset: new mask
Description
It is wrong to change ->blocked directly, this helper should be used to ensure the process can't miss a shared signal we are going to block.
sys_rt_sigprocmask() #
long change the list of currently blocked signals
Parameters
int how: whether to add, remove, or set signalssigset_t __user * nset: stores pending signalssigset_t __user * oset: previous value of signal mask if non-nullsize_t sigsetsize: size of sigset_t type
sys_rt_sigpending() #
long examine a pending signal that has been raised while blocked
Parameters
sigset_t __user * uset: stores pending signalssize_t sigsetsize: size of sigset_t type or larger
copy_siginfo_to_external32() #
void copy a kernel siginfo into a compat user siginfo
Parameters
struct compat_siginfo *to: compat siginfo destinationconst struct kernel_siginfo *from: kernel siginfo source
Note
This function does not work properly for the SIGCHLD on x32, but fortunately it doesn't have to. The only valid callers for this function are copy_siginfo_to_user32, which is overriden for x32 and the coredump code. The latter does not care because SIGCHLD will never cause a coredump.
do_sigtimedwait() #
int wait for queued signals specified in which
Parameters
const sigset_t *which: queued signals to wait forkernel_siginfo_t *info: if non-null, the signal's siginfo is returned hereconst struct timespec64 *ts: upper bound on process time suspension
sys_rt_sigtimedwait() #
long synchronously wait for queued signals specified in uthese
Parameters
const sigset_t __user * uthese: queued signals to wait forsiginfo_t __user * uinfo: if non-null, the signal's siginfo is returned hereconst struct __kernel_timespec __user * uts: upper bound on process time suspensionsize_t sigsetsize: size of sigset_t type
sys_kill() #
long send a signal to a process
Parameters
pid_t pid: the PID of the processint sig: signal to be sent
sys_pidfd_send_signal() #
long Signal a process through a pidfd
Parameters
int pidfd: file descriptor of the processint sig: signal to sendsiginfo_t __user * info: signal infounsigned int flags: future flags
Description
Send the signal to the thread group or to the individual thread depending on PIDFD_THREAD. In the future extension to flags may be used to override the default scope of pidfd.
Return
0 on success, negative errno on failure
sys_tgkill() #
long send signal to one specific thread
Parameters
pid_t tgid: the thread group ID of the threadpid_t pid: the PID of the threadint sig: signal to be sent
Description
This syscall also checks the tgid and returns -ESRCH even if the PID exists but it's not belonging to the target process anymore. This method solves the problem of threads exiting and PIDs getting reused.
sys_tkill() #
long send signal to one specific task
Parameters
pid_t pid: the PID of the taskint sig: signal to be sent
Description
Send a signal to only one task, even if it's a CLONE_THREAD task.
sys_rt_sigqueueinfo() #
long send signal information to a signal
Parameters
pid_t pid: the PID of the threadint sig: signal to be sentsiginfo_t __user * uinfo: signal info to be sent
sys_sigpending() #
long examine pending signals
Parameters
old_sigset_t __user * uset: where mask of pending signal is returned
sys_sigprocmask() #
long examine and change blocked signals
Parameters
int how: whether to add, remove, or set signalsold_sigset_t __user * nset: signals to add or remove (if non-null)old_sigset_t __user * oset: previous value of signal mask if non-null
Description
Some platforms have their own version with special arguments; others support only sys_rt_sigprocmask.
sys_rt_sigaction() #
long alter an action taken by a process
Parameters
int sig: signal to be sentconst struct sigaction __user * act: new sigactionstruct sigaction __user * oact: used to save the previous sigactionsize_t sigsetsize: size of sigset_t type
sys_rt_sigsuspend() #
long replace the signal mask for a value with the unewset value until a signal is received
Parameters
sigset_t __user * unewset: new signal mask valuesize_t sigsetsize: size of sigset_t type
kthread_create() #
create a kthread on the current node
Parameters
threadfn: the function to run in the threaddata: data pointer for threadfn()namefmt: printf-style format string for the thread namearg...: arguments for namefmt.
Description
This macro will create a kthread on the current node, leaving it in
the stopped state. This is just a helper for kthread_create_on_node();
see the documentation there for more details.
kthread_run() #
create and wake a thread.
Parameters
threadfn: the function to run until signal_pending(current).data: data ptr for threadfn.namefmt: printf-style name for the thread....: variable arguments
Description
Convenient wrapper for kthread_create() followed by
wake_up_process(). Returns the kthread or ERR_PTR(-ENOMEM).
kthread_run_on_cpu() #
struct task_struct * create and wake a cpu bound thread.
Parameters
int (*threadfn)(void *data): the function to run until signal_pending(current).void *data: data ptr for threadfn.unsigned int cpu: The cpu on which the thread should be bound,const char *namefmt: printf-style name for the thread. Format is restricted to "name.*u". Code fills in cpu number.
Description
Convenient wrapper for kthread_create_on_cpu()
followed by wake_up_process(). Returns the kthread or
ERR_PTR(-ENOMEM).
kthread_run_worker() #
create and wake a kthread worker.
Parameters
flags: flags modifying the default behavior of the workernamefmt: printf-style name for the thread....: variable arguments
Description
Convenient wrapper for kthread_create_worker() followed by
wake_up_process(). Returns the kthread_worker or ERR_PTR(-ENOMEM).
kthread_run_worker_on_cpu() #
struct kthread_worker * create and wake a cpu bound kthread worker.
Parameters
int cpu: CPU numberunsigned int flags: flags modifying the default behavior of the workerconst char namefmt[]: printf-style name for the thread. Format is restricted to "name.*u". Code fills in cpu number.
Description
Convenient wrapper for kthread_create_worker_on_cpu()
followed by wake_up_process(). Returns the kthread_worker or
ERR_PTR(-ENOMEM).
kthread_should_stop() #
bool should this kthread return now?
Parameters
void: no arguments
Description
When someone calls kthread_stop() on your kthread, it will be woken
and this will return true. You should then return, and your return
value will be passed through to kthread_stop().
kthread_should_park() #
bool should this kthread park now?
Parameters
void: no arguments
Description
When someone calls kthread_park() on your kthread, it will be woken
and this will return true. You should then do the necessary
cleanup and call kthread_parkme()
Similar to kthread_should_stop(), but this keeps the thread alive
and in a park position. kthread_unpark() "restarts" the thread and
calls the thread function again.
kthread_freezable_should_stop() #
bool should this freezable kthread return now?
Parameters
bool *was_frozen: optional out parameter, indicates whethercurrentwas frozen
Description
kthread_should_stop() for freezable kthreads, which will enter
refrigerator if necessary. This function is safe from kthread_stop() /
freezer deadlock and freezable kthreads should use this function instead
of calling try_to_freeze() directly.
kthread_func() #
void * return the function specified on kthread creation
Parameters
struct task_struct *task: kthread task in question
Description
Returns NULL if the task is not a kthread.
kthread_data() #
void * return data value specified on kthread creation
Parameters
struct task_struct *task: kthread task in question
Description
Return the data value specified when kthread task was created. The caller is responsible for ensuring the validity of task when calling this function.
kthread_complete_and_exit() #
void __noreturn Exit the current kthread.
Parameters
struct completion *comp: Completion to completelong code: The integer value to return tokthread_stop().
Description
If present, complete comp and then return code to kthread_stop().
A kernel thread whose module may be removed after the completion of comp can use this function to exit safely.
Does not return.
kthread_create_on_node() #
struct task_struct * create a kthread.
Parameters
int (*threadfn)(void *data): the function to run until signal_pending(current).void *data: data ptr for threadfn.int node: task and thread structures for the thread are allocated on this nodeconst char namefmt[]: printf-style name for the thread....: variable arguments
Description
This helper function creates and names a kernel
thread. The thread will be stopped: use wake_up_process() to start
it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
is affine to all CPUs.
If thread is going to be bound on a particular cpu, give its node
in node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
When woken, the thread will run threadfn() with data as its
argument. threadfn() can either return directly if it is a
standalone thread for which no one will call kthread_stop(), or
return when 'kthread_should_stop()' is true (which means
kthread_stop() has been called). The return value should be zero
or a negative error number; it will be passed to kthread_stop().
Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
kthread_bind() #
void bind a just-created kthread to a cpu.
Parameters
struct task_struct *p: thread created bykthread_create().unsigned int cpu: cpu (might not be online, must be possible) for k to run on.
Description
This function is equivalent to set_cpus_allowed(),
except that cpu doesn't need to be online, and the thread must be
stopped (i.e., just returned from kthread_create()).
kthread_create_on_cpu() #
struct task_struct * Create a cpu bound kthread
Parameters
int (*threadfn)(void *data): the function to run until signal_pending(current).void *data: data ptr for threadfn.unsigned int cpu: The cpu on which the thread should be bound,const char *namefmt: printf-style name for the thread. Format is restricted to "name.*u". Code fills in cpu number.
Description
This helper function creates and names a kernel thread
kthread_unpark() #
void unpark a thread created by kthread_create().
Parameters
struct task_struct *k: thread created bykthread_create().
Description
Sets kthread_should_park() for k to return false, wakes it, and
waits for it to return. If the thread is marked percpu then its
bound to the cpu again.
kthread_park() #
int park a thread created by kthread_create().
Parameters
struct task_struct *k: thread created bykthread_create().
Description
Sets kthread_should_park() for k to return true, wakes it, and
waits for it to return. This can also be called after kthread_create()
instead of calling wake_up_process(): the thread will park without
calling threadfn().
Returns 0 if the thread is parked, -ENOSYS if the thread exited. If called by the kthread itself just the park bit is set.
kthread_stop() #
int stop a thread created by kthread_create().
Parameters
struct task_struct *k: thread created bykthread_create().
Description
Sets kthread_should_stop() for k to return true, wakes it, and
waits for it to exit. This can also be called after kthread_create()
instead of calling wake_up_process(): the thread will exit without
calling threadfn().
If threadfn() may call kthread_exit() itself, the caller must ensure
task_struct can't go away.
Returns the result of threadfn(), or -EINTR if wake_up_process()
was never called.
kthread_stop_put() #
int stop a thread and put its task struct
Parameters
struct task_struct *k: thread created bykthread_create().
Description
Stops a thread created by kthread_create() and put its task_struct.
Only use when holding an extra task struct reference obtained by
calling get_task_struct().
kthread_affine_preferred() #
int Define a kthread's preferred affinity
Parameters
struct task_struct *p: thread created bykthread_create().const struct cpumask *mask: preferred mask of CPUs (might not be online, must be possible) for p to run on.
Description
Similar to kthread_bind_mask() except that the affinity is not a requirement
but rather a preference that can be constrained by CPU isolation or CPU hotplug.
Must be called before the first wakeup of the kthread.
Returns 0 if the affinity has been applied.
kthread_worker_fn() #
int kthread function to process kthread_worker
Parameters
void *worker_ptr: pointer to initialized kthread_worker
Description
This function implements the main cycle of kthread worker. It processes
work_list until it is stopped with kthread_stop(). It sleeps when the queue
is empty.
The works are not allowed to keep any locks, disable preemption or interrupts when they finish. There is defined a safe point for freezing when one work finishes and before a new one is started.
Also the works must not be handled by more than one worker at the same time,
see also kthread_queue_work().
kthread_create_worker_on_node() #
struct kthread_worker * create a kthread worker
Parameters
unsigned int flags: flags modifying the default behavior of the workerint node: task structure for the thread is allocated on this nodeconst char namefmt[]: printf-style name for the kthread worker (task)....: variable arguments
Description
Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM) when the needed structures could not get allocated, and ERR_PTR(-EINTR) when the caller was killed by a fatal signal.
kthread_create_worker_on_cpu() #
struct kthread_worker * create a kthread worker and bind it to a given CPU and the associated NUMA node.
Parameters
int cpu: CPU numberunsigned int flags: flags modifying the default behavior of the workerconst char namefmt[]: printf-style name for the thread. Format is restricted to "name.*u". Code fills in cpu number.
Description
Use a valid CPU number if you want to bind the kthread worker to the given CPU and the associated NUMA node.
A good practice is to add the cpu number also into the worker name.
For example, use kthread_create_worker_on_cpu(cpu, "helper/d", cpu).
CPU hotplug: The kthread worker API is simple and generic. It just provides a way to create, use, and destroy workers.
It is up to the API user how to handle CPU hotplug. They have to decide how to handle pending work items, prevent queuing new ones, and restore the functionality when the CPU goes off and on. There are a few catches:
-
CPU affinity gets lost when it is scheduled on an offline CPU.
-
The worker might not exist when the CPU was off when the user created the workers.
Good practice is to implement two CPU hotplug callbacks and to destroy/create the worker when the CPU goes down/up.
Return
The pointer to the allocated worker on success, ERR_PTR(-ENOMEM) when the needed structures could not get allocated, and ERR_PTR(-EINTR) when the caller was killed by a fatal signal.
kthread_queue_work() #
bool queue a kthread_work
Parameters
struct kthread_worker *worker: target kthread_workerstruct kthread_work *work: kthread_work to queue
Description
Queue work to work processor task for async execution. task
must have been created with kthread_create_worker(). Returns true
if work was successfully queued, false if it was already pending.
Reinitialize the work if it needs to be used by another worker. For example, when the worker was stopped and started again.
kthread_delayed_work_timer_fn() #
void callback that queues the associated kthread delayed work when the timer expires.
Parameters
struct timer_list *t: pointer to the expired timer
Description
The format of the function is defined by struct timer_list. It should have been called from irqsafe timer with irq already off.
kthread_queue_delayed_work() #
bool queue the associated kthread work after a delay.
Parameters
struct kthread_worker *worker: target kthread_workerstruct kthread_delayed_work *dwork: kthread_delayed_work to queueunsigned long delay: number of jiffies to wait before queuing
Description
If the work has not been pending it starts a timer that will queue the work after the given delay. If delay is zero, it queues the work immediately.
Return
false if the work has already been pending. It means that
either the timer was running or the work was queued. It returns true
otherwise.
kthread_flush_work() #
void flush a kthread_work
Parameters
struct kthread_work *work: work to flush
Description
If work is queued or executing, wait for it to finish execution.
kthread_mod_delayed_work() #
bool modify delay of or queue a kthread delayed work
Parameters
struct kthread_worker *worker: kthread worker to usestruct kthread_delayed_work *dwork: kthread delayed work to queueunsigned long delay: number of jiffies to wait before queuing
Description
If dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
modify dwork's timer so that it expires after delay. If delay is zero,
work is guaranteed to be queued immediately.
A special case is when the work is being canceled in parallel.
It might be caused either by the real kthread_cancel_delayed_work_sync()
or yet another kthread_mod_delayed_work() call. We let the other command
win and return true here. The return value can be used for reference
counting and the number of queued works stays the same. Anyway, the caller
is supposed to synchronize these operations a reasonable way.
This function is safe to call from any context including IRQ handler.
See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
for details.
Return
false if dwork was idle and queued, true otherwise.
kthread_cancel_work_sync() #
bool cancel a kthread work and wait for it to finish
Parameters
struct kthread_work *work: the kthread work to cancel
Description
Cancel work and wait for its execution to finish. This function can be used even if the work re-queues itself. On return from this function, work is guaranteed to be not pending or executing on any CPU.
kthread_cancel_work_sync(delayed_work->work) must not be used for
delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
The caller must ensure that the worker on which work was last queued can't be destroyed before this function returns.
Return
true if work was pending, false otherwise.
kthread_cancel_delayed_work_sync() #
bool cancel a kthread delayed work and wait for it to finish.
Parameters
struct kthread_delayed_work *dwork: the kthread delayed work to cancel
Description
This is kthread_cancel_work_sync() for delayed works.
Return
true if dwork was pending, false otherwise.
kthread_flush_worker() #
void flush all current works on a kthread_worker
Parameters
struct kthread_worker *worker: worker to flush
Description
Wait until all currently executing or pending works on worker are finished.
kthread_destroy_worker() #
void destroy a kthread worker
Parameters
struct kthread_worker *worker: worker to be destroyed
Description
Flush and destroy worker. The simple flush is enough because the kthread worker API is used only in trivial scenarios. There are no multi-step state machines needed.
Note that this function is not responsible for handling delayed work, so caller should be responsible for queuing or canceling all delayed work items before invoke this function.
kthread_use_mm() #
void make the calling kthread operate on an address space
Parameters
struct mm_struct *mm: address space to operate on
kthread_unuse_mm() #
void reverse the effect of kthread_use_mm()
Parameters
struct mm_struct *mm: address space to operate on
kthread_associate_blkcg() #
void associate blkcg to current kthread
Parameters
struct cgroup_subsys_state *css: the cgroup info
Description
Current thread must be a kthread. The thread is running jobs on behalf of other threads. In some cases, we expect the jobs attach cgroup info of original threads instead of that of current thread. This function stores original thread's cgroup info in current kthread context for later retrieval.
Reference counting #
refcount_set() #
void set a refcount's value
Parameters
refcount_t *r: the refcountint n: value to which the refcount will be set
refcount_set_release() #
void set a refcount's value with release ordering
Parameters
refcount_t *r: the refcountint n: value to which the refcount will be set
Description
This function should be used when memory occupied by the object might be reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.
Provides release memory ordering which will order previous memory operations against this store. This ensures all updates to this object are visible once the refcount is set and stale values from the object previously occupying this memory are overwritten with new ones.
This function should be called only after new object is fully initialized. After this call the object should be considered visible to other tasks even if it was not yet added into an object collection normally used to discover it. This is because other tasks might have discovered the object previously occupying the same memory and after memory reuse they can succeed in taking refcount to the new object and start using it.
refcount_read() #
unsigned int get a refcount's value
Parameters
const refcount_t *r: the refcount
Return
the refcount's value
refcount_add_not_zero() #
bool add a value to a refcount unless it is 0
Parameters
int i: the value to add to the refcountrefcount_t *r: the refcount
Description
Will saturate at REFCOUNT_SATURATED and WARN.
Provides no memory ordering, it is assumed the caller has guaranteed the object memory to be stable (RCU, etc.). It does provide a control dependency and thereby orders future stores. See the comment on top.
Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time. In these
cases, refcount_inc(), or one of its variants, should instead be used to
increment a reference count.
Return
false if the passed refcount is 0, true otherwise
refcount_add_not_zero_acquire() #
bool add a value to a refcount with acquire ordering unless it is 0
Parameters
int i: the value to add to the refcountrefcount_t *r: the refcount
Description
Will saturate at REFCOUNT_SATURATED and WARN.
This function should be used when memory occupied by the object might be reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.
Provides acquire memory ordering on success, it is assumed the caller has guaranteed the object memory to be stable (RCU, etc.). It does provide a control dependency and thereby orders future stores. See the comment on top.
Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time. In these
cases, refcount_inc_not_zero_acquire() should instead be used to increment a
reference count.
Return
false if the passed refcount is 0, true otherwise
refcount_add() #
void add a value to a refcount
Parameters
int i: the value to add to the refcountrefcount_t *r: the refcount
Description
Similar to atomic_add(), but will saturate at REFCOUNT_SATURATED and WARN.
Provides no memory ordering, it is assumed the caller has guaranteed the object memory to be stable (RCU, etc.). It does provide a control dependency and thereby orders future stores. See the comment on top.
Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time. In these
cases, refcount_inc(), or one of its variants, should instead be used to
increment a reference count.
refcount_inc_not_zero() #
bool increment a refcount unless it is 0
Parameters
refcount_t *r: the refcount to increment
Description
Similar to atomic_inc_not_zero(), but will saturate at REFCOUNT_SATURATED
and WARN.
Provides no memory ordering, it is assumed the caller has guaranteed the object memory to be stable (RCU, etc.). It does provide a control dependency and thereby orders future stores. See the comment on top.
Return
true if the increment was successful, false otherwise
refcount_inc_not_zero_acquire() #
bool increment a refcount with acquire ordering unless it is 0
Parameters
refcount_t *r: the refcount to increment
Description
Similar to refcount_inc_not_zero(), but provides acquire memory ordering on
success.
This function should be used when memory occupied by the object might be reused to store another object -- consider SLAB_TYPESAFE_BY_RCU.
Provides acquire memory ordering on success, it is assumed the caller has guaranteed the object memory to be stable (RCU, etc.). It does provide a control dependency and thereby orders future stores. See the comment on top.
Return
true if the increment was successful, false otherwise
refcount_inc() #
void increment a refcount
Parameters
refcount_t *r: the refcount to increment
Description
Similar to atomic_inc(), but will saturate at REFCOUNT_SATURATED and WARN.
Provides no memory ordering, it is assumed the caller already has a reference on the object.
Will WARN if the refcount is 0, as this represents a possible use-after-free condition.
refcount_sub_and_test() #
bool subtract from a refcount and test if it is 0
Parameters
int i: amount to subtract from the refcountrefcount_t *r: the refcount
Description
Similar to atomic_dec_and_test(), but it will WARN, return false and
ultimately leak on underflow and will fail to decrement when saturated
at REFCOUNT_SATURATED.
Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that free()
must come after.
Use of this function is not recommended for the normal reference counting
use case in which references are taken and released one at a time. In these
cases, refcount_dec(), or one of its variants, should instead be used to
decrement a reference count.
Return
true if the resulting refcount is 0, false otherwise
refcount_dec_and_test() #
bool decrement a refcount and test if it is 0
Parameters
refcount_t *r: the refcount
Description
Similar to atomic_dec_and_test(), it will WARN on underflow and fail to
decrement when saturated at REFCOUNT_SATURATED.
Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that free()
must come after.
Return
true if the resulting refcount is 0, false otherwise
refcount_dec() #
void decrement a refcount
Parameters
refcount_t *r: the refcount
Description
Similar to atomic_dec(), it will WARN on underflow and fail to decrement
when saturated at REFCOUNT_SATURATED.
Provides release memory ordering, such that prior loads and stores are done before.
refcount_dec_if_one() #
bool decrement a refcount if it is 1
Parameters
refcount_t *r: the refcount
Description
No atomic_t counterpart, it attempts a 1 -> 0 transition and returns the success thereof.
Like all decrement operations, it provides release memory order and provides a control dependency.
It can be used like a try-delete operator; this explicit case is provided and not cmpxchg in generic, because that would allow implementing unsafe operations.
Return
true if the resulting refcount is 0, false otherwise
refcount_dec_not_one() #
bool decrement a refcount if it is not 1
Parameters
refcount_t *r: the refcount
Description
No atomic_t counterpart, it decrements unless the value is 1, in which case it will return false.
Was often done like: atomic_add_unless(var, -1, 1)
Return
true if the decrement operation was successful, false otherwise
refcount_dec_and_mutex_lock() #
bool return holding mutex if able to decrement refcount to 0
Parameters
refcount_t *r: the refcountstruct mutex *lock: the mutex to be locked
Description
Similar to atomic_dec_and_mutex_lock(), it will WARN on underflow and fail
to decrement when saturated at REFCOUNT_SATURATED.
Provides release memory ordering, such that prior loads and stores are done
before, and provides a control dependency such that free() must come after.
See the comment on top.
Return
true and hold mutex if able to decrement refcount to 0, false otherwise
refcount_dec_and_lock() #
bool return holding spinlock if able to decrement refcount to 0
Parameters
refcount_t *r: the refcountspinlock_t *lock: the spinlock to be locked
Description
Similar to atomic_dec_and_lock(), it will WARN on underflow and fail to
decrement when saturated at REFCOUNT_SATURATED.
Provides release memory ordering, such that prior loads and stores are done
before, and provides a control dependency such that free() must come after.
See the comment on top.
Return
true and hold spinlock if able to decrement refcount to 0, false otherwise
refcount_dec_and_lock_irqsave() #
bool return holding spinlock with disabled interrupts if able to decrement refcount to 0
Parameters
refcount_t *r: the refcountspinlock_t *lock: the spinlock to be lockedunsigned long *flags: saved IRQ-flags if the is acquired
Description
Same as refcount_dec_and_lock() above except that the spinlock is acquired
with disabled interrupts.
Return
true and hold spinlock if able to decrement refcount to 0, false otherwise
Atomics #
atomic_read() #
int atomic load with relaxed ordering
Parameters
const atomic_t *v: pointer to atomic_t
Description
Atomically loads the value of v with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_read() there.
Return
The value loaded from v.
atomic_read_acquire() #
int atomic load with acquire ordering
Parameters
const atomic_t *v: pointer to atomic_t
Description
Atomically loads the value of v with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_read_acquire() there.
Return
The value loaded from v.
atomic_set() #
void atomic set with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint i: int value to assign
Description
Atomically sets v to i with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_set() there.
Return
Nothing.
atomic_set_release() #
void atomic set with release ordering
Parameters
atomic_t *v: pointer to atomic_tint i: int value to assign
Description
Atomically sets v to i with release ordering.
Unsafe to use in noinstr code; use raw_atomic_set_release() there.
Return
Nothing.
atomic_add() #
void atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_add() there.
Return
Nothing.
atomic_add_return() #
int atomic add with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_add_return() there.
Return
The updated value of v.
atomic_add_return_acquire() #
int atomic add with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_add_return_acquire() there.
Return
The updated value of v.
atomic_add_return_release() #
int atomic add with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_add_return_release() there.
Return
The updated value of v.
atomic_add_return_relaxed() #
int atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_add_return_relaxed() there.
Return
The updated value of v.
atomic_fetch_add() #
int atomic add with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_add() there.
Return
The original value of v.
atomic_fetch_add_acquire() #
int atomic add with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_add_acquire() there.
Return
The original value of v.
atomic_fetch_add_release() #
int atomic add with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_add_release() there.
Return
The original value of v.
atomic_fetch_add_relaxed() #
int atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_add_relaxed() there.
Return
The original value of v.
atomic_sub() #
void atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_sub() there.
Return
Nothing.
atomic_sub_return() #
int atomic subtract with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_sub_return() there.
Return
The updated value of v.
atomic_sub_return_acquire() #
int atomic subtract with acquire ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_sub_return_acquire() there.
Return
The updated value of v.
atomic_sub_return_release() #
int atomic subtract with release ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_sub_return_release() there.
Return
The updated value of v.
atomic_sub_return_relaxed() #
int atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_sub_return_relaxed() there.
Return
The updated value of v.
atomic_fetch_sub() #
int atomic subtract with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_sub() there.
Return
The original value of v.
atomic_fetch_sub_acquire() #
int atomic subtract with acquire ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_sub_acquire() there.
Return
The original value of v.
atomic_fetch_sub_release() #
int atomic subtract with release ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_sub_release() there.
Return
The original value of v.
atomic_fetch_sub_relaxed() #
int atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_sub_relaxed() there.
Return
The original value of v.
atomic_inc() #
void atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_inc() there.
Return
Nothing.
atomic_inc_return() #
int atomic increment with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_inc_return() there.
Return
The updated value of v.
atomic_inc_return_acquire() #
int atomic increment with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_inc_return_acquire() there.
Return
The updated value of v.
atomic_inc_return_release() #
int atomic increment with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_inc_return_release() there.
Return
The updated value of v.
atomic_inc_return_relaxed() #
int atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_inc_return_relaxed() there.
Return
The updated value of v.
atomic_fetch_inc() #
int atomic increment with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_inc() there.
Return
The original value of v.
atomic_fetch_inc_acquire() #
int atomic increment with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_inc_acquire() there.
Return
The original value of v.
atomic_fetch_inc_release() #
int atomic increment with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_inc_release() there.
Return
The original value of v.
atomic_fetch_inc_relaxed() #
int atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_inc_relaxed() there.
Return
The original value of v.
atomic_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_dec() there.
Return
Nothing.
atomic_dec_return() #
int atomic decrement with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_dec_return() there.
Return
The updated value of v.
atomic_dec_return_acquire() #
int atomic decrement with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_dec_return_acquire() there.
Return
The updated value of v.
atomic_dec_return_release() #
int atomic decrement with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_dec_return_release() there.
Return
The updated value of v.
atomic_dec_return_relaxed() #
int atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_dec_return_relaxed() there.
Return
The updated value of v.
atomic_fetch_dec() #
int atomic decrement with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_dec() there.
Return
The original value of v.
atomic_fetch_dec_acquire() #
int atomic decrement with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_dec_acquire() there.
Return
The original value of v.
atomic_fetch_dec_release() #
int atomic decrement with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_dec_release() there.
Return
The original value of v.
atomic_fetch_dec_relaxed() #
int atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_dec_relaxed() there.
Return
The original value of v.
atomic_and() #
void atomic bitwise AND with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_and() there.
Return
Nothing.
atomic_fetch_and() #
int atomic bitwise AND with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_and() there.
Return
The original value of v.
atomic_fetch_and_acquire() #
int atomic bitwise AND with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_and_acquire() there.
Return
The original value of v.
atomic_fetch_and_release() #
int atomic bitwise AND with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_and_release() there.
Return
The original value of v.
atomic_fetch_and_relaxed() #
int atomic bitwise AND with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_and_relaxed() there.
Return
The original value of v.
atomic_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_andnot() there.
Return
Nothing.
atomic_fetch_andnot() #
int atomic bitwise AND NOT with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_andnot() there.
Return
The original value of v.
atomic_fetch_andnot_acquire() #
int atomic bitwise AND NOT with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_andnot_acquire() there.
Return
The original value of v.
atomic_fetch_andnot_release() #
int atomic bitwise AND NOT with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_andnot_release() there.
Return
The original value of v.
atomic_fetch_andnot_relaxed() #
int atomic bitwise AND NOT with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_andnot_relaxed() there.
Return
The original value of v.
atomic_or() #
void atomic bitwise OR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_or() there.
Return
Nothing.
atomic_fetch_or() #
int atomic bitwise OR with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_or() there.
Return
The original value of v.
atomic_fetch_or_acquire() #
int atomic bitwise OR with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_or_acquire() there.
Return
The original value of v.
atomic_fetch_or_release() #
int atomic bitwise OR with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_or_release() there.
Return
The original value of v.
atomic_fetch_or_relaxed() #
int atomic bitwise OR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_or_relaxed() there.
Return
The original value of v.
atomic_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_xor() there.
Return
Nothing.
atomic_fetch_xor() #
int atomic bitwise XOR with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_xor() there.
Return
The original value of v.
atomic_fetch_xor_acquire() #
int atomic bitwise XOR with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_xor_acquire() there.
Return
The original value of v.
atomic_fetch_xor_release() #
int atomic bitwise XOR with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_xor_release() there.
Return
The original value of v.
atomic_fetch_xor_relaxed() #
int atomic bitwise XOR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_fetch_xor_relaxed() there.
Return
The original value of v.
atomic_xchg() #
int atomic exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with full ordering.
Unsafe to use in noinstr code; use raw_atomic_xchg() there.
Return
The original value of v.
atomic_xchg_acquire() #
int atomic exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_xchg_acquire() there.
Return
The original value of v.
atomic_xchg_release() #
int atomic exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with release ordering.
Unsafe to use in noinstr code; use raw_atomic_xchg_release() there.
Return
The original value of v.
atomic_xchg_relaxed() #
int atomic exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_xchg_relaxed() there.
Return
The original value of v.
atomic_cmpxchg() #
int atomic compare and exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_cmpxchg() there.
Return
The original value of v.
atomic_cmpxchg_acquire() #
int atomic compare and exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_cmpxchg_acquire() there.
Return
The original value of v.
atomic_cmpxchg_release() #
int atomic compare and exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_cmpxchg_release() there.
Return
The original value of v.
atomic_cmpxchg_relaxed() #
int atomic compare and exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_cmpxchg_relaxed() there.
Return
The original value of v.
atomic_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_try_cmpxchg() there.
Return
true if the exchange occurred, false otherwise.
atomic_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_try_cmpxchg_acquire() there.
Return
true if the exchange occurred, false otherwise.
atomic_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_try_cmpxchg_release() there.
Return
true if the exchange occurred, false otherwise.
atomic_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_try_cmpxchg_relaxed() there.
Return
true if the exchange occurred, false otherwise.
atomic_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_sub_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_dec_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_inc_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_add_negative() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_add_negative_acquire() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_add_negative_release() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_add_negative_relaxed() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_fetch_add_unless() #
int atomic add unless value with full ordering
Parameters
atomic_t *v: pointer to atomic_tint a: int value to addint u: int value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_fetch_add_unless() there.
Return
The original value of v.
atomic_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic_t *v: pointer to atomic_tint a: int value to addint u: int value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_add_unless() there.
Return
true if v was updated, false otherwise.
atomic_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_inc_not_zero() there.
Return
true if v was updated, false otherwise.
atomic_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_inc_unless_negative() there.
Return
true if v was updated, false otherwise.
atomic_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_dec_unless_positive() there.
Return
true if v was updated, false otherwise.
atomic_dec_if_positive() #
int atomic decrement if positive with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_dec_if_positive() there.
Return
The old value of (v - 1), regardless of whether v was updated.
atomic64_read() #
s64 atomic load with relaxed ordering
Parameters
const atomic64_t *v: pointer to atomic64_t
Description
Atomically loads the value of v with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_read() there.
Return
The value loaded from v.
atomic64_read_acquire() #
s64 atomic load with acquire ordering
Parameters
const atomic64_t *v: pointer to atomic64_t
Description
Atomically loads the value of v with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_read_acquire() there.
Return
The value loaded from v.
atomic64_set() #
void atomic set with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 i: s64 value to assign
Description
Atomically sets v to i with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_set() there.
Return
Nothing.
atomic64_set_release() #
void atomic set with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 i: s64 value to assign
Description
Atomically sets v to i with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_set_release() there.
Return
Nothing.
atomic64_add() #
void atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_add() there.
Return
Nothing.
atomic64_add_return() #
s64 atomic add with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_return() there.
Return
The updated value of v.
atomic64_add_return_acquire() #
s64 atomic add with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_return_acquire() there.
Return
The updated value of v.
atomic64_add_return_release() #
s64 atomic add with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_return_release() there.
Return
The updated value of v.
atomic64_add_return_relaxed() #
s64 atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_return_relaxed() there.
Return
The updated value of v.
atomic64_fetch_add() #
s64 atomic add with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_add() there.
Return
The original value of v.
atomic64_fetch_add_acquire() #
s64 atomic add with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_add_acquire() there.
Return
The original value of v.
atomic64_fetch_add_release() #
s64 atomic add with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_add_release() there.
Return
The original value of v.
atomic64_fetch_add_relaxed() #
s64 atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_add_relaxed() there.
Return
The original value of v.
atomic64_sub() #
void atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub() there.
Return
Nothing.
atomic64_sub_return() #
s64 atomic subtract with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub_return() there.
Return
The updated value of v.
atomic64_sub_return_acquire() #
s64 atomic subtract with acquire ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub_return_acquire() there.
Return
The updated value of v.
atomic64_sub_return_release() #
s64 atomic subtract with release ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub_return_release() there.
Return
The updated value of v.
atomic64_sub_return_relaxed() #
s64 atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub_return_relaxed() there.
Return
The updated value of v.
atomic64_fetch_sub() #
s64 atomic subtract with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_sub() there.
Return
The original value of v.
atomic64_fetch_sub_acquire() #
s64 atomic subtract with acquire ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_sub_acquire() there.
Return
The original value of v.
atomic64_fetch_sub_release() #
s64 atomic subtract with release ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_sub_release() there.
Return
The original value of v.
atomic64_fetch_sub_relaxed() #
s64 atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_sub_relaxed() there.
Return
The original value of v.
atomic64_inc() #
void atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc() there.
Return
Nothing.
atomic64_inc_return() #
s64 atomic increment with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc_return() there.
Return
The updated value of v.
atomic64_inc_return_acquire() #
s64 atomic increment with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc_return_acquire() there.
Return
The updated value of v.
atomic64_inc_return_release() #
s64 atomic increment with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc_return_release() there.
Return
The updated value of v.
atomic64_inc_return_relaxed() #
s64 atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc_return_relaxed() there.
Return
The updated value of v.
atomic64_fetch_inc() #
s64 atomic increment with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_inc() there.
Return
The original value of v.
atomic64_fetch_inc_acquire() #
s64 atomic increment with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_inc_acquire() there.
Return
The original value of v.
atomic64_fetch_inc_release() #
s64 atomic increment with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_inc_release() there.
Return
The original value of v.
atomic64_fetch_inc_relaxed() #
s64 atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_inc_relaxed() there.
Return
The original value of v.
atomic64_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec() there.
Return
Nothing.
atomic64_dec_return() #
s64 atomic decrement with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec_return() there.
Return
The updated value of v.
atomic64_dec_return_acquire() #
s64 atomic decrement with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec_return_acquire() there.
Return
The updated value of v.
atomic64_dec_return_release() #
s64 atomic decrement with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec_return_release() there.
Return
The updated value of v.
atomic64_dec_return_relaxed() #
s64 atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec_return_relaxed() there.
Return
The updated value of v.
atomic64_fetch_dec() #
s64 atomic decrement with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_dec() there.
Return
The original value of v.
atomic64_fetch_dec_acquire() #
s64 atomic decrement with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_dec_acquire() there.
Return
The original value of v.
atomic64_fetch_dec_release() #
s64 atomic decrement with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_dec_release() there.
Return
The original value of v.
atomic64_fetch_dec_relaxed() #
s64 atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_dec_relaxed() there.
Return
The original value of v.
atomic64_and() #
void atomic bitwise AND with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_and() there.
Return
Nothing.
atomic64_fetch_and() #
s64 atomic bitwise AND with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_and() there.
Return
The original value of v.
atomic64_fetch_and_acquire() #
s64 atomic bitwise AND with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_and_acquire() there.
Return
The original value of v.
atomic64_fetch_and_release() #
s64 atomic bitwise AND with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_and_release() there.
Return
The original value of v.
atomic64_fetch_and_relaxed() #
s64 atomic bitwise AND with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_and_relaxed() there.
Return
The original value of v.
atomic64_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_andnot() there.
Return
Nothing.
atomic64_fetch_andnot() #
s64 atomic bitwise AND NOT with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_andnot() there.
Return
The original value of v.
atomic64_fetch_andnot_acquire() #
s64 atomic bitwise AND NOT with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_andnot_acquire() there.
Return
The original value of v.
atomic64_fetch_andnot_release() #
s64 atomic bitwise AND NOT with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_andnot_release() there.
Return
The original value of v.
atomic64_fetch_andnot_relaxed() #
s64 atomic bitwise AND NOT with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_andnot_relaxed() there.
Return
The original value of v.
atomic64_or() #
void atomic bitwise OR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_or() there.
Return
Nothing.
atomic64_fetch_or() #
s64 atomic bitwise OR with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_or() there.
Return
The original value of v.
atomic64_fetch_or_acquire() #
s64 atomic bitwise OR with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_or_acquire() there.
Return
The original value of v.
atomic64_fetch_or_release() #
s64 atomic bitwise OR with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_or_release() there.
Return
The original value of v.
atomic64_fetch_or_relaxed() #
s64 atomic bitwise OR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_or_relaxed() there.
Return
The original value of v.
atomic64_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_xor() there.
Return
Nothing.
atomic64_fetch_xor() #
s64 atomic bitwise XOR with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_xor() there.
Return
The original value of v.
atomic64_fetch_xor_acquire() #
s64 atomic bitwise XOR with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_xor_acquire() there.
Return
The original value of v.
atomic64_fetch_xor_release() #
s64 atomic bitwise XOR with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_xor_release() there.
Return
The original value of v.
atomic64_fetch_xor_relaxed() #
s64 atomic bitwise XOR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_fetch_xor_relaxed() there.
Return
The original value of v.
atomic64_xchg() #
s64 atomic exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_xchg() there.
Return
The original value of v.
atomic64_xchg_acquire() #
s64 atomic exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_xchg_acquire() there.
Return
The original value of v.
atomic64_xchg_release() #
s64 atomic exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_xchg_release() there.
Return
The original value of v.
atomic64_xchg_relaxed() #
s64 atomic exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_xchg_relaxed() there.
Return
The original value of v.
atomic64_cmpxchg() #
s64 atomic compare and exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_cmpxchg() there.
Return
The original value of v.
atomic64_cmpxchg_acquire() #
s64 atomic compare and exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_cmpxchg_acquire() there.
Return
The original value of v.
atomic64_cmpxchg_release() #
s64 atomic compare and exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_cmpxchg_release() there.
Return
The original value of v.
atomic64_cmpxchg_relaxed() #
s64 atomic compare and exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_cmpxchg_relaxed() there.
Return
The original value of v.
atomic64_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_try_cmpxchg() there.
Return
true if the exchange occurred, false otherwise.
atomic64_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_try_cmpxchg_acquire() there.
Return
true if the exchange occurred, false otherwise.
atomic64_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_try_cmpxchg_release() there.
Return
true if the exchange occurred, false otherwise.
atomic64_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_try_cmpxchg_relaxed() there.
Return
true if the exchange occurred, false otherwise.
atomic64_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_sub_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic64_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_dec_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic64_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_inc_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic64_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_negative() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic64_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_negative_acquire() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic64_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_negative_release() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic64_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic64_add_negative_relaxed() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic64_fetch_add_unless() #
s64 atomic add unless value with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 a: s64 value to adds64 u: s64 value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_fetch_add_unless() there.
Return
The original value of v.
atomic64_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 a: s64 value to adds64 u: s64 value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_add_unless() there.
Return
true if v was updated, false otherwise.
atomic64_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_inc_not_zero() there.
Return
true if v was updated, false otherwise.
atomic64_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_inc_unless_negative() there.
Return
true if v was updated, false otherwise.
atomic64_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_dec_unless_positive() there.
Return
true if v was updated, false otherwise.
atomic64_dec_if_positive() #
s64 atomic decrement if positive with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic64_dec_if_positive() there.
Return
The old value of (v - 1), regardless of whether v was updated.
atomic_long_read() #
long atomic load with relaxed ordering
Parameters
const atomic_long_t *v: pointer to atomic_long_t
Description
Atomically loads the value of v with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_read() there.
Return
The value loaded from v.
atomic_long_read_acquire() #
long atomic load with acquire ordering
Parameters
const atomic_long_t *v: pointer to atomic_long_t
Description
Atomically loads the value of v with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_read_acquire() there.
Return
The value loaded from v.
atomic_long_set() #
void atomic set with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong i: long value to assign
Description
Atomically sets v to i with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_set() there.
Return
Nothing.
atomic_long_set_release() #
void atomic set with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong i: long value to assign
Description
Atomically sets v to i with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_set_release() there.
Return
Nothing.
atomic_long_add() #
void atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add() there.
Return
Nothing.
atomic_long_add_return() #
long atomic add with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_return() there.
Return
The updated value of v.
atomic_long_add_return_acquire() #
long atomic add with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_return_acquire() there.
Return
The updated value of v.
atomic_long_add_return_release() #
long atomic add with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_return_release() there.
Return
The updated value of v.
atomic_long_add_return_relaxed() #
long atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_return_relaxed() there.
Return
The updated value of v.
atomic_long_fetch_add() #
long atomic add with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_add() there.
Return
The original value of v.
atomic_long_fetch_add_acquire() #
long atomic add with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_add_acquire() there.
Return
The original value of v.
atomic_long_fetch_add_release() #
long atomic add with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_add_release() there.
Return
The original value of v.
atomic_long_fetch_add_relaxed() #
long atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_add_relaxed() there.
Return
The original value of v.
atomic_long_sub() #
void atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub() there.
Return
Nothing.
atomic_long_sub_return() #
long atomic subtract with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub_return() there.
Return
The updated value of v.
atomic_long_sub_return_acquire() #
long atomic subtract with acquire ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub_return_acquire() there.
Return
The updated value of v.
atomic_long_sub_return_release() #
long atomic subtract with release ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub_return_release() there.
Return
The updated value of v.
atomic_long_sub_return_relaxed() #
long atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub_return_relaxed() there.
Return
The updated value of v.
atomic_long_fetch_sub() #
long atomic subtract with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_sub() there.
Return
The original value of v.
atomic_long_fetch_sub_acquire() #
long atomic subtract with acquire ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_sub_acquire() there.
Return
The original value of v.
atomic_long_fetch_sub_release() #
long atomic subtract with release ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_sub_release() there.
Return
The original value of v.
atomic_long_fetch_sub_relaxed() #
long atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_sub_relaxed() there.
Return
The original value of v.
atomic_long_inc() #
void atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc() there.
Return
Nothing.
atomic_long_inc_return() #
long atomic increment with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc_return() there.
Return
The updated value of v.
atomic_long_inc_return_acquire() #
long atomic increment with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc_return_acquire() there.
Return
The updated value of v.
atomic_long_inc_return_release() #
long atomic increment with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc_return_release() there.
Return
The updated value of v.
atomic_long_inc_return_relaxed() #
long atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc_return_relaxed() there.
Return
The updated value of v.
atomic_long_fetch_inc() #
long atomic increment with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_inc() there.
Return
The original value of v.
atomic_long_fetch_inc_acquire() #
long atomic increment with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_inc_acquire() there.
Return
The original value of v.
atomic_long_fetch_inc_release() #
long atomic increment with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_inc_release() there.
Return
The original value of v.
atomic_long_fetch_inc_relaxed() #
long atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_inc_relaxed() there.
Return
The original value of v.
atomic_long_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec() there.
Return
Nothing.
atomic_long_dec_return() #
long atomic decrement with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec_return() there.
Return
The updated value of v.
atomic_long_dec_return_acquire() #
long atomic decrement with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec_return_acquire() there.
Return
The updated value of v.
atomic_long_dec_return_release() #
long atomic decrement with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec_return_release() there.
Return
The updated value of v.
atomic_long_dec_return_relaxed() #
long atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec_return_relaxed() there.
Return
The updated value of v.
atomic_long_fetch_dec() #
long atomic decrement with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_dec() there.
Return
The original value of v.
atomic_long_fetch_dec_acquire() #
long atomic decrement with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_dec_acquire() there.
Return
The original value of v.
atomic_long_fetch_dec_release() #
long atomic decrement with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_dec_release() there.
Return
The original value of v.
atomic_long_fetch_dec_relaxed() #
long atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_dec_relaxed() there.
Return
The original value of v.
atomic_long_and() #
void atomic bitwise AND with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_and() there.
Return
Nothing.
atomic_long_fetch_and() #
long atomic bitwise AND with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_and() there.
Return
The original value of v.
atomic_long_fetch_and_acquire() #
long atomic bitwise AND with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_and_acquire() there.
Return
The original value of v.
atomic_long_fetch_and_release() #
long atomic bitwise AND with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_and_release() there.
Return
The original value of v.
atomic_long_fetch_and_relaxed() #
long atomic bitwise AND with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_and_relaxed() there.
Return
The original value of v.
atomic_long_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_andnot() there.
Return
Nothing.
atomic_long_fetch_andnot() #
long atomic bitwise AND NOT with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_andnot() there.
Return
The original value of v.
atomic_long_fetch_andnot_acquire() #
long atomic bitwise AND NOT with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_andnot_acquire() there.
Return
The original value of v.
atomic_long_fetch_andnot_release() #
long atomic bitwise AND NOT with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_andnot_release() there.
Return
The original value of v.
atomic_long_fetch_andnot_relaxed() #
long atomic bitwise AND NOT with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_andnot_relaxed() there.
Return
The original value of v.
atomic_long_or() #
void atomic bitwise OR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_or() there.
Return
Nothing.
atomic_long_fetch_or() #
long atomic bitwise OR with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_or() there.
Return
The original value of v.
atomic_long_fetch_or_acquire() #
long atomic bitwise OR with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_or_acquire() there.
Return
The original value of v.
atomic_long_fetch_or_release() #
long atomic bitwise OR with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_or_release() there.
Return
The original value of v.
atomic_long_fetch_or_relaxed() #
long atomic bitwise OR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_or_relaxed() there.
Return
The original value of v.
atomic_long_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_xor() there.
Return
Nothing.
atomic_long_fetch_xor() #
long atomic bitwise XOR with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_xor() there.
Return
The original value of v.
atomic_long_fetch_xor_acquire() #
long atomic bitwise XOR with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_xor_acquire() there.
Return
The original value of v.
atomic_long_fetch_xor_release() #
long atomic bitwise XOR with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_xor_release() there.
Return
The original value of v.
atomic_long_fetch_xor_relaxed() #
long atomic bitwise XOR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_xor_relaxed() there.
Return
The original value of v.
atomic_long_xchg() #
long atomic exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_xchg() there.
Return
The original value of v.
atomic_long_xchg_acquire() #
long atomic exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_xchg_acquire() there.
Return
The original value of v.
atomic_long_xchg_release() #
long atomic exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_xchg_release() there.
Return
The original value of v.
atomic_long_xchg_relaxed() #
long atomic exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_xchg_relaxed() there.
Return
The original value of v.
atomic_long_cmpxchg() #
long atomic compare and exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_cmpxchg() there.
Return
The original value of v.
atomic_long_cmpxchg_acquire() #
long atomic compare and exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_cmpxchg_acquire() there.
Return
The original value of v.
atomic_long_cmpxchg_release() #
long atomic compare and exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_cmpxchg_release() there.
Return
The original value of v.
atomic_long_cmpxchg_relaxed() #
long atomic compare and exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_cmpxchg_relaxed() there.
Return
The original value of v.
atomic_long_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_try_cmpxchg() there.
Return
true if the exchange occurred, false otherwise.
atomic_long_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_try_cmpxchg_acquire() there.
Return
true if the exchange occurred, false otherwise.
atomic_long_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_try_cmpxchg_release() there.
Return
true if the exchange occurred, false otherwise.
atomic_long_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_try_cmpxchg_relaxed() there.
Return
true if the exchange occurred, false otherwise.
atomic_long_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_sub_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_long_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_dec_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_long_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_inc_and_test() there.
Return
true if the resulting value of v is zero, false otherwise.
atomic_long_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_negative() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_long_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_negative_acquire() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_long_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_negative_release() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_long_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Unsafe to use in noinstr code; use raw_atomic_long_add_negative_relaxed() there.
Return
true if the resulting value of v is negative, false otherwise.
atomic_long_fetch_add_unless() #
long atomic add unless value with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong a: long value to addlong u: long value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_fetch_add_unless() there.
Return
The original value of v.
atomic_long_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong a: long value to addlong u: long value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_add_unless() there.
Return
true if v was updated, false otherwise.
atomic_long_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_inc_not_zero() there.
Return
true if v was updated, false otherwise.
atomic_long_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_inc_unless_negative() there.
Return
true if v was updated, false otherwise.
atomic_long_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_dec_unless_positive() there.
Return
true if v was updated, false otherwise.
atomic_long_dec_if_positive() #
long atomic decrement if positive with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Unsafe to use in noinstr code; use raw_atomic_long_dec_if_positive() there.
Return
The old value of (v - 1), regardless of whether v was updated.
raw_atomic_read() #
int atomic load with relaxed ordering
Parameters
const atomic_t *v: pointer to atomic_t
Description
Atomically loads the value of v with relaxed ordering.
Safe to use in noinstr code; prefer atomic_read() elsewhere.
Return
The value loaded from v.
raw_atomic_read_acquire() #
int atomic load with acquire ordering
Parameters
const atomic_t *v: pointer to atomic_t
Description
Atomically loads the value of v with acquire ordering.
Safe to use in noinstr code; prefer atomic_read_acquire() elsewhere.
Return
The value loaded from v.
raw_atomic_set() #
void atomic set with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint i: int value to assign
Description
Atomically sets v to i with relaxed ordering.
Safe to use in noinstr code; prefer atomic_set() elsewhere.
Return
Nothing.
raw_atomic_set_release() #
void atomic set with release ordering
Parameters
atomic_t *v: pointer to atomic_tint i: int value to assign
Description
Atomically sets v to i with release ordering.
Safe to use in noinstr code; prefer atomic_set_release() elsewhere.
Return
Nothing.
raw_atomic_add() #
void atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_add() elsewhere.
Return
Nothing.
raw_atomic_add_return() #
int atomic add with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_add_return() elsewhere.
Return
The updated value of v.
raw_atomic_add_return_acquire() #
int atomic add with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_add_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_add_return_release() #
int atomic add with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_add_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_add_return_relaxed() #
int atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_add_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_fetch_add() #
int atomic add with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_add() elsewhere.
Return
The original value of v.
raw_atomic_fetch_add_acquire() #
int atomic add with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_add_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_add_release() #
int atomic add with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_add_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_add_relaxed() #
int atomic add with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_add_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_sub() #
void atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_sub() elsewhere.
Return
Nothing.
raw_atomic_sub_return() #
int atomic subtract with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_sub_return() elsewhere.
Return
The updated value of v.
raw_atomic_sub_return_acquire() #
int atomic subtract with acquire ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_sub_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_sub_return_release() #
int atomic subtract with release ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic_sub_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_sub_return_relaxed() #
int atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_sub_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_fetch_sub() #
int atomic subtract with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_sub() elsewhere.
Return
The original value of v.
raw_atomic_fetch_sub_acquire() #
int atomic subtract with acquire ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_sub_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_sub_release() #
int atomic subtract with release ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_sub_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_sub_relaxed() #
int atomic subtract with relaxed ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_sub_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_inc() #
void atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_inc() elsewhere.
Return
Nothing.
raw_atomic_inc_return() #
int atomic increment with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_inc_return() elsewhere.
Return
The updated value of v.
raw_atomic_inc_return_acquire() #
int atomic increment with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_inc_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_inc_return_release() #
int atomic increment with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic_inc_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_inc_return_relaxed() #
int atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_inc_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_fetch_inc() #
int atomic increment with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_inc() elsewhere.
Return
The original value of v.
raw_atomic_fetch_inc_acquire() #
int atomic increment with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_inc_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_inc_release() #
int atomic increment with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_inc_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_inc_relaxed() #
int atomic increment with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_inc_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_dec() elsewhere.
Return
Nothing.
raw_atomic_dec_return() #
int atomic decrement with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_dec_return() elsewhere.
Return
The updated value of v.
raw_atomic_dec_return_acquire() #
int atomic decrement with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_dec_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_dec_return_release() #
int atomic decrement with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic_dec_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_dec_return_relaxed() #
int atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_dec_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_fetch_dec() #
int atomic decrement with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_dec() elsewhere.
Return
The original value of v.
raw_atomic_fetch_dec_acquire() #
int atomic decrement with acquire ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_dec_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_dec_release() #
int atomic decrement with release ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_dec_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_dec_relaxed() #
int atomic decrement with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_dec_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_and() #
void atomic bitwise AND with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_and() elsewhere.
Return
Nothing.
raw_atomic_fetch_and() #
int atomic bitwise AND with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_and() elsewhere.
Return
The original value of v.
raw_atomic_fetch_and_acquire() #
int atomic bitwise AND with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_and_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_and_release() #
int atomic bitwise AND with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_and_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_and_relaxed() #
int atomic bitwise AND with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_and_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_andnot() elsewhere.
Return
Nothing.
raw_atomic_fetch_andnot() #
int atomic bitwise AND NOT with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_andnot() elsewhere.
Return
The original value of v.
raw_atomic_fetch_andnot_acquire() #
int atomic bitwise AND NOT with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_andnot_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_andnot_release() #
int atomic bitwise AND NOT with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_andnot_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_andnot_relaxed() #
int atomic bitwise AND NOT with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_andnot_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_or() #
void atomic bitwise OR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_or() elsewhere.
Return
Nothing.
raw_atomic_fetch_or() #
int atomic bitwise OR with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_or() elsewhere.
Return
The original value of v.
raw_atomic_fetch_or_acquire() #
int atomic bitwise OR with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_or_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_or_release() #
int atomic bitwise OR with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_or_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_or_relaxed() #
int atomic bitwise OR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_or_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_xor() elsewhere.
Return
Nothing.
raw_atomic_fetch_xor() #
int atomic bitwise XOR with full ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with full ordering.
Safe to use in noinstr code; prefer atomic_fetch_xor() elsewhere.
Return
The original value of v.
raw_atomic_fetch_xor_acquire() #
int atomic bitwise XOR with acquire ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_fetch_xor_acquire() elsewhere.
Return
The original value of v.
raw_atomic_fetch_xor_release() #
int atomic bitwise XOR with release ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with release ordering.
Safe to use in noinstr code; prefer atomic_fetch_xor_release() elsewhere.
Return
The original value of v.
raw_atomic_fetch_xor_relaxed() #
int atomic bitwise XOR with relaxed ordering
Parameters
int i: int valueatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_fetch_xor_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_xchg() #
int atomic exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with full ordering.
Safe to use in noinstr code; prefer atomic_xchg() elsewhere.
Return
The original value of v.
raw_atomic_xchg_acquire() #
int atomic exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with acquire ordering.
Safe to use in noinstr code; prefer atomic_xchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic_xchg_release() #
int atomic exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with release ordering.
Safe to use in noinstr code; prefer atomic_xchg_release() elsewhere.
Return
The original value of v.
raw_atomic_xchg_relaxed() #
int atomic exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint new: int value to assign
Description
Atomically updates v to new with relaxed ordering.
Safe to use in noinstr code; prefer atomic_xchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_cmpxchg() #
int atomic compare and exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_cmpxchg() elsewhere.
Return
The original value of v.
raw_atomic_cmpxchg_acquire() #
int atomic compare and exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_cmpxchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic_cmpxchg_release() #
int atomic compare and exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_cmpxchg_release() elsewhere.
Return
The original value of v.
raw_atomic_cmpxchg_relaxed() #
int atomic compare and exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint old: int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_cmpxchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_try_cmpxchg() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_try_cmpxchg_acquire() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_try_cmpxchg_release() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic_t *v: pointer to atomic_tint *old: pointer to int value to compare withint new: int value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_try_cmpxchg_relaxed() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
int i: int value to subtractatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_sub_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_dec_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_inc_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_add_negative() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_add_negative_acquire() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_add_negative_release() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
int i: int value to addatomic_t *v: pointer to atomic_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_add_negative_relaxed() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_fetch_add_unless() #
int atomic add unless value with full ordering
Parameters
atomic_t *v: pointer to atomic_tint a: int value to addint u: int value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_fetch_add_unless() elsewhere.
Return
The original value of v.
raw_atomic_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic_t *v: pointer to atomic_tint a: int value to addint u: int value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_add_unless() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_inc_not_zero() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_inc_unless_negative() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_dec_unless_positive() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_dec_if_positive() #
int atomic decrement if positive with full ordering
Parameters
atomic_t *v: pointer to atomic_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_dec_if_positive() elsewhere.
Return
The old value of (v - 1), regardless of whether v was updated.
raw_atomic64_read() #
s64 atomic load with relaxed ordering
Parameters
const atomic64_t *v: pointer to atomic64_t
Description
Atomically loads the value of v with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_read() elsewhere.
Return
The value loaded from v.
raw_atomic64_read_acquire() #
s64 atomic load with acquire ordering
Parameters
const atomic64_t *v: pointer to atomic64_t
Description
Atomically loads the value of v with acquire ordering.
Safe to use in noinstr code; prefer atomic64_read_acquire() elsewhere.
Return
The value loaded from v.
raw_atomic64_set() #
void atomic set with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 i: s64 value to assign
Description
Atomically sets v to i with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_set() elsewhere.
Return
Nothing.
raw_atomic64_set_release() #
void atomic set with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 i: s64 value to assign
Description
Atomically sets v to i with release ordering.
Safe to use in noinstr code; prefer atomic64_set_release() elsewhere.
Return
Nothing.
raw_atomic64_add() #
void atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_add() elsewhere.
Return
Nothing.
raw_atomic64_add_return() #
s64 atomic add with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic64_add_return() elsewhere.
Return
The updated value of v.
raw_atomic64_add_return_acquire() #
s64 atomic add with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_add_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic64_add_return_release() #
s64 atomic add with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic64_add_return_release() elsewhere.
Return
The updated value of v.
raw_atomic64_add_return_relaxed() #
s64 atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_add_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic64_fetch_add() #
s64 atomic add with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_add() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_add_acquire() #
s64 atomic add with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_add_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_add_release() #
s64 atomic add with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_add_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_add_relaxed() #
s64 atomic add with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_add_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_sub() #
void atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_sub() elsewhere.
Return
Nothing.
raw_atomic64_sub_return() #
s64 atomic subtract with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic64_sub_return() elsewhere.
Return
The updated value of v.
raw_atomic64_sub_return_acquire() #
s64 atomic subtract with acquire ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_sub_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic64_sub_return_release() #
s64 atomic subtract with release ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic64_sub_return_release() elsewhere.
Return
The updated value of v.
raw_atomic64_sub_return_relaxed() #
s64 atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_sub_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic64_fetch_sub() #
s64 atomic subtract with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_sub() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_sub_acquire() #
s64 atomic subtract with acquire ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_sub_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_sub_release() #
s64 atomic subtract with release ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_sub_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_sub_relaxed() #
s64 atomic subtract with relaxed ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_sub_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_inc() #
void atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_inc() elsewhere.
Return
Nothing.
raw_atomic64_inc_return() #
s64 atomic increment with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_inc_return() elsewhere.
Return
The updated value of v.
raw_atomic64_inc_return_acquire() #
s64 atomic increment with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_inc_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic64_inc_return_release() #
s64 atomic increment with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic64_inc_return_release() elsewhere.
Return
The updated value of v.
raw_atomic64_inc_return_relaxed() #
s64 atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_inc_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic64_fetch_inc() #
s64 atomic increment with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_inc() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_inc_acquire() #
s64 atomic increment with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_inc_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_inc_release() #
s64 atomic increment with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_inc_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_inc_relaxed() #
s64 atomic increment with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_inc_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_dec() elsewhere.
Return
Nothing.
raw_atomic64_dec_return() #
s64 atomic decrement with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_dec_return() elsewhere.
Return
The updated value of v.
raw_atomic64_dec_return_acquire() #
s64 atomic decrement with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_dec_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic64_dec_return_release() #
s64 atomic decrement with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic64_dec_return_release() elsewhere.
Return
The updated value of v.
raw_atomic64_dec_return_relaxed() #
s64 atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_dec_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic64_fetch_dec() #
s64 atomic decrement with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_dec() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_dec_acquire() #
s64 atomic decrement with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_dec_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_dec_release() #
s64 atomic decrement with release ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_dec_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_dec_relaxed() #
s64 atomic decrement with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_dec_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_and() #
void atomic bitwise AND with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_and() elsewhere.
Return
Nothing.
raw_atomic64_fetch_and() #
s64 atomic bitwise AND with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_and() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_and_acquire() #
s64 atomic bitwise AND with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_and_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_and_release() #
s64 atomic bitwise AND with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_and_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_and_relaxed() #
s64 atomic bitwise AND with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_and_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_andnot() elsewhere.
Return
Nothing.
raw_atomic64_fetch_andnot() #
s64 atomic bitwise AND NOT with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_andnot() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_andnot_acquire() #
s64 atomic bitwise AND NOT with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_andnot_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_andnot_release() #
s64 atomic bitwise AND NOT with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_andnot_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_andnot_relaxed() #
s64 atomic bitwise AND NOT with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_andnot_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_or() #
void atomic bitwise OR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_or() elsewhere.
Return
Nothing.
raw_atomic64_fetch_or() #
s64 atomic bitwise OR with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_or() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_or_acquire() #
s64 atomic bitwise OR with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_or_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_or_release() #
s64 atomic bitwise OR with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_or_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_or_relaxed() #
s64 atomic bitwise OR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_or_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_xor() elsewhere.
Return
Nothing.
raw_atomic64_fetch_xor() #
s64 atomic bitwise XOR with full ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with full ordering.
Safe to use in noinstr code; prefer atomic64_fetch_xor() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_xor_acquire() #
s64 atomic bitwise XOR with acquire ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_fetch_xor_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_xor_release() #
s64 atomic bitwise XOR with release ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with release ordering.
Safe to use in noinstr code; prefer atomic64_fetch_xor_release() elsewhere.
Return
The original value of v.
raw_atomic64_fetch_xor_relaxed() #
s64 atomic bitwise XOR with relaxed ordering
Parameters
s64 i: s64 valueatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_fetch_xor_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_xchg() #
s64 atomic exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with full ordering.
Safe to use in noinstr code; prefer atomic64_xchg() elsewhere.
Return
The original value of v.
raw_atomic64_xchg_acquire() #
s64 atomic exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with acquire ordering.
Safe to use in noinstr code; prefer atomic64_xchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_xchg_release() #
s64 atomic exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with release ordering.
Safe to use in noinstr code; prefer atomic64_xchg_release() elsewhere.
Return
The original value of v.
raw_atomic64_xchg_relaxed() #
s64 atomic exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 new: s64 value to assign
Description
Atomically updates v to new with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_xchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_cmpxchg() #
s64 atomic compare and exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_cmpxchg() elsewhere.
Return
The original value of v.
raw_atomic64_cmpxchg_acquire() #
s64 atomic compare and exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_cmpxchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic64_cmpxchg_release() #
s64 atomic compare and exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_cmpxchg_release() elsewhere.
Return
The original value of v.
raw_atomic64_cmpxchg_relaxed() #
s64 atomic compare and exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 old: s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_cmpxchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic64_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_try_cmpxchg() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic64_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_try_cmpxchg_acquire() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic64_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_try_cmpxchg_release() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic64_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 *old: pointer to s64 value to compare withs64 new: s64 value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_try_cmpxchg_relaxed() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic64_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
s64 i: s64 value to subtractatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic64_sub_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic64_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_dec_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic64_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic64_inc_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic64_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic64_add_negative() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic64_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic64_add_negative_acquire() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic64_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic64_add_negative_release() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic64_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
s64 i: s64 value to addatomic64_t *v: pointer to atomic64_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic64_add_negative_relaxed() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic64_fetch_add_unless() #
s64 atomic add unless value with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 a: s64 value to adds64 u: s64 value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_fetch_add_unless() elsewhere.
Return
The original value of v.
raw_atomic64_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic64_t *v: pointer to atomic64_ts64 a: s64 value to adds64 u: s64 value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_add_unless() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic64_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_inc_not_zero() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic64_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_inc_unless_negative() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic64_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_dec_unless_positive() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic64_dec_if_positive() #
s64 atomic decrement if positive with full ordering
Parameters
atomic64_t *v: pointer to atomic64_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic64_dec_if_positive() elsewhere.
Return
The old value of (v - 1), regardless of whether v was updated.
raw_atomic_long_read() #
long atomic load with relaxed ordering
Parameters
const atomic_long_t *v: pointer to atomic_long_t
Description
Atomically loads the value of v with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_read() elsewhere.
Return
The value loaded from v.
raw_atomic_long_read_acquire() #
long atomic load with acquire ordering
Parameters
const atomic_long_t *v: pointer to atomic_long_t
Description
Atomically loads the value of v with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_read_acquire() elsewhere.
Return
The value loaded from v.
raw_atomic_long_set() #
void atomic set with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong i: long value to assign
Description
Atomically sets v to i with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_set() elsewhere.
Return
Nothing.
raw_atomic_long_set_release() #
void atomic set with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong i: long value to assign
Description
Atomically sets v to i with release ordering.
Safe to use in noinstr code; prefer atomic_long_set_release() elsewhere.
Return
Nothing.
raw_atomic_long_add() #
void atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_add() elsewhere.
Return
Nothing.
raw_atomic_long_add_return() #
long atomic add with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_add_return() elsewhere.
Return
The updated value of v.
raw_atomic_long_add_return_acquire() #
long atomic add with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_add_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_long_add_return_release() #
long atomic add with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_add_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_long_add_return_relaxed() #
long atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_add_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_long_fetch_add() #
long atomic add with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_add() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_add_acquire() #
long atomic add with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_add_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_add_release() #
long atomic add with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_add_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_add_relaxed() #
long atomic add with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_add_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_sub() #
void atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_sub() elsewhere.
Return
Nothing.
raw_atomic_long_sub_return() #
long atomic subtract with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_sub_return() elsewhere.
Return
The updated value of v.
raw_atomic_long_sub_return_acquire() #
long atomic subtract with acquire ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_sub_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_long_sub_return_release() #
long atomic subtract with release ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_sub_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_long_sub_return_relaxed() #
long atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_sub_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_long_fetch_sub() #
long atomic subtract with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_sub() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_sub_acquire() #
long atomic subtract with acquire ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_sub_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_sub_release() #
long atomic subtract with release ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_sub_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_sub_relaxed() #
long atomic subtract with relaxed ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_sub_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_inc() #
void atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_inc() elsewhere.
Return
Nothing.
raw_atomic_long_inc_return() #
long atomic increment with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_inc_return() elsewhere.
Return
The updated value of v.
raw_atomic_long_inc_return_acquire() #
long atomic increment with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_inc_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_long_inc_return_release() #
long atomic increment with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic_long_inc_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_long_inc_return_relaxed() #
long atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_inc_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_long_fetch_inc() #
long atomic increment with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_inc() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_inc_acquire() #
long atomic increment with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_inc_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_inc_release() #
long atomic increment with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_inc_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_inc_relaxed() #
long atomic increment with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_inc_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_dec() #
void atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_dec() elsewhere.
Return
Nothing.
raw_atomic_long_dec_return() #
long atomic decrement with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_dec_return() elsewhere.
Return
The updated value of v.
raw_atomic_long_dec_return_acquire() #
long atomic decrement with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_dec_return_acquire() elsewhere.
Return
The updated value of v.
raw_atomic_long_dec_return_release() #
long atomic decrement with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic_long_dec_return_release() elsewhere.
Return
The updated value of v.
raw_atomic_long_dec_return_relaxed() #
long atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_dec_return_relaxed() elsewhere.
Return
The updated value of v.
raw_atomic_long_fetch_dec() #
long atomic decrement with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_dec() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_dec_acquire() #
long atomic decrement with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_dec_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_dec_release() #
long atomic decrement with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_dec_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_dec_relaxed() #
long atomic decrement with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_dec_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_and() #
void atomic bitwise AND with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_and() elsewhere.
Return
Nothing.
raw_atomic_long_fetch_and() #
long atomic bitwise AND with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_and() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_and_acquire() #
long atomic bitwise AND with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_and_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_and_release() #
long atomic bitwise AND with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_and_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_and_relaxed() #
long atomic bitwise AND with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_and_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_andnot() #
void atomic bitwise AND NOT with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_andnot() elsewhere.
Return
Nothing.
raw_atomic_long_fetch_andnot() #
long atomic bitwise AND NOT with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_andnot() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_andnot_acquire() #
long atomic bitwise AND NOT with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_andnot_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_andnot_release() #
long atomic bitwise AND NOT with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_andnot_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_andnot_relaxed() #
long atomic bitwise AND NOT with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v & ~i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_andnot_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_or() #
void atomic bitwise OR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_or() elsewhere.
Return
Nothing.
raw_atomic_long_fetch_or() #
long atomic bitwise OR with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_or() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_or_acquire() #
long atomic bitwise OR with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_or_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_or_release() #
long atomic bitwise OR with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_or_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_or_relaxed() #
long atomic bitwise OR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v | i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_or_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_xor() #
void atomic bitwise XOR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_xor() elsewhere.
Return
Nothing.
raw_atomic_long_fetch_xor() #
long atomic bitwise XOR with full ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_xor() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_xor_acquire() #
long atomic bitwise XOR with acquire ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_xor_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_xor_release() #
long atomic bitwise XOR with release ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_xor_release() elsewhere.
Return
The original value of v.
raw_atomic_long_fetch_xor_relaxed() #
long atomic bitwise XOR with relaxed ordering
Parameters
long i: long valueatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v ^ i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_fetch_xor_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_xchg() #
long atomic exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with full ordering.
Safe to use in noinstr code; prefer atomic_long_xchg() elsewhere.
Return
The original value of v.
raw_atomic_long_xchg_acquire() #
long atomic exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_xchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_xchg_release() #
long atomic exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with release ordering.
Safe to use in noinstr code; prefer atomic_long_xchg_release() elsewhere.
Return
The original value of v.
raw_atomic_long_xchg_relaxed() #
long atomic exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong new: long value to assign
Description
Atomically updates v to new with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_xchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_cmpxchg() #
long atomic compare and exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_cmpxchg() elsewhere.
Return
The original value of v.
raw_atomic_long_cmpxchg_acquire() #
long atomic compare and exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_cmpxchg_acquire() elsewhere.
Return
The original value of v.
raw_atomic_long_cmpxchg_release() #
long atomic compare and exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_cmpxchg_release() elsewhere.
Return
The original value of v.
raw_atomic_long_cmpxchg_relaxed() #
long atomic compare and exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong old: long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_cmpxchg_relaxed() elsewhere.
Return
The original value of v.
raw_atomic_long_try_cmpxchg() #
bool atomic compare and exchange with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with full ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_try_cmpxchg() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_long_try_cmpxchg_acquire() #
bool atomic compare and exchange with acquire ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with acquire ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_try_cmpxchg_acquire() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_long_try_cmpxchg_release() #
bool atomic compare and exchange with release ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with release ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_try_cmpxchg_release() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_long_try_cmpxchg_relaxed() #
bool atomic compare and exchange with relaxed ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong *old: pointer to long value to compare withlong new: long value to assign
Description
If (v == old), atomically updates v to new with relaxed ordering. Otherwise, v is not modified, old is updated to the current value of v, and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_try_cmpxchg_relaxed() elsewhere.
Return
true if the exchange occurred, false otherwise.
raw_atomic_long_sub_and_test() #
bool atomic subtract and test if zero with full ordering
Parameters
long i: long value to subtractatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_sub_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_long_dec_and_test() #
bool atomic decrement and test if zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v - 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_dec_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_long_inc_and_test() #
bool atomic increment and test if zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + 1) with full ordering.
Safe to use in noinstr code; prefer atomic_long_inc_and_test() elsewhere.
Return
true if the resulting value of v is zero, false otherwise.
raw_atomic_long_add_negative() #
bool atomic add and test if negative with full ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with full ordering.
Safe to use in noinstr code; prefer atomic_long_add_negative() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_long_add_negative_acquire() #
bool atomic add and test if negative with acquire ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with acquire ordering.
Safe to use in noinstr code; prefer atomic_long_add_negative_acquire() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_long_add_negative_release() #
bool atomic add and test if negative with release ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with release ordering.
Safe to use in noinstr code; prefer atomic_long_add_negative_release() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_long_add_negative_relaxed() #
bool atomic add and test if negative with relaxed ordering
Parameters
long i: long value to addatomic_long_t *v: pointer to atomic_long_t
Description
Atomically updates v to (v + i) with relaxed ordering.
Safe to use in noinstr code; prefer atomic_long_add_negative_relaxed() elsewhere.
Return
true if the resulting value of v is negative, false otherwise.
raw_atomic_long_fetch_add_unless() #
long atomic add unless value with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong a: long value to addlong u: long value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_fetch_add_unless() elsewhere.
Return
The original value of v.
raw_atomic_long_add_unless() #
bool atomic add unless value with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_tlong a: long value to addlong u: long value to compare with
Description
If (v != u), atomically updates v to (v + a) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_add_unless() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_long_inc_not_zero() #
bool atomic increment unless zero with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v != 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_inc_not_zero() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_long_inc_unless_negative() #
bool atomic increment unless negative with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v >= 0), atomically updates v to (v + 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_inc_unless_negative() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_long_dec_unless_positive() #
bool atomic decrement unless positive with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v <= 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_dec_unless_positive() elsewhere.
Return
true if v was updated, false otherwise.
raw_atomic_long_dec_if_positive() #
long atomic decrement if positive with full ordering
Parameters
atomic_long_t *v: pointer to atomic_long_t
Description
If (v > 0), atomically updates v to (v - 1) with full ordering. Otherwise, v is not modified and relaxed ordering is provided.
Safe to use in noinstr code; prefer atomic_long_dec_if_positive() elsewhere.
Return
The old value of (v - 1), regardless of whether v was updated.
Kernel objects manipulation #
kobject_get_path() #
char * Allocate memory and fill in the path for kobj.
Parameters
const struct kobject *kobj: kobject in question, with which to build the pathgfp_t gfp_mask: the allocation type used to allocate the path
Return
The newly allocated memory, caller must free with kfree().
kobject_set_name() #
int Set the name of a kobject.
Parameters
struct kobject *kobj: struct kobject to set the name ofconst char *fmt: format string used to build the name...: variable arguments
Description
This sets the name of the kobject. If you have already added the
kobject to the system, you must call kobject_rename() in order to
change the name of the kobject.
kobject_init() #
void Initialize a kobject structure.
Parameters
struct kobject *kobj: pointer to the kobject to initializeconst struct kobj_type *ktype: pointer to the ktype for this kobject.
Description
This function will properly initialize a kobject such that it can then
be passed to the kobject_add() call.
After this function is called, the kobject MUST be cleaned up by a call
to kobject_put(), not by a call to kfree directly to ensure that all of
the memory is cleaned up properly.
kobject_add() #
int The main kobject add function.
Parameters
struct kobject *kobj: the kobject to addstruct kobject *parent: pointer to the parent of the kobject.const char *fmt: format to name the kobject with....: variable arguments
Description
The kobject name is set and added to the kobject hierarchy in this function.
If parent is set, then the parent of the kobj will be set to it. If parent is NULL, then the parent of the kobj will be set to the kobject associated with the kset assigned to this kobject. If no kset is assigned to the kobject, then the kobject will be located in the root of the sysfs tree.
Note, no "add" uevent will be created with this call, the caller should set
up all of the necessary sysfs files for the object and then call
kobject_uevent() with the UEVENT_ADD parameter to ensure that
userspace is properly notified of this kobject's creation.
If this function returns success, kobject_put() must also be called
in order to properly clean up the memory associated with the object.
In short, once this function is called, kobject_put() MUST be called
when the use of the object is finished in order to properly free
everything.
Return
If this function returns an error, kobject_put() must be
called to properly clean up the memory associated with the
object. Under no instance should the kobject that is passed
to this function be directly freed with a call to kfree(),
that can leak memory.
kobject_init_and_add() #
int Initialize a kobject structure and add it to the kobject hierarchy.
Parameters
struct kobject *kobj: pointer to the kobject to initializeconst struct kobj_type *ktype: pointer to the ktype for this kobject.struct kobject *parent: pointer to the parent of this kobject.const char *fmt: the name of the kobject....: variable arguments
Description
This function combines the call to kobject_init() and kobject_add().
If this function returns an error, kobject_put() must be called to
properly clean up the memory associated with the object. This is the
same type of error handling after a call to kobject_add() and kobject
lifetime rules are the same here.
kobject_rename() #
int Change the name of an object.
Parameters
struct kobject *kobj: object in question.const char *new_name: object's new name
Description
It is the responsibility of the caller to provide mutual exclusion between two different calls of kobject_rename on the same kobject and to ensure that new_name is valid and won't conflict with other kobjects.
kobject_move() #
int Move object to another parent.
Parameters
struct kobject *kobj: object in question.struct kobject *new_parent: object's new parent (can be NULL)
kobject_del() #
void Unlink kobject from hierarchy.
Parameters
struct kobject *kobj: object.
Description
This is the function that should be called to delete an object
successfully added via kobject_add().
kobject_get() #
struct kobject * Increment refcount for object.
Parameters
struct kobject *kobj: object.
kobject_put() #
void Decrement refcount for object.
Parameters
struct kobject *kobj: object.
Description
Decrement the refcount, and if 0, call kobject_cleanup().
kobject_create_and_add() #
struct kobject * Create a struct kobject dynamically and register it with sysfs.
Parameters
const char *name: the name for the kobjectstruct kobject *parent: the parent kobject of this kobject, if any.
Description
This function creates a kobject structure dynamically and registers it
with sysfs. When you are finished with this structure, call
kobject_put() and the structure will be dynamically freed when
it is no longer being used.
If the kobject was not able to be created, NULL will be returned.
kset_register() #
int Initialize and add a kset.
Parameters
struct kset *k: kset.
NOTE
On error, the kset.kobj.name allocated by() kobj_set_name()
is freed, it can not be used any more.
kset_unregister() #
void Remove a kset.
Parameters
struct kset *k: kset.
kset_find_obj() #
struct kobject * Search for object in kset.
Parameters
struct kset *kset: kset we're looking in.const char *name: object's name.
Description
Lock kset via kset->subsys, and iterate over kset->list, looking for a matching kobject. If matching object is found take a reference and return the object.
kset_create_and_add() #
struct kset * Create a struct kset dynamically and add it to sysfs.
Parameters
const char *name: the name for the ksetconst struct kset_uevent_ops *uevent_ops: a struct kset_uevent_ops for the ksetstruct kobject *parent_kobj: the parent kobject of this kset, if any.
Description
This function creates a kset structure dynamically and registers it
with sysfs. When you are finished with this structure, call
kset_unregister() and the structure will be dynamically freed when it
is no longer being used.
If the kset was not able to be created, NULL will be returned.
kobject_uevent_env() #
int send an uevent with environmental data
Parameters
struct kobject *kobj: struct kobject that the action is happening toenum kobject_action action: action that is happeningchar *envp_ext[]: pointer to environmental data
Description
Returns 0 if kobject_uevent_env() is completed with success or the
corresponding error when it fails.
kobject_uevent() #
int notify userspace by sending an uevent
Parameters
struct kobject *kobj: struct kobject that the action is happening toenum kobject_action action: action that is happening
Description
Returns 0 if kobject_uevent() is completed with success or the
corresponding error when it fails.
add_uevent_var() #
int add key value string to the environment buffer
Parameters
struct kobj_uevent_env *env: environment buffer structureconst char *format: printf format for the key=value pair...: variable arguments
Description
Returns 0 if environment variable was added successfully or -ENOMEM if no space was available.
Kernel utility functions #
ARRAY_SIZE() #
get the number of elements in array arr
Parameters
arr: array to be sized
ARRAY_END() #
get a pointer to one past the last element in array arr
Parameters
arr: array
container_of() #
cast a member of a structure out to the containing structure
Parameters
ptr: the pointer to the member.type: the type of the container struct this is embedded in.member: the name of the member within the struct.
Description
WARNING: any const qualifier of ptr is lost.
Do not use container_of() in new code.
container_of_const() #
cast a member of a structure out to the containing structure and preserve the const-ness of the pointer
Parameters
ptr: the pointer to the membertype: the type of the container struct this is embedded in.member: the name of the member within the struct.
Description
Always prefer container_of_const() instead of container_of() in new code.
sizeof_field() #
Report the size of a struct field in bytes
Parameters
TYPE: The structure containing the field of interestMEMBER: The field to return the size of
offsetofend() #
Report the offset of a struct field within the struct
Parameters
TYPE: The type of the structureMEMBER: The member within the structure to get the end offset of
struct_group() #
Wrap a set of declarations in a mirrored struct
Parameters
NAME: The identifier name of the mirrored sub-structMEMBERS...: The member declarations for the mirrored structs
Description
Used to create an anonymous union of two structs with identical layout and size: one anonymous and one named. The former can be used normally without sub-struct naming, and the latter can be used to reason about the start, end, and size of the group of struct members.
struct_group_attr() #
Create a struct_group() with trailing attributes
Parameters
NAME: The identifier name of the mirrored sub-structATTRS: Any struct attributes to applyMEMBERS...: The member declarations for the mirrored structs
Description
Used to create an anonymous union of two structs with identical layout and size: one anonymous and one named. The former can be used normally without sub-struct naming, and the latter can be used to reason about the start, end, and size of the group of struct members. Includes structure attributes argument.
struct_group_tagged() #
Create a struct_group with a reusable tag
Parameters
TAG: The tag name for the named sub-structNAME: The identifier name of the mirrored sub-structMEMBERS...: The member declarations for the mirrored structs
Description
Used to create an anonymous union of two structs with identical layout and size: one anonymous and one named. The former can be used normally without sub-struct naming, and the latter can be used to reason about the start, end, and size of the group of struct members. Includes struct tag argument for the named copy, so the specified layout can be reused later.
DECLARE_FLEX_ARRAY() #
Declare a flexible array usable in a union
Parameters
TYPE: The type of each flexible array elementNAME: The name of the flexible array member
Description
In order to have a flexible array member in a union or alone in a struct, it needs to be wrapped in an anonymous struct with at least 1 named member, but that member can be empty.
__TRAILING_OVERLAP() #
Overlap a flexible-array member with trailing members.
Parameters
TYPE: Flexible structure type name, including "struct" keyword.NAME: Name for a variable to define.FAM: The flexible-array member within TYPEATTRS: Any struct attributes (usually empty)MEMBERS: Trailing overlapping members.
Description
Creates a union between a flexible-array member (FAM) in a struct and a set of additional members that would otherwise follow it.
TRAILING_OVERLAP() #
Overlap a flexible-array member with trailing members.
Parameters
TYPE: Flexible structure type name, including "struct" keyword.NAME: Name for a variable to define.FAM: The flexible-array member within TYPEMEMBERS: Trailing overlapping members.
Description
Creates a union between a flexible-array member (FAM) in a struct and a set of additional members that would otherwise follow it.
for_each_if() #
helper for handling conditionals in various for_each macros
Parameters
condition: The condition to check
Description
Typical use:
#define for_each_foo_bar(x, y) \'
list_for_each_entry(x, y->list, head) \'
for_each_if(x->something == SOMETHING)
The for_each_if() macro makes the use of for_each_foo_bar() less error
prone.
find_closest() #
locate the closest element in a sorted array
Parameters
x: The reference value.a: The array in which to look for the closest element. Must be sorted in ascending order.as: Size of 'a'.
Description
Returns the index of the element closest to 'x'.
Note
-
If using an array of negative numbers (or mixed positive numbers),
then be sure that 'x' is of a signed-type to get good results.
find_closest_descending() #
locate the closest element in a sorted array
Parameters
x: The reference value.a: The array in which to look for the closest element. Must be sorted in descending order.as: Size of 'a'.
Description
Similar to find_closest() but 'a' is expected to be sorted in descending
order. The iteration is done in reverse order, so that the comparison
of '__fc_right' & '__fc_left' also works for unsigned numbers.
PTR_IF() #
evaluate to ptr if cond is true, or to NULL otherwise.
Parameters
cond: A conditional, usually in a form of IS_ENABLED(CONFIG_FOO)ptr: A pointer to assign if cond is true.
Description
PTR_IF(IS_ENABLED(CONFIG_FOO), ptr) evaluates to ptr if CONFIG_FOO is set to 'y' or 'm', or to NULL otherwise. The ptr argument must be a pointer.
The macro can be very useful to help compiler dropping dead code.
For instance, consider the following:
#ifdef CONFIG_FOO_SUSPEND
static int foo_suspend(struct device *dev)
{
...
}
#endif
static struct pm_ops foo_ops = {
#ifdef CONFIG_FOO_SUSPEND
.suspend = foo_suspend,
#endif
};
While this works, the foo_suspend() macro is compiled conditionally,
only when CONFIG_FOO_SUSPEND is set. This is problematic, as there could
be a build bug in this function, we wouldn't have a way to know unless
the configuration option is set.
An alternative is to declare foo_suspend() always, but mark it
as __maybe_unused. This works, but the __maybe_unused attribute
is required to instruct the compiler that the function may not
be referenced anywhere, and is safe to remove without making
a fuss about it. This makes the programmer responsible for tagging
the functions that can be garbage-collected.
With the macro it is possible to write the following:
static int foo_suspend(struct device *dev)
{
...
}
static struct pm_ops foo_ops = {
.suspend = PTR_IF(IS_ENABLED(CONFIG_FOO_SUSPEND), foo_suspend),
};
The foo_suspend() function will now be automatically dropped by the
compiler, and it does not require any specific attribute.
u64_to_user_ptr() #
cast a pointer passed as u64 from user space to void __user *
Parameters
x: The u64 value from user space, usually via IOCTL
Description
u64_to_user_ptr() simply casts a pointer passed as u64 from user space to void
__user * correctly. Using this lets us get rid of all the tiresome casts.
is_insidevar() #
check if the ptr points inside the var memory range.
Parameters
ptr: the pointer to a memory address.var: the variable which address and size identify the memory range.
Description
Evaluates to true if the address in ptr lies within the memory range allocated to var.
upper_32_bits() #
return bits 32-63 of a number
Parameters
n: the number we're accessing
Description
A basic shift-right of a 64- or 32-bit quantity. Use this to suppress the "right shift count >= width of type" warning when that quantity is 32-bits.
lower_32_bits() #
return bits 0-31 of a number
Parameters
n: the number we're accessing
upper_16_bits() #
return bits 16-31 of a number
Parameters
n: the number we're accessing
lower_16_bits() #
return bits 0-15 of a number
Parameters
n: the number we're accessing
REPEAT_BYTE() #
repeat the value x multiple times as an unsigned long value
Parameters
x: value to repeat
NOTE
x is not checked for > 0xff; larger values produce odd results.
REPEAT_BYTE_U32() #
repeat the value x multiple times as a u32 value
Parameters
x: value to repeat
NOTE
x is not checked for > 0xff; larger values produce odd results.
console_list_lock() #
void Lock the console list
Parameters
void: no arguments
Description
For console list or console->flags updates
console_list_unlock() #
void Unlock the console list
Parameters
void: no arguments
Description
Counterpart to console_list_lock()
console_srcu_read_lock() #
int Register a new reader for the SRCU-protected console list
Parameters
void: no arguments
Description
Use for_each_console_srcu() to iterate the console list
Context
Any context.
Return
A cookie to pass to console_srcu_read_unlock().
console_srcu_read_unlock() #
void Unregister an old reader from the SRCU-protected console list
Parameters
int cookie: cookie returned fromconsole_srcu_read_lock()
Description
Counterpart to console_srcu_read_lock()
match_devname_and_update_preferred_console() #
int Update a preferred console when matching devname is found.
Parameters
const char *devname: DEVNAME:0.0 style device nameconst char *name: Name of the corresponding console driver, e.g. "ttyS"const short idx: Console index, e.g. port number.
Description
The function checks whether a device with the given devname is
preferred via the console=DEVNAME:0.0 command line option.
It fills the missing console driver name and console index
so that a later register_console() call could find (match)
and enable this device.
It might be used when a driver subsystem initializes particular devices with already known DEVNAME:0.0 style names. And it could predict which console driver name and index this device would later get associated with.
Return
0 on success, negative error code on failure.
console_lock() #
void block the console subsystem from printing
Parameters
void: no arguments
Description
Acquires a lock which guarantees that no consoles will
be in or enter their write() callback.
Can sleep, returns nothing.
console_trylock() #
int try to block the console subsystem from printing
Parameters
void: no arguments
Description
Try to acquire a lock which guarantees that no consoles will
be in or enter their write() callback.
returns 1 on success, and 0 on failure to acquire the lock.
console_unlock() #
void unblock the legacy console subsystem from printing
Parameters
void: no arguments
Description
Releases the console_lock which the caller holds to block printing of the legacy console subsystem.
While the console_lock was held, console output may have been buffered
by printk(). If this is the case, console_unlock() emits the output on
legacy consoles prior to releasing the lock.
console_unlock(); may be called from any context.
console_force_preferred_locked() #
void force a registered console preferred
Parameters
struct console *con: The registered console to force preferred.
Description
Must be called under console_list_lock().
printk_timed_ratelimit() #
bool caller-controlled printk ratelimiting
Parameters
unsigned long *caller_jiffies: pointer to caller's stateunsigned int interval_msecs: minimum interval between prints
Description
printk_timed_ratelimit() returns true if more than interval_msecs
milliseconds have elapsed since the last time printk_timed_ratelimit()
returned true.
kmsg_dump_register() #
int register a kernel log dumper.
Parameters
struct kmsg_dumper *dumper: pointer to the kmsg_dumper structure
Description
Adds a kernel log dumper to the system. The dump callback in the
structure will be called when the kernel oopses or panics and must be
set. Returns zero on success and -EINVAL or -EBUSY otherwise.
kmsg_dump_unregister() #
int unregister a kmsg dumper.
Parameters
struct kmsg_dumper *dumper: pointer to the kmsg_dumper structure
Description
Removes a dump device from the system. Returns zero on success and
-EINVAL otherwise.
kmsg_dump_get_line() #
bool retrieve one kmsg log line
Parameters
struct kmsg_dump_iter *iter: kmsg dump iteratorbool syslog: include the "<4>" prefixeschar *line: buffer to copy the line tosize_t size: maximum size of the buffersize_t *len: length of line placed into buffer
Description
Start at the beginning of the kmsg buffer, with the oldest kmsg record, and copy one record into the provided buffer.
Consecutive calls will return the next available record moving towards the end of the buffer with the youngest messages.
A return value of FALSE indicates that there are no more records to read.
kmsg_dump_get_buffer() #
bool copy kmsg log lines
Parameters
struct kmsg_dump_iter *iter: kmsg dump iteratorbool syslog: include the "<4>" prefixeschar *buf: buffer to copy the line tosize_t size: maximum size of the buffersize_t *len_out: length of line placed into buffer
Description
Start at the end of the kmsg buffer and fill the provided buffer with as many of the youngest kmsg records that fit into it. If the buffer is large enough, all available kmsg records will be copied with a single call.
Consecutive calls will fill the buffer with the next block of available older records, not including the earlier retrieved ones.
A return value of FALSE indicates that there are no more records to read.
kmsg_dump_rewind() #
void reset the iterator
Parameters
struct kmsg_dump_iter *iter: kmsg dump iterator
Description
Reset the dumper's iterator so that kmsg_dump_get_line() and
kmsg_dump_get_buffer() can be called again and used multiple
times within the same dumper.dump() callback.
__printk_cpu_sync_wait() #
void Busy wait until the printk cpu-reentrant spinning lock is not owned by any CPU.
Parameters
void: no arguments
Context
Any context.
__printk_cpu_sync_try_get() #
int Try to acquire the printk cpu-reentrant spinning lock.
Parameters
void: no arguments
Description
If no processor has the lock, the calling processor takes the lock and becomes the owner. If the calling processor is already the owner of the lock, this function succeeds immediately.
Context
Any context. Expects interrupts to be disabled.
Return
1 on success, otherwise 0.
__printk_cpu_sync_put() #
void Release the printk cpu-reentrant spinning lock.
Parameters
void: no arguments
Description
The calling processor must be the owner of the lock.
Context
Any context. Expects interrupts to be disabled.
vpanic() #
void halt the system
Parameters
const char *fmt: The text string to printva_list args: Arguments for the format string
Description
Display a message, then perform cleanups. This function never returns.
add_taint() #
void add a taint flag if not already set.
Parameters
unsigned flag: one of the TAINT_* constants.enum lockdep_ok lockdep_ok: whether lock debugging is still OK.
Description
If something bad has gone wrong, you'll want lockdebug_ok = false, but for some notewortht-but-not-corrupting cases, it can be set to true.
Device Resource Management #
__devres_alloc_node() #
void * Allocate device resource data
Parameters
dr_release_t release: Release function devres will be associated withsize_t size: Allocation sizegfp_t gfp: Allocation flagsint nid: NUMA nodeconst char *name: Name of the resource
Description
Allocate devres of size bytes. The allocated area is zeroed, then associated with release. The returned pointer can be passed to other devres_*() functions.
Return
Pointer to allocated devres on success, NULL on failure.
devres_for_each_res() #
void Resource iterator
Parameters
struct device *dev: Device to iterate resource fromdr_release_t release: Look for resources associated with this release functiondr_match_t match: Match function (optional)void *match_data: Data for the match functionvoid (*fn)(struct device *, void *, void *): Function to be called for each matched resource.void *data: Data for fn, the 3rd parameter of fn
Description
Call fn for each devres of dev which is associated with release and for which match returns 1.
Return
void
devres_free() #
void Free device resource data
Parameters
void *res: Pointer to devres data to free
Description
Free devres created with devres_alloc().
devres_add() #
void Register device resource
Parameters
struct device *dev: Device to add resource tovoid *res: Resource to register
Description
Register devres res to dev. res should have been allocated
using devres_alloc(). On driver detach, the associated release
function will be invoked and devres will be freed automatically.
devres_find() #
void * Find device resource
Parameters
struct device *dev: Device to lookup resource fromdr_release_t release: Look for resources associated with this release functiondr_match_t match: Match function (optional)void *match_data: Data for the match function
Description
Find the latest devres of dev which is associated with release and for which match returns 1. If match is NULL, it's considered to match all.
Return
Pointer to found devres, NULL if not found.
devres_get() #
void * Find devres, if non-existent, add one atomically
Parameters
struct device *dev: Device to lookup or add devres forvoid *new_res: Pointer to new initialized devres to add if not founddr_match_t match: Match function (optional)void *match_data: Data for the match function
Description
Find the latest devres of dev which has the same release function as new_res and for which match return 1. If found, new_res is freed; otherwise, new_res is added atomically.
Return
Pointer to found or added devres.
devres_remove() #
void * Find a device resource and remove it
Parameters
struct device *dev: Device to find resource fromdr_release_t release: Look for resources associated with this release functiondr_match_t match: Match function (optional)void *match_data: Data for the match function
Description
Find the latest devres of dev associated with release and for which match returns 1. If match is NULL, it's considered to match all. If found, the resource is removed atomically and returned.
Return
Pointer to removed devres on success, NULL if not found.
devres_destroy() #
int Find a device resource and destroy it
Parameters
struct device *dev: Device to find resource fromdr_release_t release: Look for resources associated with this release functiondr_match_t match: Match function (optional)void *match_data: Data for the match function
Description
Find the latest devres of dev associated with release and for which match returns 1. If match is NULL, it's considered to match all. If found, the resource is removed atomically and freed.
Note that the release function for the resource will not be called, only the devres-allocated data will be freed. The caller becomes responsible for freeing any other data.
Return
0 if devres is found and freed, -ENOENT if not found.
devres_release() #
int Find a device resource and destroy it, calling release
Parameters
struct device *dev: Device to find resource fromdr_release_t release: Look for resources associated with this release functiondr_match_t match: Match function (optional)void *match_data: Data for the match function
Description
Find the latest devres of dev associated with release and for which match returns 1. If match is NULL, it's considered to match all. If found, the resource is removed atomically, the release function called and the resource freed.
Return
0 if devres is found and freed, -ENOENT if not found.
devres_open_group() #
void * Open a new devres group
Parameters
struct device *dev: Device to open devres group forvoid *id: Separator IDgfp_t gfp: Allocation flags
Description
Open a new devres group for dev with id. For id, using a pointer to an object which won't be used for another group is recommended. If id is NULL, address-wise unique ID is created.
Return
ID of the new group, NULL on failure.
devres_close_group() #
void Close a devres group
Parameters
struct device *dev: Device to close devres group forvoid *id: ID of target group, can be NULL
Description
Close the group identified by id. If id is NULL, the latest open group is selected.
devres_remove_group() #
void Remove a devres group
Parameters
struct device *dev: Device to remove group forvoid *id: ID of target group, can be NULL
Description
Remove the group identified by id. If id is NULL, the latest open group is selected. Note that removing a group doesn't affect any other resources.
devres_release_group() #
int Release resources in a devres group
Parameters
struct device *dev: Device to release group forvoid *id: ID of target group, can be NULL
Description
Release all resources in the group identified by id. If id is NULL, the latest open group is selected. The selected group and groups properly nested inside the selected group are removed.
Return
The number of released non-group resources.
__devm_add_action() #
int add a custom action to list of managed resources
Parameters
struct device *dev: Device that owns the actionvoid (*action)(void *): Function that should be calledvoid *data: Pointer to data passed to action implementationconst char *name: Name of the resource (for debugging purposes)
Description
This adds a custom action to the list of managed resources so that it gets executed as part of standard resource unwinding.
devm_remove_action_nowarn() #
int removes previously added custom action
Parameters
struct device *dev: Device that owns the actionvoid (*action)(void *): Function implementing the actionvoid *data: Pointer to data passed to action implementation
Description
Removes instance of action previously added by devm_add_action().
Both action and data should match one of the existing entries.
In contrast to devm_remove_action(), this function does not WARN() if no
entry could have been found.
This should only be used if the action is contained in an object with independent lifetime management, e.g. the Devres rust abstraction.
Causing the warning from regular driver code most likely indicates an abuse of the devres API.
Return
0 on success, -ENOENT if no entry could have been found.
devm_release_action() #
void release previously added custom action
Parameters
struct device *dev: Device that owns the actionvoid (*action)(void *): Function implementing the actionvoid *data: Pointer to data passed to action implementation
Description
Releases and removes instance of action previously added by
devm_add_action(). Both action and data should match one of the
existing entries.
devm_kmalloc() #
void * Resource-managed kmalloc
Parameters
struct device *dev: Device to allocate memory forsize_t size: Allocation sizegfp_t gfp: Allocation gfp flags
Description
Managed kmalloc. Memory allocated with this function is automatically freed on driver detach. Like all other devres resources, guaranteed alignment is unsigned long long.
Return
Pointer to allocated memory on success, NULL on failure.
devm_krealloc() #
void * Resource-managed krealloc()
Parameters
struct device *dev: Device to re-allocate memory forvoid *ptr: Pointer to the memory chunk to re-allocatesize_t new_size: New allocation sizegfp_t gfp: Allocation gfp flags
Description
Managed krealloc(). Resizes the memory chunk allocated with devm_kmalloc().
Behaves similarly to regular krealloc(): if ptr is NULL or ZERO_SIZE_PTR,
it's the equivalent of devm_kmalloc(). If new_size is zero, it frees the
previously allocated memory and returns ZERO_SIZE_PTR. This function doesn't
change the order in which the release callback for the re-alloc'ed devres
will be called (except when falling back to devm_kmalloc() or when freeing
resources when new_size is zero). The contents of the memory are preserved
up to the lesser of new and old sizes.
devm_kstrdup() #
char * Allocate resource managed space and copy an existing string into that.
Parameters
struct device *dev: Device to allocate memory forconst char *s: the string to duplicategfp_t gfp: the GFP mask used in thedevm_kmalloc()call when allocating memory
Return
Pointer to allocated string on success, NULL on failure.
devm_kstrdup_const() #
const char * resource managed conditional string duplication
Parameters
struct device *dev: device for which to duplicate the stringconst char *s: the string to duplicategfp_t gfp: the GFP mask used in thekmalloc()call when allocating memory
Description
Strings allocated by devm_kstrdup_const will be automatically freed when the associated device is detached.
Return
Source string if it is in .rodata section otherwise it falls back to devm_kstrdup.
devm_kvasprintf() #
char * Allocate resource managed space and format a string into that.
Parameters
struct device *dev: Device to allocate memory forgfp_t gfp: the GFP mask used in thedevm_kmalloc()call when allocating memoryconst char *fmt: Theprintf()-style format stringva_list ap: Arguments for the format string
Return
Pointer to allocated string on success, NULL on failure.
devm_kasprintf() #
char * Allocate resource managed space and format a string into that.
Parameters
struct device *dev: Device to allocate memory forgfp_t gfp: the GFP mask used in thedevm_kmalloc()call when allocating memoryconst char *fmt: Theprintf()-style format string...: Arguments for the format string
Return
Pointer to allocated string on success, NULL on failure.
devm_kfree() #
void Resource-managed kfree
Parameters
struct device *dev: Device this memory belongs toconst void *p: Memory to free
Description
Free memory allocated with devm_kmalloc().
devm_kmemdup() #
void * Resource-managed kmemdup
Parameters
struct device *dev: Device this memory belongs toconst void *src: Memory region to duplicatesize_t len: Memory region lengthgfp_t gfp: GFP mask to use
Description
Duplicate region of a memory using resource managed kmalloc
devm_kmemdup_const() #
const void * conditionally duplicate and manage a region of memory
Parameters
struct device *dev: Device this memory belongs toconst void *src: memory region to duplicatesize_t len: memory region length,gfp_t gfp: GFP mask to use
Return
source address if it is in .rodata or the return value of kmemdup()
to which the function falls back otherwise.
devm_get_free_pages() #
unsigned long Resource-managed __get_free_pages
Parameters
struct device *dev: Device to allocate memory forgfp_t gfp_mask: Allocation gfp flagsunsigned int order: Allocation size is (1 << order) pages
Description
Managed get_free_pages. Memory allocated with this function is automatically freed on driver detach.
Return
Address of allocated memory on success, 0 on failure.
devm_free_pages() #
void Resource-managed free_pages
Parameters
struct device *dev: Device this memory belongs tounsigned long addr: Memory to free
Description
Free memory allocated with devm_get_free_pages(). Unlike free_pages,
there is no need to supply the order.
__devm_alloc_percpu() #
void __percpu * Resource-managed alloc_percpu
Parameters
struct device *dev: Device to allocate per-cpu memory forsize_t size: Size of per-cpu memory to allocatesize_t align: Alignment of per-cpu memory to allocate
Description
Managed alloc_percpu. Per-cpu memory allocated with this function is automatically freed on driver detach.
Return
Pointer to allocated memory on success, NULL on failure.
Component Helper for Aggregate Drivers
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
The component helper allows drivers to collect a pile of sub-devices,
including their bound drivers, into an aggregate driver. Various subsystems
already provide functions to get hold of such components, e.g.
of_clk_get_by_name(). The component helper can be used when such a
subsystem-specific way to find a device is not available: The component
helper fills the niche of aggregate drivers for specific hardware, where
further standardization into a subsystem would not be practical. The common
example is when a logical device (e.g. a DRM display driver) is spread around
the SoC on various components (scanout engines, blending blocks, transcoders
for various outputs and so on).
The component helper also doesn't solve runtime dependencies, e.g. for system suspend and resume operations. See also device links.
Components are registered using component_add() and unregistered with
component_del(), usually from the driver's probe and disconnect functions.
Aggregate drivers first assemble a component match list of what they need
using component_match_add(). This is then registered as an aggregate driver
using component_master_add_with_match(), and unregistered using
component_master_del().
API #
struct component_ops #
callbacks for component drivers
Definition
;
Members
bind: Called throughcomponent_bind_all()when the aggregate driver is ready to bind the overall driver.unbind: Called throughcomponent_unbind_all()when the aggregate driver is ready to bind the overall driver, or whencomponent_bind_all()fails part-ways through and needs to unbind some already bound components.
Description
Components are registered with component_add() and unregistered with
component_del().
struct component_master_ops #
callback for the aggregate driver
Definition
;
Members
-
bind: Called when all components or the aggregate driver, as specified in the match list passed tocomponent_master_add_with_match(), are ready. Usually there are 3 steps to bind an aggregate driver:-
Allocate a structure for the aggregate driver.
-
Bind all components to the aggregate driver by calling
component_bind_all()with the aggregate driver structure as opaque pointer data. -
Register the aggregate driver with the subsystem to publish its interfaces.
Note that the lifetime of the aggregate driver does not align with any of the underlying
struct deviceinstances. Therefore devm cannot be used and all resources acquired or allocated in this callback must be explicitly released in the unbind callback. -
-
unbind: Called when either the aggregate driver, usingcomponent_master_del(), or one of its components, usingcomponent_del(), is unregistered.
Description
Aggregate drivers are registered with component_master_add_with_match() and
unregistered with component_master_del().
component_match_add() #
void add a component match entry
Parameters
struct device *parent: device with the aggregate driverstruct component_match **matchptr: pointer to the list of component matchesint (*compare)(struct device *, void *): compare function to match against all componentsvoid *compare_data: opaque pointer passed to the compare function
Description
Adds a new component match to the list stored in matchptr, which the parent
aggregate driver needs to function. The list of component matches pointed to
by matchptr must be initialized to NULL before adding the first match. This
only matches against components added with component_add().
The allocated match list in matchptr is automatically released using devm actions.
See also component_match_add_release() and component_match_add_typed().
component_compare_of() #
int A common component compare function for of_node
Parameters
-
struct device *dev: component device -
void *data:compare_data from
component_match_add_release()
Description
A common compare function when compare_data is device of_node. e.g.
component_match_add_release(masterdev, match, component_release_of,
component_compare_of, component_dev_of_node)
component_release_of() #
void A common component release function for of_node
Parameters
-
struct device *dev: component device -
void *data:compare_data from
component_match_add_release()
Description
About the example, Please see component_compare_of().
component_compare_dev() #
int A common component compare function for dev
Parameters
-
struct device *dev: component device -
void *data:compare_data from
component_match_add_release()
Description
A common compare function when compare_data is struce device. e.g.
component_match_add(masterdev, match, component_compare_dev, component_dev)
component_compare_dev_name() #
int A common component compare function for device name
Parameters
-
struct device *dev: component device -
void *data:compare_data from
component_match_add_release()
Description
A common compare function when compare_data is device name string. e.g.
component_match_add(masterdev, match, component_compare_dev_name,
"component_dev_name")
component_match_add_release() #
void add a component match entry with release callback
Parameters
struct device *parent: parent device of the aggregate driverstruct component_match **matchptr: pointer to the list of component matchesvoid (*release)(struct device *, void *): release function for compare_dataint (*compare)(struct device *, void *): compare function to match against all componentsvoid *compare_data: opaque pointer passed to the compare function
Description
Adds a new component match to the list stored in matchptr, which the
aggregate driver needs to function. The list of component matches pointed to
by matchptr must be initialized to NULL before adding the first match. This
only matches against components added with component_add().
The allocated match list in matchptr is automatically released using devm
actions, where upon release will be called to free any references held by
compare_data, e.g. when compare_data is a device_node that must be
released with of_node_put().
See also component_match_add() and component_match_add_typed().
component_match_add_typed() #
void add a component match entry for a typed component
Parameters
struct device *parent: parent device of the aggregate driverstruct component_match **matchptr: pointer to the list of component matchesint (*compare_typed)(struct device *, int, void *): compare function to match against all typed componentsvoid *compare_data: opaque pointer passed to the compare function
Description
Adds a new component match to the list stored in matchptr, which the
aggregate driver needs to function. The list of component matches pointed to
by matchptr must be initialized to NULL before adding the first match. This
only matches against components added with component_add_typed().
The allocated match list in matchptr is automatically released using devm actions.
See also component_match_add_release() and component_match_add_typed().
component_master_add_with_match() #
int register an aggregate driver
Parameters
struct device *parent: parent device of the aggregate driverconst struct component_master_ops *ops: callbacks for the aggregate driverstruct component_match *match: component match list for the aggregate driver
Description
Registers a new aggregate driver consisting of the components added to match
by calling one of the component_match_add() functions. Once all components in
match are available, it will be assembled by calling
component_master_ops.bind from ops. Must be unregistered by calling
component_master_del().
component_master_del() #
void unregister an aggregate driver
Parameters
struct device *parent: parent device of the aggregate driverconst struct component_master_ops *ops: callbacks for the aggregate driver
Description
Unregisters an aggregate driver registered with
component_master_add_with_match(). If necessary the aggregate driver is first
disassembled by calling component_master_ops.unbind from ops.
component_unbind_all() #
void unbind all components of an aggregate driver
Parameters
struct device *parent: parent device of the aggregate drivervoid *data: opaque pointer, passed to all components
Description
Unbinds all components of the aggregate device by passing data to their
component_ops.unbind functions. Should be called from
component_master_ops.unbind.
component_bind_all() #
int bind all components of an aggregate driver
Parameters
struct device *parent: parent device of the aggregate drivervoid *data: opaque pointer, passed to all components
Description
Binds all components of the aggregate dev by passing data to their
component_ops.bind functions. Should be called from
component_master_ops.bind.
component_add_typed() #
int register a component
Parameters
struct device *dev: component deviceconst struct component_ops *ops: component callbacksint subcomponent: nonzero identifier for subcomponents
Description
Register a new component for dev. Functions in ops will be call when the
aggregate driver is ready to bind the overall driver by calling
component_bind_all(). See also struct component_ops.
subcomponent must be nonzero and is used to differentiate between multiple
components registered on the same device dev. These components are match
using component_match_add_typed().
The component needs to be unregistered at driver unload/disconnect by
calling component_del().
See also component_add().
component_add() #
int register a component
Parameters
struct device *dev: component deviceconst struct component_ops *ops: component callbacks
Description
Register a new component for dev. Functions in ops will be called when the
aggregate driver is ready to bind the overall driver by calling
component_bind_all(). See also struct component_ops.
The component needs to be unregistered at driver unload/disconnect by
calling component_del().
See also component_add_typed() for a variant that allows multiple different
components on the same device.
component_del() #
void unregister a component
Parameters
struct device *dev: component deviceconst struct component_ops *ops: component callbacks
Description
Unregister a component added with component_add(). If the component is bound
into an aggregate driver, this will force the entire aggregate driver, including
all its components, to be unbound.
Kernel Connector
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Kernel connector - new netlink based userspace <-> kernel space easy to use communication module.
The Connector driver makes it easy to connect various agents using a netlink based network. One must register a callback and an identifier. When the driver receives a special netlink message with the appropriate identifier, the appropriate callback will be called.
From the userspace point of view it's quite straightforward:
socket();
bind();
send();
recv();
But if kernelspace wants to use the full power of such connections, the driver writer must create special sockets, must know about struct sk_buff handling, etc... The Connector driver allows any kernelspace agents to use netlink based networking for inter-process communication in a significantly easier way:
int cn_add_callback(const struct cb_id *id, char *name, void (*callback) (struct cn_msg *, struct netlink_skb_parms *));
void cn_netlink_send_mult(struct cn_msg *msg, u16 len, u32 portid, u32 __group, int gfp_mask);
void cn_netlink_send(struct cn_msg *msg, u32 portid, u32 __group, int gfp_mask);
struct cb_id
{
__u32 idx;
__u32 val;
};
idx and val are unique identifiers which must be registered in the connector.h header for in-kernel usage. void (*callback) (void *) is a callback function which will be called when a message with above idx.val is received by the connector core. The argument for that function must be dereferenced to struct cn_msg *:
struct cn_msg
{
struct cb_id id;
__u32 seq;
__u32 ack;
__u16 len; /* Length of the following data */
__u16 flags;
__u8 data[0];
};
Connector interfaces #
cn_add_callback()#intRegisters new callback with connector core.
Parameters
const struct cb_id *id: unique connector's user identifier. It must be registered in connector.h for legal in-kernel users.const char *name: connector's callback symbolic name.void (*callback)(struct cn_msg *, struct netlink_skb_parms *): connector's callback. parameters arecn_msgand the sender's credentials
cn_del_callback()#voidUnregisters new callback with connector core.
Parameters
const struct cb_id *id: unique connector's user identifier.
cn_netlink_send_mult()#intSends message to the specified groups.
Parameters
struct cn_msg *msg: message header(with attached data).u16 len: Number of msg to be sent.u32 portid: destination port. If non-zero the message will be sent to the given port, which should be set to the original sender.u32 group: destination group. If portid and group is zero, then appropriate group will be searched through all registered connector users, and message will be delivered to the group which was created for user with the same ID as in msg. If group is not zero, then message will be delivered to the specified group.gfp_t gfp_mask: GFP mask.netlink_filter_fn filter: Filter function to be used at netlink layer.void *filter_data: Filter data to be supplied to the filter functionDescription
It can be safely called from softirq context, but may silently fail under strong memory pressure.
If there are no listeners for given group
-ESRCHcan be returned.
cn_netlink_send()#intSends message to the specified groups.
Parameters
struct cn_msg *msg: message header(with attached data).u32 portid: destination port. If non-zero the message will be sent to the given port, which should be set to the original sender.u32 group: destination group. If portid and group is zero, then appropriate group will be searched through all registered connector users, and message will be delivered to the group which was created for user with the same ID as in msg. If group is not zero, then message will be delivered to the specified group.gfp_t gfp_mask: GFP mask.Description
It can be safely called from softirq context, but may silently fail under strong memory pressure.
If there are no listeners for given group
-ESRCHcan be returned.
Note:
When registering new callback user, connector core assigns netlink group to the user which is equal to its id.idx.
Protocol description #
The current framework offers a transport layer with fixed headers. The recommended protocol which uses such a header is as following:
msg->seq and msg->ack are used to determine message genealogy. When someone sends a message, they use a locally unique sequence and random acknowledge number. The sequence number may be copied into nlmsghdr->nlmsg_seq too.
The sequence number is incremented with each message sent.
If you expect a reply to the message, then the sequence number in the received message MUST be the same as in the original message, and the acknowledge number MUST be the same + 1.
If we receive a message and its sequence number is not equal to one we are expecting, then it is a new message. If we receive a message and its sequence number is the same as one we are expecting, but its acknowledge is not equal to the sequence number in the original message + 1, then it is a new message.
Obviously, the protocol header contains the above id.
The connector allows event notification in the following form: kernel driver or userspace process can ask connector to notify it when selected ids will be turned on or off (registered or unregistered its callback). It is done by sending a special command to the connector driver (it also registers itself with id={-1, -1}).
As example of this usage can be found in the cn_test.c module which uses the connector to request notification and to send messages.
Reliability #
Netlink itself is not a reliable protocol. That means that messages can be lost due to memory pressure or process' receiving queue overflowed, so caller is warned that it must be prepared. That is why the struct cn_msg [main connector's message header] contains u32 seq and u32 ack fields.
Userspace usage #
2.6.14 has a new netlink socket implementation, which by default does not allow people to send data to netlink groups other than 1. So, if you wish to use a netlink socket (for example using connector) with a different group number, the userspace application must subscribe to that group first. It can be achieved by the following pseudocode:
s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
l_local.nl_family = AF_NETLINK;
l_local.nl_groups = 12345;
l_local.nl_pid = 0;
if (bind(s, (struct sockaddr *)&l_local, sizeof(struct sockaddr_nl)) == -1) {
perror("bind");
close(s);
return -1;
}
{
int on = l_local.nl_groups;
setsockopt(s, 270, 1, &on, sizeof(on));
}
Where 270 above is SOL_NETLINK, and 1 is a NETLINK_ADD_MEMBERSHIP socket option. To drop a multicast subscription, one should call the above socket option with the NETLINK_DROP_MEMBERSHIP parameter which is defined as 0.
2.6.14 netlink code only allows to select a group which is less or equal to the maximum group number, which is used at netlink_kernel_create() time. In case of connector it is CN_NETLINK_USERS + 0xf, so if you want to use group number 12345, you must increment CN_NETLINK_USERS to that number. Additional 0xf numbers are allocated to be used by non-in-kernel users.
Due to this limitation, group 0xffffffff does not work now, so one can not use add/remove connector's group notifications, but as far as I know, only cn_test.c test module used it.
Some work in netlink area is still being done, so things can be changed in 2.6.15 timeframe, if it will happen, documentation will be updated for that kernel.
Code samples #
Sample code for a connector test module and user space can be found in samples/connector/. To build this code, enable CONFIG_CONNECTOR and CONFIG_SAMPLES.
Console Drivers
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
The Linux kernel has 2 general types of console drivers. The first type is assigned by the kernel to all the virtual consoles during the boot process. This type will be called 'system driver', and only one system driver is allowed to exist. The system driver is persistent and it can never be unloaded, though it may become inactive.
The second type has to be explicitly loaded and unloaded. This will be called 'modular driver' by this document. Multiple modular drivers can coexist at any time with each driver sharing the console with other drivers including the system driver. However, modular drivers cannot take over the console that is currently occupied by another modular driver. (Exception: Drivers that call do_take_over_console() will succeed in the takeover regardless of the type of driver occupying the consoles.) They can only take over the console that is occupied by the system driver. In the same token, if the modular driver is released by the console, the system driver will take over.
Modular drivers, from the programmer's point of view, have to call:
do_take_over_console() - load and bind driver to console layer
give_up_console() - unload driver; it will only work if driver
is fully unbound
In newer kernels, the following are also available:
do_register_con_driver()
do_unregister_con_driver()
If sysfs is enabled, the contents of /sys/class/vtconsole can be examined. This shows the console backends currently registered by the system which are named vtcon<n> where <n> is an integer from 0 to 15. Thus:
ls /sys/class/vtconsole
. .. vtcon0 vtcon1
Each directory in /sys/class/vtconsole has 3 files:
ls /sys/class/vtconsole/vtcon0
. .. bind name uevent
What do these files signify?
bind - this is a read/write file. It shows the status of the driver if read, or acts to bind or unbind the driver to the virtual consoles when written to. The possible values are:
0
- means the driver is not bound and if echo'ed, commands the driver to unbind
1
- means the driver is bound and if echo'ed, commands the driver to bind
name - read-only file. Shows the name of the driver in this format:
cat /sys/class/vtconsole/vtcon0/name (S) VGA+ '(S)' stands for a (S)ystem driver, i.e., it cannot be directly commanded to bind or unbind 'VGA+' is the name of the driver cat /sys/class/vtconsole/vtcon1/name (M) frame buffer device In this case, '(M)' stands for a (M)odular driver, one that can be directly commanded to bind or unbind.uevent - ignore this file
When unbinding, the modular driver is detached first, and then the system driver takes over the consoles vacated by the driver. Binding, on the other hand, will bind the driver to the consoles that are currently occupied by a system driver.
-
NOTE1:
Binding and unbinding must be selected in Kconfig. It's under:
Device Drivers -> Character devices -> Support for binding and unbinding console drivers -
NOTE2:
If any of the virtual consoles are in KD_GRAPHICS mode, then binding or unbinding will not succeed. An example of an application that sets the console to KD_GRAPHICS is X.
How useful is this feature? This is very useful for console driver developers. By unbinding the driver from the console layer, one can unload the driver, make changes, recompile, reload and rebind the driver without any need for rebooting the kernel. For regular users who may want to switch from framebuffer console to VGA console and vice versa, this feature also makes this possible. (NOTE NOTE NOTE: Please read fbcon.txt under Documentation/fb for more details.)
Notes for developers #
do_take_over_console() is now broken up into:
do_register_con_driver()
do_bind_con_driver() - private function
give_up_console() is a wrapper to do_unregister_con_driver(), and a driver must be fully unbound for this call to succeed. con_is_bound() will check if the driver is bound or not.
Guidelines for console driver writers #
In order for binding to and unbinding from the console to properly work, console drivers must follow these guidelines:
-
All drivers, except system drivers, must call either do_register_con_driver() or do_take_over_console(). do_register_con_driver() will just add the driver to the console's internal list. It won't take over the console. do_take_over_console(), as it name implies, will also take over (or bind to) the console.
-
All resources allocated during con->con_init() must be released in con->con_deinit().
-
All resources allocated in con->con_startup() must be released when the driver, which was previously bound, becomes unbound. The console layer does not have a complementary call to con->con_startup() so it's up to the driver to check when it's legal to release these resources. Calling con_is_bound() in con->con_deinit() will help. If the call returned false(), then it's safe to release the resources. This balance has to be ensured because con->con_startup() can be called again when a request to rebind the driver to the console arrives.
-
Upon exit of the driver, ensure that the driver is totally unbound. If the condition is satisfied, then the driver must call do_unregister_con_driver() or give_up_console().
-
do_unregister_con_driver() can also be called on conditions which make it impossible for the driver to service console requests. This can happen with the framebuffer console that suddenly lost all of its drivers.
The current crop of console drivers should still work correctly, but binding and unbinding them may cause problems. With minimal fixes, these drivers can be made to work correctly.
Antonino Daplas <adaplas@pol.net>
Device links
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
By default, the driver core only enforces dependencies between devices that are borne out of a parent/child relationship within the device hierarchy: When suspending, resuming or shutting down the system, devices are ordered based on this relationship, i.e. children are always suspended before their parent, and the parent is always resumed before its children.
Sometimes there is a need to represent device dependencies beyond the mere parent/child relationship, e.g. between siblings, and have the driver core automatically take care of them.
Secondly, the driver core by default does not enforce any driver presence dependencies, i.e. that one device must be bound to a driver before another one can probe or function correctly.
Often these two dependency types come together, so a device depends on another one both with regards to driver presence and with regards to suspend/resume and shutdown ordering.
Device links allow representation of such dependencies in the driver core.
In its standard or managed form, a device link combines both dependency types: It guarantees correct suspend/resume and shutdown ordering between a "supplier" device and its "consumer" devices, and it guarantees driver presence on the supplier. The consumer devices are not probed before the supplier is bound to a driver, and they're unbound before the supplier is unbound.
When driver presence on the supplier is irrelevant and only correct suspend/resume and shutdown ordering is needed, the device link may simply be set up with the DL_FLAG_STATELESS flag. In other words, enforcing driver presence on the supplier is optional.
Another optional feature is runtime PM integration: By setting the DL_FLAG_PM_RUNTIME flag on addition of the device link, the PM core is instructed to runtime resume the supplier and keep it active whenever and for as long as the consumer is runtime resumed.
Usage #
The earliest point in time when device links can be added is after device_add() has been called for the supplier and device_initialize() has been called for the consumer.
It is legal to add them later, but care must be taken that the system remains in a consistent state: E.g. a device link cannot be added in the midst of a suspend/resume transition, so either commencement of such a transition needs to be prevented with lock_system_sleep(), or the device link needs to be added from a function which is guaranteed not to run in parallel to a suspend/resume transition, such as from a device ->probe callback or a boot-time PCI quirk.
Another example for an inconsistent state would be a device link that represents a driver presence dependency, yet is added from the consumer's ->probe callback while the supplier hasn't started to probe yet: Had the driver core known about the device link earlier, it wouldn't have probed the consumer in the first place. The onus is thus on the consumer to check presence of the supplier after adding the link, and defer probing on non-presence. [Note that it is valid to create a link from the consumer's ->probe callback while the supplier is still probing, but the consumer must know that the supplier is functional already at the link creation time (that is the case, for instance, if the consumer has just acquired some resources that would not have been available had the supplier not been functional then).]
If a device link with DL_FLAG_STATELESS set (i.e. a stateless device link) is added in the ->probe callback of the supplier or consumer driver, it is typically deleted in its ->remove callback for symmetry. That way, if the driver is compiled as a module, the device link is added on module load and orderly deleted on unload. The same restrictions that apply to device link addition (e.g. exclusion of a parallel suspend/resume transition) apply equally to deletion. Device links managed by the driver core are deleted automatically by it.
Several flags may be specified on device link addition, two of which have already been mentioned above: DL_FLAG_STATELESS to express that no driver presence dependency is needed (but only correct suspend/resume and shutdown ordering) and DL_FLAG_PM_RUNTIME to express that runtime PM integration is desired.
Two other flags are specifically targeted at use cases where the device link is added from the consumer's ->probe callback: DL_FLAG_RPM_ACTIVE can be specified to runtime resume the supplier and prevent it from suspending before the consumer is runtime suspended. DL_FLAG_AUTOREMOVE_CONSUMER causes the device link to be automatically purged when the consumer fails to probe or later unbinds.
Similarly, when the device link is added from supplier's ->probe callback, DL_FLAG_AUTOREMOVE_SUPPLIER causes the device link to be automatically purged when the supplier fails to probe or later unbinds.
If neither DL_FLAG_AUTOREMOVE_CONSUMER nor DL_FLAG_AUTOREMOVE_SUPPLIER is set, DL_FLAG_AUTOPROBE_CONSUMER can be used to request the driver core to probe for a driver for the consumer driver on the link automatically after a driver has been bound to the supplier device.
Note, however, that any combinations of DL_FLAG_AUTOREMOVE_CONSUMER, DL_FLAG_AUTOREMOVE_SUPPLIER or DL_FLAG_AUTOPROBE_CONSUMER with DL_FLAG_STATELESS are invalid and cannot be used.
Limitations #
Driver authors should be aware that a driver presence dependency for managed device links (i.e. when DL_FLAG_STATELESS is not specified on link addition) may cause probing of the consumer to be deferred indefinitely. This can become a problem if the consumer is required to probe before a certain initcall level is reached. Worse, if the supplier driver is blacklisted or missing, the consumer will never be probed.
Moreover, managed device links cannot be deleted directly. They are deleted by the driver core when they are not necessary any more in accordance with the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER flags. However, stateless device links (i.e. device links with DL_FLAG_STATELESS set) are expected to be removed by whoever called device_link_add() to add them with the help of either device_link_del() or device_link_remove().
Passing DL_FLAG_RPM_ACTIVE along with DL_FLAG_STATELESS to device_link_add() may cause the PM-runtime usage counter of the supplier device to remain nonzero after a subsequent invocation of either device_link_del() or device_link_remove() to remove the device link returned by it. This happens if device_link_add() is called twice in a row for the same consumer-supplier pair without removing the link between these calls, in which case allowing the PM-runtime usage counter of the supplier to drop on an attempt to remove the link may cause it to be suspended while the consumer is still PM-runtime-active and that has to be avoided. [To work around this limitation it is sufficient to let the consumer runtime suspend at least once, or call pm_runtime_set_suspended() for it with PM-runtime disabled, between the device_link_add() and device_link_del() or device_link_remove() calls.]
Sometimes drivers depend on optional resources. They are able to operate in a degraded mode (reduced feature set or performance) when those resources are not present. An example is an SPI controller that can use a DMA engine or work in PIO mode. The controller can determine presence of the optional resources at probe time but on non-presence there is no way to know whether they will become available in the near future (due to a supplier driver probing) or never. Consequently it cannot be determined whether to defer probing or not. It would be possible to notify drivers when optional resources become available after probing, but it would come at a high cost for drivers as switching between modes of operation at runtime based on the availability of such resources would be much more complex than a mechanism based on probe deferral. In any case optional resources are beyond the scope of device links.
Examples #
-
An MMU device exists alongside a busmaster device, both are in the same power domain. The MMU implements DMA address translation for the busmaster device and shall be runtime resumed and kept active whenever and as long as the busmaster device is active. The busmaster device's driver shall not bind before the MMU is bound. To achieve this, a device link with runtime PM integration is added from the busmaster device (consumer) to the MMU device (supplier). The effect with regards to runtime PM is the same as if the MMU was the parent of the master device.
The fact that both devices share the same power domain would normally suggest usage of a struct dev_pm_domain or struct generic_pm_domain, however these are not independent devices that happen to share a power switch, but rather the MMU device serves the busmaster device and is useless without it. A device link creates a synthetic hierarchical relationship between the devices and is thus more apt.
-
A Thunderbolt host controller comprises a number of PCIe hotplug ports and an NHI device to manage the PCIe switch. On resume from system sleep, the NHI device needs to re-establish PCI tunnels to attached devices before the hotplug ports can resume. If the hotplug ports were children of the NHI, this resume order would automatically be enforced by the PM core, but unfortunately they're aunts. The solution is to add device links from the hotplug ports (consumers) to the NHI device (supplier). A driver presence dependency is not necessary for this use case.
-
Discrete GPUs in hybrid graphics laptops often feature an HDA controller for HDMI/DP audio. In the device hierarchy the HDA controller is a sibling of the VGA device, yet both share the same power domain and the HDA controller is only ever needed when an HDMI/DP display is attached to the VGA device. A device link from the HDA controller (consumer) to the VGA device (supplier) aptly represents this relationship.
-
ACPI allows definition of a device start order by way of _DEP objects. A classical example is when ACPI power management methods on one device are implemented in terms of I2C accesses and require a specific I2C controller to be present and functional for the power management of the device in question to work.
-
In some SoCs a functional dependency exists from display, video codec and video processing IP cores on transparent memory access IP cores that handle burst access and compression/decompression.
Alternatives #
-
A struct dev_pm_domain can be used to override the bus, class or device type callbacks. It is intended for devices sharing a single on/off switch, however it does not guarantee a specific suspend/resume ordering, this needs to be implemented separately. It also does not by itself track the runtime PM status of the involved devices and turn off the power switch only when all of them are runtime suspended. Furthermore it cannot be used to enforce a specific shutdown ordering or a driver presence dependency.
-
A struct generic_pm_domain is a lot more heavyweight than a device link and does not allow for shutdown ordering or driver presence dependencies. It also cannot be used on ACPI systems.
Implementation #
The device hierarchy, which -- as the name implies -- is a tree, becomes a directed acyclic graph once device links are added.
Ordering of these devices during suspend/resume is determined by the dpm_list. During shutdown it is determined by the devices_kset. With no device links present, the two lists are a flattened, one-dimensional representations of the device tree such that a device is placed behind all its ancestors. That is achieved by traversing the ACPI namespace or OpenFirmware device tree top-down and appending devices to the lists as they are discovered.
Once device links are added, the lists need to satisfy the additional constraint that a device is placed behind all its suppliers, recursively. To ensure this, upon addition of the device link the consumer and the entire sub-graph below it (all children and consumers of the consumer) are moved to the end of the list. (Call to device_reorder_to_tail() from device_link_add().)
To prevent introduction of dependency loops into the graph, it is verified upon device link addition that the supplier is not dependent on the consumer or any children or consumers of the consumer. (Call to device_is_dependent() from device_link_add().) If that constraint is violated, device_link_add() will return NULL and a WARNING will be logged.
Notably this also prevents the addition of a device link from a parent device to a child. However the converse is allowed, i.e. a device link from a child to a parent. Since the driver core already guarantees correct suspend/resume and shutdown ordering between parent and child, such a device link only makes sense if a driver presence dependency is needed on top of that. In this case driver authors should weigh carefully if a device link is at all the right tool for the purpose. A more suitable approach might be to simply use deferred probing or add a device flag causing the parent driver to be probed before the child one.
State machine #
enum device_link_state #
Device link states.
Constants
DL_STATE_NONE: The presence of the drivers is not being tracked.DL_STATE_DORMANT: None of the supplier/consumer drivers is present.DL_STATE_AVAILABLE: The supplier driver is present, but the consumer is not.DL_STATE_CONSUMER_PROBE: The consumer is probing (supplier driver present).DL_STATE_ACTIVE: Both the supplier and consumer drivers are present.DL_STATE_SUPPLIER_UNBIND: The supplier driver is unbinding.
.=============================.
| |
v |
DORMANT <=> AVAILABLE <=> CONSUMER_PROBE => ACTIVE
^ |
| |
'============ SUPPLIER_UNBIND <============'
-
The initial state of a device link is automatically determined by
device_link_add()based on the driver presence on the supplier and consumer. If the link is created before any devices are probed, it is set toDL_STATE_DORMANT. -
When a supplier device is bound to a driver, links to its consumers progress to
DL_STATE_AVAILABLE. (Call todevice_links_driver_bound()fromdriver_bound().) -
Before a consumer device is probed, presence of supplier drivers is verified by checking the consumer device is not in the wait_for_suppliers list and by checking that links to suppliers are in
DL_STATE_AVAILABLEstate. The state of the links is updated toDL_STATE_CONSUMER_PROBE. (Call todevice_links_check_suppliers()fromreally_probe().) This prevents the supplier from unbinding. (Call towait_for_device_probe()fromdevice_links_unbind_consumers().) -
If the probe fails, links to suppliers revert back to
DL_STATE_AVAILABLE. (Call todevice_links_no_driver()fromreally_probe().) -
If the probe succeeds, links to suppliers progress to
DL_STATE_ACTIVE. (Call todevice_links_driver_bound()fromdriver_bound().) -
When the consumer's driver is later on removed, links to suppliers revert back to
DL_STATE_AVAILABLE. (Call to__device_links_no_driver()fromdevice_links_driver_cleanup(), which in turn is called from__device_release_driver().) -
Before a supplier's driver is removed, links to consumers that are not bound to a driver are updated to
DL_STATE_SUPPLIER_UNBIND. (Call todevice_links_busy()from__device_release_driver().) This prevents the consumers from binding. (Call todevice_links_check_suppliers()fromreally_probe().) Consumers that are bound are freed from their driver; consumers that are probing are waited for until they are done. (Call todevice_links_unbind_consumers()from__device_release_driver().) Once all links to consumers are inDL_STATE_SUPPLIER_UNBINDstate, the supplier driver is released and the links revert toDL_STATE_DORMANT. (Call todevice_links_driver_cleanup()from__device_release_driver().)
API #
See device_link_add(), device_link_del() and device_link_remove().
Frame Buffer Library
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
The frame buffer drivers depend heavily on four data structures. These structures are declared in include/linux/fb.h. They are fb_info, fb_var_screeninfo, fb_fix_screeninfo and fb_monospecs. The last three can be made available to and from userland.
fb_info defines the current state of a particular video card. Inside fb_info, there exists a fb_ops structure which is a collection of needed functions to make fbdev and fbcon work. fb_info is only visible to the kernel.
fb_var_screeninfo is used to describe the features of a video card that are user defined. With fb_var_screeninfo, things such as depth and the resolution may be defined.
The next structure is fb_fix_screeninfo. This defines the properties of a card that are created when a mode is set and can't be changed otherwise. A good example of this is the start of the frame buffer memory. This "locks" the address of the frame buffer memory, so that it cannot be changed or moved.
The last structure is fb_monospecs. In the old API, there was little importance for fb_monospecs. This allowed for forbidden things such as setting a mode of 800x600 on a fix frequency monitor. With the new API, fb_monospecs prevents such things, and if used correctly, can prevent a monitor from being cooked. fb_monospecs will not be useful until kernels 2.5.x.
Frame Buffer Memory #
register_framebuffer() #
int registers a frame buffer device
Parameters
struct fb_info *fb_info: frame buffer info structure
Description
Registers a frame buffer device fb_info.
Returns negative errno on error, or zero for success.
unregister_framebuffer() #
void releases a frame buffer device
Parameters
struct fb_info *fb_info: frame buffer info structure
Description
Unregisters a frame buffer device fb_info.
Returns negative errno on error, or zero for success.
This function will also notify the framebuffer console to release the driver.
This is meant to be called within a driver's module_exit()
function. If this is called outside module_exit(), ensure
that the driver implements fb_open() and fb_release() to
check that no processes are using the device.
devm_register_framebuffer() #
int resource-managed frame buffer device registration
Parameters
struct device *dev: device the framebuffer belongs tostruct fb_info *fb_info: frame buffer info structure
Description
Registers a frame buffer device fb_info to device dev.
Returns negative errno on error, or zero for success.
fb_set_suspend() #
void low level driver signals suspend
Parameters
struct fb_info *info: framebuffer affectedint state: 0 = resuming, !=0 = suspending
Description
This is meant to be used by low level drivers to signal suspend/resume to the core & clients. It must be called with the console semaphore held
Frame Buffer Colormap #
fb_dealloc_cmap() #
void deallocate a colormap
Parameters
struct fb_cmap *cmap: frame buffer colormap structure
Description
Deallocates a colormap that was previously allocated with
fb_alloc_cmap().
fb_copy_cmap() #
int copy a colormap
Parameters
const struct fb_cmap *from: frame buffer colormap structurestruct fb_cmap *to: frame buffer colormap structure
Description
Copy contents of colormap from from to to.
fb_set_cmap() #
int set the colormap
Parameters
struct fb_cmap *cmap: frame buffer colormap structurestruct fb_info *info: frame buffer info structure
Description
Sets the colormap cmap for a screen of device info.
Returns negative errno on error, or zero on success.
fb_default_cmap() #
const struct fb_cmap * get default colormap
Parameters
int len: size of palette for a depth
Description
Gets the default colormap for a specific screen depth. len is the size of the palette for a particular screen depth.
Returns pointer to a frame buffer colormap structure.
fb_invert_cmaps() #
void invert all defaults colormaps
Parameters
void: no arguments
Description
Invert all default colormaps.
Frame Buffer Video Mode Database #
fb_try_mode() #
int test a video mode
Parameters
struct fb_var_screeninfo *var: frame buffer user defined part of displaystruct fb_info *info: frame buffer info structureconst struct fb_videomode *mode: frame buffer video mode structureunsigned int bpp: color depth in bits per pixel
Description
Tries a video mode to test it's validity for device info.
Returns 1 on success.
fb_delete_videomode() #
void removed videomode entry from modelist
Parameters
const struct fb_videomode *mode: videomode to removestruct list_head *head: struct list_head of modelist
NOTES
Will remove all matching mode entries
fb_find_mode() #
int finds a valid video mode
Parameters
struct fb_var_screeninfo *var: frame buffer user defined part of displaystruct fb_info *info: frame buffer info structureconst char *mode_option: string video mode to findconst struct fb_videomode *db: video mode databaseunsigned int dbsize: size of dbconst struct fb_videomode *default_mode: default video mode to fall back tounsigned int default_bpp: default color depth in bits per pixel
Description
Finds a suitable video mode, starting with the specified mode in mode_option with fallback to default_mode. If default_mode fails, all modes in the video mode database will be tried.
Valid mode specifiers for mode_option:
<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][p][m]
or
<name>[-<bpp>][@<refresh>]
with <xres>, <yres>, <bpp> and <refresh> decimal numbers and <name> a string.
If 'M' is present after yres (and before refresh/bpp if present), the function will compute the timings using VESA(tm) Coordinated Video Timings (CVT). If 'R' is present after 'M', will compute with reduced blanking (for flatpanels). If 'i' or 'p' are present, compute interlaced or progressive mode. If 'm' is present, add margins equal to 1.8% of xres rounded down to 8 pixels, and 1.8% of yres. The char 'i', 'p' and 'm' must be after 'M' and 'R'. Example:
1024x768MR-8@60m - Reduced blank with margins at 60Hz.
NOTE
The passed struct var is not cleared! This allows you to supply values for e.g. the grayscale and accel_flags fields.
Returns zero for failure, 1 if using specified mode_option, 2 if using specified mode_option with an ignored refresh rate, 3 if default mode is used, 4 if fall back to any valid mode.
fb_var_to_videomode() #
void convert fb_var_screeninfo to fb_videomode
Parameters
struct fb_videomode *mode: pointer to struct fb_videomodeconst struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfo
fb_videomode_to_var() #
void convert fb_videomode to fb_var_screeninfo
Parameters
struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfoconst struct fb_videomode *mode: pointer to struct fb_videomode
fb_mode_is_equal() #
int compare 2 videomodes
Parameters
const struct fb_videomode *mode1: first videomodeconst struct fb_videomode *mode2: second videomode
Return
1 if equal, 0 if not
fb_find_best_mode() #
const struct fb_videomode * find best matching videomode
Parameters
const struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfostruct list_head *head: pointer to struct list_head of modelist
Return
struct fb_videomode, NULL if none found
Description
IMPORTANT: This function assumes that all modelist entries in info->modelist are valid.
NOTES
Finds best matching videomode which has an equal or greater dimension than var->xres and var->yres. If more than 1 videomode is found, will return the videomode with the highest refresh rate
fb_find_nearest_mode() #
const struct fb_videomode * find closest videomode
Parameters
const struct fb_videomode *mode: pointer to struct fb_videomodestruct list_head *head: pointer to modelist
Description
Finds best matching videomode, smaller or greater in dimension. If more than 1 videomode is found, will return the videomode with the closest refresh rate.
fb_match_mode() #
const struct fb_videomode * find a videomode which exactly matches the timings in var
Parameters
const struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfostruct list_head *head: pointer to struct list_head of modelist
Return
struct fb_videomode, NULL if none found
fb_add_videomode() #
int adds videomode entry to modelist
Parameters
const struct fb_videomode *mode: videomode to addstruct list_head *head: struct list_head of modelist
NOTES
Will only add unmatched mode entries
fb_destroy_modelist() #
void destroy modelist
Parameters
struct list_head *head: struct list_head of modelist
fb_videomode_to_modelist() #
void convert mode array to mode list
Parameters
const struct fb_videomode *modedb: array of struct fb_videomodeint num: number of entries in arraystruct list_head *head: struct list_head of modelist
Frame Buffer Macintosh Video Mode Database #
mac_vmode_to_var() #
int converts vmode/cmode pair to var structure
Parameters
int vmode: MacOS video modeint cmode: MacOS color modestruct fb_var_screeninfo *var: frame buffer video mode structure
Description
Converts a MacOS vmode/cmode pair to a frame buffer video mode structure.
Returns negative errno on error, or zero for success.
mac_map_monitor_sense() #
int Convert monitor sense to vmode
Parameters
int sense: Macintosh monitor sense number
Description
Converts a Macintosh monitor sense number to a MacOS vmode number.
Returns MacOS vmode video mode number.
mac_find_mode() #
int find a video mode
Parameters
struct fb_var_screeninfo *var: frame buffer user defined part of displaystruct fb_info *info: frame buffer info structureconst char *mode_option: video mode name (see mac_modedb[])unsigned int default_bpp: default color depth in bits per pixel
Description
Finds a suitable video mode. Tries to set mode specified by mode_option. If the name of the wanted mode begins with 'mac', the Mac video mode database will be used, otherwise it will fall back to the standard video mode database.
Note
-
Function marked as __init and can only be used during
system boot.
Returns error code from fb_find_mode (see fb_find_mode function).
Frame Buffer Fonts #
Refer to the file lib/fonts/fonts.c for more information.
Device drivers infrastructure
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
The Basic Device Driver-Model Structures #
struct subsys_interface #
interfaces to device functions
Definition
;
Members
name: name of the device functionsubsys: subsystem of the devices to attach tonode: the list of functions registered at the subsystemadd_dev: device hookup to device function handlerremove_dev: device hookup to device function handler
Description
Simple interfaces attached to a subsystem. Multiple interfaces can attach to a subsystem and its devices. Unlike drivers, they do not exclusively claim or control devices. Interfaces usually represent a specific functionality of a subsystem/class of devices.
struct device_attribute #
Interface for exporting device attributes.
Definition
;
Members
attr: sysfs attribute definition.show: Show handler.store: Store handler.
struct dev_ext_attribute #
Exported device attribute with extra context.
Definition
;
Members
attr: Exported device attribute.var: Pointer to context.
DEVICE_ATTR() #
Define a device attribute.
Parameters
_name: Attribute name._mode: File mode._show: Show handler. Optional, but mandatory if attribute is readable._store: Store handler. Optional, but mandatory if attribute is writable.
Description
Convenience macro for defining a struct device_attribute.
For example, DEVICE_ATTR(foo, 0644, foo_show, foo_store); expands to:
struct device_attribute dev_attr_foo = ;
DEVICE_ATTR_PREALLOC() #
Define a preallocated device attribute.
Parameters
_name: Attribute name._mode: File mode._show: Show handler. Optional, but mandatory if attribute is readable._store: Store handler. Optional, but mandatory if attribute is writable.
Description
Like DEVICE_ATTR(), but SYSFS_PREALLOC is set on _mode.
DEVICE_ATTR_RW() #
Define a read-write device attribute.
Parameters
_name: Attribute name.
Description
Like DEVICE_ATTR(), but _mode is 0644, _show is <_name>_show,
and _store is <_name>_store.
DEVICE_ATTR_ADMIN_RW() #
Define an admin-only read-write device attribute.
Parameters
_name: Attribute name.
Description
Like DEVICE_ATTR_RW(), but _mode is 0600.
DEVICE_ATTR_RO() #
Define a readable device attribute.
Parameters
_name: Attribute name.
Description
Like DEVICE_ATTR(), but _mode is 0444 and _show is <_name>_show.
DEVICE_ATTR_ADMIN_RO() #
Define an admin-only readable device attribute.
Parameters
_name: Attribute name.
Description
Like DEVICE_ATTR_RO(), but _mode is 0400.
DEVICE_ATTR_WO() #
Define an admin-only writable device attribute.
Parameters
_name: Attribute name.
Description
Like DEVICE_ATTR(), but _mode is 0200 and _store is <_name>_store.
DEVICE_ULONG_ATTR() #
Define a device attribute backed by an unsigned long.
Parameters
_name: Attribute name._mode: File mode._var: Identifier of unsigned long.
Description
Like DEVICE_ATTR(), but _show and _store are automatically provided
such that reads and writes to the attribute from userspace affect _var.
DEVICE_INT_ATTR() #
Define a device attribute backed by an int.
Parameters
_name: Attribute name._mode: File mode._var: Identifier of int.
Description
Like DEVICE_ULONG_ATTR(), but _var is an int.
DEVICE_BOOL_ATTR() #
Define a device attribute backed by a bool.
Parameters
_name: Attribute name._mode: File mode._var: Identifier of bool.
Description
Like DEVICE_ULONG_ATTR(), but _var is a bool.
DEVICE_STRING_ATTR_RO() #
Define a device attribute backed by a r/o string.
Parameters
_name: Attribute name._mode: File mode._var: Identifier of string.
Description
Like DEVICE_ULONG_ATTR(), but _var is a string. Because the length of the
string allocation is unknown, the attribute must be read-only.
enum dl_dev_state #
Device driver presence tracking information.
Constants
DL_DEV_NO_DRIVER: There is no driver attached to the device.DL_DEV_PROBING: A driver is probing.DL_DEV_DRIVER_BOUND: The driver has been bound to the device.DL_DEV_UNBINDING: The driver is unbinding from the device.
enum device_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_SUPPORTED: This attribute is not supported for this device (default).DEVICE_REMOVABLE_UNKNOWN: Device location is Unknown.DEVICE_FIXED: Device is not removable by the user.DEVICE_REMOVABLE: Device is removable by the user.
struct dev_links_info #
Device data related to device links.
Definition
;
Members
suppliers: List of links to supplier devices.consumers: List of links to consumer devices.defer_sync: Hook to global list of devices that have deferred sync_state.status: Driver status information.
struct dev_msi_info #
Device data related to MSI
Definition
;
Members
domain: The MSI interrupt domain associated to the devicedata: Pointer to MSI device data
enum device_physical_location_panel #
Describes which panel surface of the system's housing the device connection point resides on.
Constants
DEVICE_PANEL_TOP: Device connection point is on the top panel.DEVICE_PANEL_BOTTOM: Device connection point is on the bottom panel.DEVICE_PANEL_LEFT: Device connection point is on the left panel.DEVICE_PANEL_RIGHT: Device connection point is on the right panel.DEVICE_PANEL_FRONT: Device connection point is on the front panel.DEVICE_PANEL_BACK: Device connection point is on the back panel.DEVICE_PANEL_UNKNOWN: The panel with device connection point is unknown.
enum device_physical_location_vertical_position #
Describes vertical position of the device connection point on the panel surface.
Constants
DEVICE_VERT_POS_UPPER: Device connection point is at upper part of panel.DEVICE_VERT_POS_CENTER: Device connection point is at center part of panel.DEVICE_VERT_POS_LOWER: Device connection point is at lower part of panel.
enum device_physical_location_horizontal_position #
Describes horizontal position of the device connection point on the panel surface.
Constants
DEVICE_HORI_POS_LEFT: Device connection point is at left part of panel.DEVICE_HORI_POS_CENTER: Device connection point is at center part of panel.DEVICE_HORI_POS_RIGHT: Device connection point is at right part of panel.
struct device_physical_location #
Device data related to physical location of the device connection point.
Definition
;
Members
panel: Panel surface of the system's housing that the device connection point resides on.vertical_position: Vertical position of the device connection point within the panel.horizontal_position: Horizontal position of the device connection point within the panel.dock: Set if the device connection point resides in a docking station or port replicator.lid: Set if this device connection point resides on the lid of laptop system.
enum struct_device_flags #
Flags in struct device
Constants
DEV_FLAG_READY_TO_PROBE: If set thendevice_add()has finished enough initialization that probe could be called.DEV_FLAG_COUNT: Number of defined struct_device_flags.
Description
Each flag should have a set of accessor functions created via
__create_dev_flag_accessors() for each access.
struct device #
The basic device structure
Definition
;
Members
kobj: A top-level, abstract class from which other classes are derived.parent: The device's "parent" device, the device to which it is attached. In most cases, a parent device is some sort of bus or host controller. If parent is NULL, the device, is a top-level device, which is not usually what you want.p: Holds the private data of the driver core portions of the device. See the comment of the struct device_private for detail.init_name: Initial name of the device.type: The type of device. This identifies the device type and carries type-specific information.bus: Type of bus device is on.driver: Which driver has allocated thisplatform_data: Platform data specific to the device.driver_data: Private pointer for driver specific info.driver_override: Driver name to force a match. Do not touch directly; usedevice_set_driver_override()instead.mutex: Mutex to synchronize calls to its driver.links: Links to suppliers and consumers of this device.power: For device power management. See Documentation/driver-api/pm/devices.rst for details.pm_domain: Provide callbacks that are executed during system suspend, hibernation, system resume and during runtime PM transitions along with subsystem-level and driver-level callbacks.em_pd: device's energy model performance domainpins: For device pin management. See Documentation/driver-api/pin-control.rst for details.msi: MSI related datadma_ops: DMA mapping operations for this device.dma_mask: Dma mask (if dma'ble device).coherent_dma_mask: Like dma_mask, but for alloc_coherent mapping as not all hardware supports 64-bit addresses for consistent allocations such descriptors.bus_dma_limit: Limit of an upstream bridge or bus which imposes a smaller DMA limit than the device itself supports.dma_range_map: map for DMA memory ranges relative to that of RAMdma_parms: A low level driver may set these to teach IOMMU code about segment limitations.dma_pools: Dma pools (if dma'ble device).dma_mem: Internal for coherent mem override.cma_area: Contiguous memory area for dma allocationsdma_io_tlb_mem: Software IO TLB allocator. Not for driver use.dma_io_tlb_pools: List of transient swiotlb memory pools.dma_io_tlb_lock: Protects changes to the list of active pools.dma_uses_io_tlb:trueif device has used the software IO TLB.archdata: For arch-specific additions.of_node: Associated device tree node.fwnode: Associated device node supplied by platform firmware.numa_node: NUMA node this device is close to.devt: For creating the sysfs "dev".id: device instancedevres_lock: Spinlock to protect the resource of the device.devres_head: The resources list of the device.class: The class of the device.groups: Optional attribute groups.release: Callback to free the device after all references have gone away. This should be set by the allocator of the device (i.e. the bus driver that discovered the device).iommu_group: IOMMU group the device belongs to.iommu: Per device generic IOMMU runtime dataphysical_location: Describes physical location of the device connection point in the system housing.removable: Whether the device can be removed from the system. This should be set by the subsystem / bus driver that discovered the device.offline_disabled: If set, the device is permanently online.offline: Set after successful invocation of bus type's .offline().of_node_reused: Set if the device-tree node is shared with an ancestor device.state_synced: The hardware state of this device has been synced to match the software state of this device by calling the driver/bussync_state()callback.can_match: The device has matched with a driver at least once or it is in a bus (like AMBA) which can't check for matching drivers until other devices probe successfully.dma_coherent: this particular device is dma coherent, even if the architecture supports non-coherent devices.dma_ops_bypass: If set totruethen the dma_ops are bypassed for the streaming DMA operations (->map_* / ->unmap_* / ->sync_*), and optionall (if the coherent mask is large enough) also for dma allocations. This flag is managed by the dma ops instance from ->dma_supported.dma_skip_sync: DMA sync operations can be skipped for coherent buffers.dma_iommu: Device is using default IOMMU implementation for DMA and doesn't rely on dma_ops structure.flags: DEV_FLAG_XXX flags. Use atomic bitfield operations to modify.
Example
-
For devices on custom boards, as typical of embedded
and SOC based hardware, Linux often uses platform_data to point to board-specific structures describing devices and how they are wired. That can include what ports are available, chip variants, which GPIO pins act in what additional roles, and so on. This shrinks the "Board Support Packages" (BSPs) and minimizes board-specific #ifdefs in drivers.
Description
At the lowest level, every device in a Linux system is represented by an instance of struct device. The device structure contains the information that the device model core needs to model the system. Most subsystems, however, track additional information about the devices they host. As a result, it is rare for devices to be represented by bare device structures; instead, that structure, like kobject structures, is usually embedded within a higher-level representation of the device.
struct device_link #
Device link representation.
Definition
;
Members
supplier: The device on the supplier end of the link.s_node: Hook to the supplier device's list of links to consumers.consumer: The device on the consumer end of the link.c_node: Hook to the consumer device's list of links to suppliers.link_dev: device used to expose link details in sysfsstatus: The state of the link (with respect to the presence of drivers).flags: Link flags.rpm_active: Whether or not the consumer device is runtime-PM-active.kref: Count repeated addition of the same link.rm_work: Work structure used for removing the link.supplier_preactivated: Supplier has been made active before consumer probe.
device_set_driver_override() #
int Helper to set or clear driver override.
Parameters
struct device *dev: Device to changeconst char *s: NUL-terminated string, new driver name to force a match, pass empty string to clear it ("" or "\n", where the latter is only for sysfs interface).
Description
Helper to set or clear driver override of a device.
Return
0 on success or a negative error code on failure.
device_has_driver_override() #
bool Check if a driver override has been set.
Parameters
struct device *dev: device to check
Description
Returns true if a driver override has been set for this device.
device_match_driver_override() #
int Match a driver against the device's driver_override.
Parameters
struct device *dev: device to checkconst struct device_driver *drv: driver to match against
Description
Returns > 0 if a driver override is set and matches the given driver, 0 if a driver override is set but does not match, or < 0 if a driver override is not set at all.
device_iommu_mapped() #
bool Returns true when the device DMA is translated by an IOMMU
Parameters
struct device *dev: Device to perform the check on
dev_name() #
const char * Return a device's name.
Parameters
const struct device *dev: Device with name to get.
Return
The kobject name of the device, or its initial name if unavailable.
dev_bus_name() #
const char * Return a device's bus/class name, if at all possible
Parameters
const struct device *dev: struct device to get the bus/class name of
Description
Will return the name of the bus/class the device is attached to. If it is not attached to a bus/class, an empty string will be returned.
device_find_child_by_name() #
struct device * device iterator for locating a child device.
Parameters
struct device *parent: parent struct deviceconst char *name: name of the child device
Description
This is similar to the device_find_child() function above, but it
returns a reference to a device that has the name name.
NOTE
you will need to drop the reference with put_device() after use.
device_find_any_child() #
struct device * device iterator for locating a child device, if any.
Parameters
struct device *parent: parent struct device
Description
This is similar to the device_find_child() function above, but it
returns a reference to a child device, if any.
NOTE
you will need to drop the reference with put_device() after use.
device_lock_set_class() #
Specify a temporary lock class while a device is attached to a driver
Parameters
dev: device to modifykey: lock class key data
Description
This must be called with the device_lock() already held, for example
from driver ->probe(). Take care to only override the default
lockdep_no_validate class.
device_lock_reset_class() #
Return a device to the default lockdep novalidate state
Parameters
dev: device to modify
Description
This must be called with the device_lock() already held, for example
from driver ->remove().
struct bus_type #
The bus type of the device
Definition
;
Members
name: The name of the bus.dev_name: Used for subsystems to enumerate devices like ("foou", dev->id).bus_groups: Default attributes of the bus.dev_groups: Default attributes of the devices on the bus.drv_groups: Default attributes of the device drivers on the bus.match: Called, perhaps multiple times, whenever a new device or driver is added for this bus. It should return a positive value if the given device can be handled by the given driver and zero otherwise. It may also return error code if determining that the driver supports the device is not possible. In case of -EPROBE_DEFER it will queue the device for deferred probing.uevent: Called when a device is added, removed, or a few other things that generate uevents to add the environment variables.probe: Called when a new device or driver add to this bus, and callback the specific driver's probe to initial the matched device.sync_state: Called to sync device state to software state after all the state tracking consumers linked to this device (present at the time of late_initcall) have successfully bound to a driver. If the device has no consumers, this function will be called at late_initcall_sync level. If the device has consumers that are never bound to a driver, this function will never get called until they do.remove: Called when a device removed from this bus.shutdown: Called at shut-down time to quiesce the device.irq_get_affinity: Get IRQ affinity mask for the device on this bus.online: Called to put the device back online (after offlining it).offline: Called to put the device offline for hot-removal. May fail.suspend: Called when a device on this bus wants to go to sleep mode.resume: Called to bring a device on this bus out of sleep mode.num_vf: Called to find out how many virtual functions a device on this bus supports.dma_configure: Called to setup DMA configuration on a device on this bus.dma_cleanup: Called to cleanup DMA configuration on a device on this bus.pm: Power management operations of this bus, callback the specific device driver's pm-ops.driver_override: Set to true if this bus supports the driver_override mechanism, which allows userspace to force a specific driver to bind to a device via a sysfs attribute.need_parent_lock: When probing or removing a device on this bus, the device core should lock the device's parent.
Note
-
This callback may be invoked with or without the device
lock held.
Description
A bus is a channel between the processor and one or more devices. For the purposes of the device model, all devices are connected via a bus, even if it is an internal, virtual, "platform" bus. Buses can plug into each other. A USB controller is usually a PCI device, for example. The device model represents the actual connections between buses and the devices they control. A bus is represented by the bus_type structure. It contains the name, the default attributes, the bus' methods, PM operations, and the driver core's private data.
enum bus_notifier_event #
Bus Notifier events that have happened
Constants
BUS_NOTIFY_ADD_DEVICE: device is added to this busBUS_NOTIFY_DEL_DEVICE: device is about to be removed from this busBUS_NOTIFY_REMOVED_DEVICE: device is successfully removed from this busBUS_NOTIFY_BIND_DRIVER: a driver is about to be bound to this device on this busBUS_NOTIFY_BOUND_DRIVER: a driver is successfully bound to this device on this busBUS_NOTIFY_UNBIND_DRIVER: a driver is about to be unbound from this device on this busBUS_NOTIFY_UNBOUND_DRIVER: a driver is successfully unbound from this device on this busBUS_NOTIFY_DRIVER_NOT_BOUND: a 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 already held by the driver core, so be careful in any notifier callback as to what you do with the device structure.
All bus notifiers are called with the target struct device * as an argument.
struct class #
device classes
Definition
;
Members
name: Name of the class.class_groups: Default attributes of this class.dev_groups: Default attributes of the devices that belong to the class.dev_uevent: Called when a device is added, removed from this class, or a few other things that generate uevents to add the environment variables.devnode: Callback to provide the devtmpfs.class_release: Called to release this class.dev_release: Called to release the device.shutdown_pre: Called at shut-down time before driver shutdown.ns_type: Callbacks so sysfs can detemine namespaces.namespace: Namespace of the device belongs to this class.get_ownership: Allows class to specify uid/gid of the sysfs directories for the devices belonging to the class. Usually tied to device's namespace.pm: The default device power management operations of this class.
Description
A class is a higher-level view of a device that abstracts out low-level implementation details. Drivers may see a SCSI disk or an ATA disk, but, at the class level, they are all simply disks. Classes allow user space to work with devices based on what they do, rather than how they are connected or how they work.
enum probe_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_STRATEGY: Used by drivers that work equally well whether probed synchronously or asynchronously.PROBE_PREFER_ASYNCHRONOUS: Drivers for "slow" devices which probing order is not essential for booting the system may opt into executing their probes asynchronously.PROBE_FORCE_SYNCHRONOUS: Use this to annotate drivers that need their probe routines to run synchronously with driver and device registration (with the exception of -EPROBE_DEFER handling - re-probing always ends up being done asynchronously).
Description
Note that the end goal is to switch the kernel to use asynchronous
probing by default, so annotating drivers with
PROBE_PREFER_ASYNCHRONOUS is a temporary measure that allows us
to speed up boot process while we are validating the rest of the
drivers.
struct device_driver #
The basic device driver structure
Definition
;
Members
name: Name of the device driver.bus: The bus which the device of this driver belongs to.owner: The module owner.mod_name: Used for built-in modules.suppress_bind_attrs: Disables bind/unbind via sysfs.probe_type: Type of the probe (synchronous or asynchronous) to use.of_match_table: The open firmware table.acpi_match_table: The ACPI match table.probe: Called to query the existence of a specific device, whether this driver can work with it, and bind the driver to a specific device.sync_state: Called to sync device state to software state after all the state tracking consumers linked to this device (present at the time of late_initcall) have successfully bound to a driver. If the device has no consumers, this function will be called at late_initcall_sync level. If the device has consumers that are never bound to a driver, this function will never get called until they do.remove: Called when the device is removed from the system to unbind a device from this driver.shutdown: Called at shut-down time to quiesce the device.suspend: Called to put the device to sleep mode. Usually to a low power state.resume: Called to bring a device from sleep mode.groups: Default attributes that get created by the driver core automatically.dev_groups: Additional attributes attached to device instance once it is bound to the driver.pm: Power management operations of the device which matched this driver.coredump: Called when sysfs entry is written to. The device driver is expected to call the dev_coredump API resulting in a uevent.p: Driver core's private data, no one other than the driver core can touch this.p_cb: Callbacks private to the driver core; no one other than the driver 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 match up drivers with new devices. Once drivers are known objects within the system, however, a number of other things become possible. Device drivers can export information and configuration variables that are independent of any specific device.
Device Drivers Base #
driver_init() #
void initialize driver model.
Parameters
void: no arguments
Description
Call the driver model init functions to initialize their subsystems. Called early from init/main.c.
driver_find_device_by_name() #
struct device * device iterator for locating a particular device of a specific name.
Parameters
const struct device_driver *drv: the driver we're iteratingconst char *name: name of the device to match
driver_find_device_by_of_node() #
struct device * device iterator for locating a particular device by of_node pointer.
Parameters
const struct device_driver *drv: the driver we're iteratingconst struct device_node *np: of_node pointer to match.
driver_find_device_by_fwnode() #
struct device * device iterator for locating a particular device by fwnode pointer.
Parameters
struct device_driver *drv: the driver we're iteratingconst struct fwnode_handle *fwnode: fwnode pointer to match.
driver_find_device_by_devt() #
struct device * device iterator for locating a particular device by devt.
Parameters
const struct device_driver *drv: the driver we're iteratingdev_t devt: devt pointer to match.
driver_find_device_by_acpi_dev() #
struct device * device iterator for locating a particular device matching the ACPI_COMPANION device.
Parameters
const struct device_driver *drv: the driver we're iteratingconst struct acpi_device *adev: ACPI_COMPANION device to match.
module_driver() #
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() and module_exit().
Parameters
__driver: driver name__register: register function for this driver type__unregister: unregister function for this driver type...: Additional arguments to be passed to __register and __unregister.
Description
Use this macro to construct bus specific macros for registering drivers, and do not use it on its own.
builtin_driver() #
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
__driver: driver name__register: register function for this driver type...: Additional arguments to be passed to __register
Description
Use this macro to construct bus specific macros for registering drivers, and do not use it on its own.
driver_set_override() #
int Helper to set or clear driver override.
Parameters
struct device *dev: Device to changeconst char **override: Address of string to change (e.g.device->driver_override); The contents will be freed and hold newly allocated override.const char *s: NUL-terminated string, new driver name to force a match, pass empty string to clear it ("" or "\n", where the latter is only for sysfs interface).size_t len: length of s
Description
Helper to set or clear driver override in a device, intended for the cases when the driver_override field is allocated by driver/bus code.
Return
0 on success or a negative error code on failure.
driver_for_each_device() #
int Iterator for devices bound to a driver.
Parameters
struct device_driver *drv: Driver we're iterating.struct device *start: Device to begin withvoid *data: Data to pass to the callback.device_iter_t fn: Function to call for each device.
Description
Iterate over the drv's list of devices calling fn for each one.
driver_find_device() #
struct device * device iterator for locating a particular device.
Parameters
const struct device_driver *drv: The device's driverstruct device *start: Device to begin withconst void *data: Data to pass to match functiondevice_match_t match: Callback function to check device
Description
This is similar to the driver_for_each_device() function above, but
it returns a reference to a device that is 'found' for later use, as
determined by the match callback.
The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more devices.
driver_create_file() #
int create sysfs file for driver.
Parameters
const struct device_driver *drv: driver.const struct driver_attribute *attr: driver attribute descriptor.
driver_remove_file() #
void remove sysfs file for driver.
Parameters
const struct device_driver *drv: driver.const struct driver_attribute *attr: driver attribute descriptor.
driver_register() #
int register driver with bus
Parameters
struct device_driver *drv: driver to register
Description
We pass off most of the work to the bus_add_driver() call,
since most of the things we have to do deal with the bus
structures.
driver_unregister() #
void remove driver from system.
Parameters
struct device_driver *drv: driver.
Description
Again, we pass off most of the work to the bus-level call.
device_link_wait_removal() #
void Wait for ongoing devlink removal jobs to terminate
Parameters
void: no arguments
device_link_add() #
struct device_link * Create a link between two devices.
Parameters
struct device *consumer: Consumer end of the link.struct device *supplier: Supplier end of the link.u32 flags: Link flags.
Return
On success, a device_link struct will be returned. On error or invalid flag settings, NULL will be returned.
Description
The caller is responsible for the proper synchronization of the link creation with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the runtime PM framework to take the link into account. Second, if the DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will be forced into the active meta state and reference-counted upon the creation of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be ignored.
If DL_FLAG_STATELESS is set in flags, the caller of this function is
expected to release the link returned by it directly with the help of either
device_link_del() or device_link_remove().
If that flag is not set, however, the caller of this function is handing the management of the link over to the driver core entirely and its return value can 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 link flags can be used to indicate to the driver core when the link can be safely deleted. Namely, setting one of them in flags indicates to the driver core that the link is not going to be used (by the given caller of this function) after unbinding the consumer or supplier driver, respectively, from its device, 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 (either the consumer or the supplier) is unregistered.
Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER are not set in flags (that is, a persistent managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can be used to request the driver core to automatically probe for a consumer driver 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 in flags at the same time is invalid and will cause NULL to be returned upfront. However, if a device link between the given consumer and supplier pair exists already when this function is called for them, the existing link will be returned regardless of its current type and status (the link's flags may be modified then). The caller of this function is then expected to treat the link as though it has just been created, so (in particular) if DL_FLAG_STATELESS was passed in flags, the link needs to be released explicitly when not needed any more (as stated above).
A side effect of the link creation is re-ordering of dpm_list and the devices_kset list by moving the consumer device and all devices depending on it to the ends of these lists (that does not happen to devices that have not been registered when this function is called).
The supplier device is required to be registered when this function is called and NULL will be returned if that is not the case. The consumer device need not be registered, however.
device_link_del() #
void Delete a stateless link between two devices.
Parameters
struct device_link *link: Device link to delete.
Description
The caller must ensure proper synchronization of this function with runtime
PM. 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 removal
and calling device_link_del() is then no longer allowed.
device_link_remove() #
void Delete a stateless link between two devices.
Parameters
void *consumer: Consumer end of the link.struct device *supplier: Supplier end of the link.
Description
The caller must ensure proper synchronization of this function with runtime PM.
dev_driver_string() #
const char * Return a device's driver name, if at all possible
Parameters
const struct device *dev: struct device to get the name of
Description
Will return the device's driver's name if it is bound to a device. If the device is not bound to a driver, it will return the name of the bus it is attached to. If it is not attached to a bus either, an empty string will be returned.
devm_device_add_group() #
int given a device, create a managed attribute group
Parameters
struct device *dev: The device to create the group forconst struct attribute_group *grp: The attribute group to create
Description
This function creates a group for the first time. It will explicitly warn and error if any of the attribute files being created already exist.
Returns 0 on success or error code on failure.
device_create_file() #
int create sysfs attribute file for device.
Parameters
struct device *dev: device.const struct device_attribute *attr: device attribute descriptor.
device_remove_file() #
void remove sysfs attribute file.
Parameters
struct device *dev: device.const struct device_attribute *attr: device attribute descriptor.
device_remove_file_self() #
bool remove sysfs attribute file from its own method.
Parameters
struct device *dev: device.const struct device_attribute *attr: device attribute descriptor.
Description
See kernfs_remove_self() for details.
device_create_bin_file() #
int create sysfs binary attribute file for device.
Parameters
struct device *dev: device.const struct bin_attribute *attr: device binary attribute descriptor.
device_remove_bin_file() #
void remove sysfs binary attribute file
Parameters
struct device *dev: device.const struct bin_attribute *attr: device binary attribute descriptor.
device_initialize() #
void init device structure.
Parameters
struct device *dev: device.
Description
This prepares the device for use by other layers by initializing
its fields.
It is the first half of device_register(), if called by
that function, though it can also be called separately, so one
may use dev's fields. In particular, get_device()/put_device()
may be used for reference counting of dev after calling this
function.
All fields in dev must be initialized by the caller to 0, except
for those explicitly set to some other value. The simplest
approach is to use kzalloc() to allocate the structure containing
dev.
NOTE
Use put_device() to give up your reference instead of freeing
dev directly once you have called this function.
dev_set_name() #
int set a device name
Parameters
struct device *dev: deviceconst char *fmt: format string for the device's name...: variable arguments
device_add() #
int add device to device hierarchy.
Parameters
struct device *dev: device.
Description
This is part 2 of device_register(), though may be called
separately iff device_initialize() has been called separately.
This adds dev to the kobject hierarchy via kobject_add(), adds it
to the global and sibling lists for the device, then
adds it to the other relevant subsystems of the driver model.
Do not call this routine or device_register() more than once for
any device structure. The driver model core is not designed to work
with devices that get unregistered and then spring back to life.
(Among other things, it's very hard to guarantee that all references
to the previous incarnation of dev have been dropped.) Allocate
and register a fresh new struct device instead.
NOTE
Never directly free dev after calling this function, even
if it returned an error! Always use put_device() to give up your
reference instead.
Rule of thumb is: if device_add() succeeds, you should call
device_del() when you want to get rid of it. If device_add() has
not succeeded, use only put_device() to drop the reference
count.
device_register() #
int register a device with the system.
Parameters
struct device *dev: pointer to the device structure
Description
This happens in two clean steps - initialize the device and add it to the system. The two steps can be called separately, but this is the easiest and most common. I.e. you should only call the two helpers separately if have a clearly defined need to use and refcount the device before it is added to the hierarchy.
For more information, see the kerneldoc for device_initialize()
and device_add().
NOTE
Never directly free dev after calling this function, even
if it returned an error! Always use put_device() to give up the
reference initialized in this function instead.
get_device() #
struct device * increment reference count for device.
Parameters
struct device *dev: device.
Description
This simply forwards the call to kobject_get(), though
we do take care to provide for the case that we get a NULL
pointer passed in.
put_device() #
void decrement reference count.
Parameters
struct device *dev: device in question.
device_del() #
void delete device from system.
Parameters
struct device *dev: device.
Description
This is the first part of the device unregistration
sequence. This removes the device from the lists we control
from here, has it removed from the other driver model
subsystems it was added to in device_add(), and removes it
from the kobject hierarchy.
NOTE
this should be called manually iff device_add() was
also called manually.
device_unregister() #
void unregister device from system.
Parameters
struct device *dev: device going away.
Description
We do this in two parts, like we do device_register(). First,
we remove it from all the subsystems with device_del(), then
we decrement the reference count via put_device(). If that
is the final reference count, the device will be cleaned up
via device_release() above. Otherwise, the structure will
stick around until the final reference to the device is dropped.
device_for_each_child() #
int device child iterator.
Parameters
struct device *parent: parent struct device.void *data: data for the callback.device_iter_t fn: function to be called for each device.
Description
Iterate over parent's child devices, and call fn for each, passing it data.
We check the return of fn each time. If it returns anything other than 0, we break out and return that value.
device_for_each_child_reverse() #
int device child iterator in reversed order.
Parameters
struct device *parent: parent struct device.void *data: data for the callback.device_iter_t fn: function to be called for each device.
Description
Iterate over parent's child devices, and call fn for each, passing it data.
We check the return of fn each time. If it returns anything other than 0, we break out and return that value.
device_for_each_child_reverse_from() #
int device child iterator in reversed order.
Parameters
struct device *parent: parent struct device.struct device *from: optional starting point in child listvoid *data: data for the callback.device_iter_t fn: function to be called for each device.
Description
Iterate over parent's child devices, starting at from, and call fn
for each, passing it data. This helper is identical to
device_for_each_child_reverse() when from is NULL.
fn is checked each iteration. If it returns anything other than 0,
iteration stop and that value is returned to the caller of
device_for_each_child_reverse_from();
device_find_child() #
struct device * device iterator for locating a particular device.
Parameters
struct device *parent: parent struct deviceconst void *data: Data to pass to match functiondevice_match_t match: Callback function to check device
Description
This is similar to the device_for_each_child() function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the match callback.
The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero and a reference to the current device can be obtained, this function will return to the caller and not iterate over any more devices.
NOTE
you will need to drop the reference with put_device() after use.
__root_device_register() #
struct device * allocate and register a root device
Parameters
const char *name: root device namestruct module *owner: owner module of the root device, usually THIS_MODULE
Description
This function allocates a root device and registers it
using device_register(). In order to free the returned
device, use root_device_unregister().
Root devices are dummy devices which allow other devices to be grouped under /sys/devices. Use this function to allocate a root device and then use it as the parent of any device which should appear under /sys/devices/{name}
The /sys/devices/{name} directory will also contain a 'module' symlink which points to the owner directory in sysfs.
Returns struct device pointer on success, or ERR_PTR() on error.
Note
You probably want to use root_device_register().
root_device_unregister() #
void unregister and free a root device
Parameters
struct device *dev: device going away
Description
This function unregisters and cleans up a device that was created by
root_device_register().
device_create() #
struct device * creates a device and registers it with sysfs
Parameters
const struct class *class: pointer to the struct class that this device should be registered tostruct device *parent: pointer to the parent struct device of this new device, if anydev_t devt: the dev_t for the char device to be addedvoid *drvdata: the data to be added to the device for callbacksconst char *fmt: string for the device's name...: variable arguments
Description
This function can be used by char device classes. A struct device will be created in sysfs, registered to the specified class.
A "dev" file will be created, showing the dev_t for the device, if the dev_t is not 0,0. If a pointer to a parent struct device is passed in, the newly created struct device will be a child of that device in sysfs. The pointer to the struct device will be returned from the call. Any further sysfs files that might be required can be created using this pointer.
Returns struct device pointer on success, or ERR_PTR() on error.
device_create_with_groups() #
struct device * creates a device and registers it with sysfs
Parameters
const struct class *class: pointer to the struct class that this device should be registered tostruct device *parent: pointer to the parent struct device of this new device, if anydev_t devt: the dev_t for the char device to be addedvoid *drvdata: the data to be added to the device for callbacksconst struct attribute_group **groups: NULL-terminated list of attribute groups to be createdconst char *fmt: string for the device's name...: variable arguments
Description
This function can be used by char device classes. A struct device will be created in sysfs, registered to the specified class. Additional attributes specified in the groups parameter will also be created automatically.
A "dev" file will be created, showing the dev_t for the device, if the dev_t is not 0,0. If a pointer to a parent struct device is passed in, the newly created struct device will be a child of that device in sysfs. The pointer to the struct device will be returned from the call. Any further sysfs files that might be required can be created using this pointer.
Returns struct device pointer on success, or ERR_PTR() on error.
device_destroy() #
void removes a device that was created with device_create()
Parameters
const struct class *class: pointer to the struct class that this device was registered withdev_t devt: the dev_t of the device that was previously registered
Description
This call unregisters and cleans up a device that was created with a
call to device_create().
device_rename() #
int renames a device
Parameters
struct device *dev: the pointer to the struct device to be renamedconst char *new_name: the new name of the device
Description
It is the responsibility of the caller to provide mutual exclusion between two different calls of device_rename on the same device to ensure that new_name is valid and won't conflict with other devices.
Note
given that some subsystems (networking and infiniband) use this function, with no immediate plans for this to change, we cannot assume or require that this function not be called at all.
However, if you're writing new code, do not call this function. The following text from Kay Sievers offers some insight:
Renaming devices is racy at many levels, symlinks and other stuff are not replaced atomically, and you get a "move" uevent, but it's not easy to connect the event to the old and new device. Device nodes are not renamed at all, there isn't even support for that in the kernel now.
In the meantime, during renaming, your target name might be taken by another driver, creating conflicts. Or the old name is taken directly after you renamed it -- then you get events for the same DEVPATH, before you even see the "move" event. It's just a mess, and nothing new should ever rely on kernel device renaming. Besides that, it's not even implemented now for other things than (driver-core wise very simple) network devices.
Make up a "real" name in the driver before you register anything, or add some other attributes for userspace to find the device, or use udev to add symlinks -- but never rename kernel devices later, it's a complete mess. We don't even want to get into that and try to implement the missing pieces in the core. We really have other pieces to fix in the driver core mess. :)
device_move() #
int moves a device to a new parent
Parameters
struct device *dev: the pointer to the struct device to be movedstruct device *new_parent: the new parent of the device (can be NULL)enum dpm_order dpm_order: how to reorder the dpm_list
dev_err_probe() #
int probe error check and log helper
Parameters
const struct device *dev: the pointer to the struct deviceint err: error value to testconst char *fmt: printf-style format string...: arguments as specified in the format string
Description
This helper implements common pattern present in probe functions for error checking: 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 be checked 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 if err
is known to never be -EPROBE_DEFER.
The benefit compared to a normal dev_err() is the standardized format
of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
instead of "-35"), and having the error code returned allows more
compact error paths.
Returns err.
dev_warn_probe() #
int probe error check and log helper
Parameters
const struct device *dev: the pointer to the struct deviceint err: error value to testconst char *fmt: printf-style format string...: arguments as specified in the format string
Description
This helper implements common pattern present in probe functions for error checking: 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 be checked 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 if err
is known to never be -EPROBE_DEFER.
The benefit compared to a normal dev_warn() is the standardized format
of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
instead of "-35"), and having the error code returned allows more
compact error paths.
Returns err.
set_primary_fwnode() #
void Change the primary firmware node of a given device.
Parameters
struct device *dev: Device to handle.struct fwnode_handle *fwnode: New primary firmware node of the device.
Description
Set the device's firmware node pointer to fwnode, but if a secondary firmware node of the device is present, preserve it.
- Valid fwnode cases are:
- primary --> secondary --> -ENODEV
- primary --> NULL
- secondary --> -ENODEV
- NULL
set_secondary_fwnode() #
void Change the secondary firmware node of a given device.
Parameters
struct device *dev: Device to handle.struct fwnode_handle *fwnode: New secondary firmware node of the device.
Description
If a primary firmware node of the device is present, set its secondary pointer to fwnode. Otherwise, set the device's firmware node pointer to fwnode.
device_remove_of_node() #
void Remove an of_node from a device
Parameters
struct device *dev: device whose device tree node is being removed
device_add_of_node() #
int Add an of_node to an existing device
Parameters
struct device *dev: device whose device tree node is being addedstruct device_node *of_node: of_node to add
Return
0 on success or error code on failure.
device_set_of_node_from_dev() #
void reuse device-tree node of another device
Parameters
struct device *dev: device whose device-tree node is being setconst struct device *dev2: device whose device-tree node is being reused
Description
Takes another reference to the new device-tree node after first dropping any reference held to the old node.
get_dev_from_fwnode() #
struct device * Obtain a reference count of the struct device the struct fwnode_handle is associated with.
Parameters
struct fwnode_handle *fwnode: The pointer to the struct fwnode_handle to obtain the struct device reference count of.
Description
This function obtains a reference count of the device the device pointer embedded in the struct fwnode_handle points to.
Note that the struct device pointer embedded in struct fwnode_handle does not have a reference count of the struct device itself.
Hence, it is a UAF (and thus a bug) to call this function if the caller can't guarantee that the last reference count of the corresponding struct device is not dropped concurrently.
This is possible since struct fwnode_handle has its own reference count and hence can out-live the struct device it is associated with.
register_syscore() #
void Register a set of system core operations.
Parameters
struct syscore *syscore: System core operations to register.
unregister_syscore() #
void Unregister a set of system core operations.
Parameters
struct syscore *syscore: System core operations to unregister.
syscore_suspend() #
int Execute all the registered system core suspend callbacks.
Parameters
void: no arguments
Description
This function is executed with one CPU on-line and disabled interrupts.
syscore_resume() #
void Execute all the registered system core resume callbacks.
Parameters
void: no arguments
Description
This function is executed with one CPU on-line and disabled interrupts.
class_find_device_by_name() #
struct device * device iterator for locating a particular device of a specific name.
Parameters
const struct class *class: class typeconst char *name: name of the device to match
class_find_device_by_of_node() #
struct device * device iterator for locating a particular device matching the of_node.
Parameters
const struct class *class: class typeconst struct device_node *np: of_node of the device to match.
class_find_device_by_fwnode() #
struct device * device iterator for locating a particular device matching the fwnode.
Parameters
const struct class *class: class typeconst struct fwnode_handle *fwnode: fwnode of the device to match.
class_find_device_by_devt() #
struct device * device iterator for locating a particular device matching the device type.
Parameters
const struct class *class: class typedev_t devt: device type of the device to match.
class_find_device_by_acpi_dev() #
struct device * device iterator for locating a particular device matching the ACPI_COMPANION device.
Parameters
const struct class *class: class typeconst struct acpi_device *adev: ACPI_COMPANION device to match.
class_create() #
struct class * create a struct class structure
Parameters
const char *name: pointer to a string for the name of this class.
Description
This is used to create a struct class pointer that can then be used
in calls to device_create().
Returns struct class pointer on success, or ERR_PTR() on error.
Note, the pointer created here is to be destroyed when finished by
making a call to class_destroy().
class_destroy() #
void destroys a struct class structure
Parameters
const struct class *cls: pointer to the struct class that is to be destroyed
Description
Note, the pointer to be destroyed must have been created with a call
to class_create().
class_dev_iter_init() #
void initialize class device iterator
Parameters
struct class_dev_iter *iter: class iterator to initializeconst struct class *class: the class we wanna iterate overconst struct device *start: the device to start iterating from, if anyconst struct device_type *type: device_type of the devices to iterate over, NULL for all
Description
Initialize class iterator iter such that it iterates over devices of class. If start is set, the list iteration will start there, otherwise if it is NULL, the iteration starts at the beginning of the list.
class_dev_iter_next() #
struct device * iterate to the next device
Parameters
struct class_dev_iter *iter: class iterator to proceed
Description
Proceed iter to the next device and return it. Returns NULL if iteration is complete.
The returned device is referenced and won't be released till iterator is proceed to the next device or exited. The caller is free to do whatever it wants to do with the device including calling back into class code.
class_dev_iter_exit() #
void finish iteration
Parameters
struct class_dev_iter *iter: class iterator to finish
Description
Finish an iteration. Always call this function after iteration is complete whether the iteration ran till the end or not.
class_for_each_device() #
int device iterator
Parameters
const struct class *class: the class we're iteratingconst struct device *start: the device to start with in the list, if any.void *data: data for the callbackdevice_iter_t fn: function to be called for each device
Description
Iterate over class's list of devices, and call fn for each, passing it data. If start is set, the list iteration will start there, otherwise if it is NULL, the iteration starts at the beginning of the list.
We check the return of fn each time. If it returns anything other than 0, we break out and return that value.
fn is allowed to do anything including calling back into class code. There's no locking restriction.
class_find_device() #
struct device * device iterator for locating a particular device
Parameters
const struct class *class: the class we're iteratingconst struct device *start: Device to begin withconst void *data: data for the match functiondevice_match_t match: function to check device
Description
This is similar to the class_for_each_dev() function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the match callback.
The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more devices.
Note, you will need to drop the reference with put_device() after use.
match is allowed to do anything including calling back into class code. There's no locking restriction.
class_compat_register() #
struct class_compat * register a compatibility class
Parameters
const char *name: the name of the class
Description
Compatibility class are meant as a temporary user-space compatibility workaround when converting a family of class devices to a bus devices.
class_compat_unregister() #
void unregister a compatibility class
Parameters
struct class_compat *cls: the class to unregister
class_compat_create_link() #
int create a compatibility class device link to a bus device
Parameters
struct class_compat *cls: the compatibility classstruct device *dev: the target bus device
class_compat_remove_link() #
void remove a compatibility class device link to a bus device
Parameters
struct class_compat *cls: the compatibility classstruct device *dev: the target bus device
class_is_registered() #
bool determine if at this moment in time, a class is registered in the driver core or not.
Parameters
const struct class *class: the class to check
Description
Returns a boolean to state if the class is registered in the driver core or 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 (usually to determine if the specific class has been registered yet or not).
Be careful in using this.
struct faux_device #
a "faux" device
Definition
;
Members
dev: internal struct device of the object
Description
A simple faux device that can be created/destroyed. To be used when a driver only needs to have a device to "hang" something off. This can be used for downloading firmware or other basic tasks. Use this instead of a struct platform_device if the device has no resources assigned to it at all.
struct faux_device_ops #
a set of callbacks for a struct faux_device
Definition
;
Members
probe: called when a faux device is probed by the driver core before the device is fully bound to the internal faux bus code. If probe succeeds, return 0, otherwise return a negative error number to stop the probe sequence from succeeding.remove: called when a faux device is removed from the system
Description
Both probe and remove are optional, if not needed, set to NULL.
faux_device_create_with_groups() #
struct faux_device * Create and register with the driver core a faux device and populate the device with an initial set of sysfs attributes.
Parameters
const char *name: The name of the device we are adding, must be unique for all faux devices.struct device *parent: Pointer to a potential parent struct device. If set to NULL, the device will be created in the "root" of the faux device tree in sysfs.const struct faux_device_ops *faux_ops: struct faux_device_ops that the new device will call back into, can be NULL.const struct attribute_group **groups: The set of sysfs attributes that will be created for this device 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 in faux_ops will be called with the device that for the caller to do something with at the proper time given the device's lifecycle.
Note, when this function is called, the functions specified in struct faux_ops can be called before the function returns, so be prepared for everything to be properly initialized before that point in time. If the probe callback (if one is present) does NOT succeed, the creation of the device will fail and NULL will be returned.
Return
- NULL if an error happened with creating the device
- pointer to a valid struct faux_device that is registered with sysfs
faux_device_create() #
struct faux_device * create and register with the driver core a faux device
Parameters
const char *name: The name of the device we are adding, must be unique for all faux devices.struct device *parent: Pointer to a potential parent struct device. If set to NULL, the device will be created in the "root" of the faux device tree in sysfs.const struct faux_device_ops *faux_ops: struct faux_device_ops that the new device will call back into, can be NULL.
Description
Create a new faux device and register it in the driver core properly. If present, callbacks in faux_ops will be called with the device that for the caller to do something with at the proper time given the device's lifecycle.
Note, when this function is called, the functions specified in struct faux_ops can be called before the function returns, so be prepared for everything to be properly initialized before that point in time.
Return
- NULL if an error happened with creating the device
- pointer to a valid struct faux_device that is registered with sysfs
faux_device_destroy() #
void destroy a faux device
Parameters
struct faux_device *faux_dev: faux device to destroy
Description
Unregisters and cleans up a device that was created with a call to
faux_device_create()
struct node_access_nodes #
Access class device to hold user visible relationships to other nodes.
Definition
;
Members
dev: Device for this memory access classlist_node: List element in the node's access listaccess: The access class rankcoord: Heterogeneous memory performance coordinates
struct node_cache_info #
Internal tracking for memory node caches
Definition
;
Members
dev: Device represeting the cache levelnode: List element for tracking in the nodecache_attrs: Attributes for this cache level
node_add_cache() #
void add cache attribute to a memory node
Parameters
unsigned int nid: Node identifier that has new cache attributesstruct node_cache_attrs *cache_attrs: Attributes for the cache being added
register_memory_node_under_compute_node() #
int link memory node to its compute node for a given access class.
Parameters
unsigned int mem_nid: Memory node numberunsigned int cpu_nid: Cpu node numberenum access_coordinate_class access: Access class to register
Description
For use with platforms that may have separate memory and compute nodes. This function will export node relationships linking which memory initiator nodes can access memory targets at a given ranked access class.
register_node() #
int Initialize and register the node device.
Parameters
int nid: Node number to use when creating the device.
Return
0 on success, -errno otherwise
unregister_node() #
void unregister a node device
Parameters
int nid: nid of the node going away
Description
Unregisters the node device at node id nid. All the devices on the node must be unregistered before calling this function.
transport_class_register() #
int register an initial transport class
Parameters
struct transport_class *tclass: a pointer to the transport class structure to be initialised
Description
The transport class contains an embedded class which is used to
identify it. The caller should initialise this structure with
zeros and then generic class must have been initialised with the
actual transport class unique name. There's a macro
DECLARE_TRANSPORT_CLASS() to do this (declared classes still must
be registered).
Returns 0 on success or error on failure.
transport_class_unregister() #
void unregister a previously registered class
Parameters
struct transport_class *tclass: The transport class to unregister
Description
Must be called prior to deallocating the memory for the transport class.
anon_transport_class_register() #
void register an anonymous class
Parameters
struct anon_transport_class *atc: The anon transport class to register
Description
The anonymous transport class contains both a transport class and a
container. The idea of an anonymous class is that it never
actually has any device attributes associated with it (and thus
saves on container storage). So it can only be used for triggering
events. Use prezero and then use DECLARE_ANON_TRANSPORT_CLASS() to
initialise the anon transport class storage.
anon_transport_class_unregister() #
void unregister an anon class
Parameters
struct anon_transport_class *atc: Pointer to the anon transport class to unregister
Description
Must be called prior to deallocating the memory for the anon transport class.
transport_setup_device() #
void declare a new dev for transport class association but don't make it visible yet.
Parameters
struct device *dev: the generic device representing the entity being added
Description
Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point to see if any set of transport classes wishes to associate with the added device. This allocates storage for the class device and initialises it, but does not yet add it to the system or add attributes to it (you do this with transport_add_device). If you have no need for a separate setup and add operations, use transport_register_device (see transport_class.h).
transport_add_device() #
int declare a new dev for transport class association
Parameters
struct device *dev: the generic device representing the entity being added
Description
Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point used to add the device to the system and register attributes for it.
transport_configure_device() #
void configure an already set up device
Parameters
struct device *dev: generic device representing device to be configured
Description
The idea of configure is simply to provide a point within the setup process to allow the transport class to extract information from a device after it has been setup. This is used in SCSI because we have to have a setup device to begin using the HBA, but after we send the initial inquiry, we use configure to extract the device parameters. The device need not have been added to be configured.
transport_remove_device() #
void remove the visibility of a device
Parameters
struct device *dev: generic device to remove
Description
This call removes the visibility of the device (to the user from
sysfs), but does not destroy it. To eliminate a device entirely
you must also call transport_destroy_device. If you don't need to
do remove and destroy as separate operations, use
transport_unregister_device() (see transport_class.h) which will
perform both calls for you.
transport_destroy_device() #
void destroy a removed device
Parameters
struct device *dev: device to eliminate from the transport class.
Description
This call triggers the elimination of storage associated with the transport classdev. Note: all it really does is relinquish a reference to the classdev. The memory will not be freed until the last reference goes to zero. Note also that the classdev retains a reference count on dev, so dev too will remain for as long as the transport class device remains around.
driver_deferred_probe_check_state() #
int Check deferred probe state
Parameters
struct device *dev: device to check
Return
- -ENODEV if initcalls have completed and modules are disabled.
- -ETIMEDOUT if the deferred probe timeout was set and has expired and modules are enabled.
- -EPROBE_DEFER in other cases.
Description
Drivers or subsystems can opt-in to calling this function instead of directly returning -EPROBE_DEFER.
device_is_bound() #
bool Check if device is bound to a driver
Parameters
struct device *dev: device to check
Description
Returns true if passed device has already finished probing successfully against a driver.
This function must be called with the device lock held.
device_bind_driver() #
int bind a driver to one device.
Parameters
struct device *dev: device.
Description
Allow manual attachment of a driver to a device. Caller must have already set dev->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's probe() method.)
This function must be called with the device lock held.
Callers should prefer to use device_driver_attach() instead.
wait_for_device_probe() #
void Parameters
void: no arguments
Description
Wait for device probing to be completed.
device_attach() #
int try to attach device to a driver.
Parameters
struct device *dev: device.
Description
Walk the list of drivers that the bus has and call
driver_probe_device() for each pair. If a compatible
pair 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.
device_driver_attach() #
int attach a specific driver to a specific device
Parameters
const struct device_driver *drv: Driver to attachstruct device *dev: Device to attach it to
Description
Manually attach driver to a device. Will acquire both dev lock and dev->parent lock if needed. Returns 0 on success, -ERR on failure.
driver_attach() #
int try to bind driver to devices.
Parameters
const struct device_driver *drv: driver.
Description
Walk the list of devices that the bus has on it and try to
match the driver with each one. If driver_probe_device()
returns 0 and the dev->driver is set, we've found a
compatible pair.
device_release_driver() #
void manually detach device from driver.
Parameters
struct device *dev: device.
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 with dev->parent lock held, ensure that the device's consumers are unbound in advance or that their locks can be acquired under the dev->parent lock.
platform_device_register_resndata() #
struct platform_device * add a platform-level device with resources and platform-specific data
Parameters
struct device *parent: parent device for the device we're addingconst char *name: base name of the device we're addingint id: instance idconst struct resource *res: set of resources that needs to be allocated for the deviceunsigned int num: number of resourcesconst void *data: platform specific data for this platform devicesize_t size: size of platform specific data
Description
Returns struct platform_device pointer on success, or ERR_PTR() on error.
platform_device_register_simple() #
struct platform_device * add a platform-level device and its resources
Parameters
const char *name: base name of the device we're addingint id: instance idconst struct resource *res: set of resources that needs to be allocated for the deviceunsigned int num: number of resources
Description
This function creates a simple platform device that requires minimal resource and memory management. Canned release function freeing memory allocated for the device allows drivers using such devices to be unloaded without waiting for the last reference to the device to be dropped.
This interface is primarily intended for use with legacy drivers which probe hardware directly. Because such drivers create sysfs device nodes themselves, rather than letting system infrastructure handle such device enumeration 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".
Returns struct platform_device pointer on success, or ERR_PTR() on error.
platform_device_register_data() #
struct platform_device * add a platform-level device with platform-specific data
Parameters
struct device *parent: parent device for the device we're addingconst char *name: base name of the device we're addingint id: instance idconst void *data: platform specific data for this platform devicesize_t size: size of platform specific data
Description
This function creates a simple platform device that requires minimal resource and memory management. Canned release function freeing memory allocated for the device allows drivers using such devices to be unloaded without waiting for the last reference to the device to be dropped.
Returns struct platform_device pointer on success, or ERR_PTR() on error.
platform_get_resource() #
struct resource * get a resource for a device
Parameters
struct platform_device *dev: platform deviceunsigned int type: resource typeunsigned int num: resource index
Return
a pointer to the resource or NULL on failure.
devm_platform_get_and_ioremap_resource() #
void __iomem * call devm_ioremap_resource() for a platform device and get resource
Parameters
struct platform_device *pdev: platform device to use both for memory resource lookup as well as resource managementunsigned int index: resource indexstruct resource **res: optional output parameter to store a pointer to the obtained resource.
Return
a pointer to the remapped memory or an ERR_PTR() encoded error code
on failure.
devm_platform_ioremap_resource() #
void __iomem * call devm_ioremap_resource() for a platform device
Parameters
struct platform_device *pdev: platform device to use both for memory resource lookup as well as resource managementunsigned int index: resource index
Return
a pointer to the remapped memory or an ERR_PTR() encoded error code
on failure.
devm_platform_ioremap_resource_byname() #
void __iomem * call devm_ioremap_resource for a platform device, retrieve the resource by name
Parameters
struct platform_device *pdev: platform device to use both for memory resource lookup as well as resource managementconst char *name: name of the resource
Return
a pointer to the remapped memory or an ERR_PTR() encoded error code
on failure.
platform_get_irq_affinity() #
int get an optional IRQ and its affinity for a device
Parameters
struct platform_device *dev: platform deviceunsigned int num: interrupt number indexconst struct cpumask **affinity: optional cpumask pointer to get the affinity of a per-cpu interrupt
Description
Gets an interupt for a platform device. Device drivers should check the
return value for errors so as to not pass a negative integer value to
the request_irq() APIs. Optional affinity information is provided in the
affinity pointer if available, and NULL otherwise.
Return
non-zero interrupt number on success, negative error number on failure.
platform_get_irq_optional() #
int get an optional interrupt for a device
Parameters
struct platform_device *dev: platform deviceunsigned int num: interrupt number index
Description
Gets an interrupt for a platform device. Device drivers should check the
return value for errors so as to not pass a negative integer value to
the request_irq() APIs. This is the same as platform_get_irq(), except
that it does not print an error message if an interrupt can not be
obtained.
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.
platform_get_irq() #
int get an IRQ for a device
Parameters
struct platform_device *dev: platform deviceunsigned int num: IRQ number index
Description
Gets an IRQ for a platform device and prints an error message if finding the
IRQ fails. Device drivers should check the return value for errors so as to
not pass a negative integer value to the request_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.
platform_irq_count() #
int Count the number of IRQs a platform device uses
Parameters
struct platform_device *dev: platform device
Return
Number of IRQs a platform device uses or EPROBE_DEFER
devm_platform_get_irqs_affinity() #
int devm method to get a set of IRQs for a device using an interrupt affinity descriptor
Parameters
struct platform_device *dev: platform device pointerstruct irq_affinity *affd: affinity descriptorunsigned int minvec: minimum count of interrupt vectorsunsigned int maxvec: maximum count of interrupt vectorsint **irqs: pointer holder for IRQ numbers
Description
Gets a set of IRQs for a platform device, and updates IRQ afffinty according to the passed affinity descriptor
Return
Number of vectors on success, negative error number on failure.
platform_get_resource_byname() #
struct resource * get a resource for a device by name
Parameters
struct platform_device *dev: platform deviceunsigned int type: resource typeconst char *name: resource name
platform_get_irq_byname() #
int get an IRQ for a device by name
Parameters
struct platform_device *dev: platform deviceconst char *name: IRQ name
Description
Get an IRQ like platform_get_irq(), but then by name rather then by index.
Return
non-zero IRQ number on success, negative error number on failure.
platform_get_irq_byname_optional() #
int get an optional IRQ for a device by name
Parameters
struct platform_device *dev: platform deviceconst char *name: IRQ name
Description
Get an optional IRQ by name like platform_get_irq_byname(). Except that it
does not print an error message if an IRQ can not be obtained.
Return
non-zero IRQ number on success, negative error number on failure.
platform_add_devices() #
int add a numbers of platform devices
Parameters
struct platform_device **devs: array of platform devices to addint num: number of platform devices in array
Return
0 on success, negative error number on failure.
platform_device_put() #
void destroy a platform device
Parameters
struct platform_device *pdev: platform 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.
platform_device_alloc() #
struct platform_device * create a platform device
Parameters
const char *name: base name of the device we're addingint id: instance id
Description
Create a platform device object which can have other objects attached to it, and which will have attached objects freed when it is released.
platform_device_add_resources() #
int add resources to a platform device
Parameters
struct platform_device *pdev: platform device allocated by platform_device_alloc to add resources toconst struct resource *res: set of resources that needs to be allocated for the deviceunsigned int num: number of resources
Description
Add a copy of the resources to the platform device. The memory associated with the resources will be freed when the platform device is released.
platform_device_add_data() #
int add platform-specific data to a platform device
Parameters
struct platform_device *pdev: platform device allocated by platform_device_alloc to add resources toconst void *data: platform specific data for this platform devicesize_t size: size of platform specific data
Description
Add a copy of platform specific data to the platform device's platform_data pointer. The memory associated with the platform data will be freed when the platform device is released.
platform_device_add() #
int add a platform device to device hierarchy
Parameters
struct platform_device *pdev: platform device we're adding
Description
This is part 2 of platform_device_register(), though may be called
separately iff pdev was allocated by platform_device_alloc().
platform_device_del() #
void remove a platform-level device
Parameters
struct platform_device *pdev: platform device we're removing
Description
Note that this function will also release all memory- and port-based resources owned by the device (dev->resource). This function must only be externally called in error cases. All other usage is a bug.
platform_device_register() #
int add a platform-level device
Parameters
struct platform_device *pdev: platform device we're adding
NOTE
Never directly free pdev after calling this function, even if it
returned an error! Always use platform_device_put() to give up the
reference initialised in this function instead.
platform_device_unregister() #
void unregister a platform-level device
Parameters
struct platform_device *pdev: platform device we're unregistering
Description
Unregistration is done in 2 steps. First we release all resources
and remove it from the subsystem, then we drop reference count by
calling platform_device_put().
platform_device_register_full() #
struct platform_device * add a platform-level device with resources and platform-specific data
Parameters
const struct platform_device_info *pdevinfo: data used to create device
Description
Returns struct platform_device pointer on success, or ERR_PTR() on error.
__platform_driver_register() #
int register a driver for platform-level devices
Parameters
struct platform_driver *drv: platform driver structurestruct module *owner: owning module/driver
platform_driver_unregister() #
void unregister a driver for platform-level devices
Parameters
struct platform_driver *drv: platform driver structure
__platform_driver_probe() #
int register driver for non-hotpluggable device
Parameters
struct platform_driver *drv: platform driver structureint (*probe)(struct platform_device *): the driver probe routine, probably from an __init sectionstruct module *module: module which will be the owner of the driver
Description
Use this instead of platform_driver_register() when you know the device
is not hotpluggable and has already been registered, and you want to
remove its run-once probe() infrastructure from memory after the driver
has bound to the device.
One typical use for this would be with drivers for controllers integrated into system-on-chip processors, where the controller devices have been configured 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 returns a negative error code and with the driver not registered.
__platform_create_bundle() #
struct platform_device * register driver and create corresponding device
Parameters
struct platform_driver *driver: platform driver structureint (*probe)(struct platform_device *): the driver probe routine, probably from an __init sectionstruct resource *res: set of resources that needs to be allocated for the deviceunsigned int n_res: number of resourcesconst void *data: platform specific data for this platform devicesize_t size: size of platform specific datastruct module *module: module which will be the owner of the driver
Description
Use this in legacy-style modules that probe hardware directly and register a single platform device and corresponding platform driver.
Returns struct platform_device pointer on success, or ERR_PTR() on error.
__platform_register_drivers() #
int register an array of platform drivers
Parameters
struct platform_driver * const *drivers: an array of drivers to registerunsigned int count: the number of drivers to registerstruct module *owner: module owning the drivers
Description
Registers platform drivers specified by an array. On failure to register a
driver, all previously registered drivers will be unregistered. Callers of
this API should use platform_unregister_drivers() to unregister drivers in
the reverse order.
Return
0 on success or a negative error code on failure.
platform_unregister_drivers() #
void unregister an array of platform drivers
Parameters
struct platform_driver * const *drivers: an array of drivers to unregisterunsigned int count: the number of drivers to unregister
Description
Unregisters platform drivers specified by an array. This is typically used
to complement an earlier call to platform_register_drivers(). Drivers are
unregistered in the reverse order in which they were registered.
platform_find_device_by_driver() #
struct device * Find a platform device with a given driver.
Parameters
struct device *start: The device to start the search from.const struct device_driver *drv: The device driver to look for.
bus_find_device_by_name() #
struct device * device iterator for locating a particular device of a specific name.
Parameters
const struct bus_type *bus: bus typestruct device *start: Device to begin withconst char *name: name of the device to match
bus_find_device_by_of_node() #
struct device * device iterator for locating a particular device matching the of_node.
Parameters
const struct bus_type *bus: bus typeconst struct device_node *np: of_node of the device to match.
bus_find_device_by_fwnode() #
struct device * device iterator for locating a particular device matching the fwnode.
Parameters
const struct bus_type *bus: bus typeconst struct fwnode_handle *fwnode: fwnode of the device to match.
bus_find_device_by_devt() #
struct device * device iterator for locating a particular device matching the device type.
Parameters
const struct bus_type *bus: bus typedev_t devt: device type of the device to match.
bus_find_next_device() #
struct device * Find the next device after a given device in a given bus.
Parameters
const struct bus_type *bus: bus typestruct device *cur: device to begin the search with.
bus_find_device_by_acpi_dev() #
struct device * device iterator for locating a particular device matching the ACPI COMPANION device.
Parameters
const struct bus_type *bus: bus typeconst struct acpi_device *adev: ACPI COMPANION device to match.
bus_for_each_dev() #
int device iterator.
Parameters
const struct bus_type *bus: bus type.struct device *start: device to start iterating from.void *data: data for the callback.device_iter_t fn: function to be called for each device.
Description
Iterate over bus's list of devices, and call fn for each, passing it data. If start is not NULL, we use that device to begin iterating from.
We check the return of fn each time. If it returns anything other than 0, we break out and return that value.
NOTE
The device that returns a non-zero value is not retained in any way, nor is its refcount incremented. If the caller needs to retain this data, it should do so, and increment the reference count in the supplied callback.
bus_find_device() #
struct device * device iterator for locating a particular device.
Parameters
const struct bus_type *bus: bus typestruct device *start: Device to begin withconst void *data: Data to pass to match functiondevice_match_t match: Callback function to check device
Description
This is similar to the bus_for_each_dev() function above, but it
returns a reference to a device that is 'found' for later use, as
determined by the match callback.
The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more devices.
bus_for_each_drv() #
int driver iterator
Parameters
const struct bus_type *bus: bus we're dealing with.struct device_driver *start: driver to start iterating on.void *data: data to pass to the callback.int (*fn)(struct device_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 to bus, and call fn for each. If fn returns anything but 0, we break out and return it. If start is not NULL, we use it as the head of the list.
NOTE
we don't return the driver that returns a non-zero value, nor do we leave the reference count incremented for that driver. If the caller needs to know that info, it must set it in the callback. It must also be sure to increment the refcount so it doesn't disappear before returning to the caller.
bus_rescan_devices() #
int rescan devices on the bus for possible drivers
Parameters
const struct bus_type *bus: the bus to scan.
Description
This function will look for devices on the bus with no driver
attached and rescan it against existing drivers to see if it matches
any by calling device_attach() for the unbound devices.
device_reprobe() #
int remove driver for a device and probe for a new driver
Parameters
struct device *dev: the device to reprobe
Description
This function detaches the attached driver (if any) for the given device and restarts the driver probing process. It is intended to use if probing criteria changed during a devices lifetime and driver attachment should change accordingly.
bus_register() #
int register a driver-core subsystem
Parameters
const struct bus_type *bus: bus to register
Description
Once we have that, we register the bus with the kobject infrastructure, then register the children subsystems it has: the devices and drivers that belong to the subsystem.
bus_unregister() #
void remove a bus from the system
Parameters
const struct bus_type *bus: bus.
Description
Unregister the child subsystems and the bus itself.
Finally, we call bus_put() to release the refcount
subsys_system_register() #
int register a subsystem at /sys/devices/system/
Parameters
const struct bus_type *subsys: system subsystemconst struct attribute_group **groups: default attributes for the root device
Description
All 'system' subsystems have a /sys/devices/system/<name> root device with the name of the subsystem. The root device can carry subsystem- wide attributes. All registered devices are below this single root device and are named after the subsystem with a simple enumeration number 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 compatibility with bad ideas only. New subsystems should use plain subsystems; and add the subsystem-wide attributes should be added to the subsystem directory itself and not some create fake root-device placed in /sys/devices/system/<name>.
subsys_virtual_register() #
int register a subsystem at /sys/devices/virtual/
Parameters
const struct bus_type *subsys: virtual subsystemconst struct attribute_group **groups: default attributes for the root device
Description
All 'virtual' subsystems have a /sys/devices/system/<name> root device with the name of the subsystem. The root device can carry subsystem-wide attributes. All registered devices are below this single root device. There's no restriction on device naming. This is for kernel software constructs which need sysfs interface.
driver_find() #
struct device_driver * locate driver on a bus by its name.
Parameters
const char *name: name of the driver.const struct bus_type *bus: bus to scan for the driver.
Description
Call kset_find_obj() to iterate over list of drivers on
a bus to find driver by name. Return driver if found.
This routine provides no locking to prevent the driver it returns from being unregistered or unloaded while the caller is using it. The caller is responsible for preventing this.
bus_get_dev_root() #
struct device * return a pointer to the "device root" of a bus
Parameters
const struct bus_type *bus: bus to return the device root of.
Description
If a bus has a "device root" structure, return it, WITH THE REFERENCE COUNT INCREMENTED.
Note, when finished with the device, a call to put_device() is required.
If the device root is not present (or bus is not a valid pointer), NULL will be returned.
Device Drivers DMA Management #
dmam_free_coherent() #
void Managed dma_free_coherent()
Parameters
struct device *dev: Device to free coherent memory forsize_t size: Size of allocationvoid *vaddr: Virtual address of the memory to freedma_addr_t dma_handle: DMA handle of the memory to free
Description
Managed dma_free_coherent().
dmam_alloc_attrs() #
void * Managed dma_alloc_attrs()
Parameters
struct device *dev: Device to allocate non_coherent memory forsize_t size: Size of allocationdma_addr_t *dma_handle: Out argument for allocated DMA handlegfp_t gfp: Allocation flagsunsigned long attrs: Flags in the DMA_ATTR_* namespace.
Description
Managed dma_alloc_attrs(). Memory allocated using this function will be
automatically released on driver detach.
Return
Pointer to allocated memory on success, NULL on failure.
dma_map_sg_attrs() #
unsigned int Map the given buffer for DMA
Parameters
struct device *dev: The device for which to perform the DMA operationstruct scatterlist *sg: The sg_table object describing the bufferint nents: Number of entries to mapenum dma_data_direction dir: DMA directionunsigned long attrs: Optional DMA attributes for the map operation
Description
Maps a buffer described by a scatterlist passed in the sg argument with nents segments for the dir DMA operation by the dev 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 the
original sg and original nents (not the value returned by this funciton).
dma_map_sgtable() #
int Map the given buffer for DMA
Parameters
struct device *dev: The device for which to perform the DMA operationstruct sg_table *sgt: The sg_table object describing the bufferenum dma_data_direction dir: DMA directionunsigned long attrs: Optional DMA attributes for the map operation
Description
Maps a buffer described by a scatterlist stored in the given sg_table
object for the dir DMA operation by the dev device. After success, the
ownership for the buffer is transferred to the DMA domain. One has to
call dma_sync_sgtable_for_cpu() or dma_unmap_sgtable() to move the
ownership of the buffer back to the CPU domain before touching the
buffer by the CPU.
Returns 0 on success or a negative error code on error. The following error codes are supported with the given meaning:
-
-EINVAL An invalid argument, unaligned access or other error
in usage. Will not succeed if retried.
-
-ENOMEM Insufficient resources (like memory or IOVA space) to
complete the mapping. Should succeed if retried later.
-
-EIO Legacy error code with an unknown meaning. eg. this is
returned if a lower level call returned DMA_MAPPING_ERROR.
-
-EREMOTEIO The DMA device cannot access P2PDMA memory specified
in the sg_table. This will not succeed if retried.
-
dma_need_unmap() #
bool does this device need dma_unmap_* operations
Parameters
struct device *dev: device to check
Description
If this function returns false, drivers can skip calling dma_unmap_* after
finishing an I/O. This function must be called after all mappings that might
need to be unmapped have been performed.
dma_can_mmap() #
bool check if a given device supports dma_mmap_*
Parameters
struct device *dev: device to check
Description
Returns true if dev supports dma_mmap_coherent() and dma_mmap_attrs() to
map DMA allocations to userspace.
dma_mmap_attrs() #
int map a coherent DMA allocation into user space
Parameters
struct device *dev: valid struct device pointer, or NULL for ISA and EISA-like devicesstruct vm_area_struct *vma: vm_area_struct describing requested user mappingvoid *cpu_addr: kernel CPU-view address returned from dma_alloc_attrsdma_addr_t dma_addr: device-view address returned from dma_alloc_attrssize_t size: size of memory originally requested in dma_alloc_attrsunsigned long attrs: attributes of mapping properties requested in dma_alloc_attrs
Description
Map a coherent DMA buffer previously allocated by dma_alloc_attrs into user space. The coherent DMA buffer must not be freed by the driver until the user space mapping has been released.
dma_addressing_limited() #
bool return if the device is addressing limited
Parameters
struct device *dev: device to check
Description
Return true if the devices DMA mask is too small to address all memory in
the system, else false. Lack of addressing bits is the prime reason for
bounce buffering, but might not be the only one.
Device drivers PnP support #
pnp_register_protocol() #
int adds a pnp protocol to the pnp layer
Parameters
struct pnp_protocol *protocol: pointer to the corresponding pnp_protocol structure
Description
Ex protocols: ISAPNP, PNPBIOS, etc
pnp_request_card_device() #
struct pnp_dev * Searches for a PnP device under the specified card
Parameters
struct pnp_card_link *clink: pointer to the card link, cannot be NULLconst char *id: pointer to a PnP ID structure that explains the rules for finding the devicestruct pnp_dev *from: Starting place to search from. If NULL it will start from the beginning.
pnp_release_card_device() #
void call this when the driver no longer needs the device
Parameters
struct pnp_dev *dev: pointer to the PnP device structure
pnp_register_card_driver() #
int registers a PnP card driver with the PnP Layer
Parameters
struct pnp_card_driver *drv: pointer to the driver to register
pnp_unregister_card_driver() #
void unregisters a PnP card driver from the PnP Layer
Parameters
struct pnp_card_driver *drv: pointer to the driver to unregister
pnp_add_id() #
struct pnp_id * adds an EISA id to the specified device
Parameters
struct pnp_dev *dev: pointer to the desired deviceconst char *id: pointer to an EISA id string
pnp_start_dev() #
int low-level start of the PnP device
Parameters
struct pnp_dev *dev: pointer to the desired device
Description
assumes that resources have already been allocated
pnp_stop_dev() #
int low-level disable of the PnP device
Parameters
struct pnp_dev *dev: pointer to the desired device
Description
does not free resources
pnp_activate_dev() #
int activates a PnP device for use
Parameters
struct pnp_dev *dev: pointer to the desired device
Description
does not validate or set resources so be careful.
pnp_disable_dev() #
int disables device
Parameters
struct pnp_dev *dev: pointer to the desired device
Description
inform the correct pnp protocol so that resources can be used by other devices
pnp_is_active() #
int Determines if a device is active based on its current resources
Parameters
struct pnp_dev *dev: pointer to the desired PnP device
Userspace IO devices #
uio_event_notify() #
void trigger an interrupt event
Parameters
struct uio_info *info: UIO device capabilities
__uio_register_device() #
int register a new userspace IO device
Parameters
struct module *owner: module that creates the new devicestruct device *parent: parent devicestruct uio_info *info: UIO device capabilities
Description
returns zero on success or a negative error code.
__devm_uio_register_device() #
int Resource managed uio_register_device()
Parameters
struct module *owner: module that creates the new devicestruct device *parent: parent devicestruct uio_info *info: UIO device capabilities
Description
returns zero on success or a negative error code.
uio_unregister_device() #
void unregister a industrial IO device
Parameters
struct uio_info *info: UIO device capabilities
struct uio_mem #
description of a UIO memory region
Definition
;
Members
name: name of the memory region for identificationaddr: address of the device's memory rounded to page size (phys_addr is used since addr can be logical, virtual, or physical & phys_addr_t should always be large enough to handle any of the address types)dma_addr: DMA handle set by dma_alloc_coherent, used with UIO_MEM_DMA_COHERENT only (addr should be the void * returned from the same dma_alloc_coherent call)offs: offset of device memory within the pagesize: size of IO (multiple of page size)memtype: type of memory addr points tointernal_addr: ioremap-ped version of addr, for driver internal usedma_device: device struct that was passed to dma_alloc_coherent, used with UIO_MEM_DMA_COHERENT onlymap: for use by the UIO core only.
struct uio_port #
description of a UIO port region
Definition
;
Members
name: name of the port region for identificationstart: start of port regionsize: size of port regionporttype: type of port (see UIO_PORT_* below)portio: for use by the UIO core only.
struct uio_info #
UIO device capabilities
Definition
;
Members
uio_dev: the UIO device this info belongs toname: device nameversion: device driver versionmem: list of mappable memory regions, size==0 for end of listport: list of port regions, size==0 for end of listirq: interrupt number or UIO_IRQ_CUSTOMirq_flags: flags forrequest_irq()priv: optional private datahandler: the device's irq handlermmap: mmap operation for this uio deviceopen: open operation for this uio devicerelease: release operation for this uio deviceirqcontrol: disable/enable irqs when 0/1 is written to /dev/uioX
uio_register_device() #
register a new userspace IO device
Parameters
parent: parent deviceinfo: UIO device capabilities
Description
returns zero on success or a negative error code.
devm_uio_register_device() #
Resource managed uio_register_device()
Parameters
parent: parent deviceinfo: UIO device capabilities
Description
returns zero on success or a negative error code.
Message-based devices
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Fusion message devices #
mpt_register() #
u8 Register protocol-specific main callback handler.
Parameters
MPT_CALLBACK cbfunc: callback function pointerMPT_DRIVER_CLASS dclass: Protocol driver's class (MPT_DRIVER_CLASSenum value)char *func_name: call function's name
Description
This routine is called by a protocol-specific driver (SCSI host, LAN, SCSI target) to register its reply callback routine. Each protocol-specific driver must do this before it will be able to use any IOC resources, such as obtaining request frames.
NOTES
-
The SCSI protocol driver currently calls this routine thrice
in order to register separate callbacks; one for "normal" SCSI IO; one for MptScsiTaskMgmt requests; one for Scan/DV requests.
Returns u8 valued "handle" in the range (and S.O.D. order) {N,...,7,6,5,...,1} if successful. A return value of MPT_MAX_PROTOCOL_DRIVERS (including zero!) should be considered an error by the caller.
mpt_deregister() #
void Deregister a protocol drivers resources.
Parameters
u8 cb_idx: previously registered callback handle
Description
Each protocol-specific driver should call this routine when its module is unloaded.
mpt_event_register() #
int Register protocol-specific event callback handler.
Parameters
u8 cb_idx: previously registered (via mpt_register) callback handleMPT_EVHANDLER ev_cbfunc: callback function
Description
This routine can be called by one or more protocol-specific drivers if/when they choose to be notified of MPT events.
Returns 0 for success.
mpt_event_deregister() #
void Deregister protocol-specific event callback handler
Parameters
u8 cb_idx: previously registered callback handle
Description
Each protocol-specific driver should call this routine when it does not (or can no longer) handle events, or when its module is unloaded.
mpt_reset_register() #
int Register protocol-specific IOC reset handler.
Parameters
u8 cb_idx: previously registered (via mpt_register) callback handleMPT_RESETHANDLER reset_func: reset function
Description
This routine can be called by one or more protocol-specific drivers if/when they choose to be notified of IOC resets.
Returns 0 for success.
mpt_reset_deregister() #
void Deregister protocol-specific IOC reset handler.
Parameters
u8 cb_idx: previously registered callback handle
Description
Each protocol-specific driver should call this routine when it does not (or can no longer) handle IOC reset handling, or when its module is unloaded.
mpt_device_driver_register() #
int Register device driver hooks
Parameters
struct mpt_pci_driver * dd_cbfunc: driver callbacks structu8 cb_idx: MPT protocol driver index
mpt_device_driver_deregister() #
void DeRegister device driver hooks
Parameters
u8 cb_idx: MPT protocol driver index
mpt_get_msg_frame() #
MPT_FRAME_HDR* Obtain an MPT request frame from the pool
Parameters
u8 cb_idx: Handle of registered MPT protocol driverMPT_ADAPTER *ioc: Pointer to MPT adapter structure
Description
Obtain an MPT request frame from the pool (of 1024) that are allocated per MPT adapter.
Returns pointer to a MPT request frame or NULL if none are available
or IOC is not active.
mpt_put_msg_frame() #
void Send a protocol-specific MPT request frame to an IOC
Parameters
u8 cb_idx: Handle of registered MPT protocol driverMPT_ADAPTER *ioc: Pointer to MPT adapter structureMPT_FRAME_HDR *mf: Pointer to MPT request frame
Description
This routine posts an MPT request frame to the request post FIFO of a specific MPT adapter.
mpt_put_msg_frame_hi_pri() #
void Send a hi-pri protocol-specific MPT request frame
Parameters
u8 cb_idx: Handle of registered MPT protocol driverMPT_ADAPTER *ioc: Pointer to MPT adapter structureMPT_FRAME_HDR *mf: Pointer to MPT request frame
Description
Send a protocol-specific MPT request frame to an IOC using hi-priority request queue.
This routine posts an MPT request frame to the request post FIFO of a specific MPT adapter.
mpt_free_msg_frame() #
void Place MPT request frame back on FreeQ.
Parameters
MPT_ADAPTER *ioc: Pointer to MPT adapter structureMPT_FRAME_HDR *mf: Pointer to MPT request frame
Description
This routine places a MPT request frame back on the MPT adapter's FreeQ.
mpt_send_handshake_request() #
int Send MPT request via doorbell handshake method.
Parameters
u8 cb_idx: Handle of registered MPT protocol driverMPT_ADAPTER *ioc: Pointer to MPT adapter structureint reqBytes: Size of the request in bytesu32 *req: Pointer to MPT request frameint sleepFlag: Use schedule if CAN_SLEEP else use udelay.
Description
This routine is used exclusively to send MptScsiTaskMgmt requests since they are required to be sent via doorbell handshake.
NOTE
-
It is the callers responsibility to byte-swap fields in the
request which are greater than 1 byte in size.
Returns 0 for success, non-zero for failure.
mpt_verify_adapter() #
int Given IOC identifier, set pointer to its adapter structure.
Parameters
int iocid: IOC unique identifier (integer)MPT_ADAPTER **iocpp: Pointer to pointer to IOC adapter
Description
Given a unique IOC identifier, set pointer to the associated MPT adapter structure.
Returns iocid and sets iocpp if iocid is found. Returns -1 if iocid is not found.
mpt_attach() #
int Install a PCI intelligent MPT adapter.
Parameters
struct pci_dev *pdev: Pointer to pci_dev structureconst struct pci_device_id *id: PCI device ID information
Description
This routine performs all the steps necessary to bring the IOC of a MPT adapter to a OPERATIONAL state. This includes registering memory regions, registering the interrupt, and allocating request and reply memory pools.
This routine also pre-fetches the LAN MAC address of a Fibre Channel MPT adapter.
Returns 0 for success, non-zero for failure.
TODO: Add support for polled controllers
mpt_detach() #
void Remove a PCI intelligent MPT adapter.
Parameters
struct pci_dev *pdev: Pointer to pci_dev structure
mpt_suspend() #
int Fusion MPT base driver suspend routine.
Parameters
struct pci_dev *pdev: Pointer to pci_dev structurepm_message_t state: new state to enter
mpt_resume() #
int Fusion MPT base driver resume routine.
Parameters
struct pci_dev *pdev: Pointer to pci_dev structure
mpt_GetIocState() #
u32 Get the current state of a MPT adapter.
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureint cooked: Request raw or cooked IOC state
Description
Returns all IOC Doorbell register bits if cooked==0, else just the Doorbell bits in MPI_IOC_STATE_MASK.
mpt_alloc_fw_memory() #
int allocate firmware memory
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureint size: total FW bytes
Description
If memory has already been allocated, the same (cached) value is returned.
Return 0 if successful, or non-zero for failure
mpt_free_fw_memory() #
void free firmware memory
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
Description
If alt_img is NULL, delete from ioc structure. Else, delete a secondary image in same format.
mptbase_sas_persist_operation() #
int Perform operation on SAS Persistent Table
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureu8 persist_opcode: see below
Description
=============================== ======================================
MPI_SAS_OP_CLEAR_NOT_PRESENT Free all persist TargetID mappings for
devices not currently present.
MPI_SAS_OP_CLEAR_ALL_PERSISTENT Clear al persist TargetID mappings
=============================== ======================================
NOTE
Don't use not this function during interrupt time.
Returns 0 for success, non-zero error
mpt_raid_phys_disk_pg0() #
int returns phys disk page zero
Parameters
MPT_ADAPTER *ioc: Pointer to a Adapter Structureu8 phys_disk_num: io unit unique phys disk num generated by the iocRaidPhysDiskPage0_t *phys_disk: requested payload data returned
Return
0 on success -EFAULT if read of config page header fails or data pointer not NULL -ENOMEM if pci_alloc failed
mpt_raid_phys_disk_get_num_paths() #
int returns number paths associated to this phys_num
Parameters
MPT_ADAPTER *ioc: Pointer to a Adapter Structureu8 phys_disk_num: io unit unique phys disk num generated by the ioc
Return
returns number paths
mpt_raid_phys_disk_pg1() #
int returns phys disk page 1
Parameters
MPT_ADAPTER *ioc: Pointer to a Adapter Structureu8 phys_disk_num: io unit unique phys disk num generated by the iocRaidPhysDiskPage1_t *phys_disk: requested payload data returned
Return
0 on success -EFAULT if read of config page header fails or data pointer not NULL -ENOMEM if pci_alloc failed
mpt_findImVolumes() #
int Identify IDs of hidden disks and RAID Volumes
Parameters
MPT_ADAPTER *ioc: Pointer to a Adapter Strucutre
Return
0 on success -EFAULT if read of config page header fails or data pointer not NULL -ENOMEM if pci_alloc failed
mpt_config() #
int Generic function to issue config message
Parameters
MPT_ADAPTER *ioc: Pointer to an adapter structureCONFIGPARMS *pCfg: Pointer to a configuration structure. Struct contains action, page address, direction, physical address and pointer to a configuration page header Page header is updated.
Description
Returns 0 for success -EAGAIN if no msg frames currently available -EFAULT for non-successful reply or no reply (timeout)
mpt_print_ioc_summary() #
void Write ASCII summary of IOC to a buffer.
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structurechar *buffer: Pointer to buffer where IOC summary info should be writtenint *size: Pointer to number of bytes we wrote (set by this routine)int len: Offset at which to start writing in bufferint showlan: Display LAN stuff?
Description
This routine writes (english readable) ASCII text, which represents a summary of IOC information, to a buffer.
mpt_set_taskmgmt_in_progress_flag() #
int set flags associated with task management
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
Description
Returns 0 for SUCCESS or -1 if FAILED.
If -1 is return, then it was not possible to set the flags
mpt_clear_taskmgmt_in_progress_flag() #
void clear flags associated with task management
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
mpt_halt_firmware() #
void __noreturn Halts the firmware if it is operational and panic the kernel
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
mpt_Soft_Hard_ResetHandler() #
int Try less expensive reset
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureint sleepFlag: Indicates if sleep or schedule must be called.
Description
Returns 0 for SUCCESS or -1 if FAILED. Try for softreset first, only if it fails go for expensive HardReset.
mpt_HardResetHandler() #
int Generic reset handler
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureint sleepFlag: Indicates if sleep or schedule must be called.
Description
Issues SCSI Task Management call based on input arg values. If TaskMgmt fails, returns associated SCSI request.
Remark: _HardResetHandler can be invoked from an interrupt thread (timer)
or a non-interrupt thread. In the former, must not call schedule().
Note
-
A return of -1 is a FATAL error case, as it means a
FW reload/initialization failed.
Returns 0 for SUCCESS or -1 if FAILED.
mptscsih_info() #
const char * Return information about MPT adapter
Parameters
struct Scsi_Host *SChost: Pointer to Scsi_Host structure
Description
(linux scsi_host_template.info routine)
Returns pointer to buffer where information was written.
mptscsih_qcmd() #
enum scsi_qc_status Primary Fusion MPT SCSI initiator IO start routine.
Parameters
struct scsi_cmnd *SCpnt: Pointer to scsi_cmnd structure
Description
(linux scsi_host_template.queuecommand routine) This is the primary SCSI IO start routine. Create a MPI SCSIIORequest from a linux scsi_cmnd request and send it to the IOC.
Returns 0. (rtn value discarded by linux scsi mid-layer)
mptscsih_IssueTaskMgmt() #
int Generic send Task Management function.
Parameters
MPT_SCSI_HOST *hd: Pointer to MPT_SCSI_HOST structureu8 type: Task Management typeu8 channel: channel number for task managementu8 id: Logical Target ID for reset (if appropriate)u64 lun: Logical Unit for reset (if appropriate)int ctx2abort: Context for the task to be aborted (if appropriate)ulong timeout: timeout for task management control
Description
Remark: _HardResetHandler can be invoked from an interrupt thread (timer)
or a non-interrupt thread. In the former, must not call schedule().
Not all fields are meaningfull for all task types.
Returns 0 for SUCCESS, or FAILED.
mptscsih_abort() #
int Abort linux scsi_cmnd routine, new_eh variant
Parameters
struct scsi_cmnd * SCpnt: Pointer to scsi_cmnd structure, IO to be aborted
Description
(linux scsi_host_template.eh_abort_handler routine)
Returns SUCCESS or FAILED.
mptscsih_dev_reset() #
int Perform a SCSI LOGICAL_UNIT_RESET!
Parameters
struct scsi_cmnd * SCpnt: Pointer to scsi_cmnd structure, IO which reset is due to
Description
(linux scsi_host_template.eh_dev_reset_handler routine)
Returns SUCCESS or FAILED.
mptscsih_bus_reset() #
int Perform a SCSI BUS_RESET! new_eh variant
Parameters
struct scsi_cmnd * SCpnt: Pointer to scsi_cmnd structure, IO which reset is due to
Description
(linux scsi_host_template.eh_bus_reset_handler routine)
Returns SUCCESS or FAILED.
mptscsih_host_reset() #
int Perform a SCSI host adapter RESET (new_eh variant)
Parameters
struct scsi_cmnd *SCpnt: Pointer to scsi_cmnd structure, IO which reset is due to
Description
(linux scsi_host_template.eh_host_reset_handler routine)
Returns SUCCESS or FAILED.
mptscsih_taskmgmt_complete() #
int Registered with Fusion MPT base driver
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureMPT_FRAME_HDR *mf: Pointer to SCSI task mgmt request frameMPT_FRAME_HDR *mr: Pointer to SCSI task mgmt reply frame
Description
This routine is called from mptbase.c::mpt_interrupt() at the completion
of any SCSI task management request.
This routine is registered with the MPT (base) driver at driver
load/init time via the mpt_register() API call.
Returns 1 indicating alloc'd request frame ptr should be freed.
mptscsih_get_scsi_lookup() #
struct scsi_cmnd * retrieves scmd entry
Parameters
MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structureint i: index into the array
Description
Returns the scsi_cmd pointer
Miscellaneous Devices
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
misc_register() #
int register a miscellaneous device
Parameters
struct miscdevice *misc: device structure
Description
Register a miscellaneous device with the kernel. If the minor
number is set to MISC_DYNAMIC_MINOR a minor number is assigned
and placed in the minor field of the structure. For other cases
the minor number requested is used.
The structure passed is linked into the kernel and may not be
destroyed until it has been unregistered. By default, an open()
syscall to the device sets file->private_data to point to the
structure. Drivers don't need open in fops for this.
A zero is returned on success and a negative errno code for failure.
misc_deregister() #
void unregister a miscellaneous device
Parameters
struct miscdevice *misc: device to unregister
Description
Unregister a miscellaneous device that was previously
successfully registered with misc_register().
Parallel Port Devices
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Parallel Port Devices #
parport_register_driver() #
register a parallel port device driver
Parameters
driver: structure describing the driver
Description
This can be called by a parallel port device driver in order to receive notifications about ports being found in the system, as well as ports no longer available.
The driver structure is allocated by the caller and must not be
deallocated until after calling parport_unregister_driver().
If using the non device model:
The driver's attach() function may block. The port that
attach() is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call parport_get_port() to do so. Calling
parport_register_device() on that port will do this for you.
The driver's detach() function may block. The port that
detach() is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call parport_get_port() to do so.
Returns 0 on success. The non device model will always succeeds. but the new device model can fail and will return the error code.
module_parport_driver() #
Helper macro for registering a modular parport driver
Parameters
__parport_driver: struct parport_driver to be used
Description
Helper macro for parport drivers which do not do anything special in module
init and exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces module_init() and module_exit().
parport_yield() #
int relinquish a parallel port temporarily
Parameters
struct pardevice *dev: a device on the parallel port
Description
This function relinquishes the port if it would be helpful to other
drivers to do so. Afterwards it tries to reclaim the port using
parport_claim(), and the return value is the same as for
parport_claim(). If it fails, the port is left unclaimed and it is
the driver's responsibility to reclaim the port.
The parport_yield() and parport_yield_blocking() functions are for
marking points in the driver at which other drivers may claim the
port and use their devices. Yielding the port is similar to
releasing it and reclaiming it, but is more efficient because no
action is taken if there are no other devices needing the port. In
fact, nothing is done even if there are other devices waiting but
the current device is still within its "timeslice". The default
timeslice is half a second, but it can be adjusted via the /proc
interface.
parport_yield_blocking() #
int relinquish a parallel port temporarily
Parameters
struct pardevice *dev: a device on the parallel port
Description
This function relinquishes the port if it would be helpful to other
drivers to do so. Afterwards it tries to reclaim the port using
parport_claim_or_block(), and the return value is the same as for
parport_claim_or_block().
parport_wait_event() #
int wait for an event on a parallel port
Parameters
struct parport *port: port to wait onsigned long timeout: time to wait (in jiffies)
Description
This function waits for up to timeout jiffies for an interrupt to occur on a parallel port. If the port timeout is set to zero, it returns immediately.
If an interrupt occurs before the timeout period elapses, this function returns zero immediately. If it times out, it returns one. An error code less than zero indicates an error (most likely a pending signal), and the calling code should finish what it's doing as soon as it can.
parport_wait_peripheral() #
int wait for status lines to change in 35ms
Parameters
struct parport *port: port to watchunsigned char mask: status lines to watchunsigned char result: desired values of chosen status lines
Description
This function waits until the masked status lines have the
desired values, or until 35ms have elapsed (see IEEE 1284-1994
page 24 to 25 for why this value in particular is hardcoded).
The mask and result parameters are bitmasks, with the bits
defined by the constants in parport.h: PARPORT_STATUS_BUSY,
and so on.
The port is polled quickly to start off with, in anticipation
of a fast response from the peripheral. This fast polling
time is configurable (using /proc), and defaults to 500usec.
If the timeout for this port (see parport_set_timeout()) is
zero, the fast polling time is 35ms, and this function does
not call schedule().
If the timeout for this port is non-zero, after the fast
polling fails it uses parport_wait_event() to wait for up to
10ms, waking up if an interrupt occurs.
parport_negotiate() #
int negotiate an IEEE 1284 mode
Parameters
struct parport *port: port to useint mode: mode to negotiate to
Description
Use this to negotiate to a particular IEEE 1284 transfer mode.
The mode parameter should be one of the constants in
parport.h starting IEEE1284_MODE_xxx.
The return value is 0 if the peripheral has accepted the negotiation to the mode specified, -1 if the peripheral is not IEEE 1284 compliant (or not present), or 1 if the peripheral has rejected the negotiation.
parport_write() #
ssize_t write a block of data to a parallel port
Parameters
struct parport *port: port to write toconst void *buffer: data buffer (in kernel space)size_t len: number of bytes of data to transfer
Description
This will write up to len bytes of buffer to the port
specified, using the IEEE 1284 transfer mode most recently
negotiated to (using parport_negotiate()), as long as that
mode supports forward transfers (host to peripheral).
It is the caller's responsibility to ensure that the first len bytes of buffer are valid.
This function returns the number of bytes transferred (if zero or positive), or else an error code.
parport_read() #
ssize_t read a block of data from a parallel port
Parameters
struct parport *port: port to read fromvoid *buffer: data buffer (in kernel space)size_t len: number of bytes of data to transfer
Description
This will read up to len bytes of buffer to the port
specified, using the IEEE 1284 transfer mode most recently
negotiated to (using parport_negotiate()), as long as that
mode supports reverse transfers (peripheral to host).
It is the caller's responsibility to ensure that the first len bytes of buffer are available to write to.
This function returns the number of bytes transferred (if zero or positive), or else an error code.
parport_set_timeout() #
long set the inactivity timeout for a device
Parameters
struct pardevice *dev: device on a portlong inactivity: inactivity timeout (in jiffies)
Description
This sets the inactivity timeout for a particular device on a
port. This affects functions like parport_wait_peripheral().
The special value 0 means not to call schedule() while dealing
with this device.
The return value is the previous inactivity timeout.
Any callers of parport_wait_event() for this device are woken
up.
__parport_register_driver() #
int register a parallel port device driver
Parameters
struct parport_driver *drv: structure describing the driverstruct module *owner: owner module of drvconst char *mod_name: module name string
Description
This can be called by a parallel port device driver in order to receive notifications about ports being found in the system, as well as ports no longer available.
If devmodel is true then the new device model is used for registration.
The drv structure is allocated by the caller and must not be
deallocated until after calling parport_unregister_driver().
If using the non device model:
The driver's attach() function may block. The port that
attach() is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call parport_get_port() to do so. Calling
parport_register_device() on that port will do this for you.
The driver's detach() function may block. The port that
detach() is given will be valid for the duration of the
callback, but if the driver wants to take a copy of the
pointer it must call parport_get_port() to do so.
Returns 0 on success. The non device model will always succeeds. but the new device model can fail and will return the error code.
parport_unregister_driver() #
void deregister a parallel port device driver
Parameters
struct parport_driver *drv: structure describing the driver that was given toparport_register_driver()
Description
This should be called by a parallel port device driver that
has registered itself using parport_register_driver() when it
is about to be unloaded.
When it returns, the driver's attach() routine will no longer
be called, and for each port that attach() was called for, the
detach() routine will have been called.
All the driver's attach() and detach() calls are guaranteed to have
finished by the time this function returns.
parport_get_port() #
struct parport * increment a port's reference count
Parameters
struct parport *port: the port
Description
This ensures that a struct parport pointer remains valid
until the matching parport_put_port() call.
parport_put_port() #
void decrement a port's reference count
Parameters
struct parport *port: the port
Description
This should be called once for each call to parport_get_port(),
once the port is no longer needed. When the reference count reaches
zero (port is no longer used), free_port is called.
parport_register_port() #
struct parport * register a parallel port
Parameters
unsigned long base: base I/O addressint irq: IRQ lineint dma: DMA channelstruct parport_operations *ops: pointer to the port driver's port operations structure
Description
When a parallel port (lowlevel) driver finds a port that
should be made available to parallel port device drivers, it
should call parport_register_port(). The base, irq, and
dma parameters are for the convenience of port drivers, and
for ports where they aren't meaningful needn't be set to
anything special. They can be altered afterwards by adjusting
the relevant members of the parport structure that is returned
and represents the port. They should not be tampered with
after calling parport_announce_port, however.
If there are parallel port device drivers in the system that
have registered themselves using parport_register_driver(),
they are not told about the port at this time; that is done by
parport_announce_port().
The ops structure is allocated by the caller, and must not be
deallocated before calling parport_remove_port().
If there is no memory to allocate a new parport structure,
this function will return NULL.
parport_announce_port() #
void tell device drivers about a parallel port
Parameters
struct parport *port: parallel port to announce
Description
After a port driver has registered a parallel port with
parport_register_port, and performed any necessary
initialisation or adjustments, it should call
parport_announce_port() in order to notify all device drivers
that have called parport_register_driver(). Their attach()
functions will be called, with port as the parameter.
parport_remove_port() #
void deregister a parallel port
Parameters
struct parport *port: parallel port to deregister
Description
When a parallel port driver is forcibly unloaded, or a parallel port becomes inaccessible, the port driver must call this function in order to deal with device drivers that still want to use it.
The parport structure associated with the port has its operations structure replaced with one containing 'null' operations that return errors or just don't do anything.
Any drivers that have registered themselves using
parport_register_driver() are notified that the port is no
longer accessible by having their detach() routines called
with port as the parameter.
parport_register_dev_model() #
struct pardevice * register a device on a parallel port
Parameters
struct parport *port: port to which the device is attachedconst char *name: a name to refer to the deviceconst struct pardev_cb *par_dev_cb: struct containing callbacksint id: device number to be given to the device
Description
This function, called by parallel port device drivers, declares that a device is connected to a port, and tells the system all it needs to know.
The struct pardev_cb contains pointer to callbacks. preemption
callback function, preempt, is called when this device driver
has claimed access to the port but another device driver wants
to use it. It is given, private, as its parameter, and should
return zero if it is willing for the system to release the port
to another driver on its behalf. If it wants to keep control of
the port it should return non-zero, and no action will be taken.
It is good manners for the driver to try to release the port at
the earliest opportunity after its preemption callback rejects a
preemption attempt. Note that if a preemption callback is happy
for preemption to go ahead, there is no need to release the
port; it is done automatically. This function may not block, as
it may be called from interrupt context. If the device driver
does not support preemption, preempt can be NULL.
The wake-up ("kick") callback function, wakeup, is called when
the port is available to be claimed for exclusive access; that
is, parport_claim() is guaranteed to succeed when called from
inside the wake-up callback function. If the driver wants to
claim the port it should do so; otherwise, it need not take
any action. This function may not block, as it may be called
from interrupt context. If the device driver does not want to
be explicitly invited to claim the port in this way, wakeup can
be NULL.
The interrupt handler, irq_func, is called when an interrupt
arrives from the parallel port. Note that if a device driver
wants to use interrupts it should use parport_enable_irq(),
and can also check the irq member of the parport structure
representing the port.
The parallel port (lowlevel) driver is the one that has called
request_irq() and whose interrupt handler is called first.
This handler does whatever needs to be done to the hardware to
acknowledge the interrupt (for PC-style ports there is nothing
special to be done). It then tells the IEEE 1284 code about
the interrupt, which may involve reacting to an IEEE 1284
event depending on the current IEEE 1284 phase. After this,
it calls irq_func. Needless to say, irq_func will be called
from interrupt context, and may not block.
The PARPORT_DEV_EXCL flag is for preventing port sharing, and
so should only be used when sharing the port with other device
drivers is impossible and would lead to incorrect behaviour.
Use it sparingly! Normally, flags will be zero.
This function returns a pointer to a structure that represents
the device on the port, or NULL if there is not enough memory
to allocate space for that structure.
parport_unregister_device() #
void deregister a device on a parallel port
Parameters
struct pardevice *dev: pointer to structure representing device
Description
This undoes the effect of parport_register_device().
parport_find_number() #
struct parport * find a parallel port by number
Parameters
int number: parallel port number
Description
This returns the parallel port with the specified number, or
NULL if there is none.
There is an implicit parport_get_port() done already; to throw
away the reference to the port that parport_find_number()
gives you, use parport_put_port().
parport_find_base() #
struct parport * find a parallel port by base address
Parameters
unsigned long base: base I/O address
Description
This returns the parallel port with the specified base
address, or NULL if there is none.
There is an implicit parport_get_port() done already; to throw
away the reference to the port that parport_find_base()
gives you, use parport_put_port().
parport_claim() #
int claim access to a parallel port device
Parameters
struct pardevice *dev: pointer to structure representing a device on the port
Description
This function will not block and so can be used from interrupt
context. If parport_claim() succeeds in claiming access to
the port it returns zero and the port is available to use. It
may fail (returning non-zero) if the port is in use by another
driver and that driver is not willing to relinquish control of
the port.
parport_claim_or_block() #
int claim access to a parallel port device
Parameters
struct pardevice *dev: pointer to structure representing a device on the port
Description
This behaves like parport_claim(), but will block if necessary
to wait for the port to be free. A return value of 1
indicates that it slept; 0 means that it succeeded without
needing to sleep. A negative error code indicates failure.
parport_release() #
void give up access to a parallel port device
Parameters
struct pardevice *dev: pointer to structure representing parallel port device
Description
This function cannot fail, but it should not be called without the port claimed. Similarly, if the port is already claimed you should not try claiming it again.
parport_open() #
struct pardevice * find a device by canonical device number
Parameters
int devnum: canonical device numberconst char *name: name to associate with the device
Description
This function is similar to parport_register_device(), except
that it locates a device by its number rather than by the port
it is attached to.
All parameters except for devnum are the same as for
parport_register_device(). The return value is the same as
for parport_register_device().
parport_close() #
void close a device opened with parport_open()
Parameters
struct pardevice *dev: device to close
Description
This is to parport_open() as parport_unregister_device() is to
parport_register_device().
16x50 UART Driver #
serial8250_get_port() #
struct uart_8250_port * retrieve struct uart_8250_port
Parameters
int line: serial line number
Description
This function retrieves struct uart_8250_port for the specific line. This struct must not be used to perform a 8250 or serial core operation which is not accessible otherwise. Its only purpose is to make the struct accessible to the runtime-pm callbacks for context suspend/restore. The lock assumption made here is none because runtime-pm suspend/resume callbacks should not be invoked if there is any operation performed on the port.
serial8250_suspend_port() #
void suspend one serial port
Parameters
int line: serial line number
Description
Suspend one serial port.
serial8250_resume_port() #
void resume one serial port
Parameters
int line: serial line number
Description
Resume one serial port.
serial8250_register_8250_port() #
int register a serial port
Parameters
const struct uart_8250_port *up: serial port template
Description
Configure the serial port specified by the request. If the port exists and is in use, it is hung up and unregistered first.
The port is then probed and if necessary the IRQ is autodetected If this fails an error is returned.
On success the port is ready to use and the line number is returned.
serial8250_unregister_port() #
void remove a 16x50 serial port at runtime
Parameters
int line: serial line number
Description
Remove one serial port. This may not be called from interrupt context. We hand the port back to the our control.
See serial/driver.rst for related APIs.
Pulse-Width Modulation (PWM) #
Pulse-width modulation is a modulation technique primarily used to control power supplied to electrical devices.
The PWM framework provides an abstraction for providers and consumers of PWM signals. A controller that provides one or more PWM signals is registered as struct pwm_chip <pwm_chip>. Providers are expected to embed this structure in a driver-specific structure. This structure contains fields that describe a particular chip.
A chip exposes one or more PWM signal sources, each of which exposed as a struct pwm_device <pwm_device>. Operations can be performed on PWM devices to control the period, duty cycle, polarity and active state of the signal.
Note that PWM devices are exclusive resources: they can always only be used by one consumer at a time.
enum pwm_polarity #
polarity of a PWM signal
Constants
PWM_POLARITY_NORMAL: a high signal for the duration of the duty- cycle, followed by a low signal for the remainder of the pulse periodPWM_POLARITY_INVERSED: a low signal for the duration of the duty- cycle, followed by a high signal for the remainder of the pulse period
struct pwm_args #
board-dependent PWM arguments
Definition
;
Members
period: reference periodpolarity: reference polarity
Description
This structure describes board-dependent arguments attached to a PWM device. These arguments are usually retrieved from the PWM lookup table or device tree.
Do not confuse this with the PWM state: PWM arguments represent the initial configuration that users want to use on this PWM device rather than the current PWM hardware state.
struct pwm_waveform #
description of a PWM waveform
Definition
;
Members
period_length_ns: PWM periodduty_length_ns: PWM duty cycleduty_offset_ns: offset of the rising edge from the period's start
Description
This is a representation of a PWM waveform alternative to struct pwm_state below. It's more expressive than struct pwm_state as it contains a duty_offset_ns and so can represent offsets other than zero (with .polarity = PWM_POLARITY_NORMAL) and period - duty_cycle (.polarity = PWM_POLARITY_INVERSED).
Note there is no explicit bool for enabled. A "disabled" PWM is represented by .period_length_ns = 0. Note further that the behaviour of a "disabled" PWM is undefined. Depending on the hardware's capabilities it might drive the active or inactive level, go high-z or even continue to toggle.
The unit for all three members is nanoseconds.
struct pwm_device #
PWM channel object
Definition
;
Members
label: name of the PWM deviceflags: flags associated with the PWM devicehwpwm: per-chip relative index of the PWM devicechip: PWM chip providing this PWM deviceargs: PWM argumentsstate: last applied statelast: last implemented state (for PWM_DEBUG)
pwm_get_state() #
void retrieve the current PWM state
Parameters
const struct pwm_device *pwm: PWM devicestruct pwm_state *state: state to fill with the current PWM state
Description
The returned PWM state represents the state that was applied by a previous call to
pwm_apply_might_sleep(). Drivers may have to slightly tweak that state before programming it to
hardware. If pwm_apply_might_sleep() was never called, this returns either the current hardware
state (if supported) or the default settings.
pwm_init_state() #
void prepare a new state to be applied with pwm_apply_might_sleep()
Parameters
const struct pwm_device *pwm: PWM devicestruct pwm_state *state: state to fill with the prepared PWM state
Description
This functions prepares a state that can later be tweaked and applied
to the PWM device with pwm_apply_might_sleep(). This is a convenient function
that first retrieves the current PWM state and the replaces the period
and polarity fields with the reference values defined in pwm->args.
Once the function returns, you can adjust the ->enabled and ->duty_cycle
fields according to your needs before calling pwm_apply_might_sleep().
->duty_cycle is initially set to zero to avoid cases where the current
->duty_cycle value exceed the pwm_args->period one, which would trigger
an error if the user calls pwm_apply_might_sleep() without adjusting ->duty_cycle
first.
pwm_get_relative_duty_cycle() #
unsigned int Get a relative duty cycle value
Parameters
const struct pwm_state *state: PWM state to extract the duty cycle fromunsigned int scale: target scale of the relative duty cycle
Description
This functions converts the absolute duty cycle stored in state (expressed in nanosecond) into a value relative to the period.
For example if you want to get the duty_cycle expressed in percent, call:
pwm_get_state(pwm, state);
duty = pwm_get_relative_duty_cycle(state, 100);
Return
rounded relative duty cycle multiplied by scale
pwm_set_relative_duty_cycle() #
int Set a relative duty cycle value
Parameters
struct pwm_state *state: PWM state to fillunsigned int duty_cycle: relative duty cycle valueunsigned int scale: scale in which duty_cycle is expressed
Description
This functions converts a relative into an absolute duty cycle (expressed in nanoseconds), and puts the result in state->duty_cycle.
For example if you want to configure a 50% duty cycle, call:
pwm_init_state(pwm, state);
pwm_set_relative_duty_cycle(state, 50, 100);
pwm_apply_might_sleep(pwm, state);
Return
0 on success or -EINVAL if duty_cycle and/or scale are
inconsistent (scale == 0 or duty_cycle > scale)
struct pwm_capture #
PWM capture data
Definition
;
Members
period: period of the PWM signal (in nanoseconds)duty_cycle: duty cycle of the PWM signal (in nanoseconds)
struct pwm_ops #
PWM controller operations
Definition
;
Members
request: optional hook for requesting a PWMfree: optional hook for freeing a PWMcapture: capture and report PWM signalsizeof_wfhw: size (in bytes) of driver specific waveform presentationround_waveform_tohw: convert a struct pwm_waveform to driver specific presentationround_waveform_fromhw: convert a driver specific waveform presentation to struct pwm_waveformread_waveform: read driver specific waveform presentation from hardwarewrite_waveform: write driver specific waveform presentation to hardwareapply: atomically apply a new PWM configget_state: get the current PWM state.
struct pwm_chip #
abstract a PWM controller
Definition
;
Members
dev: device providing the PWMscdev:struct cdevfor this deviceops: callbacks for this PWM controllerowner: module providing this chipid: unique number of this PWM chipnpwm: number of PWMs controlled by this chipof_xlate: request a PWM device given a device tree PWM specifieratomic: can the driver's ->apply()be called in atomic contextgpio:struct gpio_chipto operate this PWM chip's lines as GPOuses_pwmchip_alloc: signals if pwmchip_allow was used to allocate this chipoperational: signals if the chip can be used (or is already deregistered){unnamed_union}: anonymousnonatomic_lock: mutex for nonatomic chipsatomic_lock: mutex for atomic chipspwms: array of PWM devices allocated by the framework
pwmchip_supports_waveform() #
bool checks if the given chip supports waveform callbacks
Parameters
struct pwm_chip *chip: The pwm_chip to test
Return
true iff the pwm chip support the waveform functions like
pwm_set_waveform_might_sleep() and pwm_round_waveform_might_sleep()
pwm_config() #
int change a PWM device configuration
Parameters
struct pwm_device *pwm: PWM deviceint duty_ns: "on" time (in nanoseconds)int period_ns: duration (in nanoseconds) of one cycle
Return
0 on success or a negative error code on failure.
pwm_enable() #
int start a PWM output toggling
Parameters
struct pwm_device *pwm: PWM device
Return
0 on success or a negative error code on failure.
pwm_disable() #
void stop a PWM output toggling
Parameters
struct pwm_device *pwm: PWM device
pwm_might_sleep() #
bool is pwm_apply_atomic() supported?
Parameters
struct pwm_device *pwm: PWM device
Return
false if pwm_apply_atomic() can be called from atomic context.
pwm_round_waveform_might_sleep() #
int Query hardware capabilities Cannot be used in atomic context.
Parameters
struct pwm_device *pwm: PWM devicestruct pwm_waveform *wf: waveform to round and output parameter
Description
Typically a given waveform cannot be implemented exactly by hardware, e.g.
because hardware only supports coarse period resolution or no duty_offset.
This function returns the actually implemented waveform if you pass wf to
pwm_set_waveform_might_sleep() now.
Note however that the world doesn't stop turning when you call it, so when doing:
pwm_round_waveform_might_sleep(mypwm, &wf);
pwm_set_waveform_might_sleep(mypwm, &wf, true);
the latter might fail, e.g. because an input clock changed its rate between
these two calls and the waveform determined by
pwm_round_waveform_might_sleep() cannot be implemented any more.
Usually all values passed in wf are rounded down to the nearest possible
value (in the order period_length_ns, duty_length_ns and then
duty_offset_ns). Only if this isn't possible, a value might grow. See the
documentation for pwm_set_waveform_might_sleep() for a more formal
description.
Return
0 on success, 1 if at least one value had to be rounded up or a negative errno.
Context
May sleep.
pwm_get_waveform_might_sleep() #
int Query hardware about current configuration Cannot be used in atomic context.
Parameters
struct pwm_device *pwm: PWM devicestruct pwm_waveform *wf: output parameter
Description
Stores the current configuration of the PWM in wf. Note this is the
equivalent of pwm_get_state_hw() (and not pwm_get_state()) for pwm_waveform.
Return
0 on success or a negative errno
Context
May sleep.
pwm_set_waveform_might_sleep() #
int Apply a new waveform Cannot be used in atomic context.
Parameters
struct pwm_device *pwm: PWM deviceconst struct pwm_waveform *wf: The waveform to applybool exact: If true no rounding is allowed
Description
Typically a requested waveform cannot be implemented exactly, e.g. because
you requested .period_length_ns = 100 ns, but the hardware can only set
periods that are a multiple of 8.5 ns. With that hardware passing exact =
true results in pwm_set_waveform_might_sleep() failing and returning -EDOM.
If exact = false you get a period of 93.5 ns (i.e. the biggest period not
bigger than the requested value).
Note that even with exact = true, some rounding by less than 1 ns is
possible/needed. In the above example requesting .period_length_ns = 94 and
exact = true, you get the hardware configured with period = 93.5 ns.
Let C be the set of possible hardware configurations for a given PWM device, consisting of tuples (p, d, o) where p is the period length, d is the duty length and o the duty offset.
The following algorithm is implemented to pick the hardware setting (p, d, o) ∈ C for a given request (p', d', o') with exact = false:
p = max( { ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C ∧ ṗ ≤ p' } ∪ { min({ ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C }) })
d = max( { ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C ∧ ḋ ≤ d' } ∪ { min({ ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C }) })
o = max( { ȯ | (p, d, ȯ) ∈ C ∧ ȯ ≤ o' } ∪ { min({ ȯ | (p, d, ȯ) ∈ C }) })
In words: The chosen period length is the maximal possible period length not bigger than the requested period length and if that doesn't exist, the minimal period length. The chosen duty length is the maximal possible duty length that is compatible with the chosen period length and isn't bigger than the requested duty length. Again if such a value doesn't exist, the minimal duty length compatible with the chosen period is picked. After that the duty offset compatible with the chosen period and duty length is chosen in the same way.
Return
0 on success, -EDOM if setting failed due to the exact waveform not being possible (if exact), or a different negative errno on failure.
Context
May sleep.
pwm_apply_might_sleep() #
int atomically apply a new state to a PWM device Cannot be used in atomic context.
Parameters
struct pwm_device *pwm: PWM deviceconst struct pwm_state *state: new state to apply
Return
0 on success, or a negative errno
Context
May sleep.
pwm_apply_atomic() #
int apply a new state to a PWM device from atomic context Not all PWM devices support this function, check with pwm_might_sleep().
Parameters
struct pwm_device *pwm: PWM deviceconst struct pwm_state *state: new state to apply
Return
0 on success, or a negative errno
Context
Any
pwm_get_state_hw() #
int get the current PWM state from hardware
Parameters
struct pwm_device *pwm: PWM devicestruct pwm_state *state: state to fill with the current PWM state
Description
Similar to pwm_get_state() but reads the current PWM state from hardware
instead of the requested state.
Return
0 on success or a negative error code on failure.
Context
May sleep.
pwm_adjust_config() #
int adjust the current PWM config to the PWM arguments
Parameters
struct pwm_device *pwm: PWM device
Description
This function will adjust the PWM config to the PWM arguments provided by the DT or PWM lookup table. This is particularly useful to adapt the bootloader config to the Linux one.
Return
0 on success or a negative error code on failure.
Context
May sleep.
pwm_get() #
struct pwm_device * look up and request a PWM device
Parameters
struct device *dev: device for PWM consumerconst char *con_id: consumer name
Description
Lookup is first attempted using DT. If the device was not instantiated from
a device tree, a PWM chip and a relative index is looked up via a table
supplied by board setup code (see pwm_add_table()).
Once a PWM chip has been found the specified PWM device will be requested and is ready to be used.
Return
A pointer to the requested PWM device or an ERR_PTR()-encoded
error code on failure.
pwm_put() #
void release a PWM device
Parameters
struct pwm_device *pwm: PWM device
devm_pwm_get() #
struct pwm_device * resource managed pwm_get()
Parameters
struct device *dev: device for PWM consumerconst char *con_id: consumer name
Description
This function performs like pwm_get() but the acquired PWM device will
automatically be released on driver detach.
Return
A pointer to the requested PWM device or an ERR_PTR()-encoded
error code on failure.
devm_fwnode_pwm_get() #
struct pwm_device * request a resource managed PWM from firmware node
Parameters
struct device *dev: device for PWM consumerstruct fwnode_handle *fwnode: firmware node to get the PWM fromconst char *con_id: consumer name
Description
Returns the PWM device parsed from the firmware node. See of_pwm_get() and
acpi_pwm_get() for a detailed description.
Return
A pointer to the requested PWM device or an ERR_PTR()-encoded
error code on failure.
__pwmchip_add() #
int register a new PWM chip
Parameters
struct pwm_chip *chip: the PWM chip to addstruct module *owner: reference to the module providing the chip.
Description
Register a new PWM chip. owner is supposed to be THIS_MODULE, use the pwmchip_add wrapper to do this right.
Return
0 on success or a negative error code on failure.
pwmchip_remove() #
void remove a PWM chip
Parameters
struct pwm_chip *chip: the PWM chip to remove
Description
Removes a PWM chip.
MTD NAND Driver Programming Interface
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Author: Thomas Gleixner
Introduction #
The generic NAND driver supports almost all NAND and AG-AND based chips and connects them to the Memory Technology Devices (MTD) subsystem of the Linux Kernel.
This documentation is provided for developers who want to implement board drivers or filesystem drivers suitable for NAND devices.
Known Bugs And Assumptions #
None.
Documentation hints #
The function and structure docs are autogenerated. Each function and struct member has a short description which is marked with an [XXX] identifier. The following chapters explain the meaning of those identifiers.
Function identifiers [XXX] #
The functions are marked with [XXX] identifiers in the short comment. The identifiers explain the usage and scope of the functions. Following identifiers are used:
-
[MTD Interface]
These functions provide the interface to the MTD kernel API. They are not replaceable and provide functionality which is complete hardware independent.
-
[NAND Interface]
These functions are exported and provide the interface to the NAND kernel API.
-
[GENERIC]
Generic functions are not replaceable and provide functionality which is complete hardware independent.
-
[DEFAULT]
Default functions provide hardware related functionality which is suitable for most of the implementations. These functions can be replaced by the board driver if necessary. Those functions are called via pointers in the NAND chip description structure. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.
Struct member identifiers [XXX] #
The struct members are marked with [XXX] identifiers in the comment. The identifiers explain the usage and scope of the members. Following identifiers are used:
-
[INTERN]
These members are for NAND driver internal use only and must not be modified. Most of these values are calculated from the chip geometry information which is evaluated during nand_scan().
-
[REPLACEABLE]
Replaceable members hold hardware related functions which can be provided by the board driver. The board driver can set the functions which should be replaced by board dependent functions before calling nand_scan(). If the function pointer is NULL on entry to nand_scan() then the pointer is set to the default function which is suitable for the detected chip type.
-
[BOARDSPECIFIC]
Board specific members hold hardware related information which must be provided by the board driver. The board driver must set the function pointers and datafields before calling nand_scan().
-
[OPTIONAL]
Optional members can hold information relevant for the board driver. The generic NAND driver code does not use this information.
Basic board driver #
For most boards it will be sufficient to provide just the basic functions and fill out some really board dependent members in the nand chip description structure.
Basic defines #
At least you have to provide a nand_chip structure and a storage for the ioremap'ed chip address. You can allocate the nand_chip structure using kmalloc or you can allocate it statically. The NAND chip structure embeds an mtd structure which will be registered to the MTD subsystem. You can extract a pointer to the mtd structure from a nand_chip pointer using the nand_to_mtd() helper.
Kmalloc based example
static struct mtd_info *board_mtd;
static void __iomem *baseaddr;
Static example
static struct nand_chip board_chip;
static void __iomem *baseaddr;
Partition defines #
If you want to divide your device into partitions, then define a partitioning scheme suitable to your board.
#define NUM_PARTITIONS 2
static struct mtd_partition partition_info[] = {
{ .name = "Flash partition 1",
.offset = 0,
.size = 8 * 1024 * 1024 },
{ .name = "Flash partition 2",
.offset = MTDPART_OFS_NEXT,
.size = MTDPART_SIZ_FULL },
};
Hardware control function #
The hardware control function provides access to the control pins of the NAND chip(s). The access can be done by GPIO pins or by address lines. If you use address lines, make sure that the timing requirements are met.
GPIO based example
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
switch(cmd){
case NAND_CTL_SETCLE: /* Set CLE pin high */ break;
case NAND_CTL_CLRCLE: /* Set CLE pin low */ break;
case NAND_CTL_SETALE: /* Set ALE pin high */ break;
case NAND_CTL_CLRALE: /* Set ALE pin low */ break;
case NAND_CTL_SETNCE: /* Set nCE pin low */ break;
case NAND_CTL_CLRNCE: /* Set nCE pin high */ break;
}
}
Address lines based example. It's assumed that the nCE pin is driven by a chip select decoder.
static void board_hwcontrol(struct mtd_info *mtd, int cmd)
{
struct nand_chip *this = mtd_to_nand(mtd);
switch(cmd){
case NAND_CTL_SETCLE: this->legacy.IO_ADDR_W |= CLE_ADRR_BIT; break;
case NAND_CTL_CLRCLE: this->legacy.IO_ADDR_W &= ~CLE_ADRR_BIT; break;
case NAND_CTL_SETALE: this->legacy.IO_ADDR_W |= ALE_ADRR_BIT; break;
case NAND_CTL_CLRALE: this->legacy.IO_ADDR_W &= ~ALE_ADRR_BIT; break;
}
}
Device ready function #
If the hardware interface has the ready busy pin of the NAND chip connected to a GPIO or other accessible I/O pin, this function is used to read back the state of the pin. The function has no arguments and should return 0, if the device is busy (R/B pin is low) and 1, if the device is ready (R/B pin is high). If the hardware interface does not give access to the ready busy pin, then the function must not be defined and the function pointer this->legacy.dev_ready is set to NULL.
Init function #
The init function allocates memory and sets up all the board specific parameters and function pointers. When everything is set up nand_scan() is called. This function tries to detect and identify then chip. If a chip is found all the internal data fields are initialized accordingly. The structure(s) have to be zeroed out first and then filled with the necessary information about the device.
static int __init board_init (void)
{
struct nand_chip *this;
int err = 0;
/* Allocate memory for MTD device structure and private data */
this = kzalloc(sizeof(struct nand_chip), GFP_KERNEL);
if (!this) {
printk ("Unable to allocate NAND MTD device structure.\n");
err = -ENOMEM;
goto out;
}
board_mtd = nand_to_mtd(this);
/* map physical address */
baseaddr = ioremap(CHIP_PHYSICAL_ADDRESS, 1024);
if (!baseaddr) {
printk("Ioremap to access NAND chip failed\n");
err = -EIO;
goto out_mtd;
}
/* Set address of NAND IO lines */
this->legacy.IO_ADDR_R = baseaddr;
this->legacy.IO_ADDR_W = baseaddr;
/* Reference hardware control function */
this->hwcontrol = board_hwcontrol;
/* Set command delay time, see datasheet for correct value */
this->legacy.chip_delay = CHIP_DEPENDEND_COMMAND_DELAY;
/* Assign the device ready function, if available */
this->legacy.dev_ready = board_dev_ready;
this->eccmode = NAND_ECC_SOFT;
/* Scan to find existence of the device */
if (nand_scan (this, 1)) {
err = -ENXIO;
goto out_ior;
}
add_mtd_partitions(board_mtd, partition_info, NUM_PARTITIONS);
goto out;
out_ior:
iounmap(baseaddr);
out_mtd:
kfree (this);
out:
return err;
}
module_init(board_init);
Exit function #
The exit function is only necessary if the driver is compiled as a module. It releases all resources which are held by the chip driver and unregisters the partitions in the MTD layer.
#ifdef MODULE
static void __exit board_cleanup (void)
{
/* Unregister device */
WARN_ON(mtd_device_unregister(board_mtd));
/* Release resources */
nand_cleanup(mtd_to_nand(board_mtd));
/* unmap physical address */
iounmap(baseaddr);
/* Free the MTD device structure */
kfree (mtd_to_nand(board_mtd));
}
module_exit(board_cleanup);
#endif
Advanced board driver functions #
This chapter describes the advanced functionality of the NAND driver. For a list of functions which can be overridden by the board driver see the documentation of the nand_chip structure.
Multiple chip control #
The nand driver can control chip arrays. Therefore the board driver must provide an own select_chip function. This function must (de)select the requested chip. The function pointer in the nand_chip structure must be set before calling nand_scan(). The maxchip parameter of nand_scan() defines the maximum number of chips to scan for. Make sure that the select_chip function can handle the requested number of chips.
The nand driver concatenates the chips to one virtual chip and provides this virtual chip to the MTD layer.
Note: The driver can only handle linear chip arrays of equally sized chips. There is no support for parallel arrays which extend the buswidth.
GPIO based example
static void board_select_chip (struct mtd_info *mtd, int chip)
{
/* Deselect all chips, set all nCE pins high */
GPIO(BOARD_NAND_NCE) |= 0xff;
if (chip >= 0)
GPIO(BOARD_NAND_NCE) &= ~ (1 << chip);
}
Address lines based example. Its assumed that the nCE pins are connected to an address decoder.
static void board_select_chip (struct mtd_info *mtd, int chip)
{
struct nand_chip *this = mtd_to_nand(mtd);
/* Deselect all chips */
this->legacy.IO_ADDR_R &= ~BOARD_NAND_ADDR_MASK;
this->legacy.IO_ADDR_W &= ~BOARD_NAND_ADDR_MASK;
switch (chip) {
case 0:
this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIP0;
this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIP0;
break;
....
case n:
this->legacy.IO_ADDR_R |= BOARD_NAND_ADDR_CHIPn;
this->legacy.IO_ADDR_W |= BOARD_NAND_ADDR_CHIPn;
break;
}
}
Hardware ECC support #
Functions and constants #
The nand driver supports three different types of hardware ECC.
-
NAND_ECC_HW3_256
Hardware ECC generator providing 3 bytes ECC per 256 byte.
-
NAND_ECC_HW3_512
Hardware ECC generator providing 3 bytes ECC per 512 byte.
-
NAND_ECC_HW6_512
Hardware ECC generator providing 6 bytes ECC per 512 byte.
-
NAND_ECC_HW8_512
Hardware ECC generator providing 8 bytes ECC per 512 byte.
If your hardware generator has a different functionality add it at the appropriate place in nand_base.c
The board driver must provide following functions:
-
enable_hwecc
This function is called before reading / writing to the chip. Reset or initialize the hardware generator in this function. The function is called with an argument which let you distinguish between read and write operations.
-
calculate_ecc
This function is called after read / write from / to the chip. Transfer the ECC from the hardware to the buffer. If the option NAND_HWECC_SYNDROME is set then the function is only called on write. See below.
-
correct_data
In case of an ECC error this function is called for error detection and correction. Return 1 respectively 2 in case the error can be corrected. If the error is not correctable return -1. If your hardware generator matches the default algorithm of the nand_ecc software generator then use the correction function provided by nand_ecc instead of implementing duplicated code.
Hardware ECC with syndrome calculation #
Many hardware ECC implementations provide Reed-Solomon codes and calculate an error syndrome on read. The syndrome must be converted to a standard Reed-Solomon syndrome before calling the error correction code in the generic Reed-Solomon library.
The ECC bytes must be placed immediately after the data bytes in order to make the syndrome generator work. This is contrary to the usual layout used by software ECC. The separation of data and out of band area is not longer possible. The nand driver code handles this layout and the remaining free bytes in the oob area are managed by the autoplacement code. Provide a matching oob-layout in this case. See rts_from4.c and diskonchip.c for implementation reference. In those cases we must also use bad block tables on FLASH, because the ECC layout is interfering with the bad block marker positions. See bad block table support for details.
Bad block table support #
Most NAND chips mark the bad blocks at a defined position in the spare area. Those blocks must not be erased under any circumstances as the bad block information would be lost. It is possible to check the bad block mark each time when the blocks are accessed by reading the spare area of the first page in the block. This is time consuming so a bad block table is used.
The nand driver supports various types of bad block tables.
-
Per device
The bad block table contains all bad block information of the device which can consist of multiple chips.
-
Per chip
A bad block table is used per chip and contains the bad block information for this particular chip.
-
Fixed offset
The bad block table is located at a fixed offset in the chip (device). This applies to various DiskOnChip devices.
-
Automatic placed
The bad block table is automatically placed and detected either at the end or at the beginning of a chip (device)
-
Mirrored tables
The bad block table is mirrored on the chip (device) to allow updates of the bad block table without data loss.
nand_scan() calls the function nand_default_bbt(). nand_default_bbt() selects appropriate default bad block table descriptors depending on the chip information which was retrieved by nand_scan().
The standard policy is scanning the device for bad blocks and build a ram based bad block table which allows faster access than always checking the bad block information on the flash chip itself.
Flash based tables #
It may be desired or necessary to keep a bad block table in FLASH. For AG-AND chips this is mandatory, as they have no factory marked bad blocks. They have factory marked good blocks. The marker pattern is erased when the block is erased to be reused. So in case of powerloss before writing the pattern back to the chip this block would be lost and added to the bad blocks. Therefore we scan the chip(s) when we detect them the first time for good blocks and store this information in a bad block table before erasing any of the blocks.
The blocks in which the tables are stored are protected against accidental access by marking them bad in the memory bad block table. The bad block table management functions are allowed to circumvent this protection.
The simplest way to activate the FLASH based bad block table support is to set the option NAND_BBT_USE_FLASH in the bbt_option field of the nand chip structure before calling nand_scan(). For AG-AND chips is this done by default. This activates the default FLASH based bad block table functionality of the NAND driver. The default bad block table options are
-
Store bad block table per chip
-
Use 2 bits per block
-
Automatic placement at the end of the chip
-
Use mirrored tables with version numbers
-
Reserve 4 blocks at the end of the chip
User defined tables #
User defined tables are created by filling out a nand_bbt_descr structure and storing the pointer in the nand_chip structure member bbt_td before calling nand_scan(). If a mirror table is necessary a second structure must be created and a pointer to this structure must be stored in bbt_md inside the nand_chip structure. If the bbt_md member is set to NULL then only the main table is used and no scan for the mirrored table is performed.
The most important field in the nand_bbt_descr structure is the options field. The options define most of the table properties. Use the predefined constants from rawnand.h to define the options.
-
Number of bits per block
The supported number of bits is 1, 2, 4, 8.
-
Table per chip
Setting the constant NAND_BBT_PERCHIP selects that a bad block table is managed for each chip in a chip array. If this option is not set then a per device bad block table is used.
-
Table location is absolute
Use the option constant NAND_BBT_ABSPAGE and define the absolute page number where the bad block table starts in the field pages. If you have selected bad block tables per chip and you have a multi chip array then the start page must be given for each chip in the chip array. Note: there is no scan for a table ident pattern performed, so the fields pattern, veroffs, offs, len can be left uninitialized
-
Table location is automatically detected
The table can either be located in the first or the last good blocks of the chip (device). Set NAND_BBT_LASTBLOCK to place the bad block table at the end of the chip (device). The bad block tables are marked and identified by a pattern which is stored in the spare area of the first page in the block which holds the bad block table. Store a pointer to the pattern in the pattern field. Further the length of the pattern has to be stored in len and the offset in the spare area must be given in the offs member of the nand_bbt_descr structure. For mirrored bad block tables different patterns are mandatory.
-
Table creation
Set the option NAND_BBT_CREATE to enable the table creation if no table can be found during the scan. Usually this is done only once if a new chip is found.
-
Table write support
Set the option NAND_BBT_WRITE to enable the table write support. This allows the update of the bad block table(s) in case a block has to be marked bad due to wear. The MTD interface function block_markbad is calling the update function of the bad block table. If the write support is enabled then the table is updated on FLASH.
Note: Write support should only be enabled for mirrored tables with version control.
-
Table version control
Set the option NAND_BBT_VERSION to enable the table version control. It's highly recommended to enable this for mirrored tables with write support. It makes sure that the risk of losing the bad block table information is reduced to the loss of the information about the one worn out block which should be marked bad. The version is stored in 4 consecutive bytes in the spare area of the device. The position of the version number is defined by the member veroffs in the bad block table descriptor.
-
Save block contents on write
In case that the block which holds the bad block table does contain other useful information, set the option NAND_BBT_SAVECONTENT. When the bad block table is written then the whole block is read the bad block table is updated and the block is erased and everything is written back. If this option is not set only the bad block table is written and everything else in the block is ignored and erased.
-
Number of reserved blocks
For automatic placement some blocks must be reserved for bad block table storage. The number of reserved blocks is defined in the maxblocks member of the bad block table description structure. Reserving 4 blocks for mirrored tables should be a reasonable number. This also limits the number of blocks which are scanned for the bad block table ident pattern.
Spare area (auto)placement #
The nand driver implements different possibilities for placement of filesystem data in the spare area,
-
Placement defined by fs driver
-
Automatic placement
The default placement function is automatic placement. The nand driver has built in default placement schemes for the various chiptypes. If due to hardware ECC functionality the default placement does not fit then the board driver can provide a own placement scheme.
File system drivers can provide a own placement scheme which is used instead of the default placement scheme.
Placement schemes are defined by a nand_oobinfo structure
struct nand_oobinfo {
int useecc;
int eccbytes;
int eccpos[24];
int oobfree[8][2];
};
-
useecc
The useecc member controls the ecc and placement function. The header file include/mtd/mtd-abi.h contains constants to select ecc and placement. MTD_NANDECC_OFF switches off the ecc complete. This is not recommended and available for testing and diagnosis only. MTD_NANDECC_PLACE selects caller defined placement, MTD_NANDECC_AUTOPLACE selects automatic placement.
-
eccbytes
The eccbytes member defines the number of ecc bytes per page.
-
eccpos
The eccpos array holds the byte offsets in the spare area where the ecc codes are placed.
-
oobfree
The oobfree array defines the areas in the spare area which can be used for automatic placement. The information is given in the format {offset, size}. offset defines the start of the usable area, size the length in bytes. More than one area can be defined. The list is terminated by an {0, 0} entry.
Placement defined by fs driver #
The calling function provides a pointer to a nand_oobinfo structure which defines the ecc placement. For writes the caller must provide a spare area buffer along with the data buffer. The spare area buffer size is (number of pages) * (size of spare area). For reads the buffer size is (number of pages) * ((size of spare area) + (number of ecc steps per page) * sizeof (int)). The driver stores the result of the ecc check for each tuple in the spare buffer. The storage sequence is:
<spare data page 0><ecc result 0>...<ecc result n>
...
<spare data page n><ecc result 0>...<ecc result n>
This is a legacy mode used by YAFFS1.
If the spare area buffer is NULL then only the ECC placement is done according to the given scheme in the nand_oobinfo structure.
Automatic placement #
Automatic placement uses the built in defaults to place the ecc bytes in the spare area. If filesystem data have to be stored / read into the spare area then the calling function must provide a buffer. The buffer size per page is determined by the oobfree array in the nand_oobinfo structure.
If the spare area buffer is NULL then only the ECC placement is done according to the default builtin scheme.
Spare area autoplacement default schemes #
256 byte pagesize #
|
Offset |
Content |
Comment |
|---|---|---|
|
0x00 |
ECC byte 0 |
Error correction code byte 0 |
|
0x01 |
ECC byte 1 |
Error correction code byte 1 |
|
0x02 |
ECC byte 2 |
Error correction code byte 2 |
|
0x03 |
Autoplace 0 |
|
|
0x04 |
Autoplace 1 |
|
|
0x05 |
Bad block marker |
If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved |
|
0x06 |
Autoplace 2 |
|
|
0x07 |
Autoplace 3 |
512 byte pagesize #
|
Offset |
Content |
Comment |
|---|---|---|
|
0x00 |
ECC byte 0 |
Error correction code byte 0 of the lower 256 Byte data in this page |
|
0x01 |
ECC byte 1 |
Error correction code byte 1 of the lower 256 Bytes of data in this page |
|
0x02 |
ECC byte 2 |
Error correction code byte 2 of the lower 256 Bytes of data in this page |
|
0x03 |
ECC byte 3 |
Error correction code byte 0 of the upper 256 Bytes of data in this page |
|
0x04 |
reserved |
reserved |
|
0x05 |
Bad block marker |
If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved |
|
0x06 |
ECC byte 4 |
Error correction code byte 1 of the upper 256 Bytes of data in this page |
|
0x07 |
ECC byte 5 |
Error correction code byte 2 of the upper 256 Bytes of data in this page |
|
0x08 - 0x0F |
Autoplace 0 - 7 |
2048 byte pagesize #
|
Offset |
Content |
Comment |
|---|---|---|
|
0x00 |
Bad block marker |
If any bit in this byte is zero, then this block is bad. This applies only to the first page in a block. In the remaining pages this byte is reserved |
|
0x01 |
Reserved |
Reserved |
|
0x02-0x27 |
Autoplace 0 - 37 |
|
|
0x28 |
ECC byte 0 |
Error correction code byte 0 of the first 256 Byte data in this page |
|
0x29 |
ECC byte 1 |
Error correction code byte 1 of the first 256 Bytes of data in this page |
|
0x2A |
ECC byte 2 |
Error correction code byte 2 of the first 256 Bytes data in this page |
|
0x2B |
ECC byte 3 |
Error correction code byte 0 of the second 256 Bytes of data in this page |
|
0x2C |
ECC byte 4 |
Error correction code byte 1 of the second 256 Bytes of data in this page |
|
0x2D |
ECC byte 5 |
Error correction code byte 2 of the second 256 Bytes of data in this page |
|
0x2E |
ECC byte 6 |
Error correction code byte 0 of the third 256 Bytes of data in this page |
|
0x2F |
ECC byte 7 |
Error correction code byte 1 of the third 256 Bytes of data in this page |
|
0x30 |
ECC byte 8 |
Error correction code byte 2 of the third 256 Bytes of data in this page |
|
0x31 |
ECC byte 9 |
Error correction code byte 0 of the fourth 256 Bytes of data in this page |
|
0x32 |
ECC byte 10 |
Error correction code byte 1 of the fourth 256 Bytes of data in this page |
|
0x33 |
ECC byte 11 |
Error correction code byte 2 of the fourth 256 Bytes of data in this page |
|
0x34 |
ECC byte 12 |
Error correction code byte 0 of the fifth 256 Bytes of data in this page |
|
0x35 |
ECC byte 13 |
Error correction code byte 1 of the fifth 256 Bytes of data in this page |
|
0x36 |
ECC byte 14 |
Error correction code byte 2 of the fifth 256 Bytes of data in this page |
|
0x37 |
ECC byte 15 |
Error correction code byte 0 of the sixth 256 Bytes of data in this page |
|
0x38 |
ECC byte 16 |
Error correction code byte 1 of the sixth 256 Bytes of data in this page |
|
0x39 |
ECC byte 17 |
Error correction code byte 2 of the sixth 256 Bytes of data in this page |
|
0x3A |
ECC byte 18 |
Error correction code byte 0 of the seventh 256 Bytes of data in this page |
|
0x3B |
ECC byte 19 |
Error correction code byte 1 of the seventh 256 Bytes of data in this page |
|
0x3C |
ECC byte 20 |
Error correction code byte 2 of the seventh 256 Bytes of data in this page |
|
0x3D |
ECC byte 21 |
Error correction code byte 0 of the eighth 256 Bytes of data in this page |
|
0x3E |
ECC byte 22 |
Error correction code byte 1 of the eighth 256 Bytes of data in this page |
|
0x3F |
ECC byte 23 |
Error correction code byte 2 of the eighth 256 Bytes of data in this page |
Filesystem support #
The NAND driver provides all necessary functions for a filesystem via the MTD interface.
Filesystems must be aware of the NAND peculiarities and restrictions. One major restrictions of NAND Flash is, that you cannot write as often as you want to a page. The consecutive writes to a page, before erasing it again, are restricted to 1-3 writes, depending on the manufacturers specifications. This applies similar to the spare area.
Therefore NAND aware filesystems must either write in page size chunks or hold a writebuffer to collect smaller writes until they sum up to pagesize. Available NAND aware filesystems: JFFS2, YAFFS.
The spare area usage to store filesystem data is controlled by the spare area placement functionality which is described in one of the earlier chapters.
Tools #
The MTD project provides a couple of helpful tools to handle NAND Flash.
-
flasherase, flasheraseall: Erase and format FLASH partitions
-
nandwrite: write filesystem images to NAND FLASH
-
nanddump: dump the contents of a NAND FLASH partitions
These tools are aware of the NAND restrictions. Please use those tools instead of complaining about errors which are caused by non NAND aware access methods.
Constants #
This chapter describes the constants which might be relevant for a driver developer.
Chip option constants #
Constants for chip id table #
These constants are defined in rawnand.h. They are OR-ed together to describe the chip functionality:
/* Buswitdh is 16 bit */
#define NAND_BUSWIDTH_16 0x00000002
/* Device supports partial programming without padding */
#define NAND_NO_PADDING 0x00000004
/* Chip has cache program function */
#define NAND_CACHEPRG 0x00000008
/* Chip has copy back function */
#define NAND_COPYBACK 0x00000010
/* AND Chip which has 4 banks and a confusing page / block
* assignment. See Renesas datasheet for further information */
#define NAND_IS_AND 0x00000020
/* Chip has a array of 4 pages which can be read without
* additional ready /busy waits */
#define NAND_4PAGE_ARRAY 0x00000040
Constants for runtime options #
These constants are defined in rawnand.h. They are OR-ed together to describe the functionality:
/* The hw ecc generator provides a syndrome instead a ecc value on read
* This can only work if we have the ecc bytes directly behind the
* data bytes. Applies for DOC and AG-AND Renesas HW Reed Solomon generators */
#define NAND_HWECC_SYNDROME 0x00020000
ECC selection constants #
Use these constants to select the ECC algorithm:
/* No ECC. Usage is not recommended ! */
#define NAND_ECC_NONE 0
/* Software ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_SOFT 1
/* Hardware ECC 3 byte ECC per 256 Byte data */
#define NAND_ECC_HW3_256 2
/* Hardware ECC 3 byte ECC per 512 Byte data */
#define NAND_ECC_HW3_512 3
/* Hardware ECC 6 byte ECC per 512 Byte data */
#define NAND_ECC_HW6_512 4
/* Hardware ECC 8 byte ECC per 512 Byte data */
#define NAND_ECC_HW8_512 6
Hardware control related constants #
These constants describe the requested hardware access function when the boardspecific hardware control function is called:
/* Select the chip by setting nCE to low */
#define NAND_CTL_SETNCE 1
/* Deselect the chip by setting nCE to high */
#define NAND_CTL_CLRNCE 2
/* Select the command latch by setting CLE to high */
#define NAND_CTL_SETCLE 3
/* Deselect the command latch by setting CLE to low */
#define NAND_CTL_CLRCLE 4
/* Select the address latch by setting ALE to high */
#define NAND_CTL_SETALE 5
/* Deselect the address latch by setting ALE to low */
#define NAND_CTL_CLRALE 6
/* Set write protection by setting WP to high. Not used! */
#define NAND_CTL_SETWP 7
/* Clear write protection by setting WP to low. Not used! */
#define NAND_CTL_CLRWP 8
Bad block table related constants #
These constants describe the options used for bad block table descriptors:
/* Options for the bad block table descriptors */
/* The number of bits used per block in the bbt on the device */
#define NAND_BBT_NRBITS_MSK 0x0000000F
#define NAND_BBT_1BIT 0x00000001
#define NAND_BBT_2BIT 0x00000002
#define NAND_BBT_4BIT 0x00000004
#define NAND_BBT_8BIT 0x00000008
/* The bad block table is in the last good block of the device */
#define NAND_BBT_LASTBLOCK 0x00000010
/* The bbt is at the given page, else we must scan for the bbt */
#define NAND_BBT_ABSPAGE 0x00000020
/* bbt is stored per chip on multichip devices */
#define NAND_BBT_PERCHIP 0x00000080
/* bbt has a version counter at offset veroffs */
#define NAND_BBT_VERSION 0x00000100
/* Create a bbt if none axists */
#define NAND_BBT_CREATE 0x00000200
/* Write bbt if necessary */
#define NAND_BBT_WRITE 0x00001000
/* Read and write back block contents when writing bbt */
#define NAND_BBT_SAVECONTENT 0x00002000
Structures #
This chapter contains the autogenerated documentation of the structures which are used in the NAND driver and might be relevant for a driver developer. Each struct member has a short description which is marked with an [XXX] identifier. See the chapter "Documentation hints" for an explanation.
struct nand_parameters #
NAND generic parameters from the parameter page
Definition
;
Members
model: Model namesupports_set_get_features: The NAND chip supports setting/getting featuressupports_read_cache: The NAND chip supports read cache operationsset_feature_list: Bitmap of features that can be setget_feature_list: Bitmap of features that can be getonfi: ONFI specific parameters
struct nand_id #
NAND id structure
Definition
;
Members
data: buffer containing the id bytes.len: ID length.
struct nand_ecc_step_info #
ECC step information of ECC engine
Definition
;
Members
stepsize: data bytes per ECC stepstrengths: array of supported strengthsnstrengths: number of supported strengths
struct nand_ecc_caps #
capability of ECC engine
Definition
;
Members
stepinfos: array of ECC step informationnstepinfos: number of ECC step informationcalc_ecc_bytes: driver's hook to calculate ECC bytes per step
struct nand_ecc_ctrl #
Control structure for ECC
Definition
;
Members
engine_type: ECC engine typeplacement: OOB bytes placementalgo: ECC algorithmsteps: number of ECC steps per pagesize: data bytes per ECC stepbytes: ECC bytes per steptotal: total number of ECC bytes per pagestrength: max number of correctible bits per ECC stepprepad: padding information for syndrome based ECC generatorspostpad: padding information for syndrome based ECC generatorsoptions: ECC specific options (see NAND_ECC_XXX flags defined above)calc_buf: buffer for calculated ECC, size is oobsize.code_buf: buffer for ECC read from flash, size is oobsize.hwctl: function to control hardware ECC generator. Must only be provided if an hardware ECC is availablecalculate: function for ECC calculation or readback from ECC hardwarecorrect: function for ECC correction, matching to ECC generator (sw/hw). Should return a positive number representing the number of corrected bitflips, -EBADMSG if the number of bitflips exceed ECC strength, or any other error code if the error is not directly related to correction. If -EBADMSG is returned the input buffers should be left untouched.read_page_raw: function to read a raw page without ECC. This function should hide the specific layout used by the ECC controller and always return contiguous in-band and out-of-band data even if they're not stored contiguously on the NAND chip (e.g. NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and out-of-band data).write_page_raw: function to write a raw page without ECC. This function should hide the specific layout used by the ECC controller and consider the passed data as contiguous in-band and out-of-band data. ECC controller is responsible for doing the appropriate transformations to adapt to its specific layout (e.g. NAND_ECC_PLACEMENT_INTERLEAVED interleaves in-band and out-of-band data).read_page: function to read a page according to the ECC generator requirements; returns maximum number of bitflips corrected in any single ECC step, -EIO hw errorread_subpage: function to read parts of the page covered by ECC; returns same asread_page()write_subpage: function to write parts of the page covered by ECC.write_page: function to write a page according to the ECC generator requirements.write_oob_raw: function to write chip OOB data without ECCread_oob_raw: function to read chip OOB data without ECCread_oob: function to read chip OOB datawrite_oob: function to write chip OOB data
struct nand_sdr_timings #
SDR NAND chip timings
Definition
;
Members
tBERS_max: Block erase timetCCS_min: Change column setup timetPROG_max: Page program timetR_max: Page read timetALH_min: ALE hold timetADL_min: ALE to data loading timetALS_min: ALE setup timetAR_min: ALE to RE# delaytCEA_max: CE# access timetCEH_min: CE# high hold timetCH_min: CE# hold timetCHZ_max: CE# high to output hi-ZtCLH_min: CLE hold timetCLR_min: CLE to RE# delaytCLS_min: CLE setup timetCOH_min: CE# high to output holdtCS_min: CE# setup timetDH_min: Data hold timetDS_min: Data setup timetFEAT_max: Busy time for Set Features and Get FeaturestIR_min: Output hi-Z to RE# lowtITC_max: Interface and Timing Mode Change timetRC_min: RE# cycle timetREA_max: RE# access timetREH_min: RE# high hold timetRHOH_min: RE# high to output holdtRHW_min: RE# high to WE# lowtRHZ_max: RE# high to output hi-ZtRLOH_min: RE# low to output holdtRP_min: RE# pulse widthtRR_min: Ready to RE# low (data only)tRST_max: Device reset time, measured from the falling edge of R/B# to the rising edge of R/B#.tWB_max: WE# high to SR[6] lowtWC_min: WE# cycle timetWH_min: WE# high hold timetWHR_min: WE# high to RE# lowtWP_min: WE# pulse widthtWW_min: WP# transition to WE# low
Description
This struct defines the timing requirements of a SDR NAND chip. These information can be found in every NAND datasheets and the timings meaning are described in the ONFI specifications: https://media-www.micron.com/-/media/client/onfi/specs/onfi_3_1_spec.pdf (chapter 4.15 Timing Parameters)
All these timings are expressed in picoseconds.
struct nand_nvddr_timings #
NV-DDR NAND chip timings
Definition
;
Members
tBERS_max: Block erase timetCCS_min: Change column setup timetPROG_max: Page program timetR_max: Page read timetAC_min: Access window of DQ[7:0] from CLKtAC_max: Access window of DQ[7:0] from CLKtADL_min: ALE to data loading timetCAD_min: Command, Address, Data delaytCAH_min: Command/Address DQ hold timetCALH_min: W/R_n, CLE and ALE hold timetCALS_min: W/R_n, CLE and ALE setup timetCAS_min: Command/address DQ setup timetCEH_min: CE# high hold timetCH_min: CE# hold timetCK_min: Average clock cycle timetCS_min: CE# setup timetDH_min: Data hold timetDQSCK_min: Start of the access window of DQS from CLKtDQSCK_max: End of the access window of DQS from CLKtDQSD_min: Min W/R_n low to DQS/DQ driven by devicetDQSD_max: Max W/R_n low to DQS/DQ driven by devicetDQSHZ_max: W/R_n high to DQS/DQ tri-state by devicetDQSQ_max: DQS-DQ skew, DQS to last DQ valid, per accesstDS_min: Data setup timetDSC_min: DQS cycle timetFEAT_max: Busy time for Set Features and Get FeaturestITC_max: Interface and Timing Mode Change timetQHS_max: Data hold skew factortRHW_min: Data output cycle to command, address, or data input cycletRR_min: Ready to RE# low (data only)tRST_max: Device reset time, measured from the falling edge of R/B# to the rising edge of R/B#.tWB_max: WE# high to SR[6] lowtWHR_min: WE# high to RE# lowtWRCK_min: W/R_n low to data output cycletWW_min: WP# transition to WE# low
Description
This struct defines the timing requirements of a NV-DDR NAND data interface. These information can be found in every NAND datasheets and the timings meaning are described in the ONFI specifications: https://media-www.micron.com/-/media/client/onfi/specs/onfi_4_1_gold.pdf (chapter 4.18.2 NV-DDR)
All these timings are expressed in picoseconds.
enum nand_interface_type #
NAND interface type
Constants
NAND_SDR_IFACE: Single Data Rate interfaceNAND_NVDDR_IFACE: Double Data Rate interface
struct nand_interface_config #
NAND interface timing
Definition
;
Members
type: type of the timingtimings: The timing informationtimings.mode: Timing mode as defined in the specification{unnamed_union}: anonymoustimings.sdr: Use it when type isNAND_SDR_IFACE.timings.nvddr: Use it when type isNAND_NVDDR_IFACE.
nand_interface_is_sdr() #
bool get the interface type
Parameters
const struct nand_interface_config *conf: The data interface
nand_interface_is_nvddr() #
bool get the interface type
Parameters
const struct nand_interface_config *conf: The data interface
nand_get_sdr_timings() #
const struct nand_sdr_timings * get SDR timing from data interface
Parameters
const struct nand_interface_config *conf: The data interface
nand_get_nvddr_timings() #
const struct nand_nvddr_timings * get NV-DDR timing from data interface
Parameters
const struct nand_interface_config *conf: The data interface
struct nand_op_cmd_instr #
Definition of a command instruction
Definition
;
Members
opcode: the command to issue in one cycle
struct nand_op_addr_instr #
Definition of an address instruction
Definition
;
Members
naddrs: length of the addrs arrayaddrs: array containing the address cycles to issue
struct nand_op_data_instr #
Definition of a data instruction
Definition
;
Members
len: number of data bytes to movebuf: buffer to fillbuf.in: buffer to fill when reading from the NAND chipbuf.out: buffer to read from when writing to the NAND chipforce_8bit: force 8-bit access
Description
Please note that "in" and "out" are inverted from the ONFI specification and are from the controller perspective, so a "in" is a read from the NAND chip while a "out" is a write to the NAND chip.
struct nand_op_waitrdy_instr #
Definition of a wait ready instruction
Definition
;
Members
timeout_ms: maximum delay while waiting for the ready/busy pin in ms
enum nand_op_instr_type #
Definition of all instruction types
Constants
NAND_OP_CMD_INSTR: command instructionNAND_OP_ADDR_INSTR: address instructionNAND_OP_DATA_IN_INSTR: data in instructionNAND_OP_DATA_OUT_INSTR: data out instructionNAND_OP_WAITRDY_INSTR: wait ready instruction
struct nand_op_instr #
Instruction object
Definition
;
Members
type: the instruction typectx: extra data associated to the instruction. You'll have to use the appropriate element depending on typectx.cmd: use it if type isNAND_OP_CMD_INSTRctx.addr: use it if type isNAND_OP_ADDR_INSTRctx.data: use it if type isNAND_OP_DATA_IN_INSTRorNAND_OP_DATA_OUT_INSTRctx.waitrdy: use it if type isNAND_OP_WAITRDY_INSTRdelay_ns: delay the controller should apply after the instruction has been issued on the bus. Most modern controllers have internal timings control logic, and in this case, the controller driver can ignore this field.
struct nand_subop #
a sub operation
Definition
;
Members
cs: the CS line to select for this NAND sub-operationinstrs: array of instructionsninstrs: length of the instrs arrayfirst_instr_start_off: offset to start from for the first instruction of the sub-operationlast_instr_end_off: offset to end at (excluded) for the last instruction of the sub-operation
Description
Both first_instr_start_off and last_instr_end_off only apply to data or address instructions.
When an operation cannot be handled as is by the NAND controller, it will be split by the parser into sub-operations which will be passed to the controller driver.
struct nand_op_parser_addr_constraints #
Constraints for address instructions
Definition
;
Members
maxcycles: maximum number of address cycles the controller can issue in a single step
struct nand_op_parser_data_constraints #
Constraints for data instructions
Definition
;
Members
maxlen: maximum data length that the controller can handle in a single step
struct nand_op_parser_pattern_elem #
One element of a pattern
Definition
;
Members
type: the instructuction typeoptional: whether this element of the pattern is optional or mandatoryctx: address or data constraintctx.addr: address constraint (number of cycles)ctx.data: data constraint (data length)
struct nand_op_parser_pattern #
NAND sub-operation pattern descriptor
Definition
;
Members
elems: array of pattern elementsnelems: number of pattern elements in elems arrayexec: the function that will issue a sub-operation
Description
A pattern is a list of elements, each element reprensenting one instruction
with its constraints. The pattern itself is used by the core to match NAND
chip operation with NAND controller operations.
Once a match between a NAND controller operation pattern and a NAND chip
operation (or a sub-set of a NAND operation) is found, the pattern ->exec()
hook is called so that the controller driver can issue the operation on the
bus.
Controller drivers should declare as many patterns as they support and pass
this list of patterns (created with the help of the following macro) to
the nand_op_parser_exec_op() helper.
struct nand_op_parser #
NAND controller operation parser descriptor
Definition
;
Members
patterns: array of supported patternsnpatterns: length of the patterns array
Description
The parser descriptor is just an array of supported patterns which will be
iterated by nand_op_parser_exec_op() everytime it tries to execute an
NAND operation (or tries to determine if a specific operation is supported).
It is worth mentioning that patterns will be tested in their declaration order, and the first match will be taken, so it's important to order patterns appropriately so that simple/inefficient patterns are placed at the end of the list. Usually, this is where you put single instruction patterns.
struct nand_operation #
NAND operation descriptor
Definition
;
Members
cs: the CS line to select for this NAND operationdeassert_wp: set to true when the operation requires the WP pin to be de-asserted (ERASE, PROG, ...)instrs: array of instructions to executeninstrs: length of the instrs array
Description
The actual operation structure that will be passed to chip->exec_op().
struct nand_controller_ops #
Controller operations
Definition
;
Members
attach_chip: this method is called after the NAND detection phase after flash ID and MTD fields such as erase size, page size and OOB size have been set up. ECC requirements are available if provided by the NAND chip or device tree. Typically used to choose the appropriate ECC configuration and allocate associated resources. This hook is optional.detach_chip: free all resources allocated/claimed in nand_controller_ops->attach_chip(). This hook is optional.exec_op: controller specific method to execute NAND operations. This method replaces chip->legacy.cmdfunc(), chip->legacy.{read,write}_{buf,byte,word}(), chip->legacy.dev_ready()and chip->legacy.waitfunc().setup_interface: setup the data interface and timing. If chipnr is set toNAND_DATA_IFACE_CHECK_ONLYthis means the configuration should not be applied but only checked. This hook is optional.
struct nand_controller #
Structure used to describe a NAND controller
Definition
;
Members
lock: lock used to serialize accesses to the NAND controllerops: NAND controller operations.supported_op: NAND controller known-to-be-supported operations, only writable by the core after initial checking.supported_op.data_only_read: The controller supports reading more data from the bus without restarting an entire read operation nor changing the column.supported_op.cont_read: The controller supports sequential cache reads.controller_wp: the controller is in charge of handling the WP pin.
struct nand_legacy #
NAND chip legacy fields/hooks
Definition
;
Members
IO_ADDR_R: address to read the 8 I/O lines of the flash deviceIO_ADDR_W: address to write the 8 I/O lines of the flash deviceselect_chip: select/deselect a specific target/dieread_byte: read one byte from the chipwrite_byte: write a single byte to the chip on the low 8 I/O lineswrite_buf: write data from the buffer to the chipread_buf: read data from the chip into the buffercmd_ctrl: hardware specific function for controlling ALE/CLE/nCE. Also used to write command and addresscmdfunc: hardware specific function for writing commands to the chip.dev_ready: hardware specific function for accessing device ready/busy line. If set to NULL no access to ready/busy is available and the ready/busy information is read from the chip status register.waitfunc: hardware specific function for wait on ready.block_bad: check if a block is bad, using OOB markersblock_markbad: mark a block badset_features: set the NAND chip featuresget_features: get the NAND chip featureschip_delay: chip dependent delay for transferring data from array to read regs (tR).dummy_controller: dummy controller implementation for drivers that can only control a single chip
Description
If you look at this structure you're already wrong. These fields/hooks are all deprecated.
struct nand_chip_ops #
NAND chip operations
Definition
;
Members
suspend: Suspend operationresume: Resume operationlock_area: Lock operationunlock_area: Unlock operationsetup_read_retry: Set the read-retry mode (mostly needed for MLC NANDs)choose_interface_config: Choose the best interface configuration
struct nand_manufacturer #
NAND manufacturer structure
Definition
;
Members
desc: The manufacturer descriptionpriv: Private information for the manufacturer driver
struct nand_secure_region #
NAND secure region structure
Definition
;
Members
offset: Offset of the start of the secure regionsize: Size of the secure region
struct nand_chip #
NAND Private Flash Chip Data
Definition
;
Members
base: Inherit from the generic NAND deviceid: Holds NAND IDparameters: Holds generic parameters under an easily readable formmanufacturer: Manufacturer informationops: NAND chip operationslegacy: All legacy fields/hooks. If you develop a new driver, don't even try to use any of these fields/hooks, and if you're modifying an existing driver that is using those fields/hooks, you should consider reworking the driver and avoid using them.options: Various chip options. They can partly be set to inform nand_scan about special functionality. See the defines for further explanation.current_interface_config: The currently used NAND interface configurationbest_interface_config: The best NAND interface configuration which fits both the NAND chip and NAND controller constraints. If unset, the default reset interface configuration must be used.bbt_erase_shift: Number of address bits in a bbt entrybbt_options: Bad block table specific options. All options used here must come from bbm.h. By default, these options will be copied to the appropriate nand_bbt_descr's.badblockpos: Bad block marker position in the oob areabadblockbits: Minimum number of set bits in a good block's bad block marker position; i.e., BBM = 11110111b is good when badblockbits = 7bbt_td: Bad block table descriptor for flash lookupbbt_md: Bad block table mirror descriptorbadblock_pattern: Bad block scan pattern used for initial bad block scanbbt: Bad block table pointerpage_shift: Number of address bits in a page (column address bits)phys_erase_shift: Number of address bits in a physical eraseblockchip_shift: Number of address bits in one chippagemask: Page number mask = number of (pages / chip) - 1subpagesize: Holds the subpagesizedata_buf: Buffer for data, size is (page size + oobsize)oob_poi: pointer on the OOB area covered by data_bufpagecache: Structure containing page cache related fieldspagecache.bitflips: Number of bitflips of the cached pagepagecache.page: Page number currently in the cache. -1 means no page is currently cachedbuf_align: Minimum buffer alignment required by a platformlock: Lock protecting the suspended field. Also used to serialize accesses to the NAND devicesuspended: Set to 1 when the device is suspended, 0 when it's notresume_wq: wait queue to sleep if rawnand is in suspended state.cur_cs: Currently selected target. -1 means no target selected, otherwise we should always have cur_cs >= 0 && cur_cs <nanddev_ntargets(). NAND Controller drivers should not modify this value, but they're allowed to read it.read_retries: The number of read retry modes supportedsecure_regions: Structure containing the secure regions infonr_secure_regions: Number of secure regionscont_read: Sequential page read internalscont_read.ongoing: Whether a continuous read is ongoing or notcont_read.first_page: Start of the continuous read operationcont_read.pause_page: End of the current sequential cache read operationcont_read.last_page: End of the continuous read operationcontroller: The hardware controller structure which is shared among multiple independent devicesecc: The ECC controller structurepriv: Chip private data
nand_get_interface_config() #
const struct nand_interface_config * Retrieve the current interface configuration of a NAND chip
Parameters
struct nand_chip *chip: The NAND chip
struct nand_flash_dev #
NAND Flash Device ID Structure
Definition
;
Members
name: a human-readable name of the NAND chip{unnamed_union}: anonymous{unnamed_struct}: anonymousmfr_id: manufacturer ID part of the full chip ID array (refers the same memory address asid[0])dev_id: device ID part of the full chip ID array (refers the same memory address asid[1])id: full device ID arraypagesize: size of the NAND page in bytes; if 0, then the real page size (as well as the eraseblock size) is determined from the extended NAND chip ID array)chipsize: total chip size in MiBerasesize: eraseblock size in bytes (determined from the extended ID if 0)options: stores various chip bit optionsid_len: The valid length of the id.oobsize: OOB sizeecc: ECC correctability and step information from the datasheet.ecc.strength_ds: The ECC correctability from the datasheet, same as the ecc_strength_ds in nand_chip{}.ecc.step_ds: The ECC step required by the ecc.strength_ds, same as the ecc_step_ds in nand_chip{}, also from the datasheet. For example, the "4bit ECC for each 512Byte" can be set with NAND_ECC_INFO(4, 512).
nand_opcode_8bits() #
int Check if the opcode's address should be sent only on the lower 8 bits
Parameters
unsigned int command: opcode to check
nand_get_data_buf() #
void * Get the internal page buffer
Parameters
struct nand_chip *chip: NAND chip object
Description
Returns the pre-allocated page buffer after invalidating the cache. This function should be used by drivers that do not want to allocate their own bounce buffer and still need such a buffer for specific operations (most commonly when reading OOB data only).
Be careful to never call this function in the write/write_oob path, because the core may have placed the data to be written out in this buffer.
Return
pointer to the page cache buffer
Public Functions Provided #
This chapter contains the autogenerated documentation of the NAND kernel API functions which are exported. Each function has a short description which is marked with an [XXX] identifier. See the chapter "Documentation hints" for an explanation.
nand_extract_bits() #
void Copy unaligned bits from one buffer to another one
Parameters
u8 *dst: destination bufferunsigned int dst_off: bit offset at which the writing startsconst u8 *src: source bufferunsigned int src_off: bit offset at which the reading startsunsigned int nbits: number of bits to copy from src to dst
Description
Copy bits from one memory region to another (overlap authorized).
nand_select_target() #
void Select a NAND target (A.K.A. die)
Parameters
struct nand_chip *chip: NAND chip objectunsigned int cs: the CS line to select. Note that this CS id is always from the chip PoV, not the controller one
Description
Select a NAND target so that further operations executed on chip go to the selected NAND target.
nand_deselect_target() #
void Deselect the currently selected target
Parameters
struct nand_chip *chip: NAND chip object
Description
Deselect the currently selected NAND target. The result of operations executed on chip after the target has been deselected is undefined.
nand_soft_waitrdy() #
int Poll STATUS reg until RDY bit is set to 1
Parameters
struct nand_chip *chip: NAND chip structureunsigned long timeout_ms: Timeout in ms
Description
Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
If that does not happen whitin the specified timeout, -ETIMEDOUT is
returned.
This helper is intended to be used when the controller does not have access to the NAND R/B pin.
Be aware that calling this helper from an ->exec_op() implementation means
->exec_op() must be re-entrant.
Return 0 if the NAND chip is ready, a negative error otherwise.
nand_gpio_waitrdy() #
int Poll R/B GPIO pin until ready
Parameters
struct nand_chip *chip: NAND chip structurestruct gpio_desc *gpiod: GPIO descriptor of R/B pinunsigned long timeout_ms: Timeout in ms
Description
Poll the R/B GPIO pin until it becomes ready. If that does not happen whitin the specified timeout, -ETIMEDOUT is returned.
This helper is intended to be used when the controller has access to the NAND R/B pin over GPIO.
Return 0 if the R/B pin indicates chip is ready, a negative error otherwise.
nand_read_page_op() #
int Do a READ PAGE operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int page: page to readunsigned int offset_in_page: offset within the pagevoid *buf: buffer used to store the dataunsigned int len: length of the buffer
Description
This function issues a READ PAGE operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_change_read_column_op() #
int Do a CHANGE READ COLUMN operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int offset_in_page: offset within the pagevoid *buf: buffer used to store the dataunsigned int len: length of the bufferbool force_8bit: force 8-bit bus access
Description
This function issues a CHANGE READ COLUMN operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_read_oob_op() #
int Do a READ OOB operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int page: page to readunsigned int offset_in_oob: offset within the OOB areavoid *buf: buffer used to store the dataunsigned int len: length of the buffer
Description
This function issues a READ OOB operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_prog_page_begin_op() #
int starts a PROG PAGE operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int page: page to writeunsigned int offset_in_page: offset within the pageconst void *buf: buffer containing the data to write to the pageunsigned int len: length of the buffer
Description
This function issues the first half of a PROG PAGE operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_prog_page_end_op() #
int ends a PROG PAGE operation
Parameters
struct nand_chip *chip: The NAND chip
Description
This function issues the second half of a PROG PAGE operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_prog_page_op() #
int Do a full PROG PAGE operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int page: page to writeunsigned int offset_in_page: offset within the pageconst void *buf: buffer containing the data to write to the pageunsigned int len: length of the buffer
Description
This function issues a full PROG PAGE operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_change_write_column_op() #
int Do a CHANGE WRITE COLUMN operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int offset_in_page: offset within the pageconst void *buf: buffer containing the data to send to the NANDunsigned int len: length of the bufferbool force_8bit: force 8-bit bus access
Description
This function issues a CHANGE WRITE COLUMN operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_readid_op() #
int Do a READID operation
Parameters
struct nand_chip *chip: The NAND chipu8 addr: address cycle to pass after the READID commandvoid *buf: buffer used to store the IDunsigned int len: length of the buffer
Description
This function sends a READID command and reads back the ID returned by the NAND. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_status_op() #
int Do a STATUS operation
Parameters
struct nand_chip *chip: The NAND chipu8 *status: out variable to store the NAND status
Description
This function sends a STATUS command and reads back the status returned by the NAND. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_exit_status_op() #
int Exit a STATUS operation
Parameters
struct nand_chip *chip: The NAND chip
Description
This function sends a READ0 command to cancel the effect of the STATUS command to avoid reading only the status until a new read command is sent.
This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_erase_op() #
int Do an erase operation
Parameters
struct nand_chip *chip: The NAND chipunsigned int eraseblock: block to erase
Description
This function sends an ERASE command and waits for the NAND to be ready before returning. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_reset_op() #
int Do a reset operation
Parameters
struct nand_chip *chip: The NAND chip
Description
This function sends a RESET command and waits for the NAND to be ready before returning. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_read_data_op() #
int Read data from the NAND
Parameters
struct nand_chip *chip: The NAND chipvoid *buf: buffer used to store the dataunsigned int len: length of the bufferbool force_8bit: force 8-bit bus accessbool check_only: do not actually run the command, only checks if the controller driver supports it
Description
This function does a raw data read on the bus. Usually used after launching
another NAND operation like nand_read_page_op().
This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_write_data_op() #
int Write data from the NAND
Parameters
struct nand_chip *chip: The NAND chipconst void *buf: buffer containing the data to send on the busunsigned int len: length of the bufferbool force_8bit: force 8-bit bus access
Description
This function does a raw data write on the bus. Usually used after launching
another NAND operation like nand_write_page_begin_op().
This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_op_parser_exec_op() #
int exec_op parser
Parameters
struct nand_chip *chip: the NAND chipconst struct nand_op_parser *parser: patterns description provided by the controller driverconst struct nand_operation *op: the NAND operation to addressbool check_only: when true, the function only checks if op can be handled but does not execute the operation
Description
Helper function designed to ease integration of NAND controller drivers that
only support a limited set of instruction sequences. The supported sequences
are described in parser, and the framework takes care of splitting op into
multiple sub-operations (if required) and pass them back to the ->exec()
callback of the matching pattern if check_only is set to false.
NAND controller drivers should call this function from their own ->exec_op()
implementation.
Returns 0 on success, a negative error code otherwise. A failure can be
caused by an unsupported operation (none of the supported patterns is able
to handle the requested operation), or an error returned by one of the
matching pattern->exec() hook.
nand_subop_get_addr_start_off() #
unsigned int Get the start offset in an address array
Parameters
const struct nand_subop *subop: The entire sub-operationunsigned int instr_idx: Index of the instruction inside the sub-operation
Description
During driver development, one could be tempted to directly use the ->addr.addrs field of address instructions. This is wrong as address instructions might be split.
Given an address instruction, returns the offset of the first cycle to issue.
nand_subop_get_num_addr_cyc() #
unsigned int Get the remaining address cycles to assert
Parameters
const struct nand_subop *subop: The entire sub-operationunsigned int instr_idx: Index of the instruction inside the sub-operation
Description
During driver development, one could be tempted to directly use the ->addr->naddrs field of a data instruction. This is wrong as instructions might be split.
Given an address instruction, returns the number of address cycle to issue.
nand_subop_get_data_start_off() #
unsigned int Get the start offset in a data array
Parameters
const struct nand_subop *subop: The entire sub-operationunsigned int instr_idx: Index of the instruction inside the sub-operation
Description
During driver development, one could be tempted to directly use the ->data->buf.{in,out} field of data instructions. This is wrong as data instructions might be split.
Given a data instruction, returns the offset to start from.
nand_subop_get_data_len() #
unsigned int Get the number of bytes to retrieve
Parameters
const struct nand_subop *subop: The entire sub-operationunsigned int instr_idx: Index of the instruction inside the sub-operation
Description
During driver development, one could be tempted to directly use the ->data->len field of a data instruction. This is wrong as data instructions might be split.
Returns the length of the chunk of data to send/receive.
nand_reset() #
int Reset and initialize a NAND device
Parameters
struct nand_chip *chip: The NAND chipint chipnr: Internal die id
Description
Save the timings data structure, then apply SDR timings mode 0 (see nand_reset_interface for details), do the reset operation, and apply back the previous timings.
Returns 0 on success, a negative error code otherwise.
nand_read_page_raw() #
int [INTERN] read raw page data without ecc
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
Not for syndrome calculating ECC controllers, which use a special oob layout.
nand_monolithic_read_page_raw() #
int Monolithic page read in raw mode
Parameters
struct nand_chip *chip: NAND chip info structureu8 *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
This is a raw page read, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be loaded in the NAND cache and sent over the
bus (from the NAND chip to the NAND controller) in a single
operation. This is an alternative to nand_read_page_raw(), which
first reads the main data, and if the OOB data is requested too,
then reads more data on the bus.
nand_read_page_hwecc_oob_first() #
int Hardware ECC page read with ECC data read from OOB area
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
Hardware ECC for large page chips, which requires the ECC data to be extracted from the OOB before the actual data is read.
nand_read_oob_std() #
int [REPLACEABLE] the most common OOB data read function
Parameters
struct nand_chip *chip: nand chip info structureint page: page number to read
nand_write_oob_std() #
int [REPLACEABLE] the most common OOB data write function
Parameters
struct nand_chip *chip: nand chip info structureint page: page number to write
nand_write_page_raw() #
int [INTERN] raw page write function
Parameters
struct nand_chip *chip: nand chip info structureconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
Description
Not for syndrome calculating ECC controllers, which use a special oob layout.
nand_monolithic_write_page_raw() #
int Monolithic page write in raw mode
Parameters
struct nand_chip *chip: NAND chip info structureconst u8 *buf: data buffer to writeint oob_required: must write chip->oob_poi to OOBint page: page number to write
Description
This is a raw page write, ie. without any error detection/correction.
Monolithic means we are requesting all the relevant data (main plus
eventually OOB) to be sent over the bus and effectively programmed
into the NAND chip arrays in a single operation. This is an
alternative to nand_write_page_raw(), which first sends the main
data, then eventually send the OOB data by latching more data
cycles on the NAND bus, and finally sends the program command to
synchronyze the NAND chip cache.
rawnand_dt_parse_gpio_cs() #
int Parse the gpio-cs property of a controller
Parameters
struct device *dev: Device that will be parsed. Also used for managed allocations.struct gpio_desc ***cs_array: Array of GPIO desc pointers allocated on successunsigned int *ncs_array: Number of entries in cs_array updated on success. return 0 on success, an error otherwise.
nand_ecc_choose_conf() #
int Set the ECC strength and ECC step size
Parameters
struct nand_chip *chip: nand chip info structureconst struct nand_ecc_caps *caps: ECC engine caps info structureint oobavail: OOB size that the ECC engine can use
Description
Choose the ECC configuration according to following logic.
- If both ECC step size and ECC strength are already set (usually by DT) then check if it is supported by this controller.
- If the user provided the nand-ecc-maximize property, then select maximum ECC strength.
- Otherwise, try to match the ECC step size and ECC strength closest to the chip's requirement. If available OOB size can't fit the chip requirement then fallback to the maximum ECC step size and ECC strength.
On success, the chosen ECC settings are set.
nand_scan_with_ids() #
int [NAND Interface] Scan for the NAND device
Parameters
struct nand_chip *chip: NAND chip objectunsigned int maxchips: number of chips to scan for.struct nand_flash_dev *ids: optional flash IDs table
Description
This fills out all the uninitialized function pointers with the defaults. The flash ID is read and the mtd/chip structures are filled with the appropriate values.
nand_cleanup() #
void [NAND Interface] Free resources held by the NAND device
Parameters
struct nand_chip *chip: NAND chip object
Internal Functions Provided #
This chapter contains the autogenerated documentation of the NAND driver internal functions. Each function has a short description which is marked with an [XXX] identifier. See the chapter "Documentation hints" for an explanation. The functions marked with [DEFAULT] might be relevant for a board driver developer.
nand_release_device() #
void [GENERIC] release chip
Parameters
struct nand_chip *chip: NAND chip object
Description
Release chip lock and wake up anyone waiting on the device.
nand_bbm_get_next_page() #
int Get the next page for bad block markers
Parameters
struct nand_chip *chip: NAND chip objectint page: First page to start checking for bad block marker usage
Description
Returns an integer that corresponds to the page offset within a block, for a page that is used to store bad block markers. If no more pages are available, -EINVAL is returned.
nand_block_bad() #
int [DEFAULT] Read bad block marker from the chip
Parameters
struct nand_chip *chip: NAND chip objectloff_t ofs: offset from device start
Description
Check, if the block is bad.
nand_region_is_secured() #
bool Check if the region is secured
Parameters
struct nand_chip *chip: NAND chip objectloff_t offset: Offset of the region to checku64 size: Size of the region to check
Description
Checks if the region is secured by comparing the offset and size with the list of secure regions obtained from DT. Returns true if the region is secured else false.
nand_get_device() #
void [GENERIC] Get chip for selected access
Parameters
struct nand_chip *chip: NAND chip structure
Description
Lock the device and its controller for exclusive access
nand_check_wp() #
int [GENERIC] check if the chip is write protected
Parameters
struct nand_chip *chip: NAND chip object
Description
Check, if the device is write protected. The function expects, that the device is already selected.
nand_fill_oob() #
uint8_t * [INTERN] Transfer client buffer to oob
Parameters
struct nand_chip *chip: NAND chip objectuint8_t *oob: oob data buffersize_t len: oob data write lengthstruct mtd_oob_ops *ops: oob ops structure
nand_do_write_oob() #
int [MTD Interface] NAND write out-of-band
Parameters
struct nand_chip *chip: NAND chip objectloff_t to: offset to write tostruct mtd_oob_ops *ops: oob operation description structure
Description
NAND write out-of-band.
nand_default_block_markbad() #
int [DEFAULT] mark a block bad via bad block marker
Parameters
struct nand_chip *chip: NAND chip objectloff_t ofs: offset from device start
Description
This is the default implementation, which can be overridden by a hardware specific driver. It provides the details for writing a bad block marker to a block.
nand_markbad_bbm() #
int mark a block by updating the BBM
Parameters
struct nand_chip *chip: NAND chip objectloff_t ofs: offset of the block to mark bad
nand_block_markbad_lowlevel() #
int mark a block bad
Parameters
struct nand_chip *chip: NAND chip objectloff_t ofs: offset from device start
Description
This function performs the generic NAND bad block marking steps (i.e., bad block table(s) and/or marker(s)). We only allow the hardware driver to specify how to write bad block markers to OOB (chip->legacy.block_markbad).
We try operations in the following order:
(1) erase the affected block, to allow OOB marker to be written cleanly (2) write bad block marker to OOB area of affected block (unless flag NAND_BBT_NO_OOB_BBM is present) (3) update the BBT
Note that we retain the first error encountered in (2) or (3), finish the procedures, and dump the error in the end.
nand_block_isreserved() #
int [GENERIC] Check if a block is marked reserved.
Parameters
struct mtd_info *mtd: MTD device structureloff_t ofs: offset from device start
Description
Check if the block is marked as reserved.
nand_block_checkbad() #
int [GENERIC] Check if a block is marked bad
Parameters
struct nand_chip *chip: NAND chip objectloff_t ofs: offset from device startint allowbbt: 1, if its allowed to access the bbt area
Description
Check, if the block is bad. Either by reading the bad block table or calling of the scan function.
panic_nand_wait() #
void [GENERIC] wait until the command is done
Parameters
struct nand_chip *chip: NAND chip structureunsigned long timeo: timeout
Description
Wait for command done. This is a helper function for nand_wait used when we are in interrupt context. May happen when in panic and trying to write an oops through mtdoops.
nand_reset_interface() #
int Reset data interface and timings
Parameters
struct nand_chip *chip: The NAND chipint chipnr: Internal die id
Description
Reset the Data interface and timings to ONFI mode 0.
Returns 0 for success or negative error code otherwise.
nand_setup_interface() #
int Setup the best data interface and timings
Parameters
struct nand_chip *chip: The NAND chipint chipnr: Internal die id
Description
Configure what has been reported to be the best data interface and NAND timings supported by the chip and the driver.
Returns 0 for success or negative error code otherwise.
nand_choose_best_sdr_timings() #
int Pick up the best SDR timings that both the NAND controller and the NAND chip support
Parameters
struct nand_chip *chip: the NAND chipstruct nand_interface_config *iface: the interface configuration (can eventually be updated)struct nand_sdr_timings *spec_timings: specific timings, when not fitting the ONFI specification
Description
If specific timings are provided, use them. Otherwise, retrieve supported timing modes from ONFI information.
nand_choose_best_nvddr_timings() #
int Pick up the best NVDDR timings that both the NAND controller and the NAND chip support
Parameters
struct nand_chip *chip: the NAND chipstruct nand_interface_config *iface: the interface configuration (can eventually be updated)struct nand_nvddr_timings *spec_timings: specific timings, when not fitting the ONFI specification
Description
If specific timings are provided, use them. Otherwise, retrieve supported timing modes from ONFI information.
nand_choose_best_timings() #
int Pick up the best NVDDR or SDR timings that both NAND controller and the NAND chip support
Parameters
struct nand_chip *chip: the NAND chipstruct nand_interface_config *iface: the interface configuration (can eventually be updated)
Description
If specific timings are provided, use them. Otherwise, retrieve supported timing modes from ONFI information.
nand_choose_interface_config() #
int find the best data interface and timings
Parameters
struct nand_chip *chip: The NAND chip
Description
Find the best data interface and NAND timings supported by the chip and the driver. Eventually let the NAND manufacturer driver propose his own set of timings.
After this function nand_chip->interface_config is initialized with the best timing mode available.
Returns 0 for success or negative error code otherwise.
nand_fill_column_cycles() #
int fill the column cycles of an address
Parameters
struct nand_chip *chip: The NAND chipu8 *addrs: Array of address cycles to fillunsigned int offset_in_page: The offset in the page
Description
Fills the first or the first two bytes of the addrs field depending on the NAND bus width and the page size.
Returns the number of cycles needed to encode the column, or a negative error code in case one of the arguments is invalid.
nand_read_param_page_op() #
int Do a READ PARAMETER PAGE operation
Parameters
struct nand_chip *chip: The NAND chipu8 page: parameter page to readvoid *buf: buffer used to store the dataunsigned int len: length of the buffer
Description
This function issues a READ PARAMETER PAGE operation. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_set_features_op() #
int Do a SET FEATURES operation
Parameters
struct nand_chip *chip: The NAND chipu8 feature: feature idconst void *data: 4 bytes of data
Description
This function sends a SET FEATURES command and waits for the NAND to be ready before returning. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
nand_get_features_op() #
int Do a GET FEATURES operation
Parameters
struct nand_chip *chip: The NAND chipu8 feature: feature idvoid *data: 4 bytes of data
Description
This function sends a GET FEATURES command and waits for the NAND to be ready before returning. This function does not select/unselect the CS line.
Returns 0 on success, a negative error code otherwise.
struct nand_op_parser_ctx #
Context used by the parser
Definition
;
Members
instrs: array of all the instructions that must be addressedninstrs: length of the instrs arraysubop: Sub-operation to be passed to the NAND controller
Description
This structure is used by the core to split NAND operations into sub-operations that can be handled by the NAND controller.
nand_op_parser_must_split_instr() #
bool Checks if an instruction must be split
Parameters
const struct nand_op_parser_pattern_elem *pat: the parser pattern element that matches instrconst struct nand_op_instr *instr: pointer to the instruction to checkunsigned int *start_offset: this is an in/out parameter. If instr has already been split, then start_offset is the offset from which to start (either an address cycle or an offset in the data buffer). Conversely, if the function returns true (ie. instr must be split), this parameter is updated to point to the first data/address cycle that has not been taken care of.
Description
Some NAND controllers are limited and cannot send X address cycles with a unique operation, or cannot read/write more than Y bytes at the same time. In this case, split the instruction that does not fit in a single controller-operation into two or more chunks.
Returns true if the instruction must be split, false otherwise. The start_offset parameter is also updated to the offset at which the next bundle of instruction must start (if an address or a data instruction).
nand_op_parser_match_pat() #
bool Checks if a pattern matches the instructions remaining in the parser context
Parameters
const struct nand_op_parser_pattern *pat: the pattern to teststruct nand_op_parser_ctx *ctx: the parser context structure to match with the pattern pat
Description
Check if pat matches the set or a sub-set of instructions remaining in ctx. Returns true if this is the case, false ortherwise. When true is returned, ctx->subop is updated with the set of instructions to be passed to the controller driver.
nand_get_features() #
int wrapper to perform a GET_FEATURE
Parameters
struct nand_chip *chip: NAND chip info structureint addr: feature addressu8 *subfeature_param: the subfeature parameters, a four bytes array
Description
Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the operation cannot be handled.
nand_set_features() #
int wrapper to perform a SET_FEATURE
Parameters
struct nand_chip *chip: NAND chip info structureint addr: feature addressu8 *subfeature_param: the subfeature parameters, a four bytes array
Description
Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the operation cannot be handled.
nand_read_page_raw_notsupp() #
int dummy read raw page function
Parameters
struct nand_chip *chip: nand chip info structureu8 *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
Returns -ENOTSUPP unconditionally.
nand_read_page_raw_syndrome() #
int [INTERN] read raw page data without ecc
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
We need a special oob layout and handling even when OOB isn't used.
nand_read_page_swecc() #
int [REPLACEABLE] software ECC based page read function
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
nand_read_subpage() #
int [REPLACEABLE] ECC based sub-page read function
Parameters
struct nand_chip *chip: nand chip info structureuint32_t data_offs: offset of requested data within the pageuint32_t readlen: data lengthuint8_t *bufpoi: buffer to store read dataint page: page number to read
nand_read_page_hwecc() #
int [REPLACEABLE] hardware ECC based page read function
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
Not for syndrome calculating ECC controllers which need a special oob layout.
nand_read_page_syndrome() #
int [REPLACEABLE] hardware ECC syndrome based page read
Parameters
struct nand_chip *chip: nand chip info structureuint8_t *buf: buffer to store read dataint oob_required: caller requires OOB data read to chip->oob_poiint page: page number to read
Description
The hw generator calculates the error syndrome automatically. Therefore we need a special oob layout and handling.
nand_transfer_oob() #
uint8_t * [INTERN] Transfer oob to client buffer
Parameters
struct nand_chip *chip: NAND chip objectuint8_t *oob: oob destination addressstruct mtd_oob_ops *ops: oob ops structuresize_t len: size of oob to transfer
nand_setup_read_retry() #
int [INTERN] Set the READ RETRY mode
Parameters
struct nand_chip *chip: NAND chip objectint retry_mode: the retry mode to use
Description
Some vendors supply a special command to shift the Vt threshold, to be used when there are too many bitflips in a page (i.e., ECC error). After setting a new threshold, the host should retry reading the page.
nand_do_read_ops() #
int [INTERN] Read data with ECC
Parameters
struct nand_chip *chip: NAND chip objectloff_t from: offset to read fromstruct mtd_oob_ops *ops: oob ops structure
Description
Internal function. Called with chip held.
nand_read_oob_syndrome() #
int [REPLACEABLE] OOB data read function for HW ECC with syndromes
Parameters
struct nand_chip *chip: nand chip info structureint page: page number to read
nand_write_oob_syndrome() #
int [REPLACEABLE] OOB data write function for HW ECC with syndrome - only for large page flash
Parameters
struct nand_chip *chip: nand chip info structureint page: page number to write
nand_do_read_oob() #
int [INTERN] NAND read out-of-band
Parameters
struct nand_chip *chip: NAND chip objectloff_t from: offset to read fromstruct mtd_oob_ops *ops: oob operations description structure
Description
NAND read out-of-band data from the spare area.
nand_read_oob() #
int [MTD Interface] NAND read data and/or out-of-band
Parameters
struct mtd_info *mtd: MTD device structureloff_t from: offset to read fromstruct mtd_oob_ops *ops: oob operation description structure
Description
NAND read data and/or out-of-band data.
nand_write_page_raw_notsupp() #
int dummy raw page write function
Parameters
struct nand_chip *chip: nand chip info structureconst u8 *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
Description
Returns -ENOTSUPP unconditionally.
nand_write_page_raw_syndrome() #
int [INTERN] raw page write function
Parameters
struct nand_chip *chip: nand chip info structureconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
Description
We need a special oob layout and handling even when ECC isn't checked.
nand_write_page_swecc() #
int [REPLACEABLE] software ECC based page write function
Parameters
struct nand_chip *chip: nand chip info structureconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
nand_write_page_hwecc() #
int [REPLACEABLE] hardware ECC based page write function
Parameters
struct nand_chip *chip: nand chip info structureconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
nand_write_subpage_hwecc() #
int [REPLACEABLE] hardware ECC based subpage write
Parameters
struct nand_chip *chip: nand chip info structureuint32_t offset: column address of subpage within the pageuint32_t data_len: data lengthconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
nand_write_page_syndrome() #
int [REPLACEABLE] hardware ECC syndrome based page write
Parameters
struct nand_chip *chip: nand chip info structureconst uint8_t *buf: data bufferint oob_required: must write chip->oob_poi to OOBint page: page number to write
Description
The hw generator calculates the error syndrome automatically. Therefore we need a special oob layout and handling.
nand_write_page() #
int write one page
Parameters
struct nand_chip *chip: NAND chip descriptoruint32_t offset: address offset within the pageint data_len: length of actual data to be writtenconst uint8_t *buf: the data to writeint oob_required: must write chip->oob_poi to OOBint page: page number to writeint raw: use _raw version of write_page
nand_do_write_ops() #
int [INTERN] NAND write with ECC
Parameters
struct nand_chip *chip: NAND chip objectloff_t to: offset to write tostruct mtd_oob_ops *ops: oob operations description structure
Description
NAND write with ECC.
panic_nand_write() #
int [MTD Interface] NAND write with ECC
Parameters
struct mtd_info *mtd: MTD device structureloff_t to: offset to write tosize_t len: number of bytes to writesize_t *retlen: pointer to variable to store the number of written bytesconst uint8_t *buf: the data to write
Description
NAND write with ECC. Used when performing writes in interrupt context, this may for example be called by mtdoops when writing an oops while in panic.
nand_write_oob() #
int [MTD Interface] NAND write data and/or out-of-band
Parameters
struct mtd_info *mtd: MTD device structureloff_t to: offset to write tostruct mtd_oob_ops *ops: oob operation description structure
nand_erase() #
int [MTD Interface] erase block(s)
Parameters
struct mtd_info *mtd: MTD device structurestruct erase_info *instr: erase instruction
Description
Erase one ore more blocks.
nand_erase_nand() #
int [INTERN] erase block(s)
Parameters
struct nand_chip *chip: NAND chip objectstruct erase_info *instr: erase instructionint allowbbt: allow erasing the bbt area
Description
Erase one ore more blocks.
nand_sync() #
void [MTD Interface] sync
Parameters
struct mtd_info *mtd: MTD device structure
Description
Sync is actually a wait for chip ready function.
nand_block_isbad() #
int [MTD Interface] Check if block at offset is bad
Parameters
struct mtd_info *mtd: MTD device structureloff_t offs: offset relative to mtd start
nand_block_markbad() #
int [MTD Interface] Mark block at the given offset as bad
Parameters
struct mtd_info *mtd: MTD device structureloff_t ofs: offset relative to mtd start
nand_suspend() #
int [MTD Interface] Suspend the NAND flash
Parameters
struct mtd_info *mtd: MTD device structure
Description
Returns 0 for success or negative error code otherwise.
nand_resume() #
void [MTD Interface] Resume the NAND flash
Parameters
struct mtd_info *mtd: MTD device structure
nand_shutdown() #
void [MTD Interface] Finish the current NAND operation and prevent further operations
Parameters
struct mtd_info *mtd: MTD device structure
nand_lock() #
int [MTD Interface] Lock the NAND flash
Parameters
struct mtd_info *mtd: MTD device structureloff_t ofs: offset byte addressuint64_t len: number of bytes to lock (must be a multiple of block/page size)
nand_unlock() #
int [MTD Interface] Unlock the NAND flash
Parameters
struct mtd_info *mtd: MTD device structureloff_t ofs: offset byte addressuint64_t len: number of bytes to unlock (must be a multiple of block/page size)
nand_scan_ident() #
int Scan for the NAND device
Parameters
struct nand_chip *chip: NAND chip objectunsigned int maxchips: number of chips to scan forstruct nand_flash_dev *table: alternative NAND ID table
Description
This is the first phase of the normal nand_scan() function. It reads the
flash ID and sets up MTD fields accordingly.
This helper used to be called directly from controller drivers that needed
to tweak some ECC-related parameters before nand_scan_tail(). This separation
prevented dynamic allocations during this phase which was unconvenient and
as been banned for the benefit of the ->init_ecc()/cleanup_ecc() hooks.
nand_check_ecc_caps() #
int check the sanity of preset ECC settings
Parameters
struct nand_chip *chip: nand chip info structureconst struct nand_ecc_caps *caps: ECC caps info structureint oobavail: OOB size that the ECC engine can use
Description
When ECC step size and strength are already set, check if they are supported by the controller and the calculated ECC bytes fit within the chip's OOB. On success, the calculated ECC bytes is set.
nand_match_ecc_req() #
int meet the chip's requirement with least ECC bytes
Parameters
struct nand_chip *chip: nand chip info structureconst struct nand_ecc_caps *caps: ECC engine caps info structureint oobavail: OOB size that the ECC engine can use
Description
If a chip's ECC requirement is provided, try to meet it with the least number of ECC bytes (i.e. with the largest number of OOB-free bytes). On success, the chosen ECC settings are set.
nand_maximize_ecc() #
int choose the max ECC strength available
Parameters
struct nand_chip *chip: nand chip info structureconst struct nand_ecc_caps *caps: ECC engine caps info structureint oobavail: OOB size that the ECC engine can use
Description
Choose the max ECC strength that is supported on the controller, and can fit within the chip's OOB. On success, the chosen ECC settings are set.
nand_scan_tail() #
int Scan for the NAND device
Parameters
struct nand_chip *chip: NAND chip object
Description
This is the second phase of the normal nand_scan() function. It fills out
all the uninitialized function pointers with the defaults and scans for a
bad block table if appropriate.
check_pattern() #
int [GENERIC] check if a pattern is in the buffer
Parameters
uint8_t *buf: the buffer to searchint len: the length of buffer to searchint paglen: the pagelengthstruct nand_bbt_descr *td: search pattern descriptor
Description
Check for a pattern at the given place. Used to search bad block tables and good / bad block identifiers.
check_short_pattern() #
int [GENERIC] check if a pattern is in the buffer
Parameters
uint8_t *buf: the buffer to searchstruct nand_bbt_descr *td: search pattern descriptor
Description
Check for a pattern at the given place. Used to search bad block tables and good / bad block identifiers. Same as check_pattern, but no optional empty check.
add_marker_len() #
u32 compute the length of the marker in data area
Parameters
struct nand_bbt_descr *td: BBT descriptor used for computation
Description
The length will be 0 if the marker is located in OOB area.
read_bbt() #
int [GENERIC] Read the bad block table starting from page
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferint page: the starting pageint num: the number of bbt descriptors to readstruct nand_bbt_descr *td: the bbt describtion tableint offs: block number offset in the table
Description
Read the bad block table starting from page.
read_abs_bbt() #
int [GENERIC] Read the bad block table starting at a given page
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *td: descriptor for the bad block tableint chip: read the table for a specific chip, -1 read all chips; applies only if NAND_BBT_PERCHIP option is set
Description
Read the bad block table for all chips starting at a given page. We assume that the bbt bits are in consecutive order.
scan_read_oob() #
int [GENERIC] Scan data+OOB region to buffer
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferloff_t offs: offset at which to scansize_t len: length of data region to read
Description
Scan read data from data+OOB. May traverse multiple pages, interleaving page,OOB,page,OOB,... in buf. Completes transfer and returns the "strongest" ECC condition (error or bitflip). May quit on the first (non-ECC) error.
read_abs_bbts() #
void [GENERIC] Read the bad block table(s) for all chips starting at a given page
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *td: descriptor for the bad block tablestruct nand_bbt_descr *md: descriptor for the bad block table mirror
Description
Read the bad block table(s) for all chips starting at a given page. We assume that the bbt bits are in consecutive order.
create_bbt() #
int [GENERIC] Create a bad block table by scanning the device
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *bd: descriptor for the good/bad block search patternint chip: create the table for a specific chip, -1 read all chips; applies only if NAND_BBT_PERCHIP option is set
Description
Create a bad block table by scanning the device for the given good/bad block identify pattern.
search_bbt() #
int [GENERIC] scan the device for a specific bad block table
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *td: descriptor for the bad block table
Description
Read the bad block table by searching for a given ident pattern. Search is preformed either from the beginning up or from the end of the device downwards. The search starts always at the start of a block. If the option NAND_BBT_PERCHIP is given, each chip is searched for a bbt, which contains the bad block information of this chip. This is necessary to provide support for certain DOC devices.
The bbt ident pattern resides in the oob area of the first page in a block.
search_read_bbts() #
void [GENERIC] scan the device for bad block table(s)
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *td: descriptor for the bad block tablestruct nand_bbt_descr *md: descriptor for the bad block table mirror
Description
Search and read the bad block table(s).
get_bbt_block() #
int Get the first valid eraseblock suitable to store a BBT
Parameters
struct nand_chip *this: the NAND devicestruct nand_bbt_descr *td: the BBT descriptionstruct nand_bbt_descr *md: the mirror BBT descriptorint chip: the CHIP selector
Description
This functions returns a positive block number pointing a valid eraseblock suitable to store a BBT (i.e. in the range reserved for BBT), or -ENOSPC if all blocks are already used of marked bad. If td->pages[chip] was already pointing to a valid block we re-use it, otherwise we search for the next valid one.
mark_bbt_block_bad() #
void Mark one of the block reserved for BBT bad
Parameters
struct nand_chip *this: the NAND devicestruct nand_bbt_descr *td: the BBT descriptionint chip: the CHIP selectorint block: the BBT block to mark
Description
Blocks reserved for BBT can become bad. This functions is an helper to mark such blocks as bad. It takes care of updating the in-memory BBT, marking the block as bad using a bad block marker and invalidating the associated td->pages[] entry.
write_bbt() #
int [GENERIC] (Re)write the bad block table
Parameters
struct nand_chip *this: NAND chip objectuint8_t *buf: temporary bufferstruct nand_bbt_descr *td: descriptor for the bad block tablestruct nand_bbt_descr *md: descriptor for the bad block table mirrorint chipsel: selector for a specific chip, -1 for all
Description
(Re)write the bad block table.
nand_memory_bbt() #
int [GENERIC] create a memory based bad block table
Parameters
struct nand_chip *this: NAND chip objectstruct nand_bbt_descr *bd: descriptor for the good/bad block search pattern
Description
The function creates a memory based bbt by scanning the device for manufacturer / software marked good / bad blocks.
check_create() #
int [GENERIC] create and write bbt(s) if necessary
Parameters
struct nand_chip *this: the NAND deviceuint8_t *buf: temporary bufferstruct nand_bbt_descr *bd: descriptor for the good/bad block search pattern
Description
The function checks the results of the previous call to read_bbt and creates / updates the bbt(s) if necessary. Creation is necessary if no bbt was found for the chip/device. Update is necessary if one of the tables is missing or the version nr. of one table is less than the other.
nand_update_bbt() #
int update bad block table(s)
Parameters
struct nand_chip *this: the NAND deviceloff_t offs: the offset of the newly marked block
Description
The function updates the bad block table(s).
mark_bbt_region() #
void [GENERIC] mark the bad block table regions
Parameters
struct nand_chip *this: the NAND devicestruct nand_bbt_descr *td: bad block table descriptor
Description
The bad block table regions are marked as "bad" to prevent accidental erasures / writes. The regions are identified by the mark 0x02.
verify_bbt_descr() #
void verify the bad block description
Parameters
struct nand_chip *this: the NAND devicestruct nand_bbt_descr *bd: the table to verify
Description
This functions performs a few sanity checks on the bad block description table.
nand_scan_bbt() #
int [NAND Interface] scan, find, read and maybe create bad block table(s)
Parameters
struct nand_chip *this: the NAND devicestruct nand_bbt_descr *bd: descriptor for the good/bad block search pattern
Description
The function checks, if a bad block table(s) is/are already available. If not it scans the device for manufacturer marked good / bad blocks and writes the bad block table(s) to the selected place.
The bad block table memory is allocated here. It must be freed by calling the nand_free_bbt function.
nand_create_badblock_pattern() #
int [INTERN] Creates a BBT descriptor structure
Parameters
struct nand_chip *this: NAND chip to create descriptor for
Description
This function allocates and initializes a nand_bbt_descr for BBM detection based on the properties of this. The new descriptor is stored in this->badblock_pattern. Thus, this->badblock_pattern should be NULL when passed to this function.
nand_isreserved_bbt() #
int [NAND Interface] Check if a block is reserved
Parameters
struct nand_chip *this: NAND chip objectloff_t offs: offset in the device
nand_isbad_bbt() #
int [NAND Interface] Check if a block is bad
Parameters
struct nand_chip *this: NAND chip objectloff_t offs: offset in the deviceint allowbbt: allow access to bad block table region
nand_markbad_bbt() #
int [NAND Interface] Mark a block bad in the BBT
Parameters
struct nand_chip *this: NAND chip objectloff_t offs: offset of the bad block
Credits #
The following people have contributed to the NAND driver:
-
Steven J. Hillsjhill@realitydiluted.com
-
David Woodhousedwmw2@infradead.org
-
Thomas Gleixnertglx@kernel.org
A lot of users have provided bugfixes, improvements and helping hands for testing. Thanks a lot.
The following people have contributed to this document:
- Thomas Gleixnertglx@kernel.org
Writing s390 channel device drivers
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Author: Cornelia Huck
Introduction #
This document describes the interfaces available for device drivers that drive s390 based channel attached I/O devices. This includes interfaces for interaction with the hardware and interfaces for interacting with the common driver core. Those interfaces are provided by the s390 common I/O layer.
The document assumes a familarity with the technical terms associated with the s390 channel I/O architecture. For a description of this architecture, please refer to the "z/Architecture: Principles of Operation", IBM publication no. SA22-7832.
While most I/O devices on a s390 system are typically driven through the channel I/O mechanism described here, there are various other methods (like the diag interface). These are out of the scope of this document.
The s390 common I/O layer also provides access to some devices that are not strictly considered I/O devices. They are considered here as well, although they are not the focus of this document.
Some additional information can also be found in the kernel source under Documentation/arch/s390/driver-model.rst.
The css bus #
The css bus contains the subchannels available on the system. They fall into several categories:
-
Standard I/O subchannels, for use by the system. They have a child device on the ccw bus and are described below.
-
I/O subchannels bound to the vfio-ccw driver. See Documentation/arch/s390/vfio-ccw.rst.
-
Message subchannels. No Linux driver currently exists.
-
CHSC subchannels (at most one). The chsc subchannel driver can be used to send asynchronous chsc commands.
-
eADM subchannels. Used for talking to storage class memory.
The ccw bus #
The ccw bus typically contains the majority of devices available to a s390 system. Named after the channel command word (ccw), the basic command structure used to address its devices, the ccw bus contains so-called channel attached devices. They are addressed via I/O subchannels, visible on the css bus. A device driver for channel-attached devices, however, will never interact with the subchannel directly, but only via the I/O device on the ccw bus, the ccw device.
I/O functions for channel-attached devices #
Some hardware structures have been translated into C structures for use by the common I/O layer and device drivers. For more information on the hardware structures represented here, please consult the Principles of Operation.
struct ccw1 #
channel command word
Definition
;
Members
cmd_code: command codeflags: flags, like IDA addressing, etc.count: byte countcda: data address
Description
The ccw is the basic structure to build channel programs that perform operations with the device or the control unit. Only Format-1 channel command words are supported.
struct ccw0 #
channel command word
Definition
;
Members
cmd_code: command codecda: data addressflags: flags, like IDA addressing, etc.reserved: will be ignoredcount: byte count
Description
The format-0 ccw structure.
struct erw #
extended report word
Definition
;
Members
res0: reservedauth: authorization checkpvrf: path-verification-required flagcpt: channel-path timeoutfsavf: failing storage address validity flagcons: concurrent sensescavf: secondary ccw address validity flagfsaf: failing storage address formatscnt: sense count, if cons ==1res16: reserved
struct erw_eadm #
EADM Subchannel extended report word
Definition
;
Members
b: aob errorr: arsb error
struct sublog #
subchannel logout area
Definition
;
Members
res0: reservedesf: extended status flagslpum: last path used maskarep: ancillary reportfvf: field-validity flagssacc: storage access codetermc: termination codedevsc: device-status checkserr: secondary errorioerr: i/o-error alertseqc: sequence code
struct esw0 #
Format 0 Extended Status Word (ESW)
Definition
;
Members
sublog: subchannel logouterw: extended report wordfaddr: failing storage addresssaddr: secondary ccw address
struct esw1 #
Format 1 Extended Status Word (ESW)
Definition
;
Members
zero0: reserved zeroslpum: last path used maskzero16: reserved zeroserw: extended report wordzeros: three fullwords of zeros
struct esw2 #
Format 2 Extended Status Word (ESW)
Definition
;
Members
zero0: reserved zeroslpum: last path used maskdcti: device-connect-time intervalerw: extended report wordzeros: three fullwords of zeros
struct esw3 #
Format 3 Extended Status Word (ESW)
Definition
;
Members
zero0: reserved zeroslpum: last path used maskres: reservederw: extended report wordzeros: three fullwords of zeros
struct esw_eadm #
EADM Subchannel Extended Status Word (ESW)
Definition
;
Members
sublog: subchannel logouterw: extended report word
struct irb #
interruption response block
Definition
;
Members
scsw: subchannel status wordesw: extended status wordecw: extended control word
Description
The irb that is handed to the device driver when an interrupt occurs. For
solicited interrupts, the common I/O layer already performs checks whether
a field is valid; a field not being valid is always passed as 0.
If a unit check occurred, ecw may contain sense data; this is retrieved
by the common I/O layer itself if the device doesn't support concurrent
sense (so that the device driver never needs to perform basic sense itself).
For unsolicited interrupts, the irb is passed as-is (expect for sense data,
if applicable).
struct ciw #
command information word (CIW) layout
Definition
;
Members
et: entry typereserved: reserved bitsct: command typecmd: command codecount: command count
struct ccw_dev_id #
unique identifier for ccw devices
Definition
;
Members
ssid: subchannel set iddevno: device number
Description
This structure is not directly based on any hardware structure. The hardware identifies a device by its device number and its subchannel, which is in turn identified by its id. In order to get a unique identifier for ccw devices across subchannel sets, struct ccw_dev_id has been introduced.
ccw_dev_id_is_equal() #
int compare two ccw_dev_ids
Parameters
struct ccw_dev_id *dev_id1: a ccw_dev_idstruct ccw_dev_id *dev_id2: another ccw_dev_id
Return
1 if the two structures are equal field-by-field,
0 if not.
Context
any
pathmask_to_pos() #
u8 find the position of the left-most bit in a pathmask
Parameters
u8 mask: pathmask with at least one bit set
ccw devices #
Devices that want to initiate channel I/O need to attach to the ccw bus. Interaction with the driver core is done via the common I/O layer, which provides the abstractions of ccw devices and ccw device drivers.
The functions that initiate or terminate channel I/O all act upon a ccw device structure. Device drivers must not bypass those functions or strange side effects may happen.
struct ccw_device #
channel attached device
Definition
;
Members
ccwlock: pointer to device lockid: id of this devicedrv: ccw driver for this devicedev: embedded device structureonline: online status of devicehandler: interrupt handler
Description
handler is a member of the device rather than the driver since a driver can have different interrupt handlers for different ccw devices (multi-subchannel drivers).
struct ccw_driver #
device driver for channel attached devices
Definition
;
Members
ids: ids supported by this driverprobe: function called on proberemove: function called on removeset_online: called when setting device onlineset_offline: called when setting device offlinenotify: notify driver of device state changespath_event: notify driver of channel path eventsshutdown: called at device shutdownuc_handler: callback for unit check handlerdriver: embedded device driver structureint_class: interruption class to use for accounting interrupts
ccw_device_set_offline() #
int disable a ccw device for I/O
Parameters
struct ccw_device *cdev: target ccw device
Description
This function calls the driver's set_offline() function for cdev, if
given, and then disables cdev.
Return
0 on success and a negative error value on failure.
Context
enabled, ccw device lock not held
ccw_device_set_online() #
int enable a ccw device for I/O
Parameters
struct ccw_device *cdev: target ccw device
Description
This function first enables cdev and then calls the driver's set_online()
function for cdev, if given. If set_online() returns an error, cdev is
disabled again.
Return
0 on success and a negative error value on failure.
Context
enabled, ccw device lock not held
get_ccwdev_by_dev_id() #
struct ccw_device * obtain device from a ccw device id
Parameters
struct ccw_dev_id *dev_id: id of the device to be searched
Description
This function searches all devices attached to the ccw bus for a device matching dev_id.
Return
If a device is found its reference count is increased and returned;
else NULL is returned.
get_ccwdev_by_busid() #
struct ccw_device * obtain device from a bus id
Parameters
struct ccw_driver *cdrv: driver the device is owned byconst char *bus_id: bus id of the device to be searched
Description
This function searches all devices owned by cdrv for a device with a bus id matching bus_id.
Return
If a match is found, its reference count of the found device is increased
and it is returned; else NULL is returned.
ccw_driver_register() #
int register a ccw driver
Parameters
struct ccw_driver *cdriver: driver to be registered
Description
This function is mainly a wrapper around driver_register().
Return
0 on success and a negative error value on failure.
ccw_driver_unregister() #
void deregister a ccw driver
Parameters
struct ccw_driver *cdriver: driver to be deregistered
Description
This function is mainly a wrapper around driver_unregister().
ccw_device_siosl() #
int initiate logging
Parameters
struct ccw_device *cdev: ccw device
Description
This function is used to invoke model-dependent logging within the channel subsystem.
ccw_device_set_options_mask() #
int set some options and unset the rest
Parameters
struct ccw_device *cdev: device for which the options are to be setunsigned long flags: options to be set
Description
All flags specified in flags are set, all flags not specified in flags are cleared.
Return
0 on success, -EINVAL on an invalid flag combination.
ccw_device_set_options() #
int set some options
Parameters
struct ccw_device *cdev: device for which the options are to be setunsigned long flags: options to be set
Description
All flags specified in flags are set, the remainder is left untouched.
Return
0 on success, -EINVAL if an invalid flag combination would ensue.
ccw_device_clear_options() #
void clear some options
Parameters
struct ccw_device *cdev: device for which the options are to be clearedunsigned long flags: options to be cleared
Description
All flags specified in flags are cleared, the remainder is left untouched.
ccw_device_is_pathgroup() #
int determine if paths to this device are grouped
Parameters
struct ccw_device *cdev: ccw device
Description
Return non-zero if there is a path group, zero otherwise.
ccw_device_is_multipath() #
int determine if device is operating in multipath mode
Parameters
struct ccw_device *cdev: ccw device
Description
Return non-zero if device is operating in multipath mode, zero otherwise.
ccw_device_clear() #
int terminate I/O request processing
Parameters
struct ccw_device *cdev: target ccw deviceunsigned long intparm: interruption parameter to be returned upon conclusion of csch
Description
ccw_device_clear() calls csch on cdev's subchannel.
Return
0 on success,
-ENODEV on device not operational,
-EINVAL on invalid device state.
Context
Interrupts disabled, ccw device lock held
ccw_device_start_timeout_key() #
int start a s390 channel program with timeout and key
Parameters
struct ccw_device *cdev: target ccw devicestruct ccw1 *cpa: logical start address of channel programunsigned long intparm: user specific interruption parameter; will be presented back to cdev's interrupt handler. Allows a device driver to associate the interrupt with a particular I/O request.__u8 lpm: defines the channel path to be used for a specific I/O request. A value of 0 will make cio use the opm.__u8 key: storage key to be used for the I/Ounsigned long flags: additional flags; defines the action to be performed for I/O processing.int expires: timeout value in jiffies
Description
Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
This function notifies the device driver if the channel program has not
completed during the time specified by expires. If a timeout occurs, the
channel program is terminated via xsch, hsch or csch, and the device's
interrupt handler will be called with an irb containing ERR_PTR(-ETIMEDOUT).
The interruption handler will echo back the intparm specified here, unless
another interruption parameter is specified by a subsequent invocation of
ccw_device_halt() or ccw_device_clear().
Return
0, if the operation was successful;
-EBUSY, if the device is busy, or status pending;
-EACCES, if no path specified in lpm is operational;
-ENODEV, if the device is not operational.
Context
Interrupts disabled, ccw device lock held
ccw_device_start_key() #
int start a s390 channel program with key
Parameters
struct ccw_device *cdev: target ccw devicestruct ccw1 *cpa: logical start address of channel programunsigned long intparm: user specific interruption parameter; will be presented back to cdev's interrupt handler. Allows a device driver to associate the interrupt with a particular I/O request.__u8 lpm: defines the channel path to be used for a specific I/O request. A value of 0 will make cio use the opm.__u8 key: storage key to be used for the I/Ounsigned long flags: additional flags; defines the action to be performed for I/O processing.
Description
Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
The interruption handler will echo back the intparm specified here, unless
another interruption parameter is specified by a subsequent invocation of
ccw_device_halt() or ccw_device_clear().
Return
0, if the operation was successful;
-EBUSY, if the device is busy, or status pending;
-EACCES, if no path specified in lpm is operational;
-ENODEV, if the device is not operational.
Context
Interrupts disabled, ccw device lock held
ccw_device_start() #
int start a s390 channel program
Parameters
struct ccw_device *cdev: target ccw devicestruct ccw1 *cpa: logical start address of channel programunsigned long intparm: user specific interruption parameter; will be presented back to cdev's interrupt handler. Allows a device driver to associate the interrupt with a particular I/O request.__u8 lpm: defines the channel path to be used for a specific I/O request. A value of 0 will make cio use the opm.unsigned long flags: additional flags; defines the action to be performed for I/O processing.
Description
Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
The interruption handler will echo back the intparm specified here, unless
another interruption parameter is specified by a subsequent invocation of
ccw_device_halt() or ccw_device_clear().
Return
0, if the operation was successful;
-EBUSY, if the device is busy, or status pending;
-EACCES, if no path specified in lpm is operational;
-ENODEV, if the device is not operational.
Context
Interrupts disabled, ccw device lock held
ccw_device_start_timeout() #
int start a s390 channel program with timeout
Parameters
struct ccw_device *cdev: target ccw devicestruct ccw1 *cpa: logical start address of channel programunsigned long intparm: user specific interruption parameter; will be presented back to cdev's interrupt handler. Allows a device driver to associate the interrupt with a particular I/O request.__u8 lpm: defines the channel path to be used for a specific I/O request. A value of 0 will make cio use the opm.unsigned long flags: additional flags; defines the action to be performed for I/O processing.int expires: timeout value in jiffies
Description
Start a S/390 channel program. When the interrupt arrives, the
IRQ handler is called, either immediately, delayed (dev-end missing,
or sense required) or never (no IRQ handler registered).
This function notifies the device driver if the channel program has not
completed during the time specified by expires. If a timeout occurs, the
channel program is terminated via xsch, hsch or csch, and the device's
interrupt handler will be called with an irb containing ERR_PTR(-ETIMEDOUT).
The interruption handler will echo back the intparm specified here, unless
another interruption parameter is specified by a subsequent invocation of
ccw_device_halt() or ccw_device_clear().
Return
0, if the operation was successful;
-EBUSY, if the device is busy, or status pending;
-EACCES, if no path specified in lpm is operational;
-ENODEV, if the device is not operational.
Context
Interrupts disabled, ccw device lock held
ccw_device_halt() #
int halt I/O request processing
Parameters
struct ccw_device *cdev: target ccw deviceunsigned long intparm: interruption parameter to be returned upon conclusion of hsch
Description
ccw_device_halt() calls hsch on cdev's subchannel.
The interruption handler will echo back the intparm specified here, unless
another interruption parameter is specified by a subsequent invocation of
ccw_device_clear().
Return
0 on success,
-ENODEV on device not operational,
-EINVAL on invalid device state,
-EBUSY on device busy or interrupt pending.
Context
Interrupts disabled, ccw device lock held
ccw_device_resume() #
int resume channel program execution
Parameters
struct ccw_device *cdev: target ccw device
Description
ccw_device_resume() calls rsch on cdev's subchannel.
Return
0 on success,
-ENODEV on device not operational,
-EINVAL on invalid device state,
-EBUSY on device busy or interrupt pending.
Context
Interrupts disabled, ccw device lock held
ccw_device_get_ciw() #
struct ciw * Search for CIW command in extended sense data.
Parameters
struct ccw_device *cdev: ccw device to inspect__u32 ct: command type to look for
Description
During SenseID, command information words (CIWs) describing special commands available to the device may have been stored in the extended sense data. This function searches for CIWs of a specified command type in the extended sense data.
Return
NULL if no extended sense data has been stored or if no CIW of the
specified command type could be found,
else a pointer to the CIW of the specified command type.
ccw_device_get_path_mask() #
__u8 get currently available paths
Parameters
struct ccw_device *cdev: ccw device to be queried
Return
0 if no subchannel for the device is available,
else the mask of currently available paths for the ccw device's subchannel.
ccw_device_get_chp_desc() #
struct channel_path_desc_fmt0 * return newly allocated channel-path descriptor
Parameters
struct ccw_device *cdev: device to obtain the descriptor forint chp_idx: index of the channel path
Description
On success return a newly allocated copy of the channel-path description
data associated with the given channel path. Return NULL on error.
ccw_device_get_util_str() #
u8 * return newly allocated utility strings
Parameters
struct ccw_device *cdev: device to obtain the utility strings forint chp_idx: index of the channel path
Description
On success return a newly allocated copy of the utility strings
associated with the given channel path. Return NULL on error.
ccw_device_get_id() #
void obtain a ccw device id
Parameters
struct ccw_device *cdev: device to obtain the id forstruct ccw_dev_id *dev_id: where to fill in the values
ccw_device_tm_start_timeout_key() #
int perform start function
Parameters
struct ccw_device *cdev: ccw device on which to perform the start functionstruct tcw *tcw: transport-command word to be startedunsigned long intparm: user defined parameter to be passed to the interrupt handleru8 lpm: mask of paths to useu8 key: storage key to use for storage accessint expires: time span in jiffies after which to abort request
Description
Start the tcw on the given ccw device. Return zero on success, non-zero otherwise.
ccw_device_tm_start_key() #
int perform start function
Parameters
struct ccw_device *cdev: ccw device on which to perform the start functionstruct tcw *tcw: transport-command word to be startedunsigned long intparm: user defined parameter to be passed to the interrupt handleru8 lpm: mask of paths to useu8 key: storage key to use for storage access
Description
Start the tcw on the given ccw device. Return zero on success, non-zero otherwise.
ccw_device_tm_start() #
int perform start function
Parameters
struct ccw_device *cdev: ccw device on which to perform the start functionstruct tcw *tcw: transport-command word to be startedunsigned long intparm: user defined parameter to be passed to the interrupt handleru8 lpm: mask of paths to use
Description
Start the tcw on the given ccw device. Return zero on success, non-zero otherwise.
ccw_device_tm_start_timeout() #
int perform start function
Parameters
struct ccw_device *cdev: ccw device on which to perform the start functionstruct tcw *tcw: transport-command word to be startedunsigned long intparm: user defined parameter to be passed to the interrupt handleru8 lpm: mask of paths to useint expires: time span in jiffies after which to abort request
Description
Start the tcw on the given ccw device. Return zero on success, non-zero otherwise.
ccw_device_get_mdc() #
int accumulate max data count
Parameters
struct ccw_device *cdev: ccw device for which the max data count is accumulatedu8 mask: mask of paths to use
Description
Return the number of 64K-bytes blocks all paths at least support for a transport command. Return value 0 indicates failure.
ccw_device_tm_intrg() #
int perform interrogate function
Parameters
struct ccw_device *cdev: ccw device on which to perform the interrogate function
Description
Perform an interrogate function on the given ccw device. Return zero on success, non-zero otherwise.
ccw_device_get_schid() #
void obtain a subchannel id
Parameters
struct ccw_device *cdev: device to obtain the id forstruct subchannel_id *schid: where to fill in the values
ccw_device_pnso() #
int Perform Network-Subchannel Operation
Parameters
struct ccw_device *cdev: device on which PNSO is performedstruct chsc_pnso_area *pnso_area: request and response block for the operationu8 oc: Operation Codestruct chsc_pnso_resume_token resume_token: resume token for multiblock responseint cnc: Boolean change-notification control
Description
pnso_area must be allocated by the caller with get_zeroed_page(GFP_KERNEL)
Returns 0 on success.
ccw_device_get_cssid() #
int obtain Channel Subsystem ID
Parameters
struct ccw_device *cdev: device to obtain the CSSID foru8 *cssid: The resulting Channel Subsystem ID
ccw_device_get_iid() #
int obtain MIF-image ID
Parameters
struct ccw_device *cdev: device to obtain the MIF-image ID foru8 *iid: The resulting MIF-image ID
ccw_device_get_chpid() #
int obtain Channel Path ID
Parameters
struct ccw_device *cdev: device to obtain the Channel Path ID forint chp_idx: Index of the channel pathu8 *chpid: The resulting Channel Path ID
ccw_device_get_chid() #
int obtain Channel ID associated with specified CHPID
Parameters
struct ccw_device *cdev: device to obtain the Channel ID forint chp_idx: Index of the channel pathu16 *chid: The resulting Channel ID
The channel-measurement facility #
The channel-measurement facility provides a means to collect measurement data which is made available by the channel subsystem for each channel attached device.
struct cmbdata #
channel measurement block data for user space
Definition
;
Members
size: size of the stored dataelapsed_time: time since last samplingssch_rsch_count: number of ssch and rschsample_count: number of samplesdevice_connect_time: time of device connectfunction_pending_time: time of function pendingdevice_disconnect_time: time of device disconnectcontrol_unit_queuing_time: time of control unit queuingdevice_active_only_time: time of device active onlydevice_busy_time: time of device busy (ext. format)initial_command_response_time: initial command response time (ext. format)
Description
All values are stored as 64 bit for simplicity, especially in 32 bit emulation mode. All time values are normalized to nanoseconds. Currently, two formats are known, which differ by the size of this structure, i.e. the last two members are only set when the extended channel measurement facility (first shipped in z990 machines) is activated. Potentially, more fields could be added, which would result in a new ioctl number.
enable_cmf() #
int switch on the channel measurement for a specific device
Parameters
struct ccw_device *cdev: The ccw device to be enabled
Description
Enable channel measurements for cdev. If this is called on a device for which channel measurement is already enabled a reset of the measurement data is triggered.
Return
0 for success or a negative error value.
Context
non-atomic
disable_cmf() #
int switch off the channel measurement for a specific device
Parameters
struct ccw_device *cdev: The ccw device to be disabled
Return
0 for success or a negative error value.
Context
non-atomic
cmf_read() #
u64 read one value from the current channel measurement block
Parameters
struct ccw_device *cdev: the channel to be readint index: the index of the value to be read
Return
The value read or 0 if the value cannot be read.
Context
any
cmf_readall() #
int read the current channel measurement block
Parameters
struct ccw_device *cdev: the channel to be readstruct cmbdata *data: a pointer to a data block that will be filled
Return
0 on success, a negative error value otherwise.
Context
any
The ccwgroup bus #
The ccwgroup bus only contains artificial devices, created by the user. Many networking devices (e.g. qeth) are in fact composed of several ccw devices (like read, write and data channel for qeth). The ccwgroup bus provides a mechanism to create a meta-device which contains those ccw devices as slave devices and can be associated with the netdevice.
ccw group devices #
struct ccwgroup_device #
ccw group device
Definition
;
Members
state: online/offline statecount: number of attached slave devicesdev: embedded device structureungroup_work: used to ungroup the ccwgroup devicecdev: variable number of slave devices, allocated as needed
struct ccwgroup_driver #
driver for ccw group devices
Definition
;
Members
setup: function called during device creation to setup the deviceremove: function called on removeset_online: function called when device is set onlineset_offline: function called when device is set offlineshutdown: function called when device is shut downdriver: embedded driver structureccw_driver: supported ccw_driver (optional)
ccwgroup_set_online() #
int enable a ccwgroup device
Parameters
struct ccwgroup_device *gdev: target ccwgroup device
Description
This function attempts to put the ccwgroup device into the online state.
Return
0 on success and a negative error value on failure.
ccwgroup_set_offline() #
int disable a ccwgroup device
Parameters
struct ccwgroup_device *gdev: target ccwgroup devicebool call_gdrv: Call the registered gdrv set_offline function
Description
This function attempts to put the ccwgroup device into the offline state.
Return
0 on success and a negative error value on failure.
ccwgroup_create_dev() #
int create and register a ccw group device
Parameters
struct device *parent: parent device for the new devicestruct ccwgroup_driver *gdrv: driver for the new group deviceint num_devices: number of slave devicesconst char *buf: buffer containing comma separated bus ids of slave devices
Description
Create and register a new ccw group device as a child of parent. Slave devices are obtained from the list of bus ids given in buf.
Return
0 on success and an error code on failure.
Context
non-atomic
ccwgroup_driver_register() #
int register a ccw group driver
Parameters
struct ccwgroup_driver *cdriver: driver to be registered
Description
This function is mainly a wrapper around driver_register().
ccwgroup_driver_unregister() #
void deregister a ccw group driver
Parameters
struct ccwgroup_driver *cdriver: driver to be deregistered
Description
This function is mainly a wrapper around driver_unregister().
ccwgroup_probe_ccwdev() #
int probe function for slave devices
Parameters
struct ccw_device *cdev: ccw device to be probed
Description
This is a dummy probe function for ccw devices that are slave devices in a ccw group device.
Return
always 0
ccwgroup_remove_ccwdev() #
void remove function for slave devices
Parameters
struct ccw_device *cdev: ccw device to be removed
Description
This is a remove function for ccw devices that are slave devices in a ccw group device. It sets the ccw device offline and also deregisters the embedding ccw group device.
Generic interfaces #
The following section contains interfaces in use not only by drivers dealing with ccw devices, but drivers for various other s390 hardware as well.
Adapter interrupts #
The common I/O layer provides helper functions for dealing with adapter interrupts and interrupt vectors.
register_adapter_interrupt() #
int register adapter interrupt handler
Parameters
struct airq_struct *airq: pointer to adapter interrupt descriptor
Description
Returns 0 on success, or -EINVAL.
unregister_adapter_interrupt() #
void unregister adapter interrupt handler
Parameters
struct airq_struct *airq: pointer to adapter interrupt descriptor
airq_iv_create() #
struct airq_iv * create an interrupt vector
Parameters
unsigned long bits: number of bits in the interrupt vectorunsigned long flags: allocation flagsunsigned long *vec: pointer to pinned guest memory if AIRQ_IV_GUESTVEC
Description
Returns a pointer to an interrupt vector structure
airq_iv_release() #
void release an interrupt vector
Parameters
struct airq_iv *iv: pointer to interrupt vector structure
airq_iv_alloc() #
unsigned long allocate irq bits from an interrupt vector
Parameters
struct airq_iv *iv: pointer to an interrupt vector structureunsigned long num: number of consecutive irq bits to allocate
Description
Returns the bit number of the first irq in the allocated block of irqs, or -1UL if no bit is available or the AIRQ_IV_ALLOC flag has not been specified
airq_iv_free() #
void free irq bits of an interrupt vector
Parameters
struct airq_iv *iv: pointer to interrupt vector structureunsigned long bit: number of the first irq bit to freeunsigned long num: number of consecutive irq bits to free
airq_iv_scan() #
unsigned long scan interrupt vector for non-zero bits
Parameters
struct airq_iv *iv: pointer to interrupt vector structureunsigned long start: bit number to start the searchunsigned long end: bit number to end the search
Description
Returns the bit number of the next non-zero interrupt bit, or -1UL if the scan completed without finding any more any non-zero bits.
SM501 Driver
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Copyright: © 2006, 2007 Simtec Electronics
The Silicon Motion SM501 multimedia companion chip is a multifunction device which may provide numerous interfaces including USB host controller USB gadget, asynchronous serial ports, audio functions, and a dual display video interface. The device may be connected by PCI or local bus with varying functions enabled.
Core #
The core driver in drivers/mfd provides common services for the drivers which manage the specific hardware blocks. These services include locking for common registers, clock control and resource management.
The core registers drivers for both PCI and generic bus based chips via the platform device and driver system.
On detection of a device, the core initialises the chip (which may be specified by the platform data) and then exports the selected peripheral set as platform devices for the specific drivers.
The core re-uses the platform device system as the platform device system provides enough features to support the drivers without the need to create a new bus-type and the associated code to go with it.
Resources #
Each peripheral has a view of the device which is implicitly narrowed to the specific set of resources that peripheral requires in order to function correctly.
The centralised memory allocation allows the driver to ensure that the maximum possible resource allocation can be made to the video subsystem as this is by-far the most resource-sensitive of the on-chip functions.
The primary issue with memory allocation is that of moving the video buffers once a display mode is chosen. Indeed when a video mode change occurs the memory footprint of the video subsystem changes.
Since video memory is difficult to move without changing the display (unless sufficient contiguous memory can be provided for the old and new modes simultaneously) the video driver fully utilises the memory area given to it by aligning fb0 to the start of the area and fb1 to the end of it. Any memory left over in the middle is used for the acceleration functions, which are transient and thus their location is less critical as it can be moved.
Configuration #
The platform device driver uses a set of platform data to pass configurations through to the core and the subsidiary drivers so that there can be support for more than one system carrying an SM501 built into a single kernel image.
The PCI driver assumes that the PCI card behaves as per the Silicon Motion reference design.
There is an errata (AB-5) affecting the selection of the of the M1XCLK and M1CLK frequencies. These two clocks must be sourced from the same PLL, although they can then be divided down individually. If this is not set, then SM501 may lock and hang the whole system. The driver will refuse to attach if the PLL selection is different.
The Userspace I/O HOWTO
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Author: Hans-Jürgen Koch Linux developer, Linutronix
Date: 2006-12-11
About this document #
Translations #
If you know of any translations for this document, or you are interested in translating it, please email me hjk@hansjkoch.de.
Preface #
For many types of devices, creating a Linux kernel driver is overkill. All that is really needed is some way to handle an interrupt and provide access to the memory space of the device. The logic of controlling the device does not necessarily have to be within the kernel, as the device does not need to take advantage of any of other resources that the kernel provides. One such common class of devices that are like this are for industrial I/O cards.
To address this situation, the userspace I/O system (UIO) was designed. For typical industrial I/O cards, only a very small kernel module is needed. The main part of the driver will run in user space. This simplifies development and reduces the risk of serious bugs within a kernel module.
Please note that UIO is not an universal driver interface. Devices that are already handled well by other kernel subsystems (like networking or serial or USB) are no candidates for an UIO driver. Hardware that is ideally suited for an UIO driver fulfills all of the following:
-
The device has memory that can be mapped. The device can be controlled completely by writing to this memory.
-
The device usually generates interrupts.
-
The device does not fit into one of the standard kernel subsystems.
Acknowledgments #
I'd like to thank Thomas Gleixner and Benedikt Spranger of Linutronix, who have not only written most of the UIO code, but also helped greatly writing this HOWTO by giving me all kinds of background information.
Feedback #
Find something wrong with this document? (Or perhaps something right?) I would love to hear from you. Please email me at hjk@hansjkoch.de.
About UIO #
If you use UIO for your card's driver, here's what you get:
-
only one small kernel module to write and maintain.
-
develop the main part of your driver in user space, with all the tools and libraries you're used to.
-
bugs in your driver won't crash the kernel.
-
updates of your driver can take place without recompiling the kernel.
How UIO works #
Each UIO device is accessed through a device file and several sysfs attribute files. The device file will be called /dev/uio0 for the first device, and /dev/uio1, /dev/uio2 and so on for subsequent devices.
/dev/uioX is used to access the address space of the card. Just use mmap() to access registers or RAM locations of your card.
Interrupts are handled by reading from /dev/uioX. A blocking read() from /dev/uioX will return as soon as an interrupt occurs. You can also use select() on /dev/uioX to wait for an interrupt. The integer value read from /dev/uioX represents the total interrupt count. You can use this number to figure out if you missed some interrupts.
For some hardware that has more than one interrupt source internally, but not separate IRQ mask and status registers, there might be situations where userspace cannot determine what the interrupt source was if the kernel handler disables them by writing to the chip's IRQ register. In such a case, the kernel has to disable the IRQ completely to leave the chip's register untouched. Now the userspace part can determine the cause of the interrupt, but it cannot re-enable interrupts. Another cornercase is chips where re-enabling interrupts is a read-modify-write operation to a combined IRQ status/acknowledge register. This would be racy if a new interrupt occurred simultaneously.
To address these problems, UIO also implements a write() function. It is normally not used and can be ignored for hardware that has only a single interrupt source or has separate IRQ mask and status registers. If you need it, however, a write to /dev/uioX will call the irqcontrol() function implemented by the driver. You have to write a 32-bit value that is usually either 0 or 1 to disable or enable interrupts. If a driver does not implement irqcontrol(), write() will return with -ENOSYS.
To handle interrupts properly, your custom kernel module can provide its own interrupt handler. It will automatically be called by the built-in handler.
For cards that don't generate interrupts but need to be polled, there is the possibility to set up a timer that triggers the interrupt handler at configurable time intervals. This interrupt simulation is done by calling uio_event_notify() from the timer's event handler.
Each driver provides attributes that are used to read or write variables. These attributes are accessible through sysfs files. A custom kernel driver module can add its own attributes to the device owned by the uio driver, but not added to the UIO device itself at this time. This might change in the future if it would be found to be useful.
The following standard attributes are provided by the UIO framework:
-
name: The name of your device. It is recommended to use the name of your kernel module for this. -
version: A version string defined by your driver. This allows the user space part of your driver to deal with different versions of the kernel module. -
event: The total number of interrupts handled by the driver since the last time the device node was read.
These attributes appear under the /sys/class/uio/uioX directory. Please note that this directory might be a symlink, and not a real directory. Any userspace code that accesses it must be able to handle this.
Each UIO device can make one or more memory regions available for memory mapping. This is necessary because some industrial I/O cards require access to more than one PCI memory region in a driver.
Each mapping has its own directory in sysfs, the first mapping appears as /sys/class/uio/uioX/maps/map0/. Subsequent mappings create directories map1/, map2/, and so on. These directories will only appear if the size of the mapping is not 0.
Each mapX/ directory contains four read-only files that show attributes of the memory:
-
name: A string identifier for this mapping. This is optional, the string can be empty. Drivers can set this to make it easier for userspace to find the correct mapping. -
addr: The address of memory that can be mapped. -
size: The size, in bytes, of the memory pointed to by addr. -
offset: The offset, in bytes, that has to be added to the pointer returned bymmap()to get to the actual device memory. This is important if the device's memory is not page aligned. Remember that pointers returned bymmap()are always page aligned, so it is good style to always add this offset.
From userspace, the different mappings are distinguished by adjusting the offset parameter of the mmap() call. To map the memory of mapping N, you have to use N times the page size as your offset:
offset = N * getpagesize();
Sometimes there is hardware with memory-like regions that can not be mapped with the technique described here, but there are still ways to access them from userspace. The most common example are x86 ioports. On x86 systems, userspace can access these ioports using ioperm(), iopl(), inb(), outb(), and similar functions.
Since these ioport regions can not be mapped, they will not appear under /sys/class/uio/uioX/maps/ like the normal memory described above. Without information about the port regions a hardware has to offer, it becomes difficult for the userspace part of the driver to find out which ports belong to which UIO device.
To address this situation, the new directory /sys/class/uio/uioX/portio/ was added. It only exists if the driver wants to pass information about one or more port regions to userspace. If that is the case, subdirectories named port0, port1, and so on, will appear underneath /sys/class/uio/uioX/portio/.
Each portX/ directory contains four read-only files that show name, start, size, and type of the port region:
-
name: A string identifier for this port region. The string is optional and can be empty. Drivers can set it to make it easier for userspace to find a certain port region. -
start: The first port of this region. -
size: The number of ports in this region. -
porttype: A string describing the type of port.
Writing your own kernel module #
Please have a look at uio_cif.c as an example. The following paragraphs explain the different sections of this file.
struct uio_info #
This structure tells the framework the details of your driver, Some of the members are required, others are optional.
-
const char *name: Required. The name of your driver as it will appear in sysfs. I recommend using the name of your module for this. -
const char *version: Required. This string appears in/sys/class/uio/uioX/version. -
struct uio_mem mem[ MAX_UIO_MAPS ]: Required if you have memory that can be mapped withmmap(). For each mapping you need to fill one of theuio_memstructures. See the description below for details. -
struct uio_port port[ MAX_UIO_PORTS_REGIONS ]: Required if you want to pass information about ioports to userspace. For each port region you need to fill one of theuio_portstructures. See the description below for details. -
long irq: Required. If your hardware generates an interrupt, it's your modules task to determine the irq number during initialization. If you don't have a hardware generated interrupt but want to trigger the interrupt handler in some other way, setirqtoUIO_IRQ_CUSTOM. If you had no interrupt at all, you could setirqtoUIO_IRQ_NONE, though this rarely makes sense. -
unsigned long irq_flags: Required if you've setirqto a hardware interrupt number. The flags given here will be used in the call torequest_irq(). -
int (*mmap)(struct uio_info *info, struct vm_area_struct *vma): Optional. If you need a specialmmap()function, you can set it here. If this pointer is not NULL, yourmmap()will be called instead of the built-in one. -
int (*open)(struct uio_info *info, struct inode *inode): Optional. You might want to have your ownopen(), e.g. to enable interrupts only when your device is actually used. -
int (*release)(struct uio_info *info, struct inode *inode): Optional. If you define your ownopen(), you will probably also want a customrelease()function. -
int (*irqcontrol)(struct uio_info *info, s32 irq_on): Optional. If you need to be able to enable or disable interrupts from userspace by writing to/dev/uioX, you can implement this function. The parameterirq_onwill be 0 to disable interrupts and 1 to enable them.
Usually, your device will have one or more memory regions that can be mapped to user space. For each region, you have to set up a struct uio_mem in the mem[] array. Here's a description of the fields of struct uio_mem:
-
const char *name: Optional. Set this to help identify the memory region, it will show up in the corresponding sysfs node. -
int memtype: Required if the mapping is used. Set this toUIO_MEM_PHYSif you have physical memory on your card to be mapped. UseUIO_MEM_LOGICALfor logical memory (e.g. allocated with__get_free_pages()but not kmalloc()). There's alsoUIO_MEM_VIRTUALfor virtual memory. -
phys_addr_t addr: Required if the mapping is used. Fill in the address of your memory block. This address is the one that appears in sysfs. -
resource_size_t size: Fill in the size of the memory block thataddrpoints to. Ifsizeis zero, the mapping is considered unused. Note that you must initializesizewith zero for all unused mappings. -
void *internal_addr: If you have to access this memory region from within your kernel module, you will want to map it internally by using something likeioremap(). Addresses returned by this function cannot be mapped to user space, so you must not store it inaddr. Useinternal_addrinstead to remember such an address.
Please do not touch the map element of struct uio_mem! It is used by the UIO framework to set up sysfs files for this mapping. Simply leave it alone.
Sometimes, your device can have one or more port regions which can not be mapped to userspace. But if there are other possibilities for userspace to access these ports, it makes sense to make information about the ports available in sysfs. For each region, you have to set up a struct uio_port in the port[] array. Here's a description of the fields of struct uio_port:
-
char *porttype: Required. Set this to one of the predefined constants. UseUIO_PORT_X86for the ioports found in x86 architectures. -
unsigned long start: Required if the port region is used. Fill in the number of the first port of this region. -
unsigned long size: Fill in the number of ports in this region. Ifsizeis zero, the region is considered unused. Note that you must initializesizewith zero for all unused regions.
Please do not touch the portio element of struct uio_port! It is used internally by the UIO framework to set up sysfs files for this region. Simply leave it alone.
Adding an interrupt handler #
What you need to do in your interrupt handler depends on your hardware and on how you want to handle it. You should try to keep the amount of code in your kernel interrupt handler low. If your hardware requires no action that you have to perform after each interrupt, then your handler can be empty.
If, on the other hand, your hardware needs some action to be performed after each interrupt, then you must do it in your kernel module. Note that you cannot rely on the userspace part of your driver. Your userspace program can terminate at any time, possibly leaving your hardware in a state where proper interrupt handling is still required.
There might also be applications where you want to read data from your hardware at each interrupt and buffer it in a piece of kernel memory you've allocated for that purpose. With this technique you could avoid loss of data if your userspace program misses an interrupt.
A note on shared interrupts: Your driver should support interrupt sharing whenever this is possible. It is possible if and only if your driver can detect whether your hardware has triggered the interrupt or not. This is usually done by looking at an interrupt status register. If your driver sees that the IRQ bit is actually set, it will perform its actions, and the handler returns IRQ_HANDLED. If the driver detects that it was not your hardware that caused the interrupt, it will do nothing and return IRQ_NONE, allowing the kernel to call the next possible interrupt handler.
If you decide not to support shared interrupts, your card won't work in computers with no free interrupts. As this frequently happens on the PC platform, you can save yourself a lot of trouble by supporting interrupt sharing.
Using uio_pdrv for platform devices #
In many cases, UIO drivers for platform devices can be handled in a generic way. In the same place where you define your struct platform_device, you simply also implement your interrupt handler and fill your struct uio_info. A pointer to this struct uio_info is then used as platform_data for your platform device.
You also need to set up an array of struct resource containing addresses and sizes of your memory mappings. This information is passed to the driver using the .resource and .num_resources elements of struct platform_device.
You now have to set the .name element of struct platform_device to "uio_pdrv" to use the generic UIO platform device driver. This driver will fill the mem[] array according to the resources given, and register the device.
The advantage of this approach is that you only have to edit a file you need to edit anyway. You do not have to create an extra driver.
Using uio_pdrv_genirq for platform devices #
Especially in embedded devices, you frequently find chips where the irq pin is tied to its own dedicated interrupt line. In such cases, where you can be really sure the interrupt is not shared, we can take the concept of uio_pdrv one step further and use a generic interrupt handler. That's what uio_pdrv_genirq does.
The setup for this driver is the same as described above for uio_pdrv, except that you do not implement an interrupt handler. The .handler element of struct uio_info must remain NULL. The .irq_flags element must not contain IRQF_SHARED.
You will set the .name element of struct platform_device to "uio_pdrv_genirq" to use this driver.
The generic interrupt handler of uio_pdrv_genirq will simply disable the interrupt line using disable_irq_nosync(). After doing its work, userspace can reenable the interrupt by writing 0x00000001 to the UIO device file. The driver already implements an irq_control() to make this possible, you must not implement your own.
Using uio_pdrv_genirq not only saves a few lines of interrupt handler code. You also do not need to know anything about the chip's internal registers to create the kernel part of the driver. All you need to know is the irq number of the pin the chip is connected to.
When used in a device-tree enabled system, the driver needs to be probed with the "of_id" module parameter set to the "compatible" string of the node the driver is supposed to handle. By default, the node's name (without the unit address) is exposed as name for the UIO device in userspace. To set a custom name, a property named "linux,uio-name" may be specified in the DT node.
Using uio_dmem_genirq for platform devices #
In addition to statically allocated memory ranges, they may also be a desire to use dynamically allocated regions in a user space driver. In particular, being able to access memory made available through the dma-mapping API, may be particularly useful. The uio_dmem_genirq driver provides a way to accomplish this.
This driver is used in a similar manner to the "uio_pdrv_genirq" driver with respect to interrupt configuration and handling.
Set the .name element of struct platform_device to "uio_dmem_genirq" to use this driver.
When using this driver, fill in the .platform_data element of struct platform_device, which is of type struct uio_dmem_genirq_pdata and which contains the following elements:
-
struct uio_info uioinfo: The same structure used as theuio_pdrv_genirqplatform data -
unsigned int *dynamic_region_sizes: Pointer to list of sizes of dynamic memory regions to be mapped into user space. -
unsigned int num_dynamic_regions: Number of elements indynamic_region_sizesarray.
The dynamic regions defined in the platform data will be appended to the `` mem[] `` array after the platform device resources, which implies that the total number of static and dynamic memory regions cannot exceed MAX_UIO_MAPS.
The dynamic memory regions will be allocated when the UIO device file, /dev/uioX is opened. Similar to static memory resources, the memory region information for dynamic regions is then visible via sysfs at /sys/class/uio/uioX/maps/mapY/*. The dynamic memory regions will be freed when the UIO device file is closed. When no processes are holding the device file open, the address returned to userspace is ~0.
Writing a driver in userspace #
Once you have a working kernel module for your hardware, you can write the userspace part of your driver. You don't need any special libraries, your driver can be written in any reasonable language, you can use floating point numbers and so on. In short, you can use all the tools and libraries you'd normally use for writing a userspace application.
Getting information about your UIO device #
Information about all UIO devices is available in sysfs. The first thing you should do in your driver is check name and version to make sure you're talking to the right device and that its kernel driver has the version you expect.
You should also make sure that the memory mapping you need exists and has the size you expect.
There is a tool called lsuio that lists UIO devices and their attributes. It is available here:
http://www.osadl.org/projects/downloads/UIO/user/
With lsuio you can quickly check if your kernel module is loaded and which attributes it exports. Have a look at the manpage for details.
The source code of lsuio can serve as an example for getting information about an UIO device. The file uio_helper.c contains a lot of functions you could use in your userspace driver code.
mmap() device memory #
After you made sure you've got the right device with the memory mappings you need, all you have to do is to call mmap() to map the device's memory to userspace.
The parameter offset of the mmap() call has a special meaning for UIO devices: It is used to select which mapping of your device you want to map. To map the memory of mapping N, you have to use N times the page size as your offset:
offset = N * getpagesize();
N starts from zero, so if you've got only one memory range to map, set offset = 0. A drawback of this technique is that memory is always mapped beginning with its start address.
Waiting for interrupts #
After you successfully mapped your devices memory, you can access it like an ordinary array. Usually, you will perform some initialization. After that, your hardware starts working and will generate an interrupt as soon as it's finished, has some data available, or needs your attention because an error occurred.
/dev/uioX is a read-only file. A read() will always block until an interrupt occurs. There is only one legal value for the count parameter of read(), and that is the size of a signed 32 bit integer (4). Any other value for count causes read() to fail. The signed 32 bit integer read is the interrupt count of your device. If the value is one more than the value you read the last time, everything is OK. If the difference is greater than one, you missed interrupts.
You can also use select() on /dev/uioX.
Generic PCI UIO driver #
The generic driver is a kernel module named uio_pci_generic. It can work with any device compliant to PCI 2.3 (circa 2002) and any compliant PCI Express device. Using this, you only need to write the userspace driver, removing the need to write a hardware-specific kernel module.
Making the driver recognize the device #
Since the driver does not declare any device ids, it will not get loaded automatically and will not automatically bind to any devices, you must load it and allocate id to the driver yourself. For example:
modprobe uio_pci_generic
echo "8086 10f5" > /sys/bus/pci/drivers/uio_pci_generic/new_id
If there already is a hardware specific kernel driver for your device, the generic driver still won't bind to it, in this case if you want to use the generic driver (why would you?) you'll have to manually unbind the hardware specific driver and bind the generic driver, like this:
echo -n 0000:00:19.0 > /sys/bus/pci/drivers/e1000e/unbind
echo -n 0000:00:19.0 > /sys/bus/pci/drivers/uio_pci_generic/bind
You can verify that the device has been bound to the driver by looking for it in sysfs, for example like the following:
ls -l /sys/bus/pci/devices/0000:00:19.0/driver
Which if successful should print:
.../0000:00:19.0/driver -> ../../../bus/pci/drivers/uio_pci_generic
Note that the generic driver will not bind to old PCI 2.2 devices. If binding the device failed, run the following command:
dmesg
and look in the output for failure reasons.
Things to know about uio_pci_generic #
Interrupts are handled using the Interrupt Disable bit in the PCI command register and Interrupt Status bit in the PCI status register. All devices compliant to PCI 2.3 (circa 2002) and all compliant PCI Express devices should support these bits. uio_pci_generic detects this support, and won't bind to devices which do not support the Interrupt Disable Bit in the command register.
On each interrupt, uio_pci_generic sets the Interrupt Disable bit. This prevents the device from generating further interrupts until the bit is cleared. The userspace driver should clear this bit before blocking and waiting for more interrupts.
Writing userspace driver using uio_pci_generic #
Userspace driver can use pci sysfs interface, or the libpci library that wraps it, to talk to the device and to re-enable interrupts by writing to the command register.
Example code using uio_pci_generic #
Here is some sample userspace driver code using uio_pci_generic:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int uiofd;
int configfd;
int err;
int i;
unsigned icount;
unsigned char command_high;
uiofd = open("/dev/uio0", O_RDONLY);
if (uiofd < 0) {
perror("uio open:");
return errno;
}
configfd = open("/sys/class/uio/uio0/device/config", O_RDWR);
if (configfd < 0) {
perror("config open:");
return errno;
}
/* Read and cache command value */
err = pread(configfd, &command_high, 1, 5);
if (err != 1) {
perror("command config read:");
return errno;
}
command_high &= ~0x4;
for(i = 0;; ++i) {
/* Print out a message, for debugging. */
if (i == 0)
fprintf(stderr, "Started uio test driver.\n");
else
fprintf(stderr, "Interrupts: %d\n", icount);
/****************************************/
/* Here we got an interrupt from the
device. Do something to it. */
/****************************************/
/* Re-enable interrupts. */
err = pwrite(configfd, &command_high, 1, 5);
if (err != 1) {
perror("config write:");
break;
}
/* Wait for next interrupt. */
err = read(uiofd, &icount, 4);
if (err != 4) {
perror("uio read:");
break;
}
}
return errno;
}
Generic Hyper-V UIO driver #
The generic driver is a kernel module named uio_hv_generic. It supports devices on the Hyper-V VMBus similar to uio_pci_generic on PCI bus.
Making the driver recognize the device #
Since the driver does not declare any device GUID's, it will not get loaded automatically and will not automatically bind to any devices, you must load it and allocate id to the driver yourself. For example, to use the network device class GUID:
modprobe uio_hv_generic
echo "f8615163-df3e-46c5-913f-f2d2f965ed0e" > /sys/bus/vmbus/drivers/uio_hv_generic/new_id
If there already is a hardware specific kernel driver for the device, the generic driver still won't bind to it, in this case if you want to use the generic driver for a userspace library you'll have to manually unbind the hardware specific driver and bind the generic driver, using the device specific GUID like this:
echo -n ed963694-e847-4b2a-85af-bc9cfc11d6f3 > /sys/bus/vmbus/drivers/hv_netvsc/unbind
echo -n ed963694-e847-4b2a-85af-bc9cfc11d6f3 > /sys/bus/vmbus/drivers/uio_hv_generic/bind
You can verify that the device has been bound to the driver by looking for it in sysfs, for example like the following:
ls -l /sys/bus/vmbus/devices/ed963694-e847-4b2a-85af-bc9cfc11d6f3/driver
Which if successful should print:
.../ed963694-e847-4b2a-85af-bc9cfc11d6f3/driver -> ../../../bus/vmbus/drivers/uio_hv_generic
Things to know about uio_hv_generic #
On each interrupt, uio_hv_generic sets the Interrupt Disable bit. This prevents the device from generating further interrupts until the bit is cleared. The userspace driver should clear this bit before blocking and waiting for more interrupts.
When host rescinds a device, the interrupt file descriptor is marked down and any reads of the interrupt file descriptor will return -EIO. Similar to a closed socket or disconnected serial device.
-
The vmbus device regions are mapped into uio device resources:
-
Channel ring buffers: guest to host and host to guest
-
Guest to host interrupt signalling pages
-
Guest to host monitor page
-
Network receive buffer region
-
Network send buffer region
-
If a subchannel is created by a request to host, then the uio_hv_generic device driver will create a sysfs binary file for the per-channel ring buffer. For example:
/sys/bus/vmbus/devices/3811fe4d-0fa0-4b62-981a-74fc1084c757/channels/21/ring
Further information #
VFIO Mediated devices
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Copyright: © 2016, NVIDIA CORPORATION. All rights reserved.
Author: Neo Jia <cjia@nvidia.com>
Author: Kirti Wankhede <kwankhede@nvidia.com>
Virtual Function I/O (VFIO) Mediated devices[1] #
The number of use cases for virtualizing DMA devices that do not have built-in SR_IOV capability is increasing. Previously, to virtualize such devices, developers had to create their own management interfaces and APIs, and then integrate them with user space software. To simplify integration with user space software, we have identified common requirements and a unified management interface for such devices.
The VFIO driver framework provides unified APIs for direct device access. It is an IOMMU/device-agnostic framework for exposing direct device access to user space in a secure, IOMMU-protected environment. This framework is used for multiple devices, such as GPUs, network adapters, and compute accelerators. With direct device access, virtual machines or user space applications have direct access to the physical device. This framework is reused for mediated devices.
The mediated core driver provides a common interface for mediated device management that can be used by drivers of different devices. This module provides a generic interface to perform these operations:
-
Create and destroy a mediated device
-
Add a mediated device to and remove it from a mediated bus driver
-
Add a mediated device to and remove it from an IOMMU group
The mediated core driver also provides an interface to register a bus driver. For example, the mediated VFIO mdev driver is designed for mediated devices and supports VFIO APIs. The mediated bus driver adds a mediated device to and removes it from a VFIO group.
The following high-level block diagram shows the main components and interfaces in the VFIO mediated driver framework. The diagram shows NVIDIA, Intel, and IBM devices as examples, as these devices are the first devices to use this module:
+---------------+
| |
| +-----------+ | mdev_register_driver() +--------------+
| | | +<------------------------+ |
| | mdev | | | |
| | bus | +------------------------>+ vfio_mdev.ko |<-> VFIO user
| | driver | | probe()/remove() | | APIs
| | | | +--------------+
| +-----------+ |
| |
| MDEV CORE |
| MODULE |
| mdev.ko |
| +-----------+ | mdev_register_parent() +--------------+
| | | +<------------------------+ |
| | | | | ccw_device.ko|<-> physical
| | | +------------------------>+ | device
| | | | callbacks +--------------+
| | Physical | |
| | device | | mdev_register_parent() +--------------+
| | interface | |<------------------------+ |
| | | | | i915.ko |<-> physical
| | | +------------------------>+ | device
| | | | callbacks +--------------+
| +-----------+ |
+---------------+
Registration Interfaces #
The mediated core driver provides the following types of registration interfaces:
-
Registration interface for a mediated bus driver
-
Physical device driver interface
Registration Interface for a Mediated Bus Driver #
The registration interface for a mediated device driver provides the following structure to represent a mediated device's driver:
/*
* struct mdev_driver [2] - Mediated device's driver
* @probe: called when new device created
* @remove: called when device removed
* @driver: device driver structure
*/
struct mdev_driver {
int (*probe) (struct mdev_device *dev);
void (*remove) (struct mdev_device *dev);
unsigned int (*get_available)(struct mdev_type *mtype);
ssize_t (*show_description)(struct mdev_type *mtype, char *buf);
struct device_driver driver;
};
A mediated bus driver for mdev should use this structure in the function calls to register and unregister itself with the core driver:
-
Register:
int mdev_register_driver(struct mdev_driver *drv); -
Unregister:
void mdev_unregister_driver(struct mdev_driver *drv);
The mediated bus driver's probe function should create a vfio_device on top of the mdev_device and connect it to an appropriate implementation of vfio_device_ops.
When a driver wants to add the GUID creation sysfs to an existing device it has probe'd to then it should call:
int mdev_register_parent(struct mdev_parent *parent, struct device *dev,
struct mdev_driver *mdev_driver);
This will provide the 'mdev_supported_types/XX/create' files which can then be used to trigger the creation of a mdev_device. The created mdev_device will be attached to the specified driver.
When the driver needs to remove itself it calls:
void mdev_unregister_parent(struct mdev_parent *parent);
Which will unbind and destroy all the created mdevs and remove the sysfs files.
Mediated Device Management Interface Through sysfs #
The management interface through sysfs enables user space software, such as libvirt, to query and configure mediated devices in a hardware-agnostic fashion. This management interface provides flexibility to the underlying physical device's driver to support features such as:
-
Mediated device hot plug
-
Multiple mediated devices in a single virtual machine
-
Multiple mediated devices from different physical devices
Links in the mdev_bus Class Directory #
The /sys/class/mdev_bus/ directory contains links to devices that are registered with the mdev core driver.
Directories and files under the sysfs for Each Physical Device #
|- [parent physical device]
|--- Vendor-specific-attributes [optional]
|--- [mdev_supported_types]
| |--- [<type-id>]
| | |--- create
| | |--- name
| | |--- available_instances
| | |--- device_api
| | |--- description
| | |--- [devices]
| |--- [<type-id>]
| | |--- create
| | |--- name
| | |--- available_instances
| | |--- device_api
| | |--- description
| | |--- [devices]
| |--- [<type-id>]
| |--- create
| |--- name
| |--- available_instances
| |--- device_api
| |--- description
| |--- [devices]
-
[mdev_supported_types]
The list of currently supported mediated device types and their details.
[<type-id>], device_api, and available_instances are mandatory attributes that should be provided by vendor driver.
-
[<type-id>]
The [<type-id>] name is created by adding the device driver string as a prefix to the string provided by the vendor driver. This format of this name is as follows:
sprintf(buf, "%s-%s", dev_driver_string(parent->dev), group->name); -
device_api
This attribute shows which device API is being created, for example, "vfio-pci" for a PCI device.
-
available_instances
This attribute shows the number of devices of type <type-id> that can be created.
-
[device]
This directory contains links to the devices of type <type-id> that have been created.
-
name
This attribute shows a human readable name.
-
description
This attribute can show brief features/description of the type. This is an optional attribute.
Directories and Files Under the sysfs for Each mdev Device #
|- [parent phy device]
|--- [$MDEV_UUID]
|--- remove
|--- mdev_type {link to its type}
|--- vendor-specific-attributes [optional]
- remove (write only)
Writing '1' to the 'remove' file destroys the mdev device. The vendor driver can fail the remove() callback if that device is active and the vendor driver doesn't support hot unplug.
Example:
# echo 1 > /sys/bus/mdev/devices/$mdev_UUID/remove
Mediated device Hot plug #
Mediated devices can be created and assigned at runtime. The procedure to hot plug a mediated device is the same as the procedure to hot plug a PCI device.
Translation APIs for Mediated Devices #
The following APIs are provided for translating user pfn to host pfn in a VFIO driver:
int vfio_pin_pages(struct vfio_device *device, dma_addr_t iova,
int npage, int prot, struct page **pages);
void vfio_unpin_pages(struct vfio_device *device, dma_addr_t iova,
int npage);
These functions call back into the back-end IOMMU module by using the pin_pages and unpin_pages callbacks of the struct vfio_iommu_driver_ops[4]. Currently these callbacks are supported in the TYPE1 IOMMU module. To enable them for other IOMMU backend modules, such as PPC64 sPAPR module, they need to provide these two callback functions.
References #
-
See Documentation/driver-api/vfio.rst for more information on VFIO.
-
struct mdev_driver in include/linux/mdev.h
-
struct mdev_parent_ops in include/linux/mdev.h
-
struct vfio_iommu_driver_ops in include/linux/vfio.h
Acceptance criteria for vfio-pci device specific driver variants
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Overview #
The vfio-pci driver exists as a device agnostic driver using the system IOMMU and relying on the robustness of platform fault handling to provide isolated device access to userspace. While the vfio-pci driver does include some device specific support, further extensions for yet more advanced device specific features are not sustainable. The vfio-pci driver has therefore split out vfio-pci-core as a library that may be reused to implement features requiring device specific knowledge, ex. saving and loading device state for the purposes of supporting migration.
In support of such features, it's expected that some device specific variants may interact with parent devices (ex. SR-IOV PF in support of a user assigned VF) or other extensions that may not be otherwise accessible via the vfio-pci base driver. Authors of such drivers should be diligent not to create exploitable interfaces via these interactions or allow unchecked userspace data to have an effect beyond the scope of the assigned device.
New driver submissions are therefore requested to have approval via sign-off/ack/review/etc for any interactions with parent drivers. Additionally, drivers should make an attempt to provide sufficient documentation for reviewers to understand the device specific extensions, for example in the case of migration data, how is the device state composed and consumed, which portions are not otherwise available to the user via vfio-pci, what safeguards exist to validate the data, etc. To that extent, authors should additionally expect to require reviews from at least one of the listed reviewers, in addition to the overall vfio maintainer.
VFIO - "Virtual Function I/O" 1
Peios Kernel / Hardware and drivers / Driver development / Driver fundamentals
Peios: The
chownexamples below describe Linux ownership metadata. They do not delegate native Peios access to VFIO devices. Provision the required descriptor and handle access, and satisfy the device/ioctl and sysfs gates as applicable. See Peios kernel behaviour.
Title notes: 1
Many modern systems now provide DMA and interrupt remapping facilities to help ensure I/O devices behave within the boundaries they've been allotted. This includes x86 hardware with AMD-Vi and Intel VT-d, POWER systems with Partitionable Endpoints (PEs) and embedded PowerPC systems such as Freescale PAMU. The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment. In other words, this allows safe 2, non-privileged, userspace drivers.
Why do we want that? Virtual machines often make use of direct device access ("device assignment") when configured for the highest possible I/O performance. From a device and host perspective, this simply turns the VM into a userspace driver, with the benefits of significantly reduced latency, higher bandwidth, and direct use of bare-metal device drivers 3.
Some applications, particularly in the high performance computing field, also benefit from low-overhead, direct device access from userspace. Examples include network adapters (often non-TCP/IP based) and compute accelerators. Prior to VFIO, these drivers had to either go through the full development cycle to become proper upstream driver, be maintained out of tree, or make use of the UIO framework, which has no notion of IOMMU protection, limited interrupt support, and requires root privileges to access things like PCI configuration space.
The VFIO driver framework intends to unify these, replacing both the KVM PCI specific device assignment code as well as provide a more secure, more featureful userspace driver environment than UIO.
Groups, Devices, and IOMMUs #
Devices are the main target of any I/O driver. Devices typically create a programming interface made up of I/O access, interrupts, and DMA. Without going into the details of each of these, DMA is by far the most critical aspect for maintaining a secure environment as allowing a device read-write access to system memory imposes the greatest risk to the overall system integrity.
To help mitigate this risk, many modern IOMMUs now incorporate isolation properties into what was, in many cases, an interface only meant for translation (ie. solving the addressing problems of devices with limited address spaces). With this, devices can now be isolated from each other and from arbitrary memory access, thus allowing things like secure direct assignment of devices into virtual machines.
This isolation is not always at the granularity of a single device though. Even when an IOMMU is capable of this, properties of devices, interconnects, and IOMMU topologies can each reduce this isolation. For instance, an individual device may be part of a larger multi- function enclosure. While the IOMMU may be able to distinguish between devices within the enclosure, the enclosure may not require transactions between devices to reach the IOMMU. Examples of this could be anything from a multi-function PCI device with backdoors between functions to a non-PCI-ACS (Access Control Services) capable bridge allowing redirection without reaching the IOMMU. Topology can also play a factor in terms of hiding devices. A PCIe-to-PCI bridge masks the devices behind it, making transaction appear as if from the bridge itself. Obviously IOMMU design plays a major factor as well.
Therefore, while for the most part an IOMMU may have device level granularity, any system is susceptible to reduced granularity. The IOMMU API therefore supports a notion of IOMMU groups. A group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO.
While the group is the minimum granularity that must be used to ensure secure user access, it's not necessarily the preferred granularity. In IOMMUs which make use of page tables, it may be possible to share a set of page tables between different groups, reducing the overhead both to the platform (reduced TLB thrashing, reduced duplicate page tables), and to the user (programming only a single set of translations). For this reason, VFIO makes use of a container class, which may hold one or more groups. A container is created by simply opening the /dev/vfio/vfio character device.
On its own, the container provides little functionality, with all but a couple version and extension query interfaces locked away. The user needs to add a group into the container for the next level of functionality. To do this, the user first needs to identify the group associated with the desired device. This can be done using the sysfs links described in the example below. By unbinding the device from the host driver and binding it to a VFIO driver, a new VFIO group will appear for the group as /dev/vfio/$GROUP, where $GROUP is the IOMMU group number of which the device is a member. If the IOMMU group contains multiple devices, each will need to be bound to a VFIO driver before operations on the VFIO group are allowed (it's also sufficient to only unbind the device from host drivers if a VFIO driver is unavailable; this will make the group available, but not that particular device). TBD - interface for disabling driver probing/locking a device.
Once the group is ready, it may be added to the container by opening the VFIO group character device (/dev/vfio/$GROUP) and using the VFIO_GROUP_SET_CONTAINER ioctl, passing the file descriptor of the previously opened container file. If desired and if the IOMMU driver supports sharing the IOMMU context between groups, multiple groups may be set to the same container. If a group fails to set to a container with existing groups, a new empty container will need to be used instead.
With a group (or groups) attached to a container, the remaining ioctls become available, enabling access to the VFIO IOMMU interfaces. Additionally, it now becomes possible to get file descriptors for each device within a group using an ioctl on the VFIO group file descriptor.
The VFIO device API includes ioctls for describing the device, the I/O regions and their read/write/mmap offsets on the device descriptor, as well as mechanisms for describing and registering interrupt notifications.
VFIO Usage Example #
Assume user wants to access PCI device 0000:06:0d.0:
$ readlink /sys/bus/pci/devices/0000:06:0d.0/iommu_group
../../../../kernel/iommu_groups/26
This device is therefore in IOMMU group 26. This device is on the pci bus, therefore the user will make use of vfio-pci to manage the group:
# modprobe vfio-pci
Binding this device to the vfio-pci driver creates the VFIO group character devices for this group:
$ lspci -n -s 0000:06:0d.0
06:0d.0 0401: 1102:0002 (rev 08)
# echo 0000:06:0d.0 > /sys/bus/pci/devices/0000:06:0d.0/driver/unbind
# echo 1102 0002 > /sys/bus/pci/drivers/vfio-pci/new_id
Now we need to look at what other devices are in the group to free it for use by VFIO:
$ ls -l /sys/bus/pci/devices/0000:06:0d.0/iommu_group/devices
total 0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:00:1e.0 ->
../../../../devices/pci0000:00/0000:00:1e.0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:06:0d.0 ->
../../../../devices/pci0000:00/0000:00:1e.0/0000:06:0d.0
lrwxrwxrwx. 1 root root 0 Apr 23 16:13 0000:06:0d.1 ->
../../../../devices/pci0000:00/0000:00:1e.0/0000:06:0d.1
This device is behind a PCIe-to-PCI bridge 4, therefore we also need to add device 0000:06:0d.1 to the group following the same procedure as above. Device 0000:00:1e.0 is a bridge that does not currently have a host driver, therefore it's not required to bind this device to the vfio-pci driver (vfio-pci does not currently support PCI bridges).
The final step is to provide the user with access to the group if unprivileged operation is desired (note that /dev/vfio/vfio provides no capabilities on its own and is therefore expected to be set to mode 0666 by the system):
# chown user:user /dev/vfio/26
The user now has full access to all the devices and the iommu for this group and can access them as follows:
int container, group, device, i;
struct vfio_group_status group_status =
{ .argsz = sizeof(group_status) };
struct vfio_iommu_type1_info iommu_info = { .argsz = sizeof(iommu_info) };
struct vfio_iommu_type1_dma_map dma_map = { .argsz = sizeof(dma_map) };
struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
/* Create a new container */
container = open("/dev/vfio/vfio", O_RDWR);
if (ioctl(container, VFIO_GET_API_VERSION) != VFIO_API_VERSION)
/* Unknown API version */
if (!ioctl(container, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU))
/* Doesn't support the IOMMU driver we want. */
/* Open the group */
group = open("/dev/vfio/26", O_RDWR);
/* Test the group is viable and available */
ioctl(group, VFIO_GROUP_GET_STATUS, &group_status);
if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE))
/* Group is not viable (ie, not all devices bound for vfio) */
/* Add the group to the container */
ioctl(group, VFIO_GROUP_SET_CONTAINER, &container);
/* Enable the IOMMU model we want */
ioctl(container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
/* Get addition IOMMU info */
ioctl(container, VFIO_IOMMU_GET_INFO, &iommu_info);
/* Allocate some space and setup a DMA mapping */
dma_map.vaddr = mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
dma_map.size = 1024 * 1024;
dma_map.iova = 0; /* 1MB starting at 0x0 from device view */
dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;
ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map);
/* Get a file descriptor for the device */
device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0");
/* Test and setup the device */
ioctl(device, VFIO_DEVICE_GET_INFO, &device_info);
for (i = 0; i < device_info.num_regions; i++) {
struct vfio_region_info reg = { .argsz = sizeof(reg) };
reg.index = i;
ioctl(device, VFIO_DEVICE_GET_REGION_INFO, ®);
/* Setup mappings... read/write offsets, mmaps
* For PCI devices, config space is a region */
}
for (i = 0; i < device_info.num_irqs; i++) {
struct vfio_irq_info irq = { .argsz = sizeof(irq) };
irq.index = i;
ioctl(device, VFIO_DEVICE_GET_IRQ_INFO, &irq);
/* Setup IRQs... eventfds, VFIO_DEVICE_SET_IRQS */
}
/* Gratuitous device reset and go... */
ioctl(device, VFIO_DEVICE_RESET);
IOMMUFD and vfio_iommu_type1 #
IOMMUFD is the new user API to manage I/O page tables from userspace. It intends to be the portal of delivering advanced userspace DMA features (nested translation 5, PASID 6, etc.) while also providing a backwards compatibility interface for existing VFIO_TYPE1v2_IOMMU use cases. Eventually the vfio_iommu_type1 driver, as well as the legacy vfio container and group model is intended to be deprecated.
The IOMMUFD backwards compatibility interface can be enabled two ways. In the first method, the kernel can be configured with CONFIG_IOMMUFD_VFIO_CONTAINER, in which case the IOMMUFD subsystem transparently provides the entire infrastructure for the VFIO container and IOMMU backend interfaces. The compatibility mode can also be accessed if the VFIO container interface, ie. /dev/vfio/vfio is simply symlink'd to /dev/iommu. Note that at the time of writing, the compatibility mode is not entirely feature complete relative to VFIO_TYPE1v2_IOMMU (ex. DMA mapping MMIO) and does not attempt to provide compatibility to the VFIO_SPAPR_TCE_IOMMU interface. Therefore it is not generally advisable at this time to switch from native VFIO implementations to the IOMMUFD compatibility interfaces.
Long term, VFIO users should migrate to device access through the cdev interface described below, and native access through the IOMMUFD provided interfaces.
VFIO Device cdev #
Traditionally user acquires a device fd via VFIO_GROUP_GET_DEVICE_FD in a VFIO group.
With CONFIG_VFIO_DEVICE_CDEV=y the user can now acquire a device fd by directly opening a character device /dev/vfio/devices/vfioX where "X" is the number allocated uniquely by VFIO for registered devices. cdev interface does not support noiommu devices, so user should use the legacy group interface if noiommu is wanted.
The cdev only works with IOMMUFD. Both VFIO drivers and applications must adapt to the new cdev security model which requires using VFIO_DEVICE_BIND_IOMMUFD to claim DMA ownership before starting to actually use the device. Once BIND succeeds then a VFIO device can be fully accessed by the user.
VFIO device cdev doesn't rely on VFIO group/container/iommu drivers. Hence those modules can be fully compiled out in an environment where no legacy VFIO application exists.
So far SPAPR does not support IOMMUFD yet. So it cannot support device cdev either.
vfio device cdev access is still bound by IOMMU group semantics, ie. there can be only one DMA owner for the group. Devices belonging to the same group can not be bound to multiple iommufd_ctx or shared between native kernel and vfio bus driver or other driver supporting the driver_managed_dma flag. A violation of this ownership requirement will fail at the VFIO_DEVICE_BIND_IOMMUFD ioctl, which gates full device access.
Device cdev Example #
Assume user wants to access PCI device 0000:6a:01.0:
$ ls /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/
vfio0
This device is therefore represented as vfio0. The user can verify its existence:
$ ls -l /dev/vfio/devices/vfio0
crw------- 1 root root 511, 0 Feb 16 01:22 /dev/vfio/devices/vfio0
$ cat /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/vfio0/dev
511:0
$ ls -l /dev/char/511\:0
lrwxrwxrwx 1 root root 21 Feb 16 01:22 /dev/char/511:0 -> ../vfio/devices/vfio0
Then provide the user with access to the device if unprivileged operation is desired:
$ chown user:user /dev/vfio/devices/vfio0
Finally the user could get cdev fd by:
cdev_fd = open("/dev/vfio/devices/vfio0", O_RDWR);
An opened cdev_fd doesn't give the user any permission of accessing the device except binding the cdev_fd to an iommufd. After that point then the device is fully accessible including attaching it to an IOMMUFD IOAS/HWPT to enable userspace DMA:
struct vfio_device_bind_iommufd bind = {
.argsz = sizeof(bind),
.flags = 0,
};
struct iommu_ioas_alloc alloc_data = {
.size = sizeof(alloc_data),
.flags = 0,
};
struct vfio_device_attach_iommufd_pt attach_data = {
.argsz = sizeof(attach_data),
.flags = 0,
};
struct iommu_ioas_map map = {
.size = sizeof(map),
.flags = IOMMU_IOAS_MAP_READABLE |
IOMMU_IOAS_MAP_WRITEABLE |
IOMMU_IOAS_MAP_FIXED_IOVA,
.__reserved = 0,
};
iommufd = open("/dev/iommu", O_RDWR);
bind.iommufd = iommufd;
ioctl(cdev_fd, VFIO_DEVICE_BIND_IOMMUFD, &bind);
ioctl(iommufd, IOMMU_IOAS_ALLOC, &alloc_data);
attach_data.pt_id = alloc_data.out_ioas_id;
ioctl(cdev_fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data);
/* Allocate some space and setup a DMA mapping */
map.user_va = (int64_t)mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
map.iova = 0; /* 1MB starting at 0x0 from device view */
map.length = 1024 * 1024;
map.ioas_id = alloc_data.out_ioas_id;
ioctl(iommufd, IOMMU_IOAS_MAP, &map);
/* Other device operations as stated in "VFIO Usage Example" */
VFIO User API #
Please see include/uapi/linux/vfio.h for complete API documentation.
VFIO bus driver API #
VFIO bus drivers, such as vfio-pci make use of only a few interfaces into VFIO core. When devices are bound and unbound to the driver, Following interfaces are called when devices are bound to and unbound from the driver:
int vfio_register_group_dev(struct vfio_device *device);
int vfio_register_emulated_iommu_dev(struct vfio_device *device);
void vfio_unregister_group_dev(struct vfio_device *device);
The driver should embed the vfio_device in its own structure and use vfio_alloc_device() to allocate the structure, and can register @init/@release callbacks to manage any private state wrapping the vfio_device:
vfio_alloc_device(dev_struct, member, dev, ops);
void vfio_put_device(struct vfio_device *device);
vfio_register_group_dev() indicates to the core to begin tracking the iommu_group of the specified dev and register the dev as owned by a VFIO bus driver. Once vfio_register_group_dev() returns it is possible for userspace to start accessing the driver, thus the driver should ensure it is completely ready before calling it. The driver provides an ops structure for callbacks similar to a file operations structure:
struct vfio_device_ops {
char *name;
int (*init)(struct vfio_device *vdev);
void (*release)(struct vfio_device *vdev);
int (*bind_iommufd)(struct vfio_device *vdev,
struct iommufd_ctx *ictx, u32 *out_device_id);
void (*unbind_iommufd)(struct vfio_device *vdev);
int (*attach_ioas)(struct vfio_device *vdev, u32 *pt_id);
void (*detach_ioas)(struct vfio_device *vdev);
int (*open_device)(struct vfio_device *vdev);
void (*close_device)(struct vfio_device *vdev);
ssize_t (*read)(struct vfio_device *vdev, char __user *buf,
size_t count, loff_t *ppos);
ssize_t (*write)(struct vfio_device *vdev, const char __user *buf,
size_t count, loff_t *size);
long (*ioctl)(struct vfio_device *vdev, unsigned int cmd,
unsigned long arg);
int (*mmap)(struct vfio_device *vdev, struct vm_area_struct *vma);
void (*request)(struct vfio_device *vdev, unsigned int count);
int (*match)(struct vfio_device *vdev, char *buf);
void (*dma_unmap)(struct vfio_device *vdev, u64 iova, u64 length);
int (*device_feature)(struct vfio_device *device, u32 flags,
void __user *arg, size_t argsz);
};
Each function is passed the vdev that was originally registered in the vfio_register_group_dev() or vfio_register_emulated_iommu_dev() call above. This allows the bus driver to obtain its private data using container_of().
- The init/release callbacks are issued when vfio_device is initialized
and released.
- The open/close device callbacks are issued when the first
instance of a file descriptor for the device is created (eg.
via VFIO_GROUP_GET_DEVICE_FD) for a user session.
- The ioctl callback provides a direct pass through for some VFIO_DEVICE_*
ioctls.
- The [un]bind_iommufd callbacks are issued when the device is bound to
and unbound from iommufd.
- The [de]attach_ioas callback is issued when the device is attached to
and detached from an IOAS managed by the bound iommufd. However, the
attached IOAS can also be automatically detached when the device is
unbound from iommufd.
- The read/write/mmap callbacks implement the device region access defined
by the device's own VFIO_DEVICE_GET_REGION_INFO ioctl.
- The request callback is issued when device is going to be unregistered,
such as when trying to unbind the device from the vfio bus driver.
- The dma_unmap callback is issued when a range of iovas are unmapped
in the container or IOAS attached by the device. Drivers which make
use of the vfio page pinning interface must implement this callback in
order to unpin pages within the dma_unmap range. Drivers must tolerate
this callback even before calls to open_device().
PPC64 sPAPR implementation note #
This implementation has some specifics:
-
On older systems (POWER7 with P5IOC2/IODA1) only one IOMMU group per container is supported as an IOMMU table is allocated at the boot time, one table per a IOMMU group which is a Partitionable Endpoint (PE) (PE is often a PCI domain but not always).
Newer systems (POWER8 with IODA2) have improved hardware design which allows to remove this limitation and have multiple IOMMU groups per a VFIO container.
-
The hardware supports so called DMA windows - the PCI address range within which DMA transfer is allowed, any attempt to access address space out of the window leads to the whole PE isolation.
-
PPC64 guests are paravirtualized but not fully emulated. There is an API to map/unmap pages for DMA, and it normally maps 1..32 pages per call and currently there is no way to reduce the number of calls. In order to make things faster, the map/unmap handling has been implemented in real mode which provides an excellent performance which has limitations such as inability to do locked pages accounting in real time.
-
According to sPAPR specification, A Partitionable Endpoint (PE) is an I/O subtree that can be treated as a unit for the purposes of partitioning and error recovery. A PE may be a single or multi-function IOA (IO Adapter), a function of a multi-function IOA, or multiple IOAs (possibly including switch and bridge structures above the multiple IOAs). PPC64 guests detect PCI errors and recover from them via EEH RTAS services, which works on the basis of additional ioctl commands.
So 4 additional ioctls have been added:
-
VFIO_IOMMU_SPAPR_TCE_GET_INFO
returns the size and the start of the DMA window on the PCI bus.
-
VFIO_IOMMU_ENABLE
enables the container. The locked pages accounting is done at this point. This lets user first to know what the DMA window is and adjust rlimit before doing any real job.
-
VFIO_IOMMU_DISABLE
disables the container.
-
VFIO_EEH_PE_OP
provides an API for EEH setup, error detection and recovery.
The code flow from the example above should be slightly changed:
struct vfio_eeh_pe_op pe_op = { .argsz = sizeof(pe_op), .flags = 0 }; ..... /* Add the group to the container */ ioctl(group, VFIO_GROUP_SET_CONTAINER, &container); /* Enable the IOMMU model we want */ ioctl(container, VFIO_SET_IOMMU, VFIO_SPAPR_TCE_IOMMU) /* Get addition sPAPR IOMMU info */ vfio_iommu_spapr_tce_info spapr_iommu_info; ioctl(container, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &spapr_iommu_info); if (ioctl(container, VFIO_IOMMU_ENABLE)) /* Cannot enable container, may be low rlimit */ /* Allocate some space and setup a DMA mapping */ dma_map.vaddr = mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); dma_map.size = 1024 * 1024; dma_map.iova = 0; /* 1MB starting at 0x0 from device view */ dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE; /* Check here is .iova/.size are within DMA window from spapr_iommu_info */ ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map); /* Get a file descriptor for the device */ device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0"); .... /* Gratuitous device reset and go... */ ioctl(device, VFIO_DEVICE_RESET); /* Make sure EEH is supported */ ioctl(container, VFIO_CHECK_EXTENSION, VFIO_EEH); /* Enable the EEH functionality on the device */ pe_op.op = VFIO_EEH_PE_ENABLE; ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* You're suggested to create additional data struct to represent * PE, and put child devices belonging to same IOMMU group to the * PE instance for later reference. */ /* Check the PE's state and make sure it's in functional state */ pe_op.op = VFIO_EEH_PE_GET_STATE; ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* Save device state using pci_save_state(). * EEH should be enabled on the specified device. */ .... /* Inject EEH error, which is expected to be caused by 32-bits * config load. */ pe_op.op = VFIO_EEH_PE_INJECT_ERR; pe_op.err.type = EEH_ERR_TYPE_32; pe_op.err.func = EEH_ERR_FUNC_LD_CFG_ADDR; pe_op.err.addr = 0ul; pe_op.err.mask = 0ul; ioctl(container, VFIO_EEH_PE_OP, &pe_op); .... /* When 0xFF's returned from reading PCI config space or IO BARs * of the PCI device. Check the PE's state to see if that has been * frozen. */ ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* Waiting for pending PCI transactions to be completed and don't * produce any more PCI traffic from/to the affected PE until * recovery is finished. */ /* Enable IO for the affected PE and collect logs. Usually, the * standard part of PCI config space, AER registers are dumped * as logs for further analysis. */ pe_op.op = VFIO_EEH_PE_UNFREEZE_IO; ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* * Issue PE reset: hot or fundamental reset. Usually, hot reset * is enough. However, the firmware of some PCI adapters would * require fundamental reset. */ pe_op.op = VFIO_EEH_PE_RESET_HOT; ioctl(container, VFIO_EEH_PE_OP, &pe_op); pe_op.op = VFIO_EEH_PE_RESET_DEACTIVATE; ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* Configure the PCI bridges for the affected PE */ pe_op.op = VFIO_EEH_PE_CONFIGURE; ioctl(container, VFIO_EEH_PE_OP, &pe_op); /* Restored state we saved at initialization time. pci_restore_state() * is good enough as an example. */ /* Hopefully, error is recovered successfully. Now, you can resume to * start PCI traffic to/from the affected PE. */ .... -
-
There is v2 of SPAPR TCE IOMMU. It deprecates VFIO_IOMMU_ENABLE/ VFIO_IOMMU_DISABLE and implements 2 new ioctls: VFIO_IOMMU_SPAPR_REGISTER_MEMORY and VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY (which are unsupported in v1 IOMMU).
PPC64 paravirtualized guests generate a lot of map/unmap requests, and the handling of those includes pinning/unpinning pages and updating mm::locked_vm counter to make sure we do not exceed the rlimit. The v2 IOMMU splits accounting and pinning into separate operations:
-
VFIO_IOMMU_SPAPR_REGISTER_MEMORY/VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY ioctls receive a user space address and size of the block to be pinned. Bisecting is not supported and VFIO_IOMMU_UNREGISTER_MEMORY is expected to be called with the exact address and size used for registering the memory block. The userspace is not expected to call these often. The ranges are stored in a linked list in a VFIO container.
-
VFIO_IOMMU_MAP_DMA/VFIO_IOMMU_UNMAP_DMA ioctls only update the actual IOMMU table and do not do pinning; instead these check that the userspace address is from pre-registered range.
This separation helps in optimizing DMA for guests.
-
-
sPAPR specification allows guests to have an additional DMA window(s) on a PCI bus with a variable page size. Two ioctls have been added to support this: VFIO_IOMMU_SPAPR_TCE_CREATE and VFIO_IOMMU_SPAPR_TCE_REMOVE. The platform has to support the functionality or error will be returned to the userspace. The existing hardware supports up to 2 DMA windows, one is 2GB long, uses 4K pages and called "default 32bit window"; the other can be as big as entire RAM, use different page size, it is optional - guests create those in run-time if the guest driver supports 64bit DMA.
VFIO_IOMMU_SPAPR_TCE_CREATE receives a page shift, a DMA window size and a number of TCE table levels (if a TCE table is going to be big enough and the kernel may not be able to allocate enough of physically contiguous memory). It creates a new window in the available slot and returns the bus address where the new window starts. Due to hardware limitation, the user space cannot choose the location of DMA windows.
VFIO_IOMMU_SPAPR_TCE_REMOVE receives the bus start address of the window and removes it.
[1] VFIO was originally an acronym for "Virtual Function I/O" in its initial implementation by Tom Lyon while as Cisco. We've since outgrown the acronym, but it's catchy.
[2] "safe" also depends upon a device being "well behaved". It's possible for multi-function devices to have backdoors between functions and even for single function devices to have alternative access to things like PCI config space through MMIO registers. To guard against the former we can include additional precautions in the IOMMU driver to group multi-function PCI devices together (iommu=group_mf). The latter we can't prevent, but the IOMMU should still provide isolation. For PCI, SR-IOV Virtual Functions are the best indicator of "well behaved", as these are designed for virtualization usage models.
[3] As always there are trade-offs to virtual machine device assignment that are beyond the scope of VFIO. It's expected that future IOMMU technologies will reduce some, but maybe not all, of these trade-offs.
[4] In this case the device is below a PCI bridge, so transactions from either function of the device are indistinguishable to the iommu:
-[0000:00]-+-1e.0-[06]--+-0d.0
\-0d.1
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90)
[5] Nested translation is an IOMMU feature which supports two stage address translations. This improves the address translation efficiency in IOMMU virtualization.
[6] PASID stands for Process Address Space ID, introduced by PCI Express. It is a prerequisite for Shared Virtual Addressing (SVA) and Scalable I/O Virtualization (Scalable IOV).