Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

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 example_probe(struct platform_device *pdev)
{
        struct resource *mem;
        resource_size_t base, size;
        int ret;

        mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
        if (!mem)
                return -ENODEV;
        base = mem->start;
        size = resource_size(mem);

        ret = aperture_remove_conflicting_devices(base, size, "example");
        if (ret)
                return ret;

        // Initialize the hardware
        ...

        return 0;
}

static const struct platform_driver example_driver = {
        .probe = example_probe,
        ...
};

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 generic_probe(struct platform_device *pdev)
{
        struct resource *mem;
        resource_size_t base, size;

        mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
        if (!mem)
                return -ENODEV;
        base = mem->start;
        size = resource_size(mem);

        ret = devm_aperture_acquire_for_platform_device(pdev, base, size);
        if (ret)
                return ret;

        // Initialize the hardware
        ...

        return 0;
}

static int generic_remove(struct platform_device *)
{
        // Hot-unplug the device
        ...

        return 0;
}

static const struct platform_driver generic_driver = {
        .probe = generic_probe,
        .remove = generic_remove,
        ...
};

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 aperture_remove_all_conflicting_devices(const char *name)

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 devm_aperture_acquire_for_platform_device(struct platform_device *pdev, resource_size_t base, resource_size_t size)

Acquires ownership of an aperture on behalf of a platform device.

Parameters

  • struct platform_device *pdev: the platform device to own the aperture
  • resource_size_t base: the aperture's byte offset in physical memory
  • resource_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 aperture_remove_conflicting_devices(resource_size_t base, resource_size_t size, const char *name)

remove devices in the given range

Parameters

  • resource_size_t base: the aperture's base address in physical memory
  • resource_size_t size: aperture size in bytes
  • const 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 __aperture_remove_legacy_vga_devices(struct pci_dev *pdev)

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 aperture_remove_conflicting_pci_devices(struct pci_dev *pdev, const char *name)

remove existing framebuffers for PCI devices

Parameters

  • struct pci_dev *pdev: PCI device
  • const 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() #

module_init(x)

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() #

module_exit(x)

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

struct klp_modinfo {
    Elf_Ehdr hdr;
    Elf_Shdr *sechdrs;
    char *secstrings;
    unsigned int symndx;
};

Members

  • hdr: ELF header
  • sechdrs: Section header table
  • secstrings: String table for the section headers
  • symndx: The symbol table section index

try_module_get() #

bool try_module_get(struct module *module)

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:

  1. 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.

  2. 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 use try_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 module_put(struct module *module)

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

struct usb_device_id {
    __u16 match_flags;
    __u16 idVendor;
    __u16 idProduct;
    __u16 bcdDevice_lo;
    __u16 bcdDevice_hi;
    __u8 bDeviceClass;
    __u8 bDeviceSubClass;
    __u8 bDeviceProtocol;
    __u8 bInterfaceClass;
    __u8 bInterfaceSubClass;
    __u8 bInterfaceProtocol;
    __u8 bInterfaceNumber;
    kernel_ulong_t driver_info  ;
};

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() #

ACPI_DEVICE_CLASS(_cls, _msk)

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

struct mdio_device_id {
    __u32 phy_id;
    __u32 phy_id_mask;
};

Members

  • phy_id: The result of (mdio_read(MII_PHYSID1) << 16 | mdio_read(MII_PHYSID2)) & phy_id_mask for this PHY type
  • phy_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

struct amba_id {
    unsigned int            id;
    unsigned int            mask;
    void *data;
};

Members

  • id: The significant bits if the hardware device ID
  • mask: 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

struct mips_cdmm_device_id {
    __u8 type;
};

Members

  • type: Device type identifier.

struct mei_cl_device_id #

MEI client device identifier

Definition

struct mei_cl_device_id {
    char name[MEI_CL_NAME_SIZE];
    uuid_le uuid;
    __u8 version;
    kernel_ulong_t driver_info;
};

Members

  • name: helper name
  • uuid: client uuid
  • version: client protocol version
  • driver_info: information used by the driver.

Description

identifies mei client device by uuid and name

struct rio_device_id #

RIO device identifier

Definition

struct rio_device_id {
    __u16 did, vid;
    __u16 asm_did, asm_vid;
};

Members

  • did: RapidIO device ID
  • vid: RapidIO vendor ID
  • asm_did: RapidIO assembly device ID
  • asm_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

struct fsl_mc_device_id {
    __u16 vendor;
    const char obj_type[16];
};

Members

  • vendor: vendor ID
  • obj_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

struct tb_service_id {
    __u32 match_flags;
    char protocol_key[8 + 1];
    __u32 protocol_id;
    __u32 protocol_version;
    __u32 protocol_revision;
    kernel_ulong_t driver_data;
};

Members

  • match_flags: Flags used to match the structure
  • protocol_key: Protocol key the service supports
  • protocol_id: Protocol id the service supports
  • protocol_version: Version of the protocol
  • protocol_revision: Revision of the protocol software
  • driver_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

struct typec_device_id {
    __u16 svid;
    __u8 mode;
    kernel_ulong_t driver_data;
};

Members

  • svid: Standard or Vendor ID
  • mode: Mode index
  • driver_data: Driver specific data

struct tee_client_device_id #

tee based device identifier

Definition

struct tee_client_device_id {
    uuid_t uuid;
};

Members

  • uuid: For TEE based client devices we use the device uuid as the identifier.

struct wmi_device_id #

WMI device identifier

Definition

struct wmi_device_id {
    const char guid_string[UUID_STRING_LEN+1];
    const void *context;
};

Members

  • guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
  • context: pointer to driver specific data

struct mhi_device_id #

MHI device identification

Definition

struct mhi_device_id {
    const char chan[MHI_NAME_SIZE];
    kernel_ulong_t driver_data;
};

Members

  • chan: MHI channel name
  • driver_data: driver data;

struct dfl_device_id #

dfl device identifier

Definition

struct dfl_device_id {
    __u16 type;
    __u16 feature_id;
    kernel_ulong_t driver_data;
};

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

struct ishtp_device_id {
    guid_t guid;
    kernel_ulong_t driver_data;
};

Members

  • guid: GUID of the device.
  • driver_data: pointer to driver specific data

struct cdx_device_id #

CDX device identifier

Definition

struct cdx_device_id {
    __u16 vendor;
    __u16 device;
    __u16 subvendor;
    __u16 subdevice;
    __u32 class;
    __u32 class_mask;
    __u32 override_only;
};

Members

  • vendor: Vendor ID
  • device: Device ID
  • subvendor: 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

struct coreboot_device_id {
    __u32 tag;
    kernel_ulong_t driver_data;
};

Members

  • tag: tag ID
  • driver_data: driver specific data

Delaying and scheduling routines #

struct prev_cputime #

snapshot of system and user cputime

Definition

struct prev_cputime {
    #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE;
        u64 utime;
        u64 stime;
        raw_spinlock_t lock;
    #endif;
};

Members

  • utime: time spent in user mode
  • stime: time spent in system mode
  • lock: protects the above two fields

Description

Stores previous user/system time values such that we can guarantee monotonicity.

__task_lazy_mmu_mode_active() #

bool __task_lazy_mmu_mode_active(struct task_struct *tsk)

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 is_lazy_mmu_mode_active(void)

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:

  1. We are not in interrupt context
  2. 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_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)

set CPU affinity mask of a task

Parameters

  • struct task_struct *p: the task
  • const struct cpumask *new_mask: CPU affinity mask

Return

zero if successful, or a negative error code

task_nice() #

int task_nice(const struct task_struct *p)

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_idle_task(const struct task_struct *p)

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_process(struct task_struct *p)

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 preempt_notifier_register(struct preempt_notifier *notifier)

tell me when current is being preempted & rescheduled

Parameters

  • struct preempt_notifier *notifier: notifier struct to register

preempt_notifier_unregister() #

void preempt_notifier_unregister(struct preempt_notifier *notifier)

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_notrace(void)

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 cpupri_find_fitness(struct cpupri *cp, struct task_struct *p, struct cpumask *lowest_mask, bool (*fitness_fn)(struct task_struct *p, int cpu))

find the best (lowest-pri) CPU in the system

Parameters

  • struct cpupri *cp: The cpupri context
  • struct task_struct *p: The task
  • struct 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 cpupri_set(struct cpupri *cp, int cpu, int newpri)

update the CPU priority setting

Parameters

  • struct cpupri *cp: The cpupri context
  • int cpu: The target CPU
  • int 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 cpupri_init(struct cpupri *cp)

initialize the cpupri structure

Parameters

  • struct cpupri *cp: The cpupri context

Return

-ENOMEM on memory allocation failure.

cpupri_cleanup() #

void cpupri_cleanup(struct cpupri *cp)

clean up the cpupri structure

Parameters

  • struct cpupri *cp: The cpupri context

update_tg_load_avg() #

void update_tg_load_avg(struct cfs_rq *cfs_rq)

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_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)

update the cfs_rq's load/util averages

Parameters

  • u64 now: current time, as per cfs_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_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)

attach this entity to its cfs_rq load avg

Parameters

  • struct cfs_rq *cfs_rq: cfs_rq to attach to
  • struct 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_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)

detach this entity from its cfs_rq load avg

Parameters

  • struct cfs_rq *cfs_rq: cfs_rq to detach from
  • struct 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 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)

Estimates the amount of CPU capacity used by CFS tasks.

Parameters

  • int cpu: the CPU to get the utilization for
  • struct task_struct *p: task for which the CPU utilization should be predicted or NULL
  • int dst_cpu: CPU p migrates to, -1 if p moves from cpu or p == NULL
  • int 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 sched_use_asym_prio(struct sched_domain *sd, int cpu)

Check whether asym_packing priority must be used

Parameters

  • struct sched_domain *sd: The scheduling domain of the load balancing
  • int 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 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)

Check if the destination CPU can do asym_packing balance

Parameters

  • struct lb_env *env: The load balancing environment
  • struct sg_lb_stats *sgs: Load-balancing statistics of the candidate busiest group
  • struct 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_sg_lb_stats(struct lb_env *env, struct sd_lb_stats *sds, struct sched_group *group, struct sg_lb_stats *sgs, bool *sg_overloaded, bool *sg_overutilized)

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 overloaded
  • bool *sg_overutilized: sched_group is overutilized

update_sd_pick_busiest() #

bool update_sd_pick_busiest(struct lb_env *env, struct sd_lb_stats *sds, struct sched_group *sg, struct sg_lb_stats *sgs)

return 1 on busiest group

Parameters

  • struct lb_env *env: The load balancing environment.
  • struct sd_lb_stats *sds: sched_domain statistics
  • struct sched_group *sg: sched_group candidate to be checked for being the busiest
  • struct 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 idle_cpu_without(int cpu, struct task_struct *p)

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_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)

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_imbalance(struct lb_env *env, struct sd_lb_stats *sds)

Calculate the amount of imbalance present within the groups of a given sched_domain during load balance.

Parameters

  • struct lb_env *env: load balance environment
  • struct sd_lb_stats *sds: statistics of the sched_domain whose imbalance is to be calculated.

sched_balance_find_src_group() #

struct sched_group * sched_balance_find_src_group(struct lb_env *env)

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_COMPLETION(work)

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_COMPLETION_ONSTACK(work)

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 init_completion(struct completion *x)

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 reinit_completion(struct completion *x)

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 get_jiffies_64(void)

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() #

time_after(a, b)

returns true if the time a is after time b.

Parameters

  • a: first comparable as unsigned long
  • b: 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() #

time_before(a, b)

returns true if the time a is before time b.

Parameters

  • a: first comparable as unsigned long
  • b: second comparable as unsigned long

Return

true is time a is before time b, otherwise false.

time_after_eq() #

time_after_eq(a, b)

returns true if the time a is after or the same as time b.

Parameters

  • a: first comparable as unsigned long
  • b: second comparable as unsigned long

Return

true is time a is after or the same as time b, otherwise false.

time_before_eq() #

time_before_eq(a, b)

returns true if the time a is before or the same as time b.

Parameters

  • a: first comparable as unsigned long
  • b: second comparable as unsigned long

Return

true is time a is before or the same as time b, otherwise false.

time_in_range() #

time_in_range(a, b, c)

Calculate whether a is in the range of [b, c].

Parameters

  • a: time to test
  • b: beginning of the range
  • c: end of the range

Return

true is time a is in the range [b, c], otherwise false.

time_in_range_open() #

time_in_range_open(a, b, c)

Calculate whether a is in the range of [b, c).

Parameters

  • a: time to test
  • b: beginning of the range
  • c: end of the range

Return

true is time a is in the range [b, c), otherwise false.

time_after64() #

time_after64(a, b)

returns true if the time a is after time b.

Parameters

  • a: first comparable as __u64
  • b: 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() #

time_before64(a, b)

returns true if the time a is before time b.

Parameters

  • a: first comparable as __u64
  • b: 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() #

time_after_eq64(a, b)

returns true if the time a is after or the same as time b.

Parameters

  • a: first comparable as __u64
  • b: 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() #

time_before_eq64(a, b)

returns true if the time a is before or the same as time b.

Parameters

  • a: first comparable as __u64
  • b: 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() #

time_in_range64(a, b, c)

Calculate whether a is in the range of [b, c].

Parameters

  • a: time to test
  • b: beginning of the range
  • c: end of the range

Return

true is time a is in the range [b, c], otherwise false.

time_is_before_jiffies() #

time_is_before_jiffies(a)

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() #

time_is_before_jiffies64(a)

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() #

time_is_after_jiffies(a)

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() #

time_is_after_jiffies64(a)

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() #

time_is_before_eq_jiffies(a)

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() #

time_is_before_eq_jiffies64(a)

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() #

time_is_after_eq_jiffies(a)

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() #

time_is_after_eq_jiffies64(a)

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 jiffies_to_msecs(const unsigned long j)

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 jiffies_to_usecs(const unsigned long j)

Convert jiffies to microseconds

Parameters

  • const unsigned long j: jiffies value

Return

microseconds value

jiffies_to_nsecs() #

u64 jiffies_to_nsecs(const unsigned long j)

Convert jiffies to nanoseconds

Parameters

  • const unsigned long j: jiffies value

Return

nanoseconds value

msecs_to_jiffies() #

unsigned long msecs_to_jiffies(const unsigned int m)
  • 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() #

secs_to_jiffies(_secs)
  • 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 usecs_to_jiffies(const unsigned int u)
  • 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 jiffies_to_msecs(const unsigned long j)

Convert jiffies to milliseconds

Parameters

  • const unsigned long j: jiffies value

Return

milliseconds value

jiffies_to_usecs() #

unsigned int jiffies_to_usecs(const unsigned long j)

Convert jiffies to microseconds

Parameters

  • const unsigned long j: jiffies value

Return

microseconds value

mktime64() #

time64_t mktime64(const unsigned int year0, const unsigned int mon0, const unsigned int day, const unsigned int hour, const unsigned int min, const unsigned int sec)

Converts date to seconds.

Parameters

  • const unsigned int year0: year to convert
  • const unsigned int mon0: month to convert
  • const unsigned int day: day to convert
  • const unsigned int hour: hour to convert
  • const unsigned int min: minute to convert
  • const 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_normalized_timespec64(struct timespec64 *ts, time64_t sec, s64 nsec)

set timespec sec and nsec parts and normalize

Parameters

  • struct timespec64 *ts: pointer to timespec variable to be set
  • time64_t sec: seconds to set
  • s64 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 ns_to_timespec64(s64 nsec)

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 __msecs_to_jiffies(const unsigned int m)
  • 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 __usecs_to_jiffies(const unsigned int u)
  • convert microseconds to jiffies

Parameters

  • const unsigned int u: time in milliseconds

Return

jiffies value

timespec64_to_jiffies() #

unsigned long timespec64_to_jiffies(const struct timespec64 *value)

convert a timespec64 value to jiffies

Parameters

  • const struct timespec64 *value: pointer to struct 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 jiffies_to_timespec64(const unsigned long jiffies, struct timespec64 *value)

convert jiffies value to struct timespec64

Parameters

  • const unsigned long jiffies: jiffies value
  • struct timespec64 *value: pointer to struct timespec64

jiffies_to_clock_t() #

clock_t jiffies_to_clock_t(unsigned long x)

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 clock_t_to_jiffies(unsigned long x)

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 jiffies_64_to_clock_t(u64 x)

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 jiffies64_to_nsecs(u64 j)

Convert jiffies64 to nanoseconds

Parameters

  • u64 j: jiffies64 value

Return

nanoseconds value

jiffies64_to_msecs() #

u64 jiffies64_to_msecs(const u64 j)

Convert jiffies64 to milliseconds

Parameters

  • const u64 j: jiffies64 value

Return

milliseconds value

nsecs_to_jiffies64() #

u64 nsecs_to_jiffies64(u64 n)

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 nsecs_to_jiffies(u64 n)

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 timespec64_add_safe(const struct timespec64 lhs, const struct timespec64 rhs)

Add two timespec64 values and do a safety check for overflow.

Parameters

  • const struct timespec64 lhs: first (left) timespec64 to add
  • const 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_timespec64(struct timespec64 *ts, const struct __kernel_timespec __user *uts)

get user's time value into kernel space

Parameters

  • struct timespec64 *ts: destination struct timespec64
  • const struct __kernel_timespec __user *uts: user's time value as struct __kernel_timespec

Description

Handles compat or 32-bit modes.

Return

0 on success or negative errno on error

put_timespec64() #

int put_timespec64(const struct timespec64 *ts, struct __kernel_timespec __user *uts)

convert timespec64 value to __kernel_timespec format and copy the latter to userspace

Parameters

  • const struct timespec64 *ts: input struct timespec64
  • struct __kernel_timespec __user *uts: user's struct __kernel_timespec

Return

0 on success or negative errno on error

get_old_timespec32() #

int get_old_timespec32(struct timespec64 *ts, const void __user *uts)

get user's old-format time value into kernel space

Parameters

  • struct timespec64 *ts: destination struct timespec64
  • const 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 put_old_timespec32(const struct timespec64 *ts, void __user *uts)

convert timespec64 value to struct old_timespec32 and copy the latter to userspace

Parameters

  • const struct timespec64 *ts: input struct timespec64
  • void __user *uts: user's struct old_timespec32

Description

Handles X86_X32_ABI compatibility conversion.

Return

0 on success or negative errno on error

get_itimerspec64() #

int get_itimerspec64(struct itimerspec64 *it, const struct __kernel_itimerspec __user *uit)

get user's struct __kernel_itimerspec into kernel space

Parameters

  • struct itimerspec64 *it: destination struct itimerspec64
  • const struct __kernel_itimerspec __user *uit: user's struct __kernel_itimerspec

Return

0 on success or negative errno on error

put_itimerspec64() #

int put_itimerspec64(const struct itimerspec64 *it, struct __kernel_itimerspec __user *uit)

convert struct itimerspec64 to __kernel_itimerspec format and copy the latter to userspace

Parameters

  • const struct itimerspec64 *it: input struct itimerspec64
  • struct __kernel_itimerspec __user *uit: user's struct __kernel_itimerspec

Return

0 on success or negative errno on error

get_old_itimerspec32() #

int get_old_itimerspec32(struct itimerspec64 *its, const struct old_itimerspec32 __user *uits)

get user's struct old_itimerspec32 into kernel space

Parameters

  • struct itimerspec64 *its: destination struct itimerspec64
  • const struct old_itimerspec32 __user *uits: user's struct old_itimerspec32

Return

0 on success or negative errno on error

put_old_itimerspec32() #

int put_old_itimerspec32(const struct itimerspec64 *its, struct old_itimerspec32 __user *uits)

convert struct itimerspec64 to struct old_itimerspec32 and copy the latter to userspace

Parameters

  • const struct itimerspec64 *its: input struct itimerspec64
  • struct old_itimerspec32 __user *uits: user's struct old_itimerspec32

Return

0 on success or negative errno on error

__round_jiffies_relative() #

unsigned long __round_jiffies_relative(unsigned long j, int cpu)

function to round jiffies to a full second

Parameters

  • unsigned long j: the time in (relative) jiffies that should be rounded
  • int 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 round_jiffies(unsigned long j)

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 round_jiffies_relative(unsigned long j)

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 __round_jiffies_up_relative(unsigned long j, int cpu)

function to round jiffies up to a full second

Parameters

  • unsigned long j: the time in (relative) jiffies that should be rounded
  • int 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 round_jiffies_up(unsigned long j)

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 round_jiffies_up_relative(unsigned long j)

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 timer_init_key(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key)

initialize a timer

Parameters

  • struct timer_list *timer: the timer to be initialized
  • void (*func)(struct timer_list *): timer callback function
  • unsigned int flags: timer flags
  • const char *name: name of the timer
  • struct 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 mod_timer_pending(struct timer_list *timer, unsigned long expires)

Modify a pending timer's timeout

Parameters

  • struct timer_list *timer: The pending timer to be modified
  • unsigned 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 discarded
  • 1 - The timer was active and requeued to expire at expires

mod_timer() #

int mod_timer(struct timer_list *timer, unsigned long expires)

Modify a timer's timeout

Parameters

  • struct timer_list *timer: The timer to be modified
  • unsigned 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 discarded
  • 1 - 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 timer_reduce(struct timer_list *timer, unsigned long expires)

Modify a timer's timeout if it would reduce the timeout

Parameters

  • struct timer_list *timer: The timer to be modified
  • unsigned 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 discarded
  • 1 - 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 add_timer(struct timer_list *timer)

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 add_timer_local(struct timer_list *timer)

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 add_timer_global(struct timer_list *timer)

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 add_timer_on(struct timer_list *timer, int cpu)

Start a timer on a particular CPU

Parameters

  • struct timer_list *timer: The timer to be started
  • int 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 timer_delete(struct timer_list *timer)

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 pending
  • 1 - The timer was pending and deactivated

timer_shutdown() #

int timer_shutdown(struct timer_list *timer)

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 pending
  • 1 - The timer was pending

timer_delete_sync_try() #

int timer_delete_sync_try(struct timer_list *timer)

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 pending
  • 1 - The timer was pending and deactivated
  • -1 - The timer callback function is running on a different CPU

timer_delete_sync() #

int timer_delete_sync(struct timer_list *timer)

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 pending
  • 1 - The timer was pending and deactivated

timer_shutdown_sync() #

int timer_shutdown_sync(struct timer_list *timer)

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 pending
  • 1 - The timer was pending

High-resolution timers #

ktime_set() #

ktime_t ktime_set(const s64 secs, const unsigned long nsecs)

Set a ktime_t variable from a seconds/nanoseconds value

Parameters

  • const s64 secs: seconds to set
  • const unsigned long nsecs: nanoseconds to set

Return

The ktime_t representation of the value.

ktime_compare() #

int ktime_compare(const ktime_t cmp1, const ktime_t cmp2)

Compares two ktime_t variables for less, greater or equal

Parameters

  • const ktime_t cmp1: comparable1
  • const ktime_t cmp2: comparable2

Return

... cmp1 < cmp2: return <0 cmp1 == cmp2: return 0 cmp1 > cmp2: return >0

ktime_after() #

bool ktime_after(const ktime_t cmp1, const ktime_t cmp2)

Compare if a ktime_t value is bigger than another one.

Parameters

  • const ktime_t cmp1: comparable1
  • const ktime_t cmp2: comparable2

Return

true if cmp1 happened after cmp2.

ktime_before() #

bool ktime_before(const ktime_t cmp1, const ktime_t cmp2)

Compare if a ktime_t value is smaller than another one.

Parameters

  • const ktime_t cmp1: comparable1
  • const ktime_t cmp2: comparable2

Return

true if cmp1 happened before cmp2.

ktime_to_timespec64_cond() #

bool ktime_to_timespec64_cond(const ktime_t kt, struct timespec64 *ts)

convert a ktime_t variable to timespec64 format only if the variable contains data

Parameters

  • const ktime_t kt: the ktime_t variable to convert
  • struct 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

struct hrtimer_sleeper {
    struct hrtimer timer;
    struct task_struct *task;
};

Members

  • timer: embedded timer structure
  • task: task to wake up

Description

task is set to NULL, when the timer expires.

hrtimer_start() #

void hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)

(re)start an hrtimer

Parameters

  • struct hrtimer *timer: the timer to be added
  • ktime_t tim: expiry time
  • const 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 hrtimer_get_remaining(const struct hrtimer *timer)

get remaining time for the timer

Parameters

  • const struct hrtimer *timer: the timer to read

hrtimer_is_queued() #

bool hrtimer_is_queued(struct hrtimer *timer)

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 hrtimer_update_function(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *))

Update the timer's callback function

Parameters

  • struct hrtimer *timer: Timer to update
  • enum 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 hrtimer_forward_now(struct hrtimer *timer, ktime_t interval)

forward the timer expiry so it expires after now

Parameters

  • struct hrtimer *timer: hrtimer to forward
  • ktime_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 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)

forward the timer expiry

Parameters

  • struct hrtimer *timer: hrtimer to forward
  • ktime_t now: forward past this time
  • ktime_t interval: the interval to forward

Description

Forward the timer expiry so it will expire in the future.

Note

This only updates the timer expiry value and does not requeue the timer.

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 hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns, const enum hrtimer_mode mode)

(re)start an hrtimer

Parameters

  • struct hrtimer *timer: the timer to be added
  • ktime_t tim: expiry time
  • u64 delta_ns: "slack" range for the timer
  • const 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 hrtimer_try_to_cancel(struct hrtimer *timer)

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 hrtimer_cancel(struct hrtimer *timer)

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 __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)

get remaining time for the timer

Parameters

  • const struct hrtimer *timer: the timer to read
  • bool adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y

hrtimer_setup() #

void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), clockid_t clock_id, enum hrtimer_mode mode)

initialize a timer to the given clock

Parameters

  • struct hrtimer *timer: the timer to be initialized
  • enum hrtimer_restart (*function)(struct hrtimer *): the callback function
  • clockid_t clock_id: the clock to be used
  • enum 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 hrtimer_setup_on_stack(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), clockid_t clock_id, enum hrtimer_mode mode)

initialize a timer on stack memory

Parameters

  • struct hrtimer *timer: The timer to be initialized
  • enum hrtimer_restart (*function)(struct hrtimer *): the callback function
  • clockid_t clock_id: The clock to be used
  • enum 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 hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl, enum hrtimer_mode mode)

Start a hrtimer sleeper timer

Parameters

  • struct hrtimer_sleeper *sl: sleeper to be started
  • enum 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 hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl, clockid_t clock_id, enum hrtimer_mode mode)

initialize a sleeper in stack memory

Parameters

  • struct hrtimer_sleeper *sl: sleeper to be initialized
  • clockid_t clock_id: the clock to be used
  • enum hrtimer_mode mode: timer mode abs/rel

Wait queues and Wake events #

waitqueue_active() #

int waitqueue_active(struct wait_queue_head *wq_head)
  • 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 wq_has_single_sleeper(struct wait_queue_head *wq_head)

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 wq_has_sleeper(struct wait_queue_head *wq_head)

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 wake_up_pollfree(struct wait_queue_head *wq_head)

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() #

wait_event(wq_head, condition)

sleep until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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() #

wait_event_freezable(wq_head, condition)

sleep (or freeze) until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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() #

wait_event_timeout(wq_head, condition, timeout)

sleep until a condition gets true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_cmd(wq_head, condition, cmd1, cmd2)

sleep until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • cmd1: the command will be executed before sleep
  • cmd2: 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() #

wait_event_interruptible(wq_head, condition)

sleep until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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() #

wait_event_interruptible_timeout(wq_head, condition, timeout)

sleep until a condition gets true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_hrtimeout(wq_head, condition, timeout)

sleep until a condition gets true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_interruptible_hrtimeout(wq, condition, timeout)

sleep until a condition gets true or a timeout elapses

Parameters

  • wq: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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_event_idle(wq_head, condition)

wait for a condition without contributing to system load

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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_event_idle_exclusive(wq_head, condition)

wait for a condition with contributing to system load

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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() #

wait_event_idle_timeout(wq_head, condition, timeout)

sleep without load until a condition becomes true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_idle_exclusive_timeout(wq_head, condition, timeout)

sleep without load until a condition becomes true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_interruptible_locked(wq, condition)

sleep until a condition gets true

Parameters

  • wq: the waitqueue to wait on
  • condition: 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() #

wait_event_interruptible_locked_irq(wq, condition)

sleep until a condition gets true

Parameters

  • wq: the waitqueue to wait on
  • condition: 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() #

wait_event_interruptible_exclusive_locked(wq, condition)

sleep exclusively until a condition gets true

Parameters

  • wq: the waitqueue to wait on
  • condition: 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() #

wait_event_interruptible_exclusive_locked_irq(wq, condition)

sleep until a condition gets true

Parameters

  • wq: the waitqueue to wait on
  • condition: 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() #

wait_event_killable(wq_head, condition)

sleep until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: 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() #

wait_event_state(wq_head, condition, state)

sleep until a condition gets true

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • state: 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() #

wait_event_killable_timeout(wq_head, condition, timeout)

sleep until a condition gets true or a timeout elapses

Parameters

  • wq_head: the waitqueue to wait on
  • condition: a C expression for the event to wait for
  • timeout: 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() #

wait_event_lock_irq_cmd(wq_head, condition, lock, 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 on
  • condition: a C expression for the event to wait for
  • lock: a locked spinlock_t, which will be released before cmd and schedule() 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() #

wait_event_lock_irq(wq_head, condition, lock)

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 on
  • condition: a C expression for the event to wait for
  • lock: a locked spinlock_t, which will be released before schedule() 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() #

wait_event_interruptible_lock_irq_cmd(wq_head, condition, lock, 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 on
  • condition: a C expression for the event to wait for
  • lock: a locked spinlock_t, which will be released before cmd and schedule() 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() #

wait_event_interruptible_lock_irq(wq_head, condition, lock)

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 on
  • condition: a C expression for the event to wait for
  • lock: a locked spinlock_t, which will be released before schedule() 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() #

wait_event_interruptible_lock_irq_timeout(wq_head, condition, lock, 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 on
  • condition: a C expression for the event to wait for
  • lock: a locked spinlock_t, which will be released before schedule() 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(struct wait_queue_head *wq_head, unsigned int mode, int nr_exclusive, void *key)

wake up threads blocked on a waitqueue.

Parameters

  • struct wait_queue_head *wq_head: the waitqueue
  • unsigned int mode: which threads
  • int nr_exclusive: how many wake-one or wake-many threads to wake up
  • void *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_sync_key(struct wait_queue_head *wq_head, unsigned int mode, void *key)

wake up threads blocked on a waitqueue.

Parameters

  • struct wait_queue_head *wq_head: the waitqueue
  • unsigned int mode: which threads
  • void *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_locked_sync_key(struct wait_queue_head *wq_head, unsigned int mode, void *key)

wake up a thread blocked on a locked waitqueue.

Parameters

  • struct wait_queue_head *wq_head: the waitqueue
  • unsigned int mode: which threads
  • void *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 finish_wait(struct wait_queue_head *wq_head, struct wait_queue_entry *wq_entry)

clean up after waiting in a queue

Parameters

  • struct wait_queue_head *wq_head: waitqueue waited on
  • struct 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_task_stopped(struct wait_opts *wo, int ptrace, struct task_struct *p)

Wait for TASK_STOPPED or TASK_TRACED

Parameters

  • struct wait_opts *wo: wait options
  • int ptrace: is the wait for ptrace
  • struct 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 task_set_jobctl_pending(struct task_struct *task, unsigned long mask)

set jobctl pending bits

Parameters

  • struct task_struct *task: target task
  • unsigned 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 task_clear_jobctl_trapping(struct task_struct *task)

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 task_clear_jobctl_pending(struct task_struct *task, unsigned long mask)

clear jobctl pending bits

Parameters

  • struct task_struct *task: target task
  • unsigned 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 task_participate_group_stop(struct task_struct *task)

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 ptrace_trap_notify(struct task_struct *t)

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 force_sig_seccomp(int syscall, int reason, bool force_coredump)

signals the task to allow in-process syscall emulation

Parameters

  • int syscall: syscall number to send to userland
  • int 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 do_notify_parent_cldstop(struct task_struct *tsk, bool for_ptracer, int why)

notify parent of stopped/continued state change

Parameters

  • struct task_struct *tsk: task reporting the state change
  • bool for_ptracer: the notification is for ptracer
  • int 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 do_signal_stop(int signr)

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 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 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 signal_delivered(struct ksignal *ksig, int stepping)

called after signal delivery to update blocked signals

Parameters

  • struct ksignal *ksig: kernel signal struct
  • int 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 sys_restart_syscall(void)

restart a system call

Parameters

  • void: no arguments

set_current_blocked() #

void set_current_blocked(sigset_t *newset)

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 sys_rt_sigprocmask(int how, sigset_t __user * nset, sigset_t __user * oset, size_t sigsetsize)

change the list of currently blocked signals

Parameters

  • int how: whether to add, remove, or set signals
  • sigset_t __user * nset: stores pending signals
  • sigset_t __user * oset: previous value of signal mask if non-null
  • size_t sigsetsize: size of sigset_t type

sys_rt_sigpending() #

long sys_rt_sigpending(sigset_t __user * uset, size_t sigsetsize)

examine a pending signal that has been raised while blocked

Parameters

  • sigset_t __user * uset: stores pending signals
  • size_t sigsetsize: size of sigset_t type or larger

copy_siginfo_to_external32() #

void copy_siginfo_to_external32(struct compat_siginfo *to, const struct kernel_siginfo *from)

copy a kernel siginfo into a compat user siginfo

Parameters

  • struct compat_siginfo *to: compat siginfo destination
  • const 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 do_sigtimedwait(const sigset_t *which, kernel_siginfo_t *info, const struct timespec64 *ts)

wait for queued signals specified in which

Parameters

  • const sigset_t *which: queued signals to wait for
  • kernel_siginfo_t *info: if non-null, the signal's siginfo is returned here
  • const struct timespec64 *ts: upper bound on process time suspension

sys_rt_sigtimedwait() #

long sys_rt_sigtimedwait(const sigset_t __user * uthese, siginfo_t __user * uinfo, const struct __kernel_timespec __user * uts, size_t sigsetsize)

synchronously wait for queued signals specified in uthese

Parameters

  • const sigset_t __user * uthese: queued signals to wait for
  • siginfo_t __user * uinfo: if non-null, the signal's siginfo is returned here
  • const struct __kernel_timespec __user * uts: upper bound on process time suspension
  • size_t sigsetsize: size of sigset_t type

sys_kill() #

long sys_kill(pid_t pid, int sig)

send a signal to a process

Parameters

  • pid_t pid: the PID of the process
  • int sig: signal to be sent

sys_pidfd_send_signal() #

long sys_pidfd_send_signal(int pidfd, int sig, siginfo_t __user * info, unsigned int flags)

Signal a process through a pidfd

Parameters

  • int pidfd: file descriptor of the process
  • int sig: signal to send
  • siginfo_t __user * info: signal info
  • unsigned 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 sys_tgkill(pid_t tgid, pid_t pid, int sig)

send signal to one specific thread

Parameters

  • pid_t tgid: the thread group ID of the thread
  • pid_t pid: the PID of the thread
  • int 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 sys_tkill(pid_t pid, int sig)

send signal to one specific task

Parameters

  • pid_t pid: the PID of the task
  • int 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 sys_rt_sigqueueinfo(pid_t pid, int sig, siginfo_t __user * uinfo)

send signal information to a signal

Parameters

  • pid_t pid: the PID of the thread
  • int sig: signal to be sent
  • siginfo_t __user * uinfo: signal info to be sent

sys_sigpending() #

long sys_sigpending(old_sigset_t __user * uset)

examine pending signals

Parameters

  • old_sigset_t __user * uset: where mask of pending signal is returned

sys_sigprocmask() #

long sys_sigprocmask(int how, old_sigset_t __user * nset, old_sigset_t __user * oset)

examine and change blocked signals

Parameters

  • int how: whether to add, remove, or set signals
  • old_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 sys_rt_sigaction(int sig, const struct sigaction __user * act, struct sigaction __user * oact, size_t sigsetsize)

alter an action taken by a process

Parameters

  • int sig: signal to be sent
  • const struct sigaction __user * act: new sigaction
  • struct sigaction __user * oact: used to save the previous sigaction
  • size_t sigsetsize: size of sigset_t type

sys_rt_sigsuspend() #

long sys_rt_sigsuspend(sigset_t __user * unewset, size_t sigsetsize)

replace the signal mask for a value with the unewset value until a signal is received

Parameters

  • sigset_t __user * unewset: new signal mask value
  • size_t sigsetsize: size of sigset_t type

kthread_create() #

kthread_create(threadfn, data, namefmt, arg...)

create a kthread on the current node

Parameters

  • threadfn: the function to run in the thread
  • data: data pointer for threadfn()
  • namefmt: printf-style format string for the thread name
  • arg...: 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() #

kthread_run(threadfn, data, namefmt, ...)

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 * kthread_run_on_cpu(int (*threadfn)(void *data), void *data, unsigned int cpu, const char *namefmt)

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() #

kthread_run_worker(flags, namefmt, ...)

create and wake a kthread worker.

Parameters

  • flags: flags modifying the default behavior of the worker
  • namefmt: 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 * kthread_run_worker_on_cpu(int cpu, unsigned int flags, const char namefmt[])

create and wake a cpu bound kthread worker.

Parameters

  • int cpu: CPU number
  • unsigned int flags: flags modifying the default behavior of the worker
  • 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_worker_on_cpu() followed by wake_up_process(). Returns the kthread_worker or ERR_PTR(-ENOMEM).

kthread_should_stop() #

bool kthread_should_stop(void)

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 kthread_should_park(void)

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 kthread_freezable_should_stop(bool *was_frozen)

should this freezable kthread return now?

Parameters

  • bool *was_frozen: optional out parameter, indicates whether current was 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 * kthread_func(struct task_struct *task)

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 * kthread_data(struct task_struct *task)

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 kthread_complete_and_exit(struct completion *comp, long code)

Exit the current kthread.

Parameters

  • struct completion *comp: Completion to complete
  • long code: The integer value to return to kthread_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 * kthread_create_on_node(int (*threadfn)(void *data), void *data, int node, const char namefmt[], ...)

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 node
  • const 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 kthread_bind(struct task_struct *p, unsigned int cpu)

bind a just-created kthread to a cpu.

Parameters

  • struct task_struct *p: thread created by kthread_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 * kthread_create_on_cpu(int (*threadfn)(void *data), void *data, unsigned int cpu, const char *namefmt)

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 kthread_unpark(struct task_struct *k)

unpark a thread created by kthread_create().

Parameters

  • struct task_struct *k: thread created by kthread_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 kthread_park(struct task_struct *k)

park a thread created by kthread_create().

Parameters

  • struct task_struct *k: thread created by kthread_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 kthread_stop(struct task_struct *k)

stop a thread created by kthread_create().

Parameters

  • struct task_struct *k: thread created by kthread_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 kthread_stop_put(struct task_struct *k)

stop a thread and put its task struct

Parameters

  • struct task_struct *k: thread created by kthread_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 kthread_affine_preferred(struct task_struct *p, const struct cpumask *mask)

Define a kthread's preferred affinity

Parameters

  • struct task_struct *p: thread created by kthread_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_worker_fn(void *worker_ptr)

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 * kthread_create_worker_on_node(unsigned int flags, int node, const char namefmt[], ...)

create a kthread worker

Parameters

  • unsigned int flags: flags modifying the default behavior of the worker
  • int node: task structure for the thread is allocated on this node
  • const 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 * kthread_create_worker_on_cpu(int cpu, unsigned int flags, const char namefmt[])

create a kthread worker and bind it to a given CPU and the associated NUMA node.

Parameters

  • int cpu: CPU number
  • unsigned int flags: flags modifying the default behavior of the worker
  • const 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 kthread_queue_work(struct kthread_worker *worker, struct kthread_work *work)

queue a kthread_work

Parameters

  • struct kthread_worker *worker: target kthread_worker
  • struct 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 kthread_delayed_work_timer_fn(struct timer_list *t)

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 kthread_queue_delayed_work(struct kthread_worker *worker, struct kthread_delayed_work *dwork, unsigned long delay)

queue the associated kthread work after a delay.

Parameters

  • struct kthread_worker *worker: target kthread_worker
  • struct kthread_delayed_work *dwork: kthread_delayed_work to queue
  • unsigned 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 kthread_flush_work(struct kthread_work *work)

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 kthread_mod_delayed_work(struct kthread_worker *worker, struct kthread_delayed_work *dwork, unsigned long delay)

modify delay of or queue a kthread delayed work

Parameters

  • struct kthread_worker *worker: kthread worker to use
  • struct kthread_delayed_work *dwork: kthread delayed work to queue
  • unsigned 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 kthread_cancel_work_sync(struct kthread_work *work)

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 kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)

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 kthread_flush_worker(struct kthread_worker *worker)

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 kthread_destroy_worker(struct kthread_worker *worker)

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 kthread_use_mm(struct mm_struct *mm)

make the calling kthread operate on an address space

Parameters

  • struct mm_struct *mm: address space to operate on

kthread_unuse_mm() #

void kthread_unuse_mm(struct mm_struct *mm)

reverse the effect of kthread_use_mm()

Parameters

  • struct mm_struct *mm: address space to operate on

kthread_associate_blkcg() #

void kthread_associate_blkcg(struct cgroup_subsys_state *css)

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 refcount_set(refcount_t *r, int n)

set a refcount's value

Parameters

  • refcount_t *r: the refcount
  • int n: value to which the refcount will be set

refcount_set_release() #

void refcount_set_release(refcount_t *r, int n)

set a refcount's value with release ordering

Parameters

  • refcount_t *r: the refcount
  • int 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 refcount_read(const refcount_t *r)

get a refcount's value

Parameters

  • const refcount_t *r: the refcount

Return

the refcount's value

refcount_add_not_zero() #

bool refcount_add_not_zero(int i, refcount_t *r)

add a value to a refcount unless it is 0

Parameters

  • int i: the value to add to the refcount
  • refcount_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 refcount_add_not_zero_acquire(int i, refcount_t *r)

add a value to a refcount with acquire ordering unless it is 0

Parameters

  • int i: the value to add to the refcount
  • refcount_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 refcount_add(int i, refcount_t *r)

add a value to a refcount

Parameters

  • int i: the value to add to the refcount
  • refcount_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 refcount_inc_not_zero(refcount_t *r)

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 refcount_inc_not_zero_acquire(refcount_t *r)

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 refcount_inc(refcount_t *r)

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 refcount_sub_and_test(int i, refcount_t *r)

subtract from a refcount and test if it is 0

Parameters

  • int i: amount to subtract from the refcount
  • refcount_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 refcount_dec_and_test(refcount_t *r)

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 refcount_dec(refcount_t *r)

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 refcount_dec_if_one(refcount_t *r)

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 refcount_dec_not_one(refcount_t *r)

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 refcount_dec_and_mutex_lock(refcount_t *r, struct mutex *lock)

return holding mutex if able to decrement refcount to 0

Parameters

  • refcount_t *r: the refcount
  • struct 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 refcount_dec_and_lock(refcount_t *r, spinlock_t *lock)

return holding spinlock if able to decrement refcount to 0

Parameters

  • refcount_t *r: the refcount
  • spinlock_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 refcount_dec_and_lock_irqsave(refcount_t *r, spinlock_t *lock, unsigned long *flags)

return holding spinlock with disabled interrupts if able to decrement refcount to 0

Parameters

  • refcount_t *r: the refcount
  • spinlock_t *lock: the spinlock to be locked
  • unsigned 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_read(const atomic_t *v)

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_read_acquire(const atomic_t *v)

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(atomic_t *v, int i)

atomic set with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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_release(atomic_t *v, int i)

atomic set with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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_return(int i, atomic_t *v)

atomic add with full ordering

Parameters

  • int i: int value to add
  • atomic_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_return_acquire(int i, atomic_t *v)

atomic add with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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_return_release(int i, atomic_t *v)

atomic add with release ordering

Parameters

  • int i: int value to add
  • atomic_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_return_relaxed(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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_fetch_add(int i, atomic_t *v)

atomic add with full ordering

Parameters

  • int i: int value to add
  • atomic_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_fetch_add_acquire(int i, atomic_t *v)

atomic add with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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_fetch_add_release(int i, atomic_t *v)

atomic add with release ordering

Parameters

  • int i: int value to add
  • atomic_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_fetch_add_relaxed(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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_sub(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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_sub_return(int i, atomic_t *v)

atomic subtract with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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_sub_return_acquire(int i, atomic_t *v)

atomic subtract with acquire ordering

Parameters

  • int i: int value to subtract
  • atomic_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_sub_return_release(int i, atomic_t *v)

atomic subtract with release ordering

Parameters

  • int i: int value to subtract
  • atomic_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_sub_return_relaxed(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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_fetch_sub(int i, atomic_t *v)

atomic subtract with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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_fetch_sub_acquire(int i, atomic_t *v)

atomic subtract with acquire ordering

Parameters

  • int i: int value to subtract
  • atomic_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_fetch_sub_release(int i, atomic_t *v)

atomic subtract with release ordering

Parameters

  • int i: int value to subtract
  • atomic_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_fetch_sub_relaxed(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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_inc(atomic_t *v)

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_inc_return(atomic_t *v)

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_inc_return_acquire(atomic_t *v)

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_inc_return_release(atomic_t *v)

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_inc_return_relaxed(atomic_t *v)

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_fetch_inc(atomic_t *v)

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_fetch_inc_acquire(atomic_t *v)

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_fetch_inc_release(atomic_t *v)

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_fetch_inc_relaxed(atomic_t *v)

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_dec(atomic_t *v)

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_dec_return(atomic_t *v)

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_dec_return_acquire(atomic_t *v)

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_dec_return_release(atomic_t *v)

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_dec_return_relaxed(atomic_t *v)

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_fetch_dec(atomic_t *v)

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_fetch_dec_acquire(atomic_t *v)

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_fetch_dec_release(atomic_t *v)

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_fetch_dec_relaxed(atomic_t *v)

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_and(int i, atomic_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_fetch_and(int i, atomic_t *v)

atomic bitwise AND with full ordering

Parameters

  • int i: int value
  • atomic_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_fetch_and_acquire(int i, atomic_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • int i: int value
  • atomic_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_fetch_and_release(int i, atomic_t *v)

atomic bitwise AND with release ordering

Parameters

  • int i: int value
  • atomic_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_fetch_and_relaxed(int i, atomic_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_andnot(int i, atomic_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_fetch_andnot(int i, atomic_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • int i: int value
  • atomic_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_fetch_andnot_acquire(int i, atomic_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • int i: int value
  • atomic_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_fetch_andnot_release(int i, atomic_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • int i: int value
  • atomic_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_fetch_andnot_relaxed(int i, atomic_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_or(int i, atomic_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_fetch_or(int i, atomic_t *v)

atomic bitwise OR with full ordering

Parameters

  • int i: int value
  • atomic_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_fetch_or_acquire(int i, atomic_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • int i: int value
  • atomic_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_fetch_or_release(int i, atomic_t *v)

atomic bitwise OR with release ordering

Parameters

  • int i: int value
  • atomic_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_fetch_or_relaxed(int i, atomic_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_xor(int i, atomic_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_fetch_xor(int i, atomic_t *v)

atomic bitwise XOR with full ordering

Parameters

  • int i: int value
  • atomic_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_fetch_xor_acquire(int i, atomic_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • int i: int value
  • atomic_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_fetch_xor_release(int i, atomic_t *v)

atomic bitwise XOR with release ordering

Parameters

  • int i: int value
  • atomic_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_fetch_xor_relaxed(int i, atomic_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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_xchg(atomic_t *v, int new)

atomic exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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_xchg_acquire(atomic_t *v, int new)

atomic exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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_xchg_release(atomic_t *v, int new)

atomic exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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_xchg_relaxed(atomic_t *v, int new)

atomic exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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_cmpxchg(atomic_t *v, int old, int new)

atomic compare and exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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_cmpxchg_acquire(atomic_t *v, int old, int new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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_cmpxchg_release(atomic_t *v, int old, int new)

atomic compare and exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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_cmpxchg_relaxed(atomic_t *v, int old, int new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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_try_cmpxchg(atomic_t *v, int *old, int new)

atomic compare and exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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_try_cmpxchg_acquire(atomic_t *v, int *old, int new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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_try_cmpxchg_release(atomic_t *v, int *old, int new)

atomic compare and exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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_try_cmpxchg_relaxed(atomic_t *v, int *old, int new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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_sub_and_test(int i, atomic_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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_dec_and_test(atomic_t *v)

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_inc_and_test(atomic_t *v)

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_negative(int i, atomic_t *v)

atomic add and test if negative with full ordering

Parameters

  • int i: int value to add
  • atomic_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_negative_acquire(int i, atomic_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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_negative_release(int i, atomic_t *v)

atomic add and test if negative with release ordering

Parameters

  • int i: int value to add
  • atomic_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_negative_relaxed(int i, atomic_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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_fetch_add_unless(atomic_t *v, int a, int u)

atomic add unless value with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int a: int value to add
  • int 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(atomic_t *v, int a, int u)

atomic add unless value with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int a: int value to add
  • int 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_inc_not_zero(atomic_t *v)

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_inc_unless_negative(atomic_t *v)

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_dec_unless_positive(atomic_t *v)

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_dec_if_positive(atomic_t *v)

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 atomic64_read(const atomic64_t *v)

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 atomic64_read_acquire(const atomic64_t *v)

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 atomic64_set(atomic64_t *v, s64 i)

atomic set with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_set_release(atomic64_t *v, s64 i)

atomic set with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_add(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_return(s64 i, atomic64_t *v)

atomic add with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_return_acquire(s64 i, atomic64_t *v)

atomic add with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_return_release(s64 i, atomic64_t *v)

atomic add with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_return_relaxed(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_fetch_add(s64 i, atomic64_t *v)

atomic add with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_fetch_add_acquire(s64 i, atomic64_t *v)

atomic add with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_fetch_add_release(s64 i, atomic64_t *v)

atomic add with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_fetch_add_relaxed(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_sub(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_sub_return(s64 i, atomic64_t *v)

atomic subtract with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_sub_return_acquire(s64 i, atomic64_t *v)

atomic subtract with acquire ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_sub_return_release(s64 i, atomic64_t *v)

atomic subtract with release ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_sub_return_relaxed(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_fetch_sub(s64 i, atomic64_t *v)

atomic subtract with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_fetch_sub_acquire(s64 i, atomic64_t *v)

atomic subtract with acquire ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_fetch_sub_release(s64 i, atomic64_t *v)

atomic subtract with release ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_fetch_sub_relaxed(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_inc(atomic64_t *v)

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 atomic64_inc_return(atomic64_t *v)

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 atomic64_inc_return_acquire(atomic64_t *v)

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 atomic64_inc_return_release(atomic64_t *v)

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 atomic64_inc_return_relaxed(atomic64_t *v)

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 atomic64_fetch_inc(atomic64_t *v)

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 atomic64_fetch_inc_acquire(atomic64_t *v)

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 atomic64_fetch_inc_release(atomic64_t *v)

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 atomic64_fetch_inc_relaxed(atomic64_t *v)

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 atomic64_dec(atomic64_t *v)

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 atomic64_dec_return(atomic64_t *v)

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 atomic64_dec_return_acquire(atomic64_t *v)

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 atomic64_dec_return_release(atomic64_t *v)

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 atomic64_dec_return_relaxed(atomic64_t *v)

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 atomic64_fetch_dec(atomic64_t *v)

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 atomic64_fetch_dec_acquire(atomic64_t *v)

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 atomic64_fetch_dec_release(atomic64_t *v)

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 atomic64_fetch_dec_relaxed(atomic64_t *v)

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 atomic64_and(s64 i, atomic64_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_and(s64 i, atomic64_t *v)

atomic bitwise AND with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_and_acquire(s64 i, atomic64_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_and_release(s64 i, atomic64_t *v)

atomic bitwise AND with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_and_relaxed(s64 i, atomic64_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_andnot(s64 i, atomic64_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_andnot(s64 i, atomic64_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_andnot_acquire(s64 i, atomic64_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_andnot_release(s64 i, atomic64_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_andnot_relaxed(s64 i, atomic64_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_or(s64 i, atomic64_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_or(s64 i, atomic64_t *v)

atomic bitwise OR with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_or_acquire(s64 i, atomic64_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_or_release(s64 i, atomic64_t *v)

atomic bitwise OR with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_or_relaxed(s64 i, atomic64_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_xor(s64 i, atomic64_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_xor(s64 i, atomic64_t *v)

atomic bitwise XOR with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_xor_acquire(s64 i, atomic64_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_xor_release(s64 i, atomic64_t *v)

atomic bitwise XOR with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_fetch_xor_relaxed(s64 i, atomic64_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 atomic64_xchg(atomic64_t *v, s64 new)

atomic exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_xchg_acquire(atomic64_t *v, s64 new)

atomic exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_xchg_release(atomic64_t *v, s64 new)

atomic exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_xchg_relaxed(atomic64_t *v, s64 new)

atomic exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 atomic64_cmpxchg(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 atomic64_cmpxchg_acquire(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 atomic64_cmpxchg_release(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 atomic64_cmpxchg_relaxed(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 atomic64_try_cmpxchg(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 atomic64_try_cmpxchg_acquire(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 atomic64_try_cmpxchg_release(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 atomic64_try_cmpxchg_relaxed(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 atomic64_sub_and_test(s64 i, atomic64_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 atomic64_dec_and_test(atomic64_t *v)

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 atomic64_inc_and_test(atomic64_t *v)

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 atomic64_add_negative(s64 i, atomic64_t *v)

atomic add and test if negative with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_negative_acquire(s64 i, atomic64_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_negative_release(s64 i, atomic64_t *v)

atomic add and test if negative with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_add_negative_relaxed(s64 i, atomic64_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u)

atomic add unless value with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 a: s64 value to add
  • s64 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 atomic64_add_unless(atomic64_t *v, s64 a, s64 u)

atomic add unless value with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 a: s64 value to add
  • s64 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 atomic64_inc_not_zero(atomic64_t *v)

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 atomic64_inc_unless_negative(atomic64_t *v)

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 atomic64_dec_unless_positive(atomic64_t *v)

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 atomic64_dec_if_positive(atomic64_t *v)

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_long_read(const atomic_long_t *v)

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_long_read_acquire(const atomic_long_t *v)

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_long_set(atomic_long_t *v, long i)

atomic set with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_set_release(atomic_long_t *v, long i)

atomic set with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_add(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_return(long i, atomic_long_t *v)

atomic add with full ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_return_acquire(long i, atomic_long_t *v)

atomic add with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_return_release(long i, atomic_long_t *v)

atomic add with release ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_return_relaxed(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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_long_fetch_add(long i, atomic_long_t *v)

atomic add with full ordering

Parameters

  • long i: long value to add
  • atomic_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_long_fetch_add_acquire(long i, atomic_long_t *v)

atomic add with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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_long_fetch_add_release(long i, atomic_long_t *v)

atomic add with release ordering

Parameters

  • long i: long value to add
  • atomic_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_long_fetch_add_relaxed(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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_long_sub(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_sub_return(long i, atomic_long_t *v)

atomic subtract with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_sub_return_acquire(long i, atomic_long_t *v)

atomic subtract with acquire ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_sub_return_release(long i, atomic_long_t *v)

atomic subtract with release ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_sub_return_relaxed(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_fetch_sub(long i, atomic_long_t *v)

atomic subtract with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_fetch_sub_acquire(long i, atomic_long_t *v)

atomic subtract with acquire ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_fetch_sub_release(long i, atomic_long_t *v)

atomic subtract with release ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_fetch_sub_relaxed(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_inc(atomic_long_t *v)

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_long_inc_return(atomic_long_t *v)

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_long_inc_return_acquire(atomic_long_t *v)

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_long_inc_return_release(atomic_long_t *v)

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_long_inc_return_relaxed(atomic_long_t *v)

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_long_fetch_inc(atomic_long_t *v)

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_long_fetch_inc_acquire(atomic_long_t *v)

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_long_fetch_inc_release(atomic_long_t *v)

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_long_fetch_inc_relaxed(atomic_long_t *v)

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_long_dec(atomic_long_t *v)

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_long_dec_return(atomic_long_t *v)

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_long_dec_return_acquire(atomic_long_t *v)

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_long_dec_return_release(atomic_long_t *v)

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_long_dec_return_relaxed(atomic_long_t *v)

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_long_fetch_dec(atomic_long_t *v)

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_long_fetch_dec_acquire(atomic_long_t *v)

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_long_fetch_dec_release(atomic_long_t *v)

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_long_fetch_dec_relaxed(atomic_long_t *v)

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_long_and(long i, atomic_long_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_and(long i, atomic_long_t *v)

atomic bitwise AND with full ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_and_acquire(long i, atomic_long_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_and_release(long i, atomic_long_t *v)

atomic bitwise AND with release ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_and_relaxed(long i, atomic_long_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_andnot(long i, atomic_long_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_andnot(long i, atomic_long_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_andnot_acquire(long i, atomic_long_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_andnot_release(long i, atomic_long_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_andnot_relaxed(long i, atomic_long_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_or(long i, atomic_long_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_or(long i, atomic_long_t *v)

atomic bitwise OR with full ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_or_acquire(long i, atomic_long_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_or_release(long i, atomic_long_t *v)

atomic bitwise OR with release ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_or_relaxed(long i, atomic_long_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_xor(long i, atomic_long_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_xor(long i, atomic_long_t *v)

atomic bitwise XOR with full ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_xor_acquire(long i, atomic_long_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_xor_release(long i, atomic_long_t *v)

atomic bitwise XOR with release ordering

Parameters

  • long i: long value
  • atomic_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_long_fetch_xor_relaxed(long i, atomic_long_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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_long_xchg(atomic_long_t *v, long new)

atomic exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_xchg_acquire(atomic_long_t *v, long new)

atomic exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_xchg_release(atomic_long_t *v, long new)

atomic exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_xchg_relaxed(atomic_long_t *v, long new)

atomic exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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_long_cmpxchg(atomic_long_t *v, long old, long new)

atomic compare and exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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_long_cmpxchg_acquire(atomic_long_t *v, long old, long new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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_long_cmpxchg_release(atomic_long_t *v, long old, long new)

atomic compare and exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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_long_cmpxchg_relaxed(atomic_long_t *v, long old, long new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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_long_try_cmpxchg(atomic_long_t *v, long *old, long new)

atomic compare and exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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_long_try_cmpxchg_acquire(atomic_long_t *v, long *old, long new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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_long_try_cmpxchg_release(atomic_long_t *v, long *old, long new)

atomic compare and exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old, long new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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_long_sub_and_test(long i, atomic_long_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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_long_dec_and_test(atomic_long_t *v)

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_long_inc_and_test(atomic_long_t *v)

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_long_add_negative(long i, atomic_long_t *v)

atomic add and test if negative with full ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_negative_acquire(long i, atomic_long_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_negative_release(long i, atomic_long_t *v)

atomic add and test if negative with release ordering

Parameters

  • long i: long value to add
  • atomic_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_long_add_negative_relaxed(long i, atomic_long_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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_long_fetch_add_unless(atomic_long_t *v, long a, long u)

atomic add unless value with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long a: long value to add
  • long 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_long_add_unless(atomic_long_t *v, long a, long u)

atomic add unless value with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long a: long value to add
  • long 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_long_inc_not_zero(atomic_long_t *v)

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_long_inc_unless_negative(atomic_long_t *v)

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_long_dec_unless_positive(atomic_long_t *v)

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_long_dec_if_positive(atomic_long_t *v)

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 raw_atomic_read(const atomic_t *v)

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 raw_atomic_read_acquire(const atomic_t *v)

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 raw_atomic_set(atomic_t *v, int i)

atomic set with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_set_release(atomic_t *v, int i)

atomic set with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_add(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_return(int i, atomic_t *v)

atomic add with full ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_return_acquire(int i, atomic_t *v)

atomic add with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_return_release(int i, atomic_t *v)

atomic add with release ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_return_relaxed(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_fetch_add(int i, atomic_t *v)

atomic add with full ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_fetch_add_acquire(int i, atomic_t *v)

atomic add with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_fetch_add_release(int i, atomic_t *v)

atomic add with release ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_fetch_add_relaxed(int i, atomic_t *v)

atomic add with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_sub(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_sub_return(int i, atomic_t *v)

atomic subtract with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_sub_return_acquire(int i, atomic_t *v)

atomic subtract with acquire ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_sub_return_release(int i, atomic_t *v)

atomic subtract with release ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_sub_return_relaxed(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_fetch_sub(int i, atomic_t *v)

atomic subtract with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_fetch_sub_acquire(int i, atomic_t *v)

atomic subtract with acquire ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_fetch_sub_release(int i, atomic_t *v)

atomic subtract with release ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_fetch_sub_relaxed(int i, atomic_t *v)

atomic subtract with relaxed ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_inc(atomic_t *v)

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 raw_atomic_inc_return(atomic_t *v)

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 raw_atomic_inc_return_acquire(atomic_t *v)

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 raw_atomic_inc_return_release(atomic_t *v)

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 raw_atomic_inc_return_relaxed(atomic_t *v)

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 raw_atomic_fetch_inc(atomic_t *v)

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 raw_atomic_fetch_inc_acquire(atomic_t *v)

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 raw_atomic_fetch_inc_release(atomic_t *v)

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 raw_atomic_fetch_inc_relaxed(atomic_t *v)

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 raw_atomic_dec(atomic_t *v)

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 raw_atomic_dec_return(atomic_t *v)

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 raw_atomic_dec_return_acquire(atomic_t *v)

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 raw_atomic_dec_return_release(atomic_t *v)

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 raw_atomic_dec_return_relaxed(atomic_t *v)

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 raw_atomic_fetch_dec(atomic_t *v)

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 raw_atomic_fetch_dec_acquire(atomic_t *v)

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 raw_atomic_fetch_dec_release(atomic_t *v)

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 raw_atomic_fetch_dec_relaxed(atomic_t *v)

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 raw_atomic_and(int i, atomic_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_and(int i, atomic_t *v)

atomic bitwise AND with full ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_and_acquire(int i, atomic_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_and_release(int i, atomic_t *v)

atomic bitwise AND with release ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_and_relaxed(int i, atomic_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_andnot(int i, atomic_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_andnot(int i, atomic_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_andnot_acquire(int i, atomic_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_andnot_release(int i, atomic_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_andnot_relaxed(int i, atomic_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_or(int i, atomic_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_or(int i, atomic_t *v)

atomic bitwise OR with full ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_or_acquire(int i, atomic_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_or_release(int i, atomic_t *v)

atomic bitwise OR with release ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_or_relaxed(int i, atomic_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_xor(int i, atomic_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_xor(int i, atomic_t *v)

atomic bitwise XOR with full ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_xor_acquire(int i, atomic_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_xor_release(int i, atomic_t *v)

atomic bitwise XOR with release ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_fetch_xor_relaxed(int i, atomic_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • int i: int value
  • atomic_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 raw_atomic_xchg(atomic_t *v, int new)

atomic exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_xchg_acquire(atomic_t *v, int new)

atomic exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_xchg_release(atomic_t *v, int new)

atomic exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_xchg_relaxed(atomic_t *v, int new)

atomic exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int 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 raw_atomic_cmpxchg(atomic_t *v, int old, int new)

atomic compare and exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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 raw_atomic_cmpxchg_acquire(atomic_t *v, int old, int new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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 raw_atomic_cmpxchg_release(atomic_t *v, int old, int new)

atomic compare and exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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 raw_atomic_cmpxchg_relaxed(atomic_t *v, int old, int new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int old: int value to compare with
  • int 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 raw_atomic_try_cmpxchg(atomic_t *v, int *old, int new)

atomic compare and exchange with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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 raw_atomic_try_cmpxchg_acquire(atomic_t *v, int *old, int new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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 raw_atomic_try_cmpxchg_release(atomic_t *v, int *old, int new)

atomic compare and exchange with release ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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 raw_atomic_try_cmpxchg_relaxed(atomic_t *v, int *old, int new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int *old: pointer to int value to compare with
  • int 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 raw_atomic_sub_and_test(int i, atomic_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • int i: int value to subtract
  • atomic_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 raw_atomic_dec_and_test(atomic_t *v)

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 raw_atomic_inc_and_test(atomic_t *v)

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 raw_atomic_add_negative(int i, atomic_t *v)

atomic add and test if negative with full ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_negative_acquire(int i, atomic_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_negative_release(int i, atomic_t *v)

atomic add and test if negative with release ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_add_negative_relaxed(int i, atomic_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • int i: int value to add
  • atomic_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 raw_atomic_fetch_add_unless(atomic_t *v, int a, int u)

atomic add unless value with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int a: int value to add
  • int 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 raw_atomic_add_unless(atomic_t *v, int a, int u)

atomic add unless value with full ordering

Parameters

  • atomic_t *v: pointer to atomic_t
  • int a: int value to add
  • int 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 raw_atomic_inc_not_zero(atomic_t *v)

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 raw_atomic_inc_unless_negative(atomic_t *v)

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 raw_atomic_dec_unless_positive(atomic_t *v)

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 raw_atomic_dec_if_positive(atomic_t *v)

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 raw_atomic64_read(const atomic64_t *v)

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 raw_atomic64_read_acquire(const atomic64_t *v)

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 raw_atomic64_set(atomic64_t *v, s64 i)

atomic set with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_set_release(atomic64_t *v, s64 i)

atomic set with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_add(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_return(s64 i, atomic64_t *v)

atomic add with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_return_acquire(s64 i, atomic64_t *v)

atomic add with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_return_release(s64 i, atomic64_t *v)

atomic add with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_return_relaxed(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_fetch_add(s64 i, atomic64_t *v)

atomic add with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_fetch_add_acquire(s64 i, atomic64_t *v)

atomic add with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_fetch_add_release(s64 i, atomic64_t *v)

atomic add with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_fetch_add_relaxed(s64 i, atomic64_t *v)

atomic add with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_sub(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_sub_return(s64 i, atomic64_t *v)

atomic subtract with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_sub_return_acquire(s64 i, atomic64_t *v)

atomic subtract with acquire ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_sub_return_release(s64 i, atomic64_t *v)

atomic subtract with release ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_sub_return_relaxed(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_fetch_sub(s64 i, atomic64_t *v)

atomic subtract with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_fetch_sub_acquire(s64 i, atomic64_t *v)

atomic subtract with acquire ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_fetch_sub_release(s64 i, atomic64_t *v)

atomic subtract with release ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_fetch_sub_relaxed(s64 i, atomic64_t *v)

atomic subtract with relaxed ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_inc(atomic64_t *v)

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 raw_atomic64_inc_return(atomic64_t *v)

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 raw_atomic64_inc_return_acquire(atomic64_t *v)

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 raw_atomic64_inc_return_release(atomic64_t *v)

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 raw_atomic64_inc_return_relaxed(atomic64_t *v)

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 raw_atomic64_fetch_inc(atomic64_t *v)

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 raw_atomic64_fetch_inc_acquire(atomic64_t *v)

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 raw_atomic64_fetch_inc_release(atomic64_t *v)

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 raw_atomic64_fetch_inc_relaxed(atomic64_t *v)

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 raw_atomic64_dec(atomic64_t *v)

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 raw_atomic64_dec_return(atomic64_t *v)

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 raw_atomic64_dec_return_acquire(atomic64_t *v)

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 raw_atomic64_dec_return_release(atomic64_t *v)

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 raw_atomic64_dec_return_relaxed(atomic64_t *v)

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 raw_atomic64_fetch_dec(atomic64_t *v)

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 raw_atomic64_fetch_dec_acquire(atomic64_t *v)

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 raw_atomic64_fetch_dec_release(atomic64_t *v)

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 raw_atomic64_fetch_dec_relaxed(atomic64_t *v)

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 raw_atomic64_and(s64 i, atomic64_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_and(s64 i, atomic64_t *v)

atomic bitwise AND with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_and_acquire(s64 i, atomic64_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_and_release(s64 i, atomic64_t *v)

atomic bitwise AND with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_and_relaxed(s64 i, atomic64_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_andnot(s64 i, atomic64_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_andnot(s64 i, atomic64_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_andnot_acquire(s64 i, atomic64_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_andnot_release(s64 i, atomic64_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_andnot_relaxed(s64 i, atomic64_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_or(s64 i, atomic64_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_or(s64 i, atomic64_t *v)

atomic bitwise OR with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_or_acquire(s64 i, atomic64_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_or_release(s64 i, atomic64_t *v)

atomic bitwise OR with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_or_relaxed(s64 i, atomic64_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_xor(s64 i, atomic64_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_xor(s64 i, atomic64_t *v)

atomic bitwise XOR with full ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_xor_acquire(s64 i, atomic64_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_xor_release(s64 i, atomic64_t *v)

atomic bitwise XOR with release ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_fetch_xor_relaxed(s64 i, atomic64_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • s64 i: s64 value
  • atomic64_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 raw_atomic64_xchg(atomic64_t *v, s64 new)

atomic exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_xchg_acquire(atomic64_t *v, s64 new)

atomic exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_xchg_release(atomic64_t *v, s64 new)

atomic exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_xchg_relaxed(atomic64_t *v, s64 new)

atomic exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 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 raw_atomic64_cmpxchg(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 raw_atomic64_cmpxchg_acquire(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 raw_atomic64_cmpxchg_release(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 raw_atomic64_cmpxchg_relaxed(atomic64_t *v, s64 old, s64 new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 old: s64 value to compare with
  • s64 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 raw_atomic64_try_cmpxchg(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 raw_atomic64_try_cmpxchg_acquire(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 raw_atomic64_try_cmpxchg_release(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with release ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 raw_atomic64_try_cmpxchg_relaxed(atomic64_t *v, s64 *old, s64 new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 *old: pointer to s64 value to compare with
  • s64 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 raw_atomic64_sub_and_test(s64 i, atomic64_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • s64 i: s64 value to subtract
  • atomic64_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 raw_atomic64_dec_and_test(atomic64_t *v)

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 raw_atomic64_inc_and_test(atomic64_t *v)

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 raw_atomic64_add_negative(s64 i, atomic64_t *v)

atomic add and test if negative with full ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_negative_acquire(s64 i, atomic64_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_negative_release(s64 i, atomic64_t *v)

atomic add and test if negative with release ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_add_negative_relaxed(s64 i, atomic64_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • s64 i: s64 value to add
  • atomic64_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 raw_atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u)

atomic add unless value with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 a: s64 value to add
  • s64 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 raw_atomic64_add_unless(atomic64_t *v, s64 a, s64 u)

atomic add unless value with full ordering

Parameters

  • atomic64_t *v: pointer to atomic64_t
  • s64 a: s64 value to add
  • s64 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 raw_atomic64_inc_not_zero(atomic64_t *v)

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 raw_atomic64_inc_unless_negative(atomic64_t *v)

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 raw_atomic64_dec_unless_positive(atomic64_t *v)

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 raw_atomic64_dec_if_positive(atomic64_t *v)

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 raw_atomic_long_read(const atomic_long_t *v)

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 raw_atomic_long_read_acquire(const atomic_long_t *v)

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 raw_atomic_long_set(atomic_long_t *v, long i)

atomic set with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_set_release(atomic_long_t *v, long i)

atomic set with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_add(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_return(long i, atomic_long_t *v)

atomic add with full ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_return_acquire(long i, atomic_long_t *v)

atomic add with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_return_release(long i, atomic_long_t *v)

atomic add with release ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_return_relaxed(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_fetch_add(long i, atomic_long_t *v)

atomic add with full ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_fetch_add_acquire(long i, atomic_long_t *v)

atomic add with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_fetch_add_release(long i, atomic_long_t *v)

atomic add with release ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_fetch_add_relaxed(long i, atomic_long_t *v)

atomic add with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_sub(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_sub_return(long i, atomic_long_t *v)

atomic subtract with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_sub_return_acquire(long i, atomic_long_t *v)

atomic subtract with acquire ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_sub_return_release(long i, atomic_long_t *v)

atomic subtract with release ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_sub_return_relaxed(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_fetch_sub(long i, atomic_long_t *v)

atomic subtract with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_fetch_sub_acquire(long i, atomic_long_t *v)

atomic subtract with acquire ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_fetch_sub_release(long i, atomic_long_t *v)

atomic subtract with release ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_fetch_sub_relaxed(long i, atomic_long_t *v)

atomic subtract with relaxed ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_inc(atomic_long_t *v)

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 raw_atomic_long_inc_return(atomic_long_t *v)

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 raw_atomic_long_inc_return_acquire(atomic_long_t *v)

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 raw_atomic_long_inc_return_release(atomic_long_t *v)

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 raw_atomic_long_inc_return_relaxed(atomic_long_t *v)

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 raw_atomic_long_fetch_inc(atomic_long_t *v)

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 raw_atomic_long_fetch_inc_acquire(atomic_long_t *v)

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 raw_atomic_long_fetch_inc_release(atomic_long_t *v)

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 raw_atomic_long_fetch_inc_relaxed(atomic_long_t *v)

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 raw_atomic_long_dec(atomic_long_t *v)

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 raw_atomic_long_dec_return(atomic_long_t *v)

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 raw_atomic_long_dec_return_acquire(atomic_long_t *v)

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 raw_atomic_long_dec_return_release(atomic_long_t *v)

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 raw_atomic_long_dec_return_relaxed(atomic_long_t *v)

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 raw_atomic_long_fetch_dec(atomic_long_t *v)

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 raw_atomic_long_fetch_dec_acquire(atomic_long_t *v)

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 raw_atomic_long_fetch_dec_release(atomic_long_t *v)

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 raw_atomic_long_fetch_dec_relaxed(atomic_long_t *v)

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 raw_atomic_long_and(long i, atomic_long_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_and(long i, atomic_long_t *v)

atomic bitwise AND with full ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_and_acquire(long i, atomic_long_t *v)

atomic bitwise AND with acquire ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_and_release(long i, atomic_long_t *v)

atomic bitwise AND with release ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_and_relaxed(long i, atomic_long_t *v)

atomic bitwise AND with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_andnot(long i, atomic_long_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_andnot(long i, atomic_long_t *v)

atomic bitwise AND NOT with full ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_andnot_acquire(long i, atomic_long_t *v)

atomic bitwise AND NOT with acquire ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_andnot_release(long i, atomic_long_t *v)

atomic bitwise AND NOT with release ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_andnot_relaxed(long i, atomic_long_t *v)

atomic bitwise AND NOT with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_or(long i, atomic_long_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_or(long i, atomic_long_t *v)

atomic bitwise OR with full ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_or_acquire(long i, atomic_long_t *v)

atomic bitwise OR with acquire ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_or_release(long i, atomic_long_t *v)

atomic bitwise OR with release ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_or_relaxed(long i, atomic_long_t *v)

atomic bitwise OR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_xor(long i, atomic_long_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_xor(long i, atomic_long_t *v)

atomic bitwise XOR with full ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_xor_acquire(long i, atomic_long_t *v)

atomic bitwise XOR with acquire ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_xor_release(long i, atomic_long_t *v)

atomic bitwise XOR with release ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_fetch_xor_relaxed(long i, atomic_long_t *v)

atomic bitwise XOR with relaxed ordering

Parameters

  • long i: long value
  • atomic_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 raw_atomic_long_xchg(atomic_long_t *v, long new)

atomic exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_xchg_acquire(atomic_long_t *v, long new)

atomic exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_xchg_release(atomic_long_t *v, long new)

atomic exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_xchg_relaxed(atomic_long_t *v, long new)

atomic exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long 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 raw_atomic_long_cmpxchg(atomic_long_t *v, long old, long new)

atomic compare and exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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 raw_atomic_long_cmpxchg_acquire(atomic_long_t *v, long old, long new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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 raw_atomic_long_cmpxchg_release(atomic_long_t *v, long old, long new)

atomic compare and exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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 raw_atomic_long_cmpxchg_relaxed(atomic_long_t *v, long old, long new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long old: long value to compare with
  • long 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 raw_atomic_long_try_cmpxchg(atomic_long_t *v, long *old, long new)

atomic compare and exchange with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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 raw_atomic_long_try_cmpxchg_acquire(atomic_long_t *v, long *old, long new)

atomic compare and exchange with acquire ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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 raw_atomic_long_try_cmpxchg_release(atomic_long_t *v, long *old, long new)

atomic compare and exchange with release ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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 raw_atomic_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old, long new)

atomic compare and exchange with relaxed ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long *old: pointer to long value to compare with
  • long 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 raw_atomic_long_sub_and_test(long i, atomic_long_t *v)

atomic subtract and test if zero with full ordering

Parameters

  • long i: long value to subtract
  • atomic_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 raw_atomic_long_dec_and_test(atomic_long_t *v)

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 raw_atomic_long_inc_and_test(atomic_long_t *v)

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 raw_atomic_long_add_negative(long i, atomic_long_t *v)

atomic add and test if negative with full ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_negative_acquire(long i, atomic_long_t *v)

atomic add and test if negative with acquire ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_negative_release(long i, atomic_long_t *v)

atomic add and test if negative with release ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_add_negative_relaxed(long i, atomic_long_t *v)

atomic add and test if negative with relaxed ordering

Parameters

  • long i: long value to add
  • atomic_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 raw_atomic_long_fetch_add_unless(atomic_long_t *v, long a, long u)

atomic add unless value with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long a: long value to add
  • long 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 raw_atomic_long_add_unless(atomic_long_t *v, long a, long u)

atomic add unless value with full ordering

Parameters

  • atomic_long_t *v: pointer to atomic_long_t
  • long a: long value to add
  • long 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 raw_atomic_long_inc_not_zero(atomic_long_t *v)

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 raw_atomic_long_inc_unless_negative(atomic_long_t *v)

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 raw_atomic_long_dec_unless_positive(atomic_long_t *v)

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 raw_atomic_long_dec_if_positive(atomic_long_t *v)

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 * kobject_get_path(const struct kobject *kobj, gfp_t gfp_mask)

Allocate memory and fill in the path for kobj.

Parameters

  • const struct kobject *kobj: kobject in question, with which to build the path
  • gfp_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 kobject_set_name(struct kobject *kobj, const char *fmt, ...)

Set the name of a kobject.

Parameters

  • struct kobject *kobj: struct kobject to set the name of
  • const 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 kobject_init(struct kobject *kobj, const struct kobj_type *ktype)

Initialize a kobject structure.

Parameters

  • struct kobject *kobj: pointer to the kobject to initialize
  • const 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 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)

The main kobject add function.

Parameters

  • struct kobject *kobj: the kobject to add
  • struct 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 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype, struct kobject *parent, const char *fmt, ...)

Initialize a kobject structure and add it to the kobject hierarchy.

Parameters

  • struct kobject *kobj: pointer to the kobject to initialize
  • const 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 kobject_rename(struct kobject *kobj, const char *new_name)

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 kobject_move(struct kobject *kobj, struct kobject *new_parent)

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 kobject_del(struct kobject *kobj)

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 * kobject_get(struct kobject *kobj)

Increment refcount for object.

Parameters

  • struct kobject *kobj: object.

kobject_put() #

void kobject_put(struct kobject *kobj)

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 * kobject_create_and_add(const char *name, struct kobject *parent)

Create a struct kobject dynamically and register it with sysfs.

Parameters

  • const char *name: the name for the kobject
  • struct 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 kset_register(struct kset *k)

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 kset_unregister(struct kset *k)

Remove a kset.

Parameters

  • struct kset *k: kset.

kset_find_obj() #

struct kobject * kset_find_obj(struct kset *kset, const char *name)

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 * kset_create_and_add(const char *name, const struct kset_uevent_ops *uevent_ops, struct kobject *parent_kobj)

Create a struct kset dynamically and add it to sysfs.

Parameters

  • const char *name: the name for the kset
  • const struct kset_uevent_ops *uevent_ops: a struct kset_uevent_ops for the kset
  • struct 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 kobject_uevent_env(struct kobject *kobj, enum kobject_action action, char *envp_ext[])

send an uevent with environmental data

Parameters

  • struct kobject *kobj: struct kobject that the action is happening to
  • enum kobject_action action: action that is happening
  • char *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 kobject_uevent(struct kobject *kobj, enum kobject_action action)

notify userspace by sending an uevent

Parameters

  • struct kobject *kobj: struct kobject that the action is happening to
  • enum 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_uevent_var(struct kobj_uevent_env *env, const char *format, ...)

add key value string to the environment buffer

Parameters

  • struct kobj_uevent_env *env: environment buffer structure
  • const 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() #

ARRAY_SIZE(arr)

get the number of elements in array arr

Parameters

  • arr: array to be sized

ARRAY_END() #

ARRAY_END(arr)

get a pointer to one past the last element in array arr

Parameters

  • arr: array

container_of() #

container_of(ptr, type, member)

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() #

container_of_const(ptr, type, member)

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 member
  • type: 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() #

sizeof_field(TYPE, MEMBER)

Report the size of a struct field in bytes

Parameters

  • TYPE: The structure containing the field of interest
  • MEMBER: The field to return the size of

offsetofend() #

offsetofend(TYPE, MEMBER)

Report the offset of a struct field within the struct

Parameters

  • TYPE: The type of the structure
  • MEMBER: The member within the structure to get the end offset of

struct_group() #

struct_group(NAME, MEMBERS...)

Wrap a set of declarations in a mirrored struct

Parameters

  • NAME: The identifier name of the mirrored sub-struct
  • MEMBERS...: 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() #

struct_group_attr(NAME, ATTRS, MEMBERS...)

Create a struct_group() with trailing attributes

Parameters

  • NAME: The identifier name of the mirrored sub-struct
  • ATTRS: Any struct attributes to apply
  • MEMBERS...: 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() #

struct_group_tagged(TAG, NAME, MEMBERS...)

Create a struct_group with a reusable tag

Parameters

  • TAG: The tag name for the named sub-struct
  • NAME: The identifier name of the mirrored sub-struct
  • MEMBERS...: 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_FLEX_ARRAY(TYPE, NAME)

Declare a flexible array usable in a union

Parameters

  • TYPE: The type of each flexible array element
  • NAME: 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() #

__TRAILING_OVERLAP(TYPE, NAME, FAM, ATTRS, MEMBERS)

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 TYPE
  • ATTRS: 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() #

TRAILING_OVERLAP(TYPE, NAME, FAM, MEMBERS)

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 TYPE
  • 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.

for_each_if() #

for_each_if(condition)

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() #

find_closest(x, a, as)

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() #

find_closest_descending(x, a, as)

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() #

PTR_IF(cond, ptr)

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() #

u64_to_user_ptr(x)

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() #

is_insidevar(ptr, var)

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() #

upper_32_bits(n)

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() #

lower_32_bits(n)

return bits 0-31 of a number

Parameters

  • n: the number we're accessing

upper_16_bits() #

upper_16_bits(n)

return bits 16-31 of a number

Parameters

  • n: the number we're accessing

lower_16_bits() #

lower_16_bits(n)

return bits 0-15 of a number

Parameters

  • n: the number we're accessing

REPEAT_BYTE() #

REPEAT_BYTE(x)

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_BYTE_U32(x)

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 console_list_lock(void)

Lock the console list

Parameters

  • void: no arguments

Description

For console list or console->flags updates

console_list_unlock() #

void console_list_unlock(void)

Unlock the console list

Parameters

  • void: no arguments

Description

Counterpart to console_list_lock()

console_srcu_read_lock() #

int console_srcu_read_lock(void)

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 console_srcu_read_unlock(int cookie)

Unregister an old reader from the SRCU-protected console list

Parameters

  • int cookie: cookie returned from console_srcu_read_lock()

Description

Counterpart to console_srcu_read_lock()

match_devname_and_update_preferred_console() #

int match_devname_and_update_preferred_console(const char *devname, const char *name, const short idx)

Update a preferred console when matching devname is found.

Parameters

  • const char *devname: DEVNAME:0.0 style device name
  • const 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 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 console_trylock(void)

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 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 console_force_preferred_locked(struct console *con)

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 printk_timed_ratelimit(unsigned long *caller_jiffies, unsigned int interval_msecs)

caller-controlled printk ratelimiting

Parameters

  • unsigned long *caller_jiffies: pointer to caller's state
  • unsigned 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 kmsg_dump_register(struct kmsg_dumper *dumper)

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 kmsg_dump_unregister(struct kmsg_dumper *dumper)

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 kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog, char *line, size_t size, size_t *len)

retrieve one kmsg log line

Parameters

  • struct kmsg_dump_iter *iter: kmsg dump iterator
  • bool syslog: include the "<4>" prefixes
  • char *line: buffer to copy the line to
  • size_t size: maximum size of the buffer
  • size_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 kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog, char *buf, size_t size, size_t *len_out)

copy kmsg log lines

Parameters

  • struct kmsg_dump_iter *iter: kmsg dump iterator
  • bool syslog: include the "<4>" prefixes
  • char *buf: buffer to copy the line to
  • size_t size: maximum size of the buffer
  • size_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 kmsg_dump_rewind(struct kmsg_dump_iter *iter)

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 __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 __printk_cpu_sync_try_get(void)

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 __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 vpanic(const char *fmt, va_list args)

halt the system

Parameters

  • const char *fmt: The text string to print
  • va_list args: Arguments for the format string

Description

Display a message, then perform cleanups. This function never returns.

add_taint() #

void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)

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 * __devres_alloc_node(dr_release_t release, size_t size, gfp_t gfp, int nid, const char *name)

Allocate device resource data

Parameters

  • dr_release_t release: Release function devres will be associated with
  • size_t size: Allocation size
  • gfp_t gfp: Allocation flags
  • int nid: NUMA node
  • const 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 devres_for_each_res(struct device *dev, dr_release_t release, dr_match_t match, void *match_data, void (*fn)(struct device *, void *, void *), void *data)

Resource iterator

Parameters

  • struct device *dev: Device to iterate resource from
  • dr_release_t release: Look for resources associated with this release function
  • dr_match_t match: Match function (optional)
  • void *match_data: Data for the match function
  • void (*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 devres_free(void *res)

Free device resource data

Parameters

  • void *res: Pointer to devres data to free

Description

Free devres created with devres_alloc().

devres_add() #

void devres_add(struct device *dev, void *res)

Register device resource

Parameters

  • struct device *dev: Device to add resource to
  • void *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 * devres_find(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)

Find device resource

Parameters

  • struct device *dev: Device to lookup resource from
  • dr_release_t release: Look for resources associated with this release function
  • dr_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 * devres_get(struct device *dev, void *new_res, dr_match_t match, void *match_data)

Find devres, if non-existent, add one atomically

Parameters

  • struct device *dev: Device to lookup or add devres for
  • void *new_res: Pointer to new initialized devres to add if not found
  • dr_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 * devres_remove(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)

Find a device resource and remove it

Parameters

  • struct device *dev: Device to find resource from
  • dr_release_t release: Look for resources associated with this release function
  • dr_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 devres_destroy(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)

Find a device resource and destroy it

Parameters

  • struct device *dev: Device to find resource from
  • dr_release_t release: Look for resources associated with this release function
  • dr_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 devres_release(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)

Find a device resource and destroy it, calling release

Parameters

  • struct device *dev: Device to find resource from
  • dr_release_t release: Look for resources associated with this release function
  • dr_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 * devres_open_group(struct device *dev, void *id, gfp_t gfp)

Open a new devres group

Parameters

  • struct device *dev: Device to open devres group for
  • void *id: Separator ID
  • gfp_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 devres_close_group(struct device *dev, void *id)

Close a devres group

Parameters

  • struct device *dev: Device to close devres group for
  • void *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 devres_remove_group(struct device *dev, void *id)

Remove a devres group

Parameters

  • struct device *dev: Device to remove group for
  • void *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 devres_release_group(struct device *dev, void *id)

Release resources in a devres group

Parameters

  • struct device *dev: Device to release group for
  • void *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 __devm_add_action(struct device *dev, void (*action)(void *), void *data, const char *name)

add a custom action to list of managed resources

Parameters

  • struct device *dev: Device that owns the action
  • void (*action)(void *): Function that should be called
  • void *data: Pointer to data passed to action implementation
  • const 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 devm_remove_action_nowarn(struct device *dev, void (*action)(void *), void *data)

removes previously added custom action

Parameters

  • struct device *dev: Device that owns the action
  • void (*action)(void *): Function implementing the action
  • void *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 devm_release_action(struct device *dev, void (*action)(void *), void *data)

release previously added custom action

Parameters

  • struct device *dev: Device that owns the action
  • void (*action)(void *): Function implementing the action
  • void *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 * devm_kmalloc(struct device *dev, size_t size, gfp_t gfp)

Resource-managed kmalloc

Parameters

  • struct device *dev: Device to allocate memory for
  • size_t size: Allocation size
  • gfp_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 * devm_krealloc(struct device *dev, void *ptr, size_t new_size, gfp_t gfp)

Resource-managed krealloc()

Parameters

  • struct device *dev: Device to re-allocate memory for
  • void *ptr: Pointer to the memory chunk to re-allocate
  • size_t new_size: New allocation size
  • gfp_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 * devm_kstrdup(struct device *dev, const char *s, gfp_t gfp)

Allocate resource managed space and copy an existing string into that.

Parameters

  • struct device *dev: Device to allocate memory for
  • const char *s: the string to duplicate
  • gfp_t gfp: the GFP mask used in the devm_kmalloc() call when allocating memory

Return

Pointer to allocated string on success, NULL on failure.

devm_kstrdup_const() #

const char * devm_kstrdup_const(struct device *dev, const char *s, gfp_t gfp)

resource managed conditional string duplication

Parameters

  • struct device *dev: device for which to duplicate the string
  • const char *s: the string to duplicate
  • gfp_t gfp: the GFP mask used in the kmalloc() 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 * devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)

Allocate resource managed space and format a string into that.

Parameters

  • struct device *dev: Device to allocate memory for
  • gfp_t gfp: the GFP mask used in the devm_kmalloc() call when allocating memory
  • const char *fmt: The printf()-style format string
  • va_list ap: Arguments for the format string

Return

Pointer to allocated string on success, NULL on failure.

devm_kasprintf() #

char * devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)

Allocate resource managed space and format a string into that.

Parameters

  • struct device *dev: Device to allocate memory for
  • gfp_t gfp: the GFP mask used in the devm_kmalloc() call when allocating memory
  • const char *fmt: The printf()-style format string
  • ...: Arguments for the format string

Return

Pointer to allocated string on success, NULL on failure.

devm_kfree() #

void devm_kfree(struct device *dev, const void *p)

Resource-managed kfree

Parameters

  • struct device *dev: Device this memory belongs to
  • const void *p: Memory to free

Description

Free memory allocated with devm_kmalloc().

devm_kmemdup() #

void * devm_kmemdup(struct device *dev, const void *src, size_t len, gfp_t gfp)

Resource-managed kmemdup

Parameters

  • struct device *dev: Device this memory belongs to
  • const void *src: Memory region to duplicate
  • size_t len: Memory region length
  • gfp_t gfp: GFP mask to use

Description

Duplicate region of a memory using resource managed kmalloc

devm_kmemdup_const() #

const void * devm_kmemdup_const(struct device *dev, const void *src, size_t len, gfp_t gfp)

conditionally duplicate and manage a region of memory

Parameters

  • struct device *dev: Device this memory belongs to
  • const void *src: memory region to duplicate
  • size_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 devm_get_free_pages(struct device *dev, gfp_t gfp_mask, unsigned int order)

Resource-managed __get_free_pages

Parameters

  • struct device *dev: Device to allocate memory for
  • gfp_t gfp_mask: Allocation gfp flags
  • unsigned 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 devm_free_pages(struct device *dev, unsigned long addr)

Resource-managed free_pages

Parameters

  • struct device *dev: Device this memory belongs to
  • unsigned 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 * __devm_alloc_percpu(struct device *dev, size_t size, size_t align)

Resource-managed alloc_percpu

Parameters

  • struct device *dev: Device to allocate per-cpu memory for
  • size_t size: Size of per-cpu memory to allocate
  • size_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

struct component_ops {
    int (*bind)(struct device *comp, struct device *master, void *master_data);
    void (*unbind)(struct device *comp, struct device *master, void *master_data);
};

Members

  • bind: Called through component_bind_all() when the aggregate driver is ready to bind the overall driver.
  • unbind: Called through component_unbind_all() when the aggregate driver is ready to bind the overall driver, or when component_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

struct component_master_ops {
    int (*bind)(struct device *master);
    void (*unbind)(struct device *master);
};

Members

  • bind: Called when all components or the aggregate driver, as specified in the match list passed to component_master_add_with_match(), are ready. Usually there are 3 steps to bind an aggregate driver:

    1. Allocate a structure for the aggregate driver.

    2. Bind all components to the aggregate driver by calling component_bind_all() with the aggregate driver structure as opaque pointer data.

    3. 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 device instances. 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, using component_master_del(), or one of its components, using component_del(), is unregistered.

Description

Aggregate drivers are registered with component_master_add_with_match() and unregistered with component_master_del().

component_match_add() #

void component_match_add(struct device *parent, struct component_match **matchptr, int (*compare)(struct device *, void *), void *compare_data)

add a component match entry

Parameters

  • struct device *parent: device with the aggregate driver
  • struct component_match **matchptr: pointer to the list of component matches
  • int (*compare)(struct device *, void *): compare function to match against all components
  • void *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 component_compare_of(struct device *dev, void *data)

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 component_release_of(struct device *dev, void *data)

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 component_compare_dev(struct device *dev, void *data)

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 component_compare_dev_name(struct device *dev, void *data)

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 component_match_add_release(struct device *parent, struct component_match **matchptr, void (*release)(struct device *, void *), int (*compare)(struct device *, void *), void *compare_data)

add a component match entry with release callback

Parameters

  • struct device *parent: parent device of the aggregate driver
  • struct component_match **matchptr: pointer to the list of component matches
  • void (*release)(struct device *, void *): release function for compare_data
  • int (*compare)(struct device *, void *): compare function to match against all components
  • void *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 component_match_add_typed(struct device *parent, struct component_match **matchptr, int (*compare_typed)(struct device *, int, void *), void *compare_data)

add a component match entry for a typed component

Parameters

  • struct device *parent: parent device of the aggregate driver
  • struct component_match **matchptr: pointer to the list of component matches
  • int (*compare_typed)(struct device *, int, void *): compare function to match against all typed components
  • void *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 component_master_add_with_match(struct device *parent, const struct component_master_ops *ops, struct component_match *match)

register an aggregate driver

Parameters

  • struct device *parent: parent device of the aggregate driver
  • const struct component_master_ops *ops: callbacks for the aggregate driver
  • struct 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 component_master_del(struct device *parent, const struct component_master_ops *ops)

unregister an aggregate driver

Parameters

  • struct device *parent: parent device of the aggregate driver
  • const 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 component_unbind_all(struct device *parent, void *data)

unbind all components of an aggregate driver

Parameters

  • struct device *parent: parent device of the aggregate driver
  • void *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 component_bind_all(struct device *parent, void *data)

bind all components of an aggregate driver

Parameters

  • struct device *parent: parent device of the aggregate driver
  • void *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 component_add_typed(struct device *dev, const struct component_ops *ops, int subcomponent)

register a component

Parameters

  • struct device *dev: component device
  • const struct component_ops *ops: component callbacks
  • int 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 component_add(struct device *dev, const struct component_ops *ops)

register a component

Parameters

  • struct device *dev: component device
  • const 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 component_del(struct device *dev, const struct component_ops *ops)

unregister a component

Parameters

  • struct device *dev: component device
  • const 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() #

int cn_add_callback(const struct cb_id *id, const char *name, void (*callback)(struct cn_msg *, struct netlink_skb_parms *))

Registers 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 are cn_msg and the sender's credentials

cn_del_callback() #

void cn_del_callback(const struct cb_id *id)

Unregisters new callback with connector core.

Parameters

  • const struct cb_id *id: unique connector's user identifier.

cn_netlink_send_mult() #

int cn_netlink_send_mult(struct cn_msg *msg, u16 len, u32 portid, u32 group, gfp_t gfp_mask, netlink_filter_fn filter, void *filter_data)

Sends 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 function

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 -ESRCH can be returned.

cn_netlink_send() #

int cn_netlink_send(struct cn_msg *msg, u32 portid, u32 group, gfp_t gfp_mask)

Sends 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 -ESRCH can 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?

  1. 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
  2. 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.
    
  3. 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:

  1. 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.

  2. All resources allocated during con->con_init() must be released in con->con_deinit().

  3. 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.

  4. 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().

  5. 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 to DL_STATE_DORMANT.

  • When a supplier device is bound to a driver, links to its consumers progress to DL_STATE_AVAILABLE. (Call to device_links_driver_bound() from driver_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_AVAILABLE state. The state of the links is updated to DL_STATE_CONSUMER_PROBE. (Call to device_links_check_suppliers() from really_probe().) This prevents the supplier from unbinding. (Call to wait_for_device_probe() from device_links_unbind_consumers().)

  • If the probe fails, links to suppliers revert back to DL_STATE_AVAILABLE. (Call to device_links_no_driver() from really_probe().)

  • If the probe succeeds, links to suppliers progress to DL_STATE_ACTIVE. (Call to device_links_driver_bound() from driver_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() from device_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 to device_links_busy() from __device_release_driver().) This prevents the consumers from binding. (Call to device_links_check_suppliers() from really_probe().) Consumers that are bound are freed from their driver; consumers that are probing are waited for until they are done. (Call to device_links_unbind_consumers() from __device_release_driver().) Once all links to consumers are in DL_STATE_SUPPLIER_UNBIND state, the supplier driver is released and the links revert to DL_STATE_DORMANT. (Call to device_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 register_framebuffer(struct fb_info *fb_info)

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 unregister_framebuffer(struct fb_info *fb_info)

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 devm_register_framebuffer(struct device *dev, struct fb_info *fb_info)

resource-managed frame buffer device registration

Parameters

  • struct device *dev: device the framebuffer belongs to
  • struct 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 fb_set_suspend(struct fb_info *info, int state)

low level driver signals suspend

Parameters

  • struct fb_info *info: framebuffer affected
  • int 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 fb_dealloc_cmap(struct fb_cmap *cmap)

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 fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to)

copy a colormap

Parameters

  • const struct fb_cmap *from: frame buffer colormap structure
  • struct fb_cmap *to: frame buffer colormap structure

Description

Copy contents of colormap from from to to.

fb_set_cmap() #

int fb_set_cmap(struct fb_cmap *cmap, struct fb_info *info)

set the colormap

Parameters

  • struct fb_cmap *cmap: frame buffer colormap structure
  • struct 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 * fb_default_cmap(int len)

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 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 fb_try_mode(struct fb_var_screeninfo *var, struct fb_info *info, const struct fb_videomode *mode, unsigned int bpp)

test a video mode

Parameters

  • struct fb_var_screeninfo *var: frame buffer user defined part of display
  • struct fb_info *info: frame buffer info structure
  • const struct fb_videomode *mode: frame buffer video mode structure
  • unsigned 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 fb_delete_videomode(const struct fb_videomode *mode, struct list_head *head)

removed videomode entry from modelist

Parameters

  • const struct fb_videomode *mode: videomode to remove
  • struct list_head *head: struct list_head of modelist

NOTES

Will remove all matching mode entries

fb_find_mode() #

int fb_find_mode(struct fb_var_screeninfo *var, struct fb_info *info, const char *mode_option, const struct fb_videomode *db, unsigned int dbsize, const struct fb_videomode *default_mode, unsigned int default_bpp)

finds a valid video mode

Parameters

  • struct fb_var_screeninfo *var: frame buffer user defined part of display
  • struct fb_info *info: frame buffer info structure
  • const char *mode_option: string video mode to find
  • const struct fb_videomode *db: video mode database
  • unsigned int dbsize: size of db
  • const struct fb_videomode *default_mode: default video mode to fall back to
  • unsigned 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 fb_var_to_videomode(struct fb_videomode *mode, const struct fb_var_screeninfo *var)

convert fb_var_screeninfo to fb_videomode

Parameters

  • struct fb_videomode *mode: pointer to struct fb_videomode
  • const struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfo

fb_videomode_to_var() #

void fb_videomode_to_var(struct fb_var_screeninfo *var, const struct fb_videomode *mode)

convert fb_videomode to fb_var_screeninfo

Parameters

  • struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfo
  • const struct fb_videomode *mode: pointer to struct fb_videomode

fb_mode_is_equal() #

int fb_mode_is_equal(const struct fb_videomode *mode1, const struct fb_videomode *mode2)

compare 2 videomodes

Parameters

  • const struct fb_videomode *mode1: first videomode
  • const struct fb_videomode *mode2: second videomode

Return

1 if equal, 0 if not

fb_find_best_mode() #

const struct fb_videomode * fb_find_best_mode(const struct fb_var_screeninfo *var, struct list_head *head)

find best matching videomode

Parameters

  • const struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfo
  • struct 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 * fb_find_nearest_mode(const struct fb_videomode *mode, struct list_head *head)

find closest videomode

Parameters

  • const struct fb_videomode *mode: pointer to struct fb_videomode
  • struct 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 * fb_match_mode(const struct fb_var_screeninfo *var, struct list_head *head)

find a videomode which exactly matches the timings in var

Parameters

  • const struct fb_var_screeninfo *var: pointer to struct fb_var_screeninfo
  • struct list_head *head: pointer to struct list_head of modelist

Return

struct fb_videomode, NULL if none found

fb_add_videomode() #

int fb_add_videomode(const struct fb_videomode *mode, struct list_head *head)

adds videomode entry to modelist

Parameters

  • const struct fb_videomode *mode: videomode to add
  • struct list_head *head: struct list_head of modelist

NOTES

Will only add unmatched mode entries

fb_destroy_modelist() #

void fb_destroy_modelist(struct list_head *head)

destroy modelist

Parameters

  • struct list_head *head: struct list_head of modelist

fb_videomode_to_modelist() #

void fb_videomode_to_modelist(const struct fb_videomode *modedb, int num, struct list_head *head)

convert mode array to mode list

Parameters

  • const struct fb_videomode *modedb: array of struct fb_videomode
  • int num: number of entries in array
  • struct list_head *head: struct list_head of modelist

Frame Buffer Macintosh Video Mode Database #

mac_vmode_to_var() #

int mac_vmode_to_var(int vmode, int cmode, struct fb_var_screeninfo *var)

converts vmode/cmode pair to var structure

Parameters

  • int vmode: MacOS video mode
  • int cmode: MacOS color mode
  • struct 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 mac_map_monitor_sense(int sense)

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 mac_find_mode(struct fb_var_screeninfo *var, struct fb_info *info, const char *mode_option, unsigned int default_bpp)

find a video mode

Parameters

  • struct fb_var_screeninfo *var: frame buffer user defined part of display
  • struct fb_info *info: frame buffer info structure
  • const 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

struct subsys_interface {
    const char *name;
    const struct bus_type *subsys;
    struct list_head node;
    int (*add_dev)(struct device *dev, struct subsys_interface *sif);
    void (*remove_dev)(struct device *dev, struct subsys_interface *sif);
};

Members

  • name: name of the device function
  • subsys: subsystem of the devices to attach to
  • node: the list of functions registered at the subsystem
  • add_dev: device hookup to device function handler
  • remove_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

struct device_attribute {
    struct attribute        attr;
    ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf);
    ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count);
};

Members

  • attr: sysfs attribute definition.
  • show: Show handler.
  • store: Store handler.

struct dev_ext_attribute #

Exported device attribute with extra context.

Definition

struct dev_ext_attribute {
    struct device_attribute attr;
    void *var;
};

Members

  • attr: Exported device attribute.
  • var: Pointer to context.

DEVICE_ATTR() #

DEVICE_ATTR(_name, _mode, _show, _store)

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 = {
        .attr   = { .name = "foo", .mode = 0644 },
        .show   = foo_show,
        .store  = foo_store,
};

DEVICE_ATTR_PREALLOC() #

DEVICE_ATTR_PREALLOC(_name, _mode, _show, _store)

Define a preallocated device attribute.

Parameters

  • _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() #

DEVICE_ATTR_RW(_name)

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() #

DEVICE_ATTR_ADMIN_RW(_name)

Define an admin-only read-write device attribute.

Parameters

  • _name: Attribute name.

Description

Like DEVICE_ATTR_RW(), but _mode is 0600.

DEVICE_ATTR_RO() #

DEVICE_ATTR_RO(_name)

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() #

DEVICE_ATTR_ADMIN_RO(_name)

Define an admin-only readable device attribute.

Parameters

  • _name: Attribute name.

Description

Like DEVICE_ATTR_RO(), but _mode is 0400.

DEVICE_ATTR_WO() #

DEVICE_ATTR_WO(_name)

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() #

DEVICE_ULONG_ATTR(_name, _mode, _var)

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() #

DEVICE_INT_ATTR(_name, _mode, _var)

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() #

DEVICE_BOOL_ATTR(_name, _mode, _var)

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() #

DEVICE_STRING_ATTR_RO(_name, _mode, _var)

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

struct dev_links_info {
    struct list_head suppliers;
    struct list_head consumers;
    struct list_head defer_sync;
    enum dl_dev_state status;
};

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

struct dev_msi_info {
    #ifdef CONFIG_GENERIC_MSI_IRQ;
        struct irq_domain       *domain;
        struct msi_device_data  *data;
    #endif;
};

Members

  • domain: The MSI interrupt domain associated to the device
  • data: 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

struct device_physical_location {
    enum device_physical_location_panel panel;
    enum device_physical_location_vertical_position vertical_position;
    enum device_physical_location_horizontal_position horizontal_position;
    bool dock;
    bool lid;
};

Members

  • 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 then device_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

struct device {
        struct kobject kobj;
        struct device           *parent;
        struct device_private   *p;
        const char              *init_name;
        const struct device_type *type;
        const struct bus_type   *bus;
        struct device_driver *driver;
        void *platform_data;
        void *driver_data;
        struct {
            const char      *name;
            spinlock_t lock;
        } driver_override;
        struct mutex            mutex;
        struct dev_links_info   links;
        struct dev_pm_info      power;
        struct dev_pm_domain    *pm_domain;
    #ifdef CONFIG_ENERGY_MODEL;
        struct em_perf_domain   *em_pd;
    #endif;
    #ifdef CONFIG_PINCTRL;
        struct dev_pin_info     *pins;
    #endif;
        struct dev_msi_info     msi;
    #ifdef CONFIG_ARCH_HAS_DMA_OPS;
        const struct dma_map_ops *dma_ops;
    #endif;
        u64 *dma_mask;
        u64 coherent_dma_mask;
        u64 bus_dma_limit;
        const struct bus_dma_region *dma_range_map;
        struct device_dma_parameters *dma_parms;
        struct list_head        dma_pools;
    #ifdef CONFIG_DMA_DECLARE_COHERENT;
        struct dma_coherent_mem *dma_mem;
    #endif;
    #ifdef CONFIG_DMA_CMA;
        struct cma *cma_area;
    #endif;
    #ifdef CONFIG_SWIOTLB;
        struct io_tlb_mem *dma_io_tlb_mem;
    #endif;
    #ifdef CONFIG_SWIOTLB_DYNAMIC;
        struct list_head dma_io_tlb_pools;
        spinlock_t dma_io_tlb_lock;
        bool dma_uses_io_tlb;
    #endif;
        struct dev_archdata     archdata;
        struct device_node      *of_node;
        struct fwnode_handle    *fwnode;
    #ifdef CONFIG_NUMA;
        int numa_node;
    #endif;
        dev_t devt;
        u32 id;
        spinlock_t devres_lock;
        struct list_head        devres_head;
        const struct class      *class;
        const struct attribute_group **groups;
        void (*release)(struct device *dev);
        struct iommu_group      *iommu_group;
        struct dev_iommu        *iommu;
        struct device_physical_location *physical_location;
        enum device_removable   removable;
        bool offline_disabled:1;
        bool offline:1;
        bool of_node_reused:1;
        bool state_synced:1;
        bool can_match:1;
    #if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) ||     defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) ||     defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL);
        bool dma_coherent:1;
    #endif;
    #ifdef CONFIG_DMA_OPS_BYPASS;
        bool dma_ops_bypass : 1;
    #endif;
    #ifdef CONFIG_DMA_NEED_SYNC;
        bool dma_skip_sync:1;
    #endif;
    #ifdef CONFIG_IOMMU_DMA;
        bool dma_iommu:1;
    #endif;
        unsigned long flags[BITS_TO_LONGS(DEV_FLAG_COUNT)];
};

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 this
  • platform_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; use device_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 domain
  • pins: For device pin management. See Documentation/driver-api/pin-control.rst for details.
  • msi: MSI related data
  • dma_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 RAM
  • dma_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 allocations
  • dma_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: true if 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 instance
  • devres_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 data
  • physical_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/bus sync_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 to true then 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

struct device_link {
    struct device *supplier;
    struct list_head s_node;
    struct device *consumer;
    struct list_head c_node;
    struct device link_dev;
    enum device_link_state status;
    u32 flags;
    refcount_t rpm_active;
    struct kref kref;
    struct work_struct rm_work;
    bool supplier_preactivated;
};

Members

  • 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 sysfs
  • status: 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 device_set_driver_override(struct device *dev, const char *s)

Helper to set or clear driver override.

Parameters

  • struct device *dev: Device to change
  • 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).

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 device_has_driver_override(struct device *dev)

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 device_match_driver_override(struct device *dev, const struct device_driver *drv)

Match a driver against the device's driver_override.

Parameters

  • struct device *dev: device to check
  • const 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 device_iommu_mapped(struct device *dev)

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 * dev_name(const struct device *dev)

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 * dev_bus_name(const struct device *dev)

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_find_child_by_name(struct device *parent, const char *name)

device iterator for locating a child device.

Parameters

  • struct device *parent: parent struct device
  • const 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_find_any_child(struct device *parent)

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() #

device_lock_set_class(dev, key)

Specify a temporary lock class while a device is attached to a driver

Parameters

  • dev: device to modify
  • key: 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() #

device_lock_reset_class(dev)

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

struct bus_type {
    const char              *name;
    const char              *dev_name;
    const struct attribute_group **bus_groups;
    const struct attribute_group **dev_groups;
    const struct attribute_group **drv_groups;
    int (*match)(struct device *dev, const struct device_driver *drv);
    int (*uevent)(const struct device *dev, struct kobj_uevent_env *env);
    int (*probe)(struct device *dev);
    void (*sync_state)(struct device *dev);
    void (*remove)(struct device *dev);
    void (*shutdown)(struct device *dev);
    const struct cpumask *(*irq_get_affinity)(struct device *dev, unsigned int irq_vec);
    int (*online)(struct device *dev);
    int (*offline)(struct device *dev);
    int (*suspend)(struct device *dev, pm_message_t state);
    int (*resume)(struct device *dev);
    int (*num_vf)(struct device *dev);
    int (*dma_configure)(struct device *dev);
    void (*dma_cleanup)(struct device *dev);
    const struct dev_pm_ops *pm;
    bool driver_override;
    bool need_parent_lock;
};

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 bus
  • BUS_NOTIFY_DEL_DEVICE: device is about to be removed from this bus
  • BUS_NOTIFY_REMOVED_DEVICE: device is successfully removed from this bus
  • BUS_NOTIFY_BIND_DRIVER: a driver is about to be bound to this device on this bus
  • BUS_NOTIFY_BOUND_DRIVER: a driver is successfully bound to this device on this bus
  • BUS_NOTIFY_UNBIND_DRIVER: a driver is about to be unbound from this device on this bus
  • BUS_NOTIFY_UNBOUND_DRIVER: a driver is successfully unbound from this device on this bus
  • BUS_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

struct class {
    const char              *name;
    const struct attribute_group    **class_groups;
    const struct attribute_group    **dev_groups;
    int (*dev_uevent)(const struct device *dev, struct kobj_uevent_env *env);
    char *(*devnode)(const struct device *dev, umode_t *mode);
    void (*class_release)(const struct class *class);
    void (*dev_release)(struct device *dev);
    int (*shutdown_pre)(struct device *dev);
    const struct kobj_ns_type_operations *ns_type;
    const struct ns_common *(*namespace)(const struct device *dev);
    void (*get_ownership)(const struct device *dev, kuid_t *uid, kgid_t *gid);
    const struct dev_pm_ops *pm;
};

Members

  • 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

struct device_driver {
    const char              *name;
    const struct bus_type   *bus;
    struct module           *owner;
    const char              *mod_name;
    bool suppress_bind_attrs;
    enum probe_type probe_type;
    const struct of_device_id       *of_match_table;
    const struct acpi_device_id     *acpi_match_table;
    int (*probe) (struct device *dev);
    void (*sync_state)(struct device *dev);
    int (*remove) (struct device *dev);
    void (*shutdown) (struct device *dev);
    int (*suspend) (struct device *dev, pm_message_t state);
    int (*resume) (struct device *dev);
    const struct attribute_group **groups;
    const struct attribute_group **dev_groups;
    const struct dev_pm_ops *pm;
    void (*coredump) (struct device *dev);
    struct driver_private *p;
    struct {
        void (*post_unbind_rust)(struct device *dev);
    } p_cb;
};

Members

  • 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 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 * driver_find_device_by_name(const struct device_driver *drv, const char *name)

device iterator for locating a particular device of a specific name.

Parameters

  • const struct device_driver *drv: the driver we're iterating
  • const char *name: name of the device to match

driver_find_device_by_of_node() #

struct device * driver_find_device_by_of_node(const struct device_driver *drv, const struct device_node *np)

device iterator for locating a particular device by of_node pointer.

Parameters

  • const struct device_driver *drv: the driver we're iterating
  • const struct device_node *np: of_node pointer to match.

driver_find_device_by_fwnode() #

struct device * driver_find_device_by_fwnode(struct device_driver *drv, const struct fwnode_handle *fwnode)

device iterator for locating a particular device by fwnode pointer.

Parameters

  • struct device_driver *drv: the driver we're iterating
  • const struct fwnode_handle *fwnode: fwnode pointer to match.

driver_find_device_by_devt() #

struct device * driver_find_device_by_devt(const struct device_driver *drv, dev_t devt)

device iterator for locating a particular device by devt.

Parameters

  • const struct device_driver *drv: the driver we're iterating
  • dev_t devt: devt pointer to match.

driver_find_device_by_acpi_dev() #

struct device * driver_find_device_by_acpi_dev(const struct device_driver *drv, const struct acpi_device *adev)

device iterator for locating a particular device matching the ACPI_COMPANION device.

Parameters

  • const struct device_driver *drv: the driver we're iterating
  • const struct acpi_device *adev: ACPI_COMPANION device to match.

module_driver() #

module_driver(__driver, __register, __unregister, ...)

Helper macro for drivers that don't do anything special in module init/exit. This eliminates a lot of boilerplate. Each module may only use this macro once, and calling it replaces module_init() 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() #

builtin_driver(__driver, __register, ...)

Helper macro for drivers that don't do anything special in init and have no exit. This eliminates some boilerplate. Each driver may only use this macro once, and calling it replaces device_initcall (or in some cases, the legacy __initcall). This is meant to be a direct parallel of module_driver() above but without the __exit stuff that is not used for builtin cases.

Parameters

  • __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 driver_set_override(struct device *dev, const char **override, const char *s, size_t len)

Helper to set or clear driver override.

Parameters

  • struct device *dev: Device to change
  • const 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 driver_for_each_device(struct device_driver *drv, struct device *start, void *data, device_iter_t fn)

Iterator for devices bound to a driver.

Parameters

  • struct device_driver *drv: Driver we're iterating.
  • struct device *start: Device to begin with
  • void *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 * driver_find_device(const struct device_driver *drv, struct device *start, const void *data, device_match_t match)

device iterator for locating a particular device.

Parameters

  • const struct device_driver *drv: The device's driver
  • struct device *start: Device to begin with
  • const void *data: Data to pass to match function
  • device_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 driver_create_file(const struct device_driver *drv, const struct driver_attribute *attr)

create sysfs file for driver.

Parameters

  • const struct device_driver *drv: driver.
  • const struct driver_attribute *attr: driver attribute descriptor.

driver_remove_file() #

void driver_remove_file(const struct device_driver *drv, const struct driver_attribute *attr)

remove sysfs file for driver.

Parameters

  • const struct device_driver *drv: driver.
  • const struct driver_attribute *attr: driver attribute descriptor.

driver_register() #

int driver_register(struct device_driver *drv)

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 driver_unregister(struct device_driver *drv)

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 device_link_wait_removal(void)

Wait for ongoing devlink removal jobs to terminate

Parameters

  • void: no arguments

device_link_add() #

struct device_link * device_link_add(struct device *consumer, struct device *supplier, u32 flags)

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 device_link_del(struct device_link *link)

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 device_link_remove(void *consumer, struct device *supplier)

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 * dev_driver_string(const struct device *dev)

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 devm_device_add_group(struct device *dev, const struct attribute_group *grp)

given a device, create a managed attribute group

Parameters

  • struct device *dev: The device to create the group for
  • const 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 device_create_file(struct device *dev, const struct device_attribute *attr)

create sysfs attribute file for device.

Parameters

  • struct device *dev: device.
  • const struct device_attribute *attr: device attribute descriptor.

device_remove_file() #

void device_remove_file(struct device *dev, const struct device_attribute *attr)

remove sysfs attribute file.

Parameters

  • struct device *dev: device.
  • const struct device_attribute *attr: device attribute descriptor.

device_remove_file_self() #

bool device_remove_file_self(struct device *dev, const struct device_attribute *attr)

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 device_create_bin_file(struct device *dev, const struct bin_attribute *attr)

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 device_remove_bin_file(struct device *dev, const struct bin_attribute *attr)

remove sysfs binary attribute file

Parameters

  • struct device *dev: device.
  • const struct bin_attribute *attr: device binary attribute descriptor.

device_initialize() #

void device_initialize(struct device *dev)

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 dev_set_name(struct device *dev, const char *fmt, ...)

set a device name

Parameters

  • struct device *dev: device
  • const char *fmt: format string for the device's name
  • ...: variable arguments

device_add() #

int device_add(struct device *dev)

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 device_register(struct device *dev)

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 * get_device(struct device *dev)

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 put_device(struct device *dev)

decrement reference count.

Parameters

  • struct device *dev: device in question.

device_del() #

void device_del(struct device *dev)

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 device_unregister(struct device *dev)

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_for_each_child(struct device *parent, void *data, device_iter_t fn)

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_for_each_child_reverse(struct device *parent, void *data, device_iter_t fn)

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_for_each_child_reverse_from(struct device *parent, struct device *from, void *data, device_iter_t fn)

device child iterator in reversed order.

Parameters

  • struct device *parent: parent struct device.
  • struct device *from: optional starting point in child list
  • void *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_find_child(struct device *parent, const void *data, device_match_t match)

device iterator for locating a particular device.

Parameters

  • struct device *parent: parent struct device
  • const void *data: Data to pass to match function
  • device_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 * __root_device_register(const char *name, struct module *owner)

allocate and register a root device

Parameters

  • const char *name: root device name
  • struct 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 root_device_unregister(struct device *dev)

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 * device_create(const struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...)

creates a device and registers it with sysfs

Parameters

  • const struct class *class: pointer to the struct class that this device should be registered to
  • struct device *parent: pointer to the parent struct device of this new device, if any
  • dev_t devt: the dev_t for the char device to be added
  • void *drvdata: the data to be added to the device for callbacks
  • const 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 * device_create_with_groups(const struct class *class, struct device *parent, dev_t devt, void *drvdata, const struct attribute_group **groups, const char *fmt, ...)

creates a device and registers it with sysfs

Parameters

  • const struct class *class: pointer to the struct class that this device should be registered to
  • struct device *parent: pointer to the parent struct device of this new device, if any
  • dev_t devt: the dev_t for the char device to be added
  • void *drvdata: the data to be added to the device for callbacks
  • const struct attribute_group **groups: NULL-terminated list of attribute groups to be created
  • const 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 device_destroy(const struct class *class, dev_t devt)

removes a device that was created with device_create()

Parameters

  • const struct class *class: pointer to the struct class that this device was registered with
  • dev_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 device_rename(struct device *dev, const char *new_name)

renames a device

Parameters

  • struct device *dev: the pointer to the struct device to be renamed
  • const 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 device_move(struct device *dev, struct device *new_parent, enum dpm_order dpm_order)

moves a device to a new parent

Parameters

  • struct device *dev: the pointer to the struct device to be moved
  • struct 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 dev_err_probe(const struct device *dev, int err, const char *fmt, ...)

probe error check and log helper

Parameters

  • const struct device *dev: the pointer to the struct device
  • int err: error value to test
  • const 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 dev_warn_probe(const struct device *dev, int err, const char *fmt, ...)

probe error check and log helper

Parameters

  • const struct device *dev: the pointer to the struct device
  • int err: error value to test
  • const 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 set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)

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 set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)

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 device_remove_of_node(struct device *dev)

Remove an of_node from a device

Parameters

  • struct device *dev: device whose device tree node is being removed

device_add_of_node() #

int device_add_of_node(struct device *dev, struct device_node *of_node)

Add an of_node to an existing device

Parameters

  • struct device *dev: device whose device tree node is being added
  • struct device_node *of_node: of_node to add

Return

0 on success or error code on failure.

device_set_of_node_from_dev() #

void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)

reuse device-tree node of another device

Parameters

  • struct device *dev: device whose device-tree node is being set
  • const 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 * get_dev_from_fwnode(struct fwnode_handle *fwnode)

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_syscore(struct syscore *syscore)

Register a set of system core operations.

Parameters

  • struct syscore *syscore: System core operations to register.

unregister_syscore() #

void unregister_syscore(struct syscore *syscore)

Unregister a set of system core operations.

Parameters

  • struct syscore *syscore: System core operations to unregister.

syscore_suspend() #

int syscore_suspend(void)

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 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 * class_find_device_by_name(const struct class *class, const char *name)

device iterator for locating a particular device of a specific name.

Parameters

  • const struct class *class: class type
  • const char *name: name of the device to match

class_find_device_by_of_node() #

struct device * class_find_device_by_of_node(const struct class *class, const struct device_node *np)

device iterator for locating a particular device matching the of_node.

Parameters

  • const struct class *class: class type
  • const struct device_node *np: of_node of the device to match.

class_find_device_by_fwnode() #

struct device * class_find_device_by_fwnode(const struct class *class, const struct fwnode_handle *fwnode)

device iterator for locating a particular device matching the fwnode.

Parameters

  • const struct class *class: class type
  • const struct fwnode_handle *fwnode: fwnode of the device to match.

class_find_device_by_devt() #

struct device * class_find_device_by_devt(const struct class *class, dev_t devt)

device iterator for locating a particular device matching the device type.

Parameters

  • const struct class *class: class type
  • dev_t devt: device type of the device to match.

class_find_device_by_acpi_dev() #

struct device * class_find_device_by_acpi_dev(const struct class *class, const struct acpi_device *adev)

device iterator for locating a particular device matching the ACPI_COMPANION device.

Parameters

  • const struct class *class: class type
  • const struct acpi_device *adev: ACPI_COMPANION device to match.

class_create() #

struct class * class_create(const char *name)

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 class_destroy(const struct class *cls)

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 class_dev_iter_init(struct class_dev_iter *iter, const struct class *class, const struct device *start, const struct device_type *type)

initialize class device iterator

Parameters

  • struct class_dev_iter *iter: class iterator to initialize
  • const struct class *class: the class we wanna iterate over
  • const struct device *start: the device to start iterating from, if any
  • const 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 * class_dev_iter_next(struct class_dev_iter *iter)

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 class_dev_iter_exit(struct class_dev_iter *iter)

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 class_for_each_device(const struct class *class, const struct device *start, void *data, device_iter_t fn)

device iterator

Parameters

  • const struct class *class: the class we're iterating
  • const struct device *start: the device to start with in the list, if any.
  • void *data: data for the callback
  • device_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 * class_find_device(const struct class *class, const struct device *start, const void *data, device_match_t match)

device iterator for locating a particular device

Parameters

  • const struct class *class: the class we're iterating
  • const struct device *start: Device to begin with
  • const void *data: data for the match function
  • device_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 * class_compat_register(const char *name)

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 class_compat_unregister(struct class_compat *cls)

unregister a compatibility class

Parameters

  • struct class_compat *cls: the class to unregister

class_compat_create_link() #

int class_compat_create_link(struct class_compat *cls, struct device *dev)

create a compatibility class device link to a bus device

Parameters

  • struct class_compat *cls: the compatibility class
  • struct device *dev: the target bus device

class_compat_remove_link() #

void class_compat_remove_link(struct class_compat *cls, struct device *dev)

remove a compatibility class device link to a bus device

Parameters

  • struct class_compat *cls: the compatibility class
  • struct device *dev: the target bus device

class_is_registered() #

bool class_is_registered(const struct class *class)

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

struct faux_device {
    struct device dev;
};

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

struct faux_device_ops {
    int (*probe)(struct faux_device *faux_dev);
    void (*remove)(struct faux_device *faux_dev);
};

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 * faux_device_create_with_groups(const char *name, struct device *parent, const struct faux_device_ops *faux_ops, const struct attribute_group **groups)

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 * faux_device_create(const char *name, struct device *parent, const struct faux_device_ops *faux_ops)

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 faux_device_destroy(struct faux_device *faux_dev)

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

struct node_access_nodes {
        struct device           dev;
        struct list_head        list_node;
        unsigned int            access;
    #ifdef CONFIG_HMEM_REPORTING;
        struct access_coordinate        coord;
    #endif;
};

Members

  • dev: Device for this memory access class
  • list_node: List element in the node's access list
  • access: The access class rank
  • coord: Heterogeneous memory performance coordinates

struct node_cache_info #

Internal tracking for memory node caches

Definition

struct node_cache_info {
    struct device dev;
    struct list_head node;
    struct node_cache_attrs cache_attrs;
};

Members

  • dev: Device represeting the cache level
  • node: List element for tracking in the node
  • cache_attrs: Attributes for this cache level

node_add_cache() #

void node_add_cache(unsigned int nid, struct node_cache_attrs *cache_attrs)

add cache attribute to a memory node

Parameters

  • unsigned int nid: Node identifier that has new cache attributes
  • struct node_cache_attrs *cache_attrs: Attributes for the cache being added

register_memory_node_under_compute_node() #

int register_memory_node_under_compute_node(unsigned int mem_nid, unsigned int cpu_nid, enum access_coordinate_class access)

link memory node to its compute node for a given access class.

Parameters

  • unsigned int mem_nid: Memory node number
  • unsigned int cpu_nid: Cpu node number
  • enum 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 register_node(int nid)

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_node(int nid)

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 transport_class_register(struct transport_class *tclass)

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 transport_class_unregister(struct transport_class *tclass)

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 anon_transport_class_register(struct anon_transport_class *atc)

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 anon_transport_class_unregister(struct anon_transport_class *atc)

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 transport_setup_device(struct device *dev)

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 transport_add_device(struct device *dev)

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 transport_configure_device(struct device *dev)

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 transport_remove_device(struct device *dev)

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 transport_destroy_device(struct device *dev)

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 driver_deferred_probe_check_state(struct device *dev)

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 device_is_bound(struct device *dev)

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 device_bind_driver(struct device *dev)

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 wait_for_device_probe(void)

Parameters

  • void: no arguments

Description

Wait for device probing to be completed.

device_attach() #

int device_attach(struct device *dev)

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 device_driver_attach(const struct device_driver *drv, struct device *dev)

attach a specific driver to a specific device

Parameters

  • const struct device_driver *drv: Driver to attach
  • struct 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 driver_attach(const struct device_driver *drv)

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 device_release_driver(struct device *dev)

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 * platform_device_register_resndata(struct device *parent, const char *name, int id, const struct resource *res, unsigned int num, const void *data, size_t size)

add a platform-level device with resources and platform-specific data

Parameters

  • struct device *parent: parent device for the device we're adding
  • const char *name: base name of the device we're adding
  • int id: instance id
  • const struct resource *res: set of resources that needs to be allocated for the device
  • unsigned int num: number of resources
  • const void *data: platform specific data for this platform device
  • size_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 * platform_device_register_simple(const char *name, int id, const struct resource *res, unsigned int num)

add a platform-level device and its resources

Parameters

  • const char *name: base name of the device we're adding
  • int id: instance id
  • const struct resource *res: set of resources that needs to be allocated for the device
  • unsigned 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 * platform_device_register_data(struct device *parent, const char *name, int id, const void *data, size_t size)

add a platform-level device with platform-specific data

Parameters

  • struct device *parent: parent device for the device we're adding
  • const char *name: base name of the device we're adding
  • int id: instance id
  • const void *data: platform specific data for this platform device
  • size_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 * platform_get_resource(struct platform_device *dev, unsigned int type, unsigned int num)

get a resource for a device

Parameters

  • struct platform_device *dev: platform device
  • unsigned int type: resource type
  • unsigned int num: resource index

Return

a pointer to the resource or NULL on failure.

devm_platform_get_and_ioremap_resource() #

void __iomem * devm_platform_get_and_ioremap_resource(struct platform_device *pdev, unsigned int index, struct resource **res)

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 management
  • unsigned int index: resource index
  • struct 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 * devm_platform_ioremap_resource(struct platform_device *pdev, unsigned int index)

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 management
  • unsigned 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 * devm_platform_ioremap_resource_byname(struct platform_device *pdev, const char *name)

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 management
  • const 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 platform_get_irq_affinity(struct platform_device *dev, unsigned int num, const struct cpumask **affinity)

get an optional IRQ and its affinity for a device

Parameters

  • struct platform_device *dev: platform device
  • unsigned int num: interrupt number index
  • const 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 platform_get_irq_optional(struct platform_device *dev, unsigned int num)

get an optional interrupt for a device

Parameters

  • struct platform_device *dev: platform device
  • unsigned 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 platform_get_irq(struct platform_device *dev, unsigned int num)

get an IRQ for a device

Parameters

  • struct platform_device *dev: platform device
  • unsigned 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 platform_irq_count(struct platform_device *dev)

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_platform_get_irqs_affinity(struct platform_device *dev, struct irq_affinity *affd, unsigned int minvec, unsigned int maxvec, int **irqs)

devm method to get a set of IRQs for a device using an interrupt affinity descriptor

Parameters

  • struct platform_device *dev: platform device pointer
  • struct irq_affinity *affd: affinity descriptor
  • unsigned int minvec: minimum count of interrupt vectors
  • unsigned int maxvec: maximum count of interrupt vectors
  • int **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 * platform_get_resource_byname(struct platform_device *dev, unsigned int type, const char *name)

get a resource for a device by name

Parameters

  • struct platform_device *dev: platform device
  • unsigned int type: resource type
  • const char *name: resource name

platform_get_irq_byname() #

int platform_get_irq_byname(struct platform_device *dev, const char *name)

get an IRQ for a device by name

Parameters

  • struct platform_device *dev: platform device
  • const 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 platform_get_irq_byname_optional(struct platform_device *dev, const char *name)

get an optional IRQ for a device by name

Parameters

  • struct platform_device *dev: platform device
  • const 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 platform_add_devices(struct platform_device **devs, int num)

add a numbers of platform devices

Parameters

  • struct platform_device **devs: array of platform devices to add
  • int num: number of platform devices in array

Return

0 on success, negative error number on failure.

platform_device_put() #

void platform_device_put(struct platform_device *pdev)

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 * platform_device_alloc(const char *name, int id)

create a platform device

Parameters

  • const char *name: base name of the device we're adding
  • int 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 platform_device_add_resources(struct platform_device *pdev, const struct resource *res, unsigned int num)

add resources to a platform device

Parameters

  • struct platform_device *pdev: platform device allocated by platform_device_alloc to add resources to
  • const struct resource *res: set of resources that needs to be allocated for the device
  • unsigned 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 platform_device_add_data(struct platform_device *pdev, const void *data, size_t size)

add platform-specific data to a platform device

Parameters

  • struct platform_device *pdev: platform device allocated by platform_device_alloc to add resources to
  • const void *data: platform specific data for this platform device
  • size_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 platform_device_add(struct platform_device *pdev)

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 platform_device_del(struct platform_device *pdev)

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 platform_device_register(struct platform_device *pdev)

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 platform_device_unregister(struct platform_device *pdev)

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 * platform_device_register_full(const struct platform_device_info *pdevinfo)

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 __platform_driver_register(struct platform_driver *drv, struct module *owner)

register a driver for platform-level devices

Parameters

  • struct platform_driver *drv: platform driver structure
  • struct module *owner: owning module/driver

platform_driver_unregister() #

void platform_driver_unregister(struct platform_driver *drv)

unregister a driver for platform-level devices

Parameters

  • struct platform_driver *drv: platform driver structure

__platform_driver_probe() #

int __platform_driver_probe(struct platform_driver *drv, int (*probe)(struct platform_device *), struct module *module)

register driver for non-hotpluggable device

Parameters

  • struct platform_driver *drv: platform driver structure
  • int (*probe)(struct platform_device *): the driver probe routine, probably from an __init section
  • struct 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 * __platform_create_bundle(struct platform_driver *driver, int (*probe)(struct platform_device *), struct resource *res, unsigned int n_res, const void *data, size_t size, struct module *module)

register driver and create corresponding device

Parameters

  • struct platform_driver *driver: platform driver structure
  • int (*probe)(struct platform_device *): the driver probe routine, probably from an __init section
  • struct resource *res: set of resources that needs to be allocated for the device
  • unsigned int n_res: number of resources
  • const void *data: platform specific data for this platform device
  • size_t size: size of platform specific data
  • struct 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 __platform_register_drivers(struct platform_driver * const *drivers, unsigned int count, struct module *owner)

register an array of platform drivers

Parameters

  • struct platform_driver * const *drivers: an array of drivers to register
  • unsigned int count: the number of drivers to register
  • struct 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 platform_unregister_drivers(struct platform_driver * const *drivers, unsigned int count)

unregister an array of platform drivers

Parameters

  • struct platform_driver * const *drivers: an array of drivers to unregister
  • unsigned 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 * platform_find_device_by_driver(struct device *start, const struct device_driver *drv)

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 * bus_find_device_by_name(const struct bus_type *bus, struct device *start, const char *name)

device iterator for locating a particular device of a specific name.

Parameters

  • const struct bus_type *bus: bus type
  • struct device *start: Device to begin with
  • const char *name: name of the device to match

bus_find_device_by_of_node() #

struct device * bus_find_device_by_of_node(const struct bus_type *bus, const struct device_node *np)

device iterator for locating a particular device matching the of_node.

Parameters

  • const struct bus_type *bus: bus type
  • const struct device_node *np: of_node of the device to match.

bus_find_device_by_fwnode() #

struct device * bus_find_device_by_fwnode(const struct bus_type *bus, const struct fwnode_handle *fwnode)

device iterator for locating a particular device matching the fwnode.

Parameters

  • const struct bus_type *bus: bus type
  • const struct fwnode_handle *fwnode: fwnode of the device to match.

bus_find_device_by_devt() #

struct device * bus_find_device_by_devt(const struct bus_type *bus, dev_t devt)

device iterator for locating a particular device matching the device type.

Parameters

  • const struct bus_type *bus: bus type
  • dev_t devt: device type of the device to match.

bus_find_next_device() #

struct device * bus_find_next_device(const struct bus_type *bus, struct device *cur)

Find the next device after a given device in a given bus.

Parameters

  • const struct bus_type *bus: bus type
  • struct device *cur: device to begin the search with.

bus_find_device_by_acpi_dev() #

struct device * bus_find_device_by_acpi_dev(const struct bus_type *bus, const struct acpi_device *adev)

device iterator for locating a particular device matching the ACPI COMPANION device.

Parameters

  • const struct bus_type *bus: bus type
  • const struct acpi_device *adev: ACPI COMPANION device to match.

bus_for_each_dev() #

int bus_for_each_dev(const struct bus_type *bus, struct device *start, void *data, device_iter_t fn)

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 * bus_find_device(const struct bus_type *bus, struct device *start, const void *data, device_match_t match)

device iterator for locating a particular device.

Parameters

  • const struct bus_type *bus: bus type
  • struct device *start: Device to begin with
  • const void *data: Data to pass to match function
  • device_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 bus_for_each_drv(const struct bus_type *bus, struct device_driver *start, void *data, int (*fn)(struct device_driver *, void *))

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 bus_rescan_devices(const struct bus_type *bus)

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 device_reprobe(struct device *dev)

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 bus_register(const struct bus_type *bus)

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 bus_unregister(const struct bus_type *bus)

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 subsys_system_register(const struct bus_type *subsys, const struct attribute_group **groups)

register a subsystem at /sys/devices/system/

Parameters

  • const struct bus_type *subsys: system subsystem
  • const 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 subsys_virtual_register(const struct bus_type *subsys, const struct attribute_group **groups)

register a subsystem at /sys/devices/virtual/

Parameters

  • const struct bus_type *subsys: virtual subsystem
  • const 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 * driver_find(const char *name, const struct bus_type *bus)

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 * bus_get_dev_root(const struct bus_type *bus)

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 dmam_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle)

Managed dma_free_coherent()

Parameters

  • struct device *dev: Device to free coherent memory for
  • size_t size: Size of allocation
  • void *vaddr: Virtual address of the memory to free
  • dma_addr_t dma_handle: DMA handle of the memory to free

Description

Managed dma_free_coherent().

dmam_alloc_attrs() #

void * dmam_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)

Managed dma_alloc_attrs()

Parameters

  • struct device *dev: Device to allocate non_coherent memory for
  • size_t size: Size of allocation
  • dma_addr_t *dma_handle: Out argument for allocated DMA handle
  • gfp_t gfp: Allocation flags
  • unsigned 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 dma_map_sg_attrs(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir, unsigned long attrs)

Map the given buffer for DMA

Parameters

  • struct device *dev: The device for which to perform the DMA operation
  • struct scatterlist *sg: The sg_table object describing the buffer
  • int nents: Number of entries to map
  • enum dma_data_direction dir: DMA direction
  • unsigned 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 dma_map_sgtable(struct device *dev, struct sg_table *sgt, enum dma_data_direction dir, unsigned long attrs)

Map the given buffer for DMA

Parameters

  • struct device *dev: The device for which to perform the DMA operation
  • struct sg_table *sgt: The sg_table object describing the buffer
  • enum dma_data_direction dir: DMA direction
  • unsigned 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 dma_need_unmap(struct device *dev)

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 dma_can_mmap(struct device *dev)

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 dma_mmap_attrs(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size, unsigned long attrs)

map a coherent DMA allocation into user space

Parameters

  • struct device *dev: valid struct device pointer, or NULL for ISA and EISA-like devices
  • struct vm_area_struct *vma: vm_area_struct describing requested user mapping
  • void *cpu_addr: kernel CPU-view address returned from dma_alloc_attrs
  • dma_addr_t dma_addr: device-view address returned from dma_alloc_attrs
  • size_t size: size of memory originally requested in dma_alloc_attrs
  • unsigned 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 dma_addressing_limited(struct device *dev)

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 pnp_register_protocol(struct pnp_protocol *protocol)

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 * pnp_request_card_device(struct pnp_card_link *clink, const char *id, struct pnp_dev *from)

Searches for a PnP device under the specified card

Parameters

  • struct pnp_card_link *clink: pointer to the card link, cannot be NULL
  • const char *id: pointer to a PnP ID structure that explains the rules for finding the device
  • struct pnp_dev *from: Starting place to search from. If NULL it will start from the beginning.

pnp_release_card_device() #

void pnp_release_card_device(struct pnp_dev *dev)

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 pnp_register_card_driver(struct pnp_card_driver *drv)

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 pnp_unregister_card_driver(struct pnp_card_driver *drv)

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 * pnp_add_id(struct pnp_dev *dev, const char *id)

adds an EISA id to the specified device

Parameters

  • struct pnp_dev *dev: pointer to the desired device
  • const char *id: pointer to an EISA id string

pnp_start_dev() #

int pnp_start_dev(struct pnp_dev *dev)

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 pnp_stop_dev(struct pnp_dev *dev)

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 pnp_activate_dev(struct pnp_dev *dev)

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 pnp_disable_dev(struct pnp_dev *dev)

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 pnp_is_active(struct pnp_dev *dev)

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 uio_event_notify(struct uio_info *info)

trigger an interrupt event

Parameters

  • struct uio_info *info: UIO device capabilities

__uio_register_device() #

int __uio_register_device(struct module *owner, struct device *parent, struct uio_info *info)

register a new userspace IO device

Parameters

  • struct module *owner: module that creates the new device
  • struct device *parent: parent device
  • struct uio_info *info: UIO device capabilities

Description

returns zero on success or a negative error code.

__devm_uio_register_device() #

int __devm_uio_register_device(struct module *owner, struct device *parent, struct uio_info *info)

Resource managed uio_register_device()

Parameters

  • struct module *owner: module that creates the new device
  • struct device *parent: parent device
  • struct uio_info *info: UIO device capabilities

Description

returns zero on success or a negative error code.

uio_unregister_device() #

void uio_unregister_device(struct uio_info *info)

unregister a industrial IO device

Parameters

  • struct uio_info *info: UIO device capabilities

struct uio_mem #

description of a UIO memory region

Definition

struct uio_mem {
    const char              *name;
    phys_addr_t addr;
    dma_addr_t dma_addr;
    unsigned long           offs;
    resource_size_t size;
    int memtype;
    void __iomem            *internal_addr;
    struct device           *dma_device;
    struct uio_map          *map;
};

Members

  • name: name of the memory region for identification
  • addr: 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 page
  • size: size of IO (multiple of page size)
  • memtype: type of memory addr points to
  • internal_addr: ioremap-ped version of addr, for driver internal use
  • dma_device: device struct that was passed to dma_alloc_coherent, used with UIO_MEM_DMA_COHERENT only
  • map: for use by the UIO core only.

struct uio_port #

description of a UIO port region

Definition

struct uio_port {
    const char              *name;
    unsigned long           start;
    unsigned long           size;
    int porttype;
    struct uio_portio       *portio;
};

Members

  • name: name of the port region for identification
  • start: start of port region
  • size: size of port region
  • porttype: type of port (see UIO_PORT_* below)
  • portio: for use by the UIO core only.

struct uio_info #

UIO device capabilities

Definition

struct uio_info {
    struct uio_device       *uio_dev;
    const char              *name;
    const char              *version;
    struct uio_mem          mem[MAX_UIO_MAPS];
    struct uio_port         port[MAX_UIO_PORT_REGIONS];
    long irq;
    unsigned long           irq_flags;
    void *priv;
    irqreturn_t (*handler)(int irq, struct uio_info *dev_info);
    int (*mmap)(struct uio_info *info, struct vm_area_struct *vma);
    int (*open)(struct uio_info *info, struct inode *inode);
    int (*release)(struct uio_info *info, struct inode *inode);
    int (*irqcontrol)(struct uio_info *info, s32 irq_on);
};

Members

  • uio_dev: the UIO device this info belongs to
  • name: device name
  • version: device driver version
  • mem: list of mappable memory regions, size==0 for end of list
  • port: list of port regions, size==0 for end of list
  • irq: interrupt number or UIO_IRQ_CUSTOM
  • irq_flags: flags for request_irq()
  • priv: optional private data
  • handler: the device's irq handler
  • mmap: mmap operation for this uio device
  • open: open operation for this uio device
  • release: release operation for this uio device
  • irqcontrol: disable/enable irqs when 0/1 is written to /dev/uioX

uio_register_device() #

uio_register_device(parent, info)

register a new userspace IO device

Parameters

  • parent: parent device
  • info: UIO device capabilities

Description

returns zero on success or a negative error code.

devm_uio_register_device() #

devm_uio_register_device(parent, info)

Resource managed uio_register_device()

Parameters

  • parent: parent device
  • info: 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 mpt_register(MPT_CALLBACK cbfunc, MPT_DRIVER_CLASS dclass, char *func_name)

Register protocol-specific main callback handler.

Parameters

  • MPT_CALLBACK cbfunc: callback function pointer
  • MPT_DRIVER_CLASS dclass: Protocol driver's class (MPT_DRIVER_CLASS enum 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 mpt_deregister(u8 cb_idx)

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 mpt_event_register(u8 cb_idx, MPT_EVHANDLER ev_cbfunc)

Register protocol-specific event callback handler.

Parameters

  • u8 cb_idx: previously registered (via mpt_register) callback handle
  • MPT_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 mpt_event_deregister(u8 cb_idx)

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 mpt_reset_register(u8 cb_idx, MPT_RESETHANDLER reset_func)

Register protocol-specific IOC reset handler.

Parameters

  • u8 cb_idx: previously registered (via mpt_register) callback handle
  • MPT_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 mpt_reset_deregister(u8 cb_idx)

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 mpt_device_driver_register(struct mpt_pci_driver * dd_cbfunc, u8 cb_idx)

Register device driver hooks

Parameters

  • struct mpt_pci_driver * dd_cbfunc: driver callbacks struct
  • u8 cb_idx: MPT protocol driver index

mpt_device_driver_deregister() #

void mpt_device_driver_deregister(u8 cb_idx)

DeRegister device driver hooks

Parameters

  • u8 cb_idx: MPT protocol driver index

mpt_get_msg_frame() #

MPT_FRAME_HDR* mpt_get_msg_frame(u8 cb_idx, MPT_ADAPTER *ioc)

Obtain an MPT request frame from the pool

Parameters

  • u8 cb_idx: Handle of registered MPT protocol driver
  • MPT_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 mpt_put_msg_frame(u8 cb_idx, MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)

Send a protocol-specific MPT request frame to an IOC

Parameters

  • u8 cb_idx: Handle of registered MPT protocol driver
  • MPT_ADAPTER *ioc: Pointer to MPT adapter structure
  • MPT_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 mpt_put_msg_frame_hi_pri(u8 cb_idx, MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)

Send a hi-pri protocol-specific MPT request frame

Parameters

  • u8 cb_idx: Handle of registered MPT protocol driver
  • MPT_ADAPTER *ioc: Pointer to MPT adapter structure
  • MPT_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 mpt_free_msg_frame(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)

Place MPT request frame back on FreeQ.

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT adapter structure
  • MPT_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 mpt_send_handshake_request(u8 cb_idx, MPT_ADAPTER *ioc, int reqBytes, u32 *req, int sleepFlag)

Send MPT request via doorbell handshake method.

Parameters

  • u8 cb_idx: Handle of registered MPT protocol driver
  • MPT_ADAPTER *ioc: Pointer to MPT adapter structure
  • int reqBytes: Size of the request in bytes
  • u32 *req: Pointer to MPT request frame
  • int 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 mpt_verify_adapter(int iocid, MPT_ADAPTER **iocpp)

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 mpt_attach(struct pci_dev *pdev, const struct pci_device_id *id)

Install a PCI intelligent MPT adapter.

Parameters

  • struct pci_dev *pdev: Pointer to pci_dev structure
  • const 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 mpt_detach(struct pci_dev *pdev)

Remove a PCI intelligent MPT adapter.

Parameters

  • struct pci_dev *pdev: Pointer to pci_dev structure

mpt_suspend() #

int mpt_suspend(struct pci_dev *pdev, pm_message_t state)

Fusion MPT base driver suspend routine.

Parameters

  • struct pci_dev *pdev: Pointer to pci_dev structure
  • pm_message_t state: new state to enter

mpt_resume() #

int mpt_resume(struct pci_dev *pdev)

Fusion MPT base driver resume routine.

Parameters

  • struct pci_dev *pdev: Pointer to pci_dev structure

mpt_GetIocState() #

u32 mpt_GetIocState(MPT_ADAPTER *ioc, int cooked)

Get the current state of a MPT adapter.

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • int 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 mpt_alloc_fw_memory(MPT_ADAPTER *ioc, int size)

allocate firmware memory

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • int 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 mpt_free_fw_memory(MPT_ADAPTER *ioc)

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 mptbase_sas_persist_operation(MPT_ADAPTER *ioc, u8 persist_opcode)

Perform operation on SAS Persistent Table

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • u8 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 mpt_raid_phys_disk_pg0(MPT_ADAPTER *ioc, u8 phys_disk_num, RaidPhysDiskPage0_t *phys_disk)

returns phys disk page zero

Parameters

  • MPT_ADAPTER *ioc: Pointer to a Adapter Structure
  • u8 phys_disk_num: io unit unique phys disk num generated by the ioc
  • RaidPhysDiskPage0_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 mpt_raid_phys_disk_get_num_paths(MPT_ADAPTER *ioc, u8 phys_disk_num)

returns number paths associated to this phys_num

Parameters

  • MPT_ADAPTER *ioc: Pointer to a Adapter Structure
  • u8 phys_disk_num: io unit unique phys disk num generated by the ioc

Return

returns number paths

mpt_raid_phys_disk_pg1() #

int mpt_raid_phys_disk_pg1(MPT_ADAPTER *ioc, u8 phys_disk_num, RaidPhysDiskPage1_t *phys_disk)

returns phys disk page 1

Parameters

  • MPT_ADAPTER *ioc: Pointer to a Adapter Structure
  • u8 phys_disk_num: io unit unique phys disk num generated by the ioc
  • RaidPhysDiskPage1_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 mpt_findImVolumes(MPT_ADAPTER *ioc)

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 mpt_config(MPT_ADAPTER *ioc, CONFIGPARMS *pCfg)

Generic function to issue config message

Parameters

  • MPT_ADAPTER *ioc: Pointer to an adapter structure
  • CONFIGPARMS *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 mpt_print_ioc_summary(MPT_ADAPTER *ioc, char *buffer, int *size, int len, int showlan)

Write ASCII summary of IOC to a buffer.

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • char *buffer: Pointer to buffer where IOC summary info should be written
  • int *size: Pointer to number of bytes we wrote (set by this routine)
  • int len: Offset at which to start writing in buffer
  • int 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 mpt_set_taskmgmt_in_progress_flag(MPT_ADAPTER *ioc)

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 mpt_clear_taskmgmt_in_progress_flag(MPT_ADAPTER *ioc)

clear flags associated with task management

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure

mpt_halt_firmware() #

void __noreturn mpt_halt_firmware(MPT_ADAPTER *ioc)

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 mpt_Soft_Hard_ResetHandler(MPT_ADAPTER *ioc, int sleepFlag)

Try less expensive reset

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • int 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 mpt_HardResetHandler(MPT_ADAPTER *ioc, int sleepFlag)

Generic reset handler

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • int 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 * mptscsih_info(struct Scsi_Host *SChost)

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 mptscsih_qcmd(struct scsi_cmnd *SCpnt)

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 mptscsih_IssueTaskMgmt(MPT_SCSI_HOST *hd, u8 type, u8 channel, u8 id, u64 lun, int ctx2abort, ulong timeout)

Generic send Task Management function.

Parameters

  • MPT_SCSI_HOST *hd: Pointer to MPT_SCSI_HOST structure
  • u8 type: Task Management type
  • u8 channel: channel number for task management
  • u8 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 mptscsih_abort(struct scsi_cmnd * SCpnt)

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 mptscsih_dev_reset(struct scsi_cmnd * SCpnt)

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 mptscsih_bus_reset(struct scsi_cmnd * SCpnt)

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 mptscsih_host_reset(struct scsi_cmnd *SCpnt)

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 mptscsih_taskmgmt_complete(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *mr)

Registered with Fusion MPT base driver

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • MPT_FRAME_HDR *mf: Pointer to SCSI task mgmt request frame
  • MPT_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 * mptscsih_get_scsi_lookup(MPT_ADAPTER *ioc, int i)

retrieves scmd entry

Parameters

  • MPT_ADAPTER *ioc: Pointer to MPT_ADAPTER structure
  • int 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 misc_register(struct miscdevice *misc)

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 misc_deregister(struct miscdevice *misc)

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() #

parport_register_driver(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() #

module_parport_driver(__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 parport_yield(struct pardevice *dev)

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 parport_yield_blocking(struct pardevice *dev)

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 parport_wait_event(struct parport *port, signed long timeout)

wait for an event on a parallel port

Parameters

  • struct parport *port: port to wait on
  • signed 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 parport_wait_peripheral(struct parport *port, unsigned char mask, unsigned char result)

wait for status lines to change in 35ms

Parameters

  • struct parport *port: port to watch
  • unsigned char mask: status lines to watch
  • unsigned 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 parport_negotiate(struct parport *port, int mode)

negotiate an IEEE 1284 mode

Parameters

  • struct parport *port: port to use
  • int 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 parport_write(struct parport *port, const void *buffer, size_t len)

write a block of data to a parallel port

Parameters

  • struct parport *port: port to write to
  • const 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 parport_read(struct parport *port, void *buffer, size_t len)

read a block of data from a parallel port

Parameters

  • struct parport *port: port to read from
  • void *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 parport_set_timeout(struct pardevice *dev, long inactivity)

set the inactivity timeout for a device

Parameters

  • struct pardevice *dev: device on a port
  • long 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 __parport_register_driver(struct parport_driver *drv, struct module *owner, const char *mod_name)

register a parallel port device driver

Parameters

  • struct parport_driver *drv: structure describing the driver
  • struct module *owner: owner module of drv
  • const 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 parport_unregister_driver(struct parport_driver *drv)

deregister a parallel port device driver

Parameters

  • struct parport_driver *drv: structure describing the driver that was given to parport_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 * parport_get_port(struct parport *port)

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 parport_put_port(struct parport *port)

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 * parport_register_port(unsigned long base, int irq, int dma, struct parport_operations *ops)

register a parallel port

Parameters

  • unsigned long base: base I/O address
  • int irq: IRQ line
  • int dma: DMA channel
  • struct 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 parport_announce_port(struct parport *port)

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 parport_remove_port(struct parport *port)

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 * parport_register_dev_model(struct parport *port, const char *name, const struct pardev_cb *par_dev_cb, int id)

register a device on a parallel port

Parameters

  • struct parport *port: port to which the device is attached
  • const char *name: a name to refer to the device
  • const struct pardev_cb *par_dev_cb: struct containing callbacks
  • int 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 parport_unregister_device(struct pardevice *dev)

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 * parport_find_number(int number)

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 * parport_find_base(unsigned long base)

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 parport_claim(struct pardevice *dev)

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 parport_claim_or_block(struct pardevice *dev)

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 parport_release(struct pardevice *dev)

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 * parport_open(int devnum, const char *name)

find a device by canonical device number

Parameters

  • int devnum: canonical device number
  • const 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 parport_close(struct pardevice *dev)

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 * serial8250_get_port(int line)

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 serial8250_suspend_port(int line)

suspend one serial port

Parameters

  • int line: serial line number

Description

Suspend one serial port.

serial8250_resume_port() #

void serial8250_resume_port(int line)

resume one serial port

Parameters

  • int line: serial line number

Description

Resume one serial port.

serial8250_register_8250_port() #

int serial8250_register_8250_port(const struct uart_8250_port *up)

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 serial8250_unregister_port(int line)

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 period
  • PWM_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

struct pwm_args {
    u64 period;
    enum pwm_polarity polarity;
};

Members

  • period: reference period
  • polarity: 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

struct pwm_waveform {
    u64 period_length_ns;
    u64 duty_length_ns;
    u64 duty_offset_ns;
};

Members

  • period_length_ns: PWM period
  • duty_length_ns: PWM duty cycle
  • duty_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

struct pwm_device {
    const char *label;
    unsigned long flags;
    unsigned int hwpwm;
    struct pwm_chip *chip;
    struct pwm_args args;
    struct pwm_state state;
    struct pwm_state last;
};

Members

  • label: name of the PWM device
  • flags: flags associated with the PWM device
  • hwpwm: per-chip relative index of the PWM device
  • chip: PWM chip providing this PWM device
  • args: PWM arguments
  • state: last applied state
  • last: last implemented state (for PWM_DEBUG)

pwm_get_state() #

void pwm_get_state(const struct pwm_device *pwm, struct pwm_state *state)

retrieve the current PWM state

Parameters

  • const struct pwm_device *pwm: PWM device
  • struct 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 pwm_init_state(const struct pwm_device *pwm, struct pwm_state *state)

prepare a new state to be applied with pwm_apply_might_sleep()

Parameters

  • const struct pwm_device *pwm: PWM device
  • struct 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 pwm_get_relative_duty_cycle(const struct pwm_state *state, unsigned int scale)

Get a relative duty cycle value

Parameters

  • const struct pwm_state *state: PWM state to extract the duty cycle from
  • unsigned 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 pwm_set_relative_duty_cycle(struct pwm_state *state, unsigned int duty_cycle, unsigned int scale)

Set a relative duty cycle value

Parameters

  • struct pwm_state *state: PWM state to fill
  • unsigned int duty_cycle: relative duty cycle value
  • unsigned 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

struct pwm_capture {
    unsigned int period;
    unsigned int duty_cycle;
};

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

struct pwm_ops {
    int (*request)(struct pwm_chip *chip, struct pwm_device *pwm);
    void (*free)(struct pwm_chip *chip, struct pwm_device *pwm);
    int (*capture)(struct pwm_chip *chip, struct pwm_device *pwm, struct pwm_capture *result, unsigned long timeout);
    size_t sizeof_wfhw;
    int (*round_waveform_tohw)(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_waveform *wf, void *wfhw);
    int (*round_waveform_fromhw)(struct pwm_chip *chip, struct pwm_device *pwm, const void *wfhw, struct pwm_waveform *wf);
    int (*read_waveform)(struct pwm_chip *chip, struct pwm_device *pwm, void *wfhw);
    int (*write_waveform)(struct pwm_chip *chip, struct pwm_device *pwm, const void *wfhw);
    int (*apply)(struct pwm_chip *chip, struct pwm_device *pwm, const struct pwm_state *state);
    int (*get_state)(struct pwm_chip *chip, struct pwm_device *pwm, struct pwm_state *state);
};

Members

  • request: optional hook for requesting a PWM
  • free: optional hook for freeing a PWM
  • capture: capture and report PWM signal
  • sizeof_wfhw: size (in bytes) of driver specific waveform presentation
  • round_waveform_tohw: convert a struct pwm_waveform to driver specific presentation
  • round_waveform_fromhw: convert a driver specific waveform presentation to struct pwm_waveform
  • read_waveform: read driver specific waveform presentation from hardware
  • write_waveform: write driver specific waveform presentation to hardware
  • apply: atomically apply a new PWM config
  • get_state: get the current PWM state.

struct pwm_chip #

abstract a PWM controller

Definition

struct pwm_chip {
    struct device dev;
    struct cdev cdev;
    const struct pwm_ops *ops;
    struct module *owner;
    unsigned int id;
    unsigned int npwm;
    struct pwm_device * (*of_xlate)(struct pwm_chip *chip, const struct of_phandle_args *args);
    bool atomic;
    struct gpio_chip gpio;
    bool uses_pwmchip_alloc;
    bool operational;
    union {
        struct mutex nonatomic_lock;
        spinlock_t atomic_lock;
    };
    struct pwm_device pwms[] ;
};

Members

  • dev: device providing the PWMs
  • cdev: struct cdev for this device
  • ops: callbacks for this PWM controller
  • owner: module providing this chip
  • id: unique number of this PWM chip
  • npwm: number of PWMs controlled by this chip
  • of_xlate: request a PWM device given a device tree PWM specifier
  • atomic: can the driver's ->apply() be called in atomic context
  • gpio: struct gpio_chip to operate this PWM chip's lines as GPO
  • uses_pwmchip_alloc: signals if pwmchip_allow was used to allocate this chip
  • operational: signals if the chip can be used (or is already deregistered)
  • {unnamed_union}: anonymous
  • nonatomic_lock: mutex for nonatomic chips
  • atomic_lock: mutex for atomic chips
  • pwms: array of PWM devices allocated by the framework

pwmchip_supports_waveform() #

bool pwmchip_supports_waveform(struct pwm_chip *chip)

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 pwm_config(struct pwm_device *pwm, int duty_ns, int period_ns)

change a PWM device configuration

Parameters

  • struct pwm_device *pwm: PWM device
  • int 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 pwm_enable(struct pwm_device *pwm)

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 pwm_disable(struct pwm_device *pwm)

stop a PWM output toggling

Parameters

  • struct pwm_device *pwm: PWM device

pwm_might_sleep() #

bool pwm_might_sleep(struct pwm_device *pwm)

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 pwm_round_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)

Query hardware capabilities Cannot be used in atomic context.

Parameters

  • struct pwm_device *pwm: PWM device
  • struct 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 pwm_get_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)

Query hardware about current configuration Cannot be used in atomic context.

Parameters

  • struct pwm_device *pwm: PWM device
  • struct 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 pwm_set_waveform_might_sleep(struct pwm_device *pwm, const struct pwm_waveform *wf, bool exact)

Apply a new waveform Cannot be used in atomic context.

Parameters

  • struct pwm_device *pwm: PWM device
  • const struct pwm_waveform *wf: The waveform to apply
  • bool 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 pwm_apply_might_sleep(struct pwm_device *pwm, const struct pwm_state *state)

atomically apply a new state to a PWM device Cannot be used in atomic context.

Parameters

  • struct pwm_device *pwm: PWM device
  • const struct pwm_state *state: new state to apply

Return

0 on success, or a negative errno

Context

May sleep.

pwm_apply_atomic() #

int pwm_apply_atomic(struct pwm_device *pwm, const struct pwm_state *state)

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 device
  • const struct pwm_state *state: new state to apply

Return

0 on success, or a negative errno

Context

Any

pwm_get_state_hw() #

int pwm_get_state_hw(struct pwm_device *pwm, struct pwm_state *state)

get the current PWM state from hardware

Parameters

  • struct pwm_device *pwm: PWM device
  • struct 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 pwm_adjust_config(struct pwm_device *pwm)

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 * pwm_get(struct device *dev, const char *con_id)

look up and request a PWM device

Parameters

  • struct device *dev: device for PWM consumer
  • const 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 pwm_put(struct pwm_device *pwm)

release a PWM device

Parameters

  • struct pwm_device *pwm: PWM device

devm_pwm_get() #

struct pwm_device * devm_pwm_get(struct device *dev, const char *con_id)

resource managed pwm_get()

Parameters

  • struct device *dev: device for PWM consumer
  • const 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 * devm_fwnode_pwm_get(struct device *dev, struct fwnode_handle *fwnode, const char *con_id)

request a resource managed PWM from firmware node

Parameters

  • struct device *dev: device for PWM consumer
  • struct fwnode_handle *fwnode: firmware node to get the PWM from
  • const 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 __pwmchip_add(struct pwm_chip *chip, struct module *owner)

register a new PWM chip

Parameters

  • struct pwm_chip *chip: the PWM chip to add
  • struct 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 pwmchip_remove(struct pwm_chip *chip)

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

struct nand_parameters {
    const char *model;
    bool supports_set_get_features;
    bool supports_read_cache;
    unsigned long set_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    unsigned long get_feature_list[BITS_TO_LONGS(ONFI_FEATURE_NUMBER)];
    struct onfi_params *onfi;
};

Members

  • model: Model name
  • supports_set_get_features: The NAND chip supports setting/getting features
  • supports_read_cache: The NAND chip supports read cache operations
  • set_feature_list: Bitmap of features that can be set
  • get_feature_list: Bitmap of features that can be get
  • onfi: ONFI specific parameters

struct nand_id #

NAND id structure

Definition

struct nand_id {
    u8 data[NAND_MAX_ID_LEN];
    int len;
};

Members

  • data: buffer containing the id bytes.
  • len: ID length.

struct nand_ecc_step_info #

ECC step information of ECC engine

Definition

struct nand_ecc_step_info {
    int stepsize;
    const int *strengths;
    int nstrengths;
};

Members

  • stepsize: data bytes per ECC step
  • strengths: array of supported strengths
  • nstrengths: number of supported strengths

struct nand_ecc_caps #

capability of ECC engine

Definition

struct nand_ecc_caps {
    const struct nand_ecc_step_info *stepinfos;
    int nstepinfos;
    int (*calc_ecc_bytes)(int step_size, int strength);
};

Members

  • stepinfos: array of ECC step information
  • nstepinfos: number of ECC step information
  • calc_ecc_bytes: driver's hook to calculate ECC bytes per step

struct nand_ecc_ctrl #

Control structure for ECC

Definition

struct nand_ecc_ctrl {
    enum nand_ecc_engine_type engine_type;
    enum nand_ecc_placement placement;
    enum nand_ecc_algo algo;
    int steps;
    int size;
    int bytes;
    int total;
    int strength;
    int prepad;
    int postpad;
    unsigned int options;
    u8 *calc_buf;
    u8 *code_buf;
    void (*hwctl)(struct nand_chip *chip, int mode);
    int (*calculate)(struct nand_chip *chip, const uint8_t *dat, uint8_t *ecc_code);
    int (*correct)(struct nand_chip *chip, uint8_t *dat, uint8_t *read_ecc, uint8_t *calc_ecc);
    int (*read_page_raw)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*write_page_raw)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*read_page)(struct nand_chip *chip, uint8_t *buf, int oob_required, int page);
    int (*read_subpage)(struct nand_chip *chip, uint32_t offs, uint32_t len, uint8_t *buf, int page);
    int (*write_subpage)(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *data_buf, int oob_required, int page);
    int (*write_page)(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page);
    int (*write_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob_raw)(struct nand_chip *chip, int page);
    int (*read_oob)(struct nand_chip *chip, int page);
    int (*write_oob)(struct nand_chip *chip, int page);
};

Members

  • engine_type: ECC engine type
  • placement: OOB bytes placement
  • algo: ECC algorithm
  • steps: number of ECC steps per page
  • size: data bytes per ECC step
  • bytes: ECC bytes per step
  • total: total number of ECC bytes per page
  • strength: max number of correctible bits per ECC step
  • prepad: padding information for syndrome based ECC generators
  • postpad: padding information for syndrome based ECC generators
  • options: 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 available
  • calculate: function for ECC calculation or readback from ECC hardware
  • correct: 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 error
  • read_subpage: function to read parts of the page covered by ECC; returns same as read_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 ECC
  • read_oob_raw: function to read chip OOB data without ECC
  • read_oob: function to read chip OOB data
  • write_oob: function to write chip OOB data

struct nand_sdr_timings #

SDR NAND chip timings

Definition

struct nand_sdr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tALH_min;
    u32 tADL_min;
    u32 tALS_min;
    u32 tAR_min;
    u32 tCEA_max;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCHZ_max;
    u32 tCLH_min;
    u32 tCLR_min;
    u32 tCLS_min;
    u32 tCOH_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDS_min;
    u32 tFEAT_max;
    u32 tIR_min;
    u32 tITC_max;
    u32 tRC_min;
    u32 tREA_max;
    u32 tREH_min;
    u32 tRHOH_min;
    u32 tRHW_min;
    u32 tRHZ_max;
    u32 tRLOH_min;
    u32 tRP_min;
    u32 tRR_min;
    u64 tRST_max;
    u32 tWB_max;
    u32 tWC_min;
    u32 tWH_min;
    u32 tWHR_min;
    u32 tWP_min;
    u32 tWW_min;
};

Members

  • tBERS_max: Block erase time
  • tCCS_min: Change column setup time
  • tPROG_max: Page program time
  • tR_max: Page read time
  • tALH_min: ALE hold time
  • tADL_min: ALE to data loading time
  • tALS_min: ALE setup time
  • tAR_min: ALE to RE# delay
  • tCEA_max: CE# access time
  • tCEH_min: CE# high hold time
  • tCH_min: CE# hold time
  • tCHZ_max: CE# high to output hi-Z
  • tCLH_min: CLE hold time
  • tCLR_min: CLE to RE# delay
  • tCLS_min: CLE setup time
  • tCOH_min: CE# high to output hold
  • tCS_min: CE# setup time
  • tDH_min: Data hold time
  • tDS_min: Data setup time
  • tFEAT_max: Busy time for Set Features and Get Features
  • tIR_min: Output hi-Z to RE# low
  • tITC_max: Interface and Timing Mode Change time
  • tRC_min: RE# cycle time
  • tREA_max: RE# access time
  • tREH_min: RE# high hold time
  • tRHOH_min: RE# high to output hold
  • tRHW_min: RE# high to WE# low
  • tRHZ_max: RE# high to output hi-Z
  • tRLOH_min: RE# low to output hold
  • tRP_min: RE# pulse width
  • tRR_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] low
  • tWC_min: WE# cycle time
  • tWH_min: WE# high hold time
  • tWHR_min: WE# high to RE# low
  • tWP_min: WE# pulse width
  • tWW_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

struct nand_nvddr_timings {
    u64 tBERS_max;
    u32 tCCS_min;
    u64 tPROG_max;
    u64 tR_max;
    u32 tAC_min;
    u32 tAC_max;
    u32 tADL_min;
    u32 tCAD_min;
    u32 tCAH_min;
    u32 tCALH_min;
    u32 tCALS_min;
    u32 tCAS_min;
    u32 tCEH_min;
    u32 tCH_min;
    u32 tCK_min;
    u32 tCS_min;
    u32 tDH_min;
    u32 tDQSCK_min;
    u32 tDQSCK_max;
    u32 tDQSD_min;
    u32 tDQSD_max;
    u32 tDQSHZ_max;
    u32 tDQSQ_max;
    u32 tDS_min;
    u32 tDSC_min;
    u32 tFEAT_max;
    u32 tITC_max;
    u32 tQHS_max;
    u32 tRHW_min;
    u32 tRR_min;
    u32 tRST_max;
    u32 tWB_max;
    u32 tWHR_min;
    u32 tWRCK_min;
    u32 tWW_min;
};

Members

  • tBERS_max: Block erase time
  • tCCS_min: Change column setup time
  • tPROG_max: Page program time
  • tR_max: Page read time
  • tAC_min: Access window of DQ[7:0] from CLK
  • tAC_max: Access window of DQ[7:0] from CLK
  • tADL_min: ALE to data loading time
  • tCAD_min: Command, Address, Data delay
  • tCAH_min: Command/Address DQ hold time
  • tCALH_min: W/R_n, CLE and ALE hold time
  • tCALS_min: W/R_n, CLE and ALE setup time
  • tCAS_min: Command/address DQ setup time
  • tCEH_min: CE# high hold time
  • tCH_min: CE# hold time
  • tCK_min: Average clock cycle time
  • tCS_min: CE# setup time
  • tDH_min: Data hold time
  • tDQSCK_min: Start of the access window of DQS from CLK
  • tDQSCK_max: End of the access window of DQS from CLK
  • tDQSD_min: Min W/R_n low to DQS/DQ driven by device
  • tDQSD_max: Max W/R_n low to DQS/DQ driven by device
  • tDQSHZ_max: W/R_n high to DQS/DQ tri-state by device
  • tDQSQ_max: DQS-DQ skew, DQS to last DQ valid, per access
  • tDS_min: Data setup time
  • tDSC_min: DQS cycle time
  • tFEAT_max: Busy time for Set Features and Get Features
  • tITC_max: Interface and Timing Mode Change time
  • tQHS_max: Data hold skew factor
  • tRHW_min: Data output cycle to command, address, or data input cycle
  • tRR_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] low
  • tWHR_min: WE# high to RE# low
  • tWRCK_min: W/R_n low to data output cycle
  • tWW_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 interface
  • NAND_NVDDR_IFACE: Double Data Rate interface

struct nand_interface_config #

NAND interface timing

Definition

struct nand_interface_config {
    enum nand_interface_type type;
    struct nand_timings {
        unsigned int mode;
        union {
            struct nand_sdr_timings sdr;
            struct nand_nvddr_timings nvddr;
        };
    } timings;
};

Members

  • type: type of the timing
  • timings: The timing information
  • timings.mode: Timing mode as defined in the specification
  • {unnamed_union}: anonymous
  • timings.sdr: Use it when type is NAND_SDR_IFACE.
  • timings.nvddr: Use it when type is NAND_NVDDR_IFACE.

nand_interface_is_sdr() #

bool nand_interface_is_sdr(const struct nand_interface_config *conf)

get the interface type

Parameters

  • const struct nand_interface_config *conf: The data interface

nand_interface_is_nvddr() #

bool nand_interface_is_nvddr(const struct nand_interface_config *conf)

get the interface type

Parameters

  • const struct nand_interface_config *conf: The data interface

nand_get_sdr_timings() #

const struct nand_sdr_timings * nand_get_sdr_timings(const struct nand_interface_config *conf)

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 * nand_get_nvddr_timings(const struct nand_interface_config *conf)

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

struct nand_op_cmd_instr {
    u8 opcode;
};

Members

  • opcode: the command to issue in one cycle

struct nand_op_addr_instr #

Definition of an address instruction

Definition

struct nand_op_addr_instr {
    unsigned int naddrs;
    const u8 *addrs;
};

Members

  • naddrs: length of the addrs array
  • addrs: array containing the address cycles to issue

struct nand_op_data_instr #

Definition of a data instruction

Definition

struct nand_op_data_instr {
    unsigned int len;
    union {
        void *in;
        const void *out;
    } buf;
    bool force_8bit;
};

Members

  • len: number of data bytes to move
  • buf: buffer to fill
  • buf.in: buffer to fill when reading from the NAND chip
  • buf.out: buffer to read from when writing to the NAND chip
  • force_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

struct nand_op_waitrdy_instr {
    unsigned int timeout_ms;
};

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 instruction
  • NAND_OP_ADDR_INSTR: address instruction
  • NAND_OP_DATA_IN_INSTR: data in instruction
  • NAND_OP_DATA_OUT_INSTR: data out instruction
  • NAND_OP_WAITRDY_INSTR: wait ready instruction

struct nand_op_instr #

Instruction object

Definition

struct nand_op_instr {
    enum nand_op_instr_type type;
    union {
        struct nand_op_cmd_instr cmd;
        struct nand_op_addr_instr addr;
        struct nand_op_data_instr data;
        struct nand_op_waitrdy_instr waitrdy;
    } ctx;
    unsigned int delay_ns;
};

Members

  • type: the instruction type
  • ctx: extra data associated to the instruction. You'll have to use the appropriate element depending on type
  • ctx.cmd: use it if type is NAND_OP_CMD_INSTR
  • ctx.addr: use it if type is NAND_OP_ADDR_INSTR
  • ctx.data: use it if type is NAND_OP_DATA_IN_INSTR or NAND_OP_DATA_OUT_INSTR
  • ctx.waitrdy: use it if type is NAND_OP_WAITRDY_INSTR
  • delay_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

struct nand_subop {
    unsigned int cs;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    unsigned int first_instr_start_off;
    unsigned int last_instr_end_off;
};

Members

  • cs: the CS line to select for this NAND sub-operation
  • instrs: array of instructions
  • ninstrs: length of the instrs array
  • first_instr_start_off: offset to start from for the first instruction of the sub-operation
  • last_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

struct nand_op_parser_addr_constraints {
    unsigned int maxcycles;
};

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

struct nand_op_parser_data_constraints {
    unsigned int maxlen;
};

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

struct nand_op_parser_pattern_elem {
    enum nand_op_instr_type type;
    bool optional;
    union {
        struct nand_op_parser_addr_constraints addr;
        struct nand_op_parser_data_constraints data;
    } ctx;
};

Members

  • type: the instructuction type
  • optional: whether this element of the pattern is optional or mandatory
  • ctx: address or data constraint
  • ctx.addr: address constraint (number of cycles)
  • ctx.data: data constraint (data length)

struct nand_op_parser_pattern #

NAND sub-operation pattern descriptor

Definition

struct nand_op_parser_pattern {
    const struct nand_op_parser_pattern_elem *elems;
    unsigned int nelems;
    int (*exec)(struct nand_chip *chip, const struct nand_subop *subop);
};

Members

  • elems: array of pattern elements
  • nelems: number of pattern elements in elems array
  • exec: 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

struct nand_op_parser {
    const struct nand_op_parser_pattern *patterns;
    unsigned int npatterns;
};

Members

  • patterns: array of supported patterns
  • npatterns: 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

struct nand_operation {
    unsigned int cs;
    bool deassert_wp;
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
};

Members

  • cs: the CS line to select for this NAND operation
  • deassert_wp: set to true when the operation requires the WP pin to be de-asserted (ERASE, PROG, ...)
  • instrs: array of instructions to execute
  • ninstrs: 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

struct nand_controller_ops {
    int (*attach_chip)(struct nand_chip *chip);
    void (*detach_chip)(struct nand_chip *chip);
    int (*exec_op)(struct nand_chip *chip, const struct nand_operation *op, bool check_only);
    int (*setup_interface)(struct nand_chip *chip, int chipnr, const struct nand_interface_config *conf);
};

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 to NAND_DATA_IFACE_CHECK_ONLY this 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

struct nand_controller {
    struct mutex lock;
    const struct nand_controller_ops *ops;
    struct {
        unsigned int data_only_read: 1;
        unsigned int cont_read: 1;
    } supported_op;
    bool controller_wp;
};

Members

  • lock: lock used to serialize accesses to the NAND controller
  • ops: 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

struct nand_legacy {
    void __iomem *IO_ADDR_R;
    void __iomem *IO_ADDR_W;
    void (*select_chip)(struct nand_chip *chip, int cs);
    u8 (*read_byte)(struct nand_chip *chip);
    void (*write_byte)(struct nand_chip *chip, u8 byte);
    void (*write_buf)(struct nand_chip *chip, const u8 *buf, int len);
    void (*read_buf)(struct nand_chip *chip, u8 *buf, int len);
    void (*cmd_ctrl)(struct nand_chip *chip, int dat, unsigned int ctrl);
    void (*cmdfunc)(struct nand_chip *chip, unsigned command, int column, int page_addr);
    int (*dev_ready)(struct nand_chip *chip);
    int (*waitfunc)(struct nand_chip *chip);
    int (*block_bad)(struct nand_chip *chip, loff_t ofs);
    int (*block_markbad)(struct nand_chip *chip, loff_t ofs);
    int (*set_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int (*get_features)(struct nand_chip *chip, int feature_addr, u8 *subfeature_para);
    int chip_delay;
    struct nand_controller dummy_controller;
};

Members

  • IO_ADDR_R: address to read the 8 I/O lines of the flash device
  • IO_ADDR_W: address to write the 8 I/O lines of the flash device
  • select_chip: select/deselect a specific target/die
  • read_byte: read one byte from the chip
  • write_byte: write a single byte to the chip on the low 8 I/O lines
  • write_buf: write data from the buffer to the chip
  • read_buf: read data from the chip into the buffer
  • cmd_ctrl: hardware specific function for controlling ALE/CLE/nCE. Also used to write command and address
  • cmdfunc: 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 markers
  • block_markbad: mark a block bad
  • set_features: set the NAND chip features
  • get_features: get the NAND chip features
  • chip_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

struct nand_chip_ops {
    int (*suspend)(struct nand_chip *chip);
    void (*resume)(struct nand_chip *chip);
    int (*lock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*unlock_area)(struct nand_chip *chip, loff_t ofs, uint64_t len);
    int (*setup_read_retry)(struct nand_chip *chip, int retry_mode);
    int (*choose_interface_config)(struct nand_chip *chip, struct nand_interface_config *iface);
};

Members

  • suspend: Suspend operation
  • resume: Resume operation
  • lock_area: Lock operation
  • unlock_area: Unlock operation
  • setup_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

struct nand_manufacturer {
    const struct nand_manufacturer_desc *desc;
    void *priv;
};

Members

  • desc: The manufacturer description
  • priv: Private information for the manufacturer driver

struct nand_secure_region #

NAND secure region structure

Definition

struct nand_secure_region {
    u64 offset;
    u64 size;
};

Members

  • offset: Offset of the start of the secure region
  • size: Size of the secure region

struct nand_chip #

NAND Private Flash Chip Data

Definition

struct nand_chip {
    struct nand_device base;
    struct nand_id id;
    struct nand_parameters parameters;
    struct nand_manufacturer manufacturer;
    struct nand_chip_ops ops;
    struct nand_legacy legacy;
    unsigned int options;
    const struct nand_interface_config *current_interface_config;
    struct nand_interface_config *best_interface_config;
    unsigned int bbt_erase_shift;
    unsigned int bbt_options;
    unsigned int badblockpos;
    unsigned int badblockbits;
    struct nand_bbt_descr *bbt_td;
    struct nand_bbt_descr *bbt_md;
    struct nand_bbt_descr *badblock_pattern;
    u8 *bbt;
    unsigned int page_shift;
    unsigned int phys_erase_shift;
    unsigned int chip_shift;
    unsigned int pagemask;
    unsigned int subpagesize;
    u8 *data_buf;
    u8 *oob_poi;
    struct {
        unsigned int bitflips;
        int page;
    } pagecache;
    unsigned long buf_align;
    struct mutex lock;
    unsigned int suspended : 1;
    wait_queue_head_t resume_wq;
    int cur_cs;
    int read_retries;
    struct nand_secure_region *secure_regions;
    u8 nr_secure_regions;
    struct {
        bool ongoing;
        unsigned int first_page;
        unsigned int pause_page;
        unsigned int last_page;
    } cont_read;
    struct nand_controller *controller;
    struct nand_ecc_ctrl ecc;
    void *priv;
};

Members

  • base: Inherit from the generic NAND device
  • id: Holds NAND ID
  • parameters: Holds generic parameters under an easily readable form
  • manufacturer: Manufacturer information
  • ops: NAND chip operations
  • legacy: 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 configuration
  • best_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 entry
  • bbt_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 area
  • badblockbits: Minimum number of set bits in a good block's bad block marker position; i.e., BBM = 11110111b is good when badblockbits = 7
  • bbt_td: Bad block table descriptor for flash lookup
  • bbt_md: Bad block table mirror descriptor
  • badblock_pattern: Bad block scan pattern used for initial bad block scan
  • bbt: Bad block table pointer
  • page_shift: Number of address bits in a page (column address bits)
  • phys_erase_shift: Number of address bits in a physical eraseblock
  • chip_shift: Number of address bits in one chip
  • pagemask: Page number mask = number of (pages / chip) - 1
  • subpagesize: Holds the subpagesize
  • data_buf: Buffer for data, size is (page size + oobsize)
  • oob_poi: pointer on the OOB area covered by data_buf
  • pagecache: Structure containing page cache related fields
  • pagecache.bitflips: Number of bitflips of the cached page
  • pagecache.page: Page number currently in the cache. -1 means no page is currently cached
  • buf_align: Minimum buffer alignment required by a platform
  • lock: Lock protecting the suspended field. Also used to serialize accesses to the NAND device
  • suspended: Set to 1 when the device is suspended, 0 when it's not
  • resume_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 supported
  • secure_regions: Structure containing the secure regions info
  • nr_secure_regions: Number of secure regions
  • cont_read: Sequential page read internals
  • cont_read.ongoing: Whether a continuous read is ongoing or not
  • cont_read.first_page: Start of the continuous read operation
  • cont_read.pause_page: End of the current sequential cache read operation
  • cont_read.last_page: End of the continuous read operation
  • controller: The hardware controller structure which is shared among multiple independent devices
  • ecc: The ECC controller structure
  • priv: Chip private data

nand_get_interface_config() #

const struct nand_interface_config * nand_get_interface_config(struct nand_chip *chip)

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

struct nand_flash_dev {
    char *name;
    union {
        struct {
            uint8_t mfr_id;
            uint8_t dev_id;
        };
        uint8_t id[NAND_MAX_ID_LEN];
    };
    unsigned int pagesize;
    unsigned int chipsize;
    unsigned int erasesize;
    unsigned int options;
    uint16_t id_len;
    uint16_t oobsize;
    struct {
        uint16_t strength_ds;
        uint16_t step_ds;
    } ecc;
};

Members

  • name: a human-readable name of the NAND chip
  • {unnamed_union}: anonymous
  • {unnamed_struct}: anonymous
  • mfr_id: manufacturer ID part of the full chip ID array (refers the same memory address as id[0])
  • dev_id: device ID part of the full chip ID array (refers the same memory address as id[1])
  • id: full device ID array
  • pagesize: 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 MiB
  • erasesize: eraseblock size in bytes (determined from the extended ID if 0)
  • options: stores various chip bit options
  • id_len: The valid length of the id.
  • oobsize: OOB size
  • ecc: 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 nand_opcode_8bits(unsigned int command)

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 * nand_get_data_buf(struct nand_chip *chip)

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 nand_extract_bits(u8 *dst, unsigned int dst_off, const u8 *src, unsigned int src_off, unsigned int nbits)

Copy unaligned bits from one buffer to another one

Parameters

  • u8 *dst: destination buffer
  • unsigned int dst_off: bit offset at which the writing starts
  • const u8 *src: source buffer
  • unsigned int src_off: bit offset at which the reading starts
  • unsigned 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 nand_select_target(struct nand_chip *chip, unsigned int cs)

Select a NAND target (A.K.A. die)

Parameters

  • struct nand_chip *chip: NAND chip object
  • unsigned 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 nand_deselect_target(struct nand_chip *chip)

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 nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)

Poll STATUS reg until RDY bit is set to 1

Parameters

  • struct nand_chip *chip: NAND chip structure
  • unsigned 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 nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod, unsigned long timeout_ms)

Poll R/B GPIO pin until ready

Parameters

  • struct nand_chip *chip: NAND chip structure
  • struct gpio_desc *gpiod: GPIO descriptor of R/B pin
  • unsigned 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 nand_read_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, void *buf, unsigned int len)

Do a READ PAGE operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int page: page to read
  • unsigned int offset_in_page: offset within the page
  • void *buf: buffer used to store the data
  • unsigned 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 nand_change_read_column_op(struct nand_chip *chip, unsigned int offset_in_page, void *buf, unsigned int len, bool force_8bit)

Do a CHANGE READ COLUMN operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int offset_in_page: offset within the page
  • void *buf: buffer used to store the data
  • unsigned int len: length of the buffer
  • bool 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 nand_read_oob_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_oob, void *buf, unsigned int len)

Do a READ OOB operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int page: page to read
  • unsigned int offset_in_oob: offset within the OOB area
  • void *buf: buffer used to store the data
  • unsigned 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 nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)

starts a PROG PAGE operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int page: page to write
  • unsigned int offset_in_page: offset within the page
  • const void *buf: buffer containing the data to write to the page
  • unsigned 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 nand_prog_page_end_op(struct nand_chip *chip)

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 nand_prog_page_op(struct nand_chip *chip, unsigned int page, unsigned int offset_in_page, const void *buf, unsigned int len)

Do a full PROG PAGE operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int page: page to write
  • unsigned int offset_in_page: offset within the page
  • const void *buf: buffer containing the data to write to the page
  • unsigned 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 nand_change_write_column_op(struct nand_chip *chip, unsigned int offset_in_page, const void *buf, unsigned int len, bool force_8bit)

Do a CHANGE WRITE COLUMN operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned int offset_in_page: offset within the page
  • const void *buf: buffer containing the data to send to the NAND
  • unsigned int len: length of the buffer
  • bool 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 nand_readid_op(struct nand_chip *chip, u8 addr, void *buf, unsigned int len)

Do a READID operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 addr: address cycle to pass after the READID command
  • void *buf: buffer used to store the ID
  • unsigned 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 nand_status_op(struct nand_chip *chip, u8 *status)

Do a STATUS operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 *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 nand_exit_status_op(struct nand_chip *chip)

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 nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)

Do an erase operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • unsigned 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 nand_reset_op(struct nand_chip *chip)

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 nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len, bool force_8bit, bool check_only)

Read data from the NAND

Parameters

  • struct nand_chip *chip: The NAND chip
  • void *buf: buffer used to store the data
  • unsigned int len: length of the buffer
  • bool force_8bit: force 8-bit bus access
  • bool 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 nand_write_data_op(struct nand_chip *chip, const void *buf, unsigned int len, bool force_8bit)

Write data from the NAND

Parameters

  • struct nand_chip *chip: The NAND chip
  • const void *buf: buffer containing the data to send on the bus
  • unsigned int len: length of the buffer
  • bool 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 nand_op_parser_exec_op(struct nand_chip *chip, const struct nand_op_parser *parser, const struct nand_operation *op, bool check_only)

exec_op parser

Parameters

  • struct nand_chip *chip: the NAND chip
  • const struct nand_op_parser *parser: patterns description provided by the controller driver
  • const struct nand_operation *op: the NAND operation to address
  • bool 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 nand_subop_get_addr_start_off(const struct nand_subop *subop, unsigned int instr_idx)

Get the start offset in an address array

Parameters

  • const struct nand_subop *subop: The entire sub-operation
  • unsigned 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 nand_subop_get_num_addr_cyc(const struct nand_subop *subop, unsigned int instr_idx)

Get the remaining address cycles to assert

Parameters

  • const struct nand_subop *subop: The entire sub-operation
  • unsigned 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 nand_subop_get_data_start_off(const struct nand_subop *subop, unsigned int instr_idx)

Get the start offset in a data array

Parameters

  • const struct nand_subop *subop: The entire sub-operation
  • unsigned 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 nand_subop_get_data_len(const struct nand_subop *subop, unsigned int instr_idx)

Get the number of bytes to retrieve

Parameters

  • const struct nand_subop *subop: The entire sub-operation
  • unsigned 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 nand_reset(struct nand_chip *chip, int chipnr)

Reset and initialize a NAND device

Parameters

  • struct nand_chip *chip: The NAND chip
  • int 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 nand_read_page_raw(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

[INTERN] read raw page data without ecc

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int page: page number to read

Description

Not for syndrome calculating ECC controllers, which use a special oob layout.

nand_monolithic_read_page_raw() #

int nand_monolithic_read_page_raw(struct nand_chip *chip, u8 *buf, int oob_required, int page)

Monolithic page read in raw mode

Parameters

  • struct nand_chip *chip: NAND chip info structure
  • u8 *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int 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 nand_read_page_hwecc_oob_first(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

Hardware ECC page read with ECC data read from OOB area

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int 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 nand_read_oob_std(struct nand_chip *chip, int page)

[REPLACEABLE] the most common OOB data read function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • int page: page number to read

nand_write_oob_std() #

int nand_write_oob_std(struct nand_chip *chip, int page)

[REPLACEABLE] the most common OOB data write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • int page: page number to write

nand_write_page_raw() #

int nand_write_page_raw(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)

[INTERN] raw page write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write

Description

Not for syndrome calculating ECC controllers, which use a special oob layout.

nand_monolithic_write_page_raw() #

int nand_monolithic_write_page_raw(struct nand_chip *chip, const u8 *buf, int oob_required, int page)

Monolithic page write in raw mode

Parameters

  • struct nand_chip *chip: NAND chip info structure
  • const u8 *buf: data buffer to write
  • int oob_required: must write chip->oob_poi to OOB
  • int 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 rawnand_dt_parse_gpio_cs(struct device *dev, struct gpio_desc ***cs_array, unsigned int *ncs_array)

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 success
  • unsigned int *ncs_array: Number of entries in cs_array updated on success. return 0 on success, an error otherwise.

nand_ecc_choose_conf() #

int nand_ecc_choose_conf(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)

Set the ECC strength and ECC step size

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const struct nand_ecc_caps *caps: ECC engine caps info structure
  • int oobavail: OOB size that the ECC engine can use

Description

Choose the ECC configuration according to following logic.

  1. If both ECC step size and ECC strength are already set (usually by DT) then check if it is supported by this controller.
  2. If the user provided the nand-ecc-maximize property, then select maximum ECC strength.
  3. 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_scan_with_ids(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *ids)

[NAND Interface] Scan for the NAND device

Parameters

  • struct nand_chip *chip: NAND chip object
  • unsigned 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_cleanup(struct nand_chip *chip)

[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 nand_release_device(struct nand_chip *chip)

[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 nand_bbm_get_next_page(struct nand_chip *chip, int page)

Get the next page for bad block markers

Parameters

  • struct nand_chip *chip: NAND chip object
  • int 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 nand_block_bad(struct nand_chip *chip, loff_t ofs)

[DEFAULT] Read bad block marker from the chip

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t ofs: offset from device start

Description

Check, if the block is bad.

nand_region_is_secured() #

bool nand_region_is_secured(struct nand_chip *chip, loff_t offset, u64 size)

Check if the region is secured

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t offset: Offset of the region to check
  • u64 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 nand_get_device(struct nand_chip *chip)

[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 nand_check_wp(struct nand_chip *chip)

[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 * nand_fill_oob(struct nand_chip *chip, uint8_t *oob, size_t len, struct mtd_oob_ops *ops)

[INTERN] Transfer client buffer to oob

Parameters

  • struct nand_chip *chip: NAND chip object
  • uint8_t *oob: oob data buffer
  • size_t len: oob data write length
  • struct mtd_oob_ops *ops: oob ops structure

nand_do_write_oob() #

int nand_do_write_oob(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)

[MTD Interface] NAND write out-of-band

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t to: offset to write to
  • struct mtd_oob_ops *ops: oob operation description structure

Description

NAND write out-of-band.

nand_default_block_markbad() #

int nand_default_block_markbad(struct nand_chip *chip, loff_t ofs)

[DEFAULT] mark a block bad via bad block marker

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_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 nand_markbad_bbm(struct nand_chip *chip, loff_t ofs)

mark a block by updating the BBM

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t ofs: offset of the block to mark bad

nand_block_markbad_lowlevel() #

int nand_block_markbad_lowlevel(struct nand_chip *chip, loff_t ofs)

mark a block bad

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_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 nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)

[GENERIC] Check if a block is marked reserved.

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t ofs: offset from device start

Description

Check if the block is marked as reserved.

nand_block_checkbad() #

int nand_block_checkbad(struct nand_chip *chip, loff_t ofs, int allowbbt)

[GENERIC] Check if a block is marked bad

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t ofs: offset from device start
  • int 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 panic_nand_wait(struct nand_chip *chip, unsigned long timeo)

[GENERIC] wait until the command is done

Parameters

  • struct nand_chip *chip: NAND chip structure
  • unsigned 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 nand_reset_interface(struct nand_chip *chip, int chipnr)

Reset data interface and timings

Parameters

  • struct nand_chip *chip: The NAND chip
  • int 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 nand_setup_interface(struct nand_chip *chip, int chipnr)

Setup the best data interface and timings

Parameters

  • struct nand_chip *chip: The NAND chip
  • int 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 nand_choose_best_sdr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_sdr_timings *spec_timings)

Pick up the best SDR timings that both the NAND controller and the NAND chip support

Parameters

  • struct nand_chip *chip: the NAND chip
  • struct 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 nand_choose_best_nvddr_timings(struct nand_chip *chip, struct nand_interface_config *iface, struct nand_nvddr_timings *spec_timings)

Pick up the best NVDDR timings that both the NAND controller and the NAND chip support

Parameters

  • struct nand_chip *chip: the NAND chip
  • struct 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 nand_choose_best_timings(struct nand_chip *chip, struct nand_interface_config *iface)

Pick up the best NVDDR or SDR timings that both NAND controller and the NAND chip support

Parameters

  • struct nand_chip *chip: the NAND chip
  • struct 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 nand_choose_interface_config(struct nand_chip *chip)

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 nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs, unsigned int offset_in_page)

fill the column cycles of an address

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 *addrs: Array of address cycles to fill
  • unsigned 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 nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf, unsigned int len)

Do a READ PARAMETER PAGE operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 page: parameter page to read
  • void *buf: buffer used to store the data
  • unsigned 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 nand_set_features_op(struct nand_chip *chip, u8 feature, const void *data)

Do a SET FEATURES operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 feature: feature id
  • const 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 nand_get_features_op(struct nand_chip *chip, u8 feature, void *data)

Do a GET FEATURES operation

Parameters

  • struct nand_chip *chip: The NAND chip
  • u8 feature: feature id
  • void *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

struct nand_op_parser_ctx {
    const struct nand_op_instr *instrs;
    unsigned int ninstrs;
    struct nand_subop subop;
};

Members

  • instrs: array of all the instructions that must be addressed
  • ninstrs: length of the instrs array
  • subop: 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 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat, const struct nand_op_instr *instr, unsigned int *start_offset)

Checks if an instruction must be split

Parameters

  • const struct nand_op_parser_pattern_elem *pat: the parser pattern element that matches instr
  • const struct nand_op_instr *instr: pointer to the instruction to check
  • unsigned 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 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat, struct nand_op_parser_ctx *ctx)

Checks if a pattern matches the instructions remaining in the parser context

Parameters

  • const struct nand_op_parser_pattern *pat: the pattern to test
  • struct 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 nand_get_features(struct nand_chip *chip, int addr, u8 *subfeature_param)

wrapper to perform a GET_FEATURE

Parameters

  • struct nand_chip *chip: NAND chip info structure
  • int addr: feature address
  • u8 *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 nand_set_features(struct nand_chip *chip, int addr, u8 *subfeature_param)

wrapper to perform a SET_FEATURE

Parameters

  • struct nand_chip *chip: NAND chip info structure
  • int addr: feature address
  • u8 *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 nand_read_page_raw_notsupp(struct nand_chip *chip, u8 *buf, int oob_required, int page)

dummy read raw page function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • u8 *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int page: page number to read

Description

Returns -ENOTSUPP unconditionally.

nand_read_page_raw_syndrome() #

int nand_read_page_raw_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

[INTERN] read raw page data without ecc

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int 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 nand_read_page_swecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

[REPLACEABLE] software ECC based page read function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int page: page number to read

nand_read_subpage() #

int nand_read_subpage(struct nand_chip *chip, uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi, int page)

[REPLACEABLE] ECC based sub-page read function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint32_t data_offs: offset of requested data within the page
  • uint32_t readlen: data length
  • uint8_t *bufpoi: buffer to store read data
  • int page: page number to read

nand_read_page_hwecc() #

int nand_read_page_hwecc(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

[REPLACEABLE] hardware ECC based page read function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int page: page number to read

Description

Not for syndrome calculating ECC controllers which need a special oob layout.

nand_read_page_syndrome() #

int nand_read_page_syndrome(struct nand_chip *chip, uint8_t *buf, int oob_required, int page)

[REPLACEABLE] hardware ECC syndrome based page read

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint8_t *buf: buffer to store read data
  • int oob_required: caller requires OOB data read to chip->oob_poi
  • int 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 * nand_transfer_oob(struct nand_chip *chip, uint8_t *oob, struct mtd_oob_ops *ops, size_t len)

[INTERN] Transfer oob to client buffer

Parameters

  • struct nand_chip *chip: NAND chip object
  • uint8_t *oob: oob destination address
  • struct mtd_oob_ops *ops: oob ops structure
  • size_t len: size of oob to transfer

nand_setup_read_retry() #

int nand_setup_read_retry(struct nand_chip *chip, int retry_mode)

[INTERN] Set the READ RETRY mode

Parameters

  • struct nand_chip *chip: NAND chip object
  • int 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 nand_do_read_ops(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)

[INTERN] Read data with ECC

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t from: offset to read from
  • struct mtd_oob_ops *ops: oob ops structure

Description

Internal function. Called with chip held.

nand_read_oob_syndrome() #

int nand_read_oob_syndrome(struct nand_chip *chip, int page)

[REPLACEABLE] OOB data read function for HW ECC with syndromes

Parameters

  • struct nand_chip *chip: nand chip info structure
  • int page: page number to read

nand_write_oob_syndrome() #

int nand_write_oob_syndrome(struct nand_chip *chip, int page)

[REPLACEABLE] OOB data write function for HW ECC with syndrome - only for large page flash

Parameters

  • struct nand_chip *chip: nand chip info structure
  • int page: page number to write

nand_do_read_oob() #

int nand_do_read_oob(struct nand_chip *chip, loff_t from, struct mtd_oob_ops *ops)

[INTERN] NAND read out-of-band

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t from: offset to read from
  • struct mtd_oob_ops *ops: oob operations description structure

Description

NAND read out-of-band data from the spare area.

nand_read_oob() #

int nand_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)

[MTD Interface] NAND read data and/or out-of-band

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t from: offset to read from
  • struct mtd_oob_ops *ops: oob operation description structure

Description

NAND read data and/or out-of-band data.

nand_write_page_raw_notsupp() #

int nand_write_page_raw_notsupp(struct nand_chip *chip, const u8 *buf, int oob_required, int page)

dummy raw page write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const u8 *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write

Description

Returns -ENOTSUPP unconditionally.

nand_write_page_raw_syndrome() #

int nand_write_page_raw_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)

[INTERN] raw page write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int 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 nand_write_page_swecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)

[REPLACEABLE] software ECC based page write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write

nand_write_page_hwecc() #

int nand_write_page_hwecc(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)

[REPLACEABLE] hardware ECC based page write function

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write

nand_write_subpage_hwecc() #

int nand_write_subpage_hwecc(struct nand_chip *chip, uint32_t offset, uint32_t data_len, const uint8_t *buf, int oob_required, int page)

[REPLACEABLE] hardware ECC based subpage write

Parameters

  • struct nand_chip *chip: nand chip info structure
  • uint32_t offset: column address of subpage within the page
  • uint32_t data_len: data length
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write

nand_write_page_syndrome() #

int nand_write_page_syndrome(struct nand_chip *chip, const uint8_t *buf, int oob_required, int page)

[REPLACEABLE] hardware ECC syndrome based page write

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const uint8_t *buf: data buffer
  • int oob_required: must write chip->oob_poi to OOB
  • int 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 nand_write_page(struct nand_chip *chip, uint32_t offset, int data_len, const uint8_t *buf, int oob_required, int page, int raw)

write one page

Parameters

  • struct nand_chip *chip: NAND chip descriptor
  • uint32_t offset: address offset within the page
  • int data_len: length of actual data to be written
  • const uint8_t *buf: the data to write
  • int oob_required: must write chip->oob_poi to OOB
  • int page: page number to write
  • int raw: use _raw version of write_page

nand_do_write_ops() #

int nand_do_write_ops(struct nand_chip *chip, loff_t to, struct mtd_oob_ops *ops)

[INTERN] NAND write with ECC

Parameters

  • struct nand_chip *chip: NAND chip object
  • loff_t to: offset to write to
  • struct mtd_oob_ops *ops: oob operations description structure

Description

NAND write with ECC.

panic_nand_write() #

int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const uint8_t *buf)

[MTD Interface] NAND write with ECC

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t to: offset to write to
  • size_t len: number of bytes to write
  • size_t *retlen: pointer to variable to store the number of written bytes
  • const 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 nand_write_oob(struct mtd_info *mtd, loff_t to, struct mtd_oob_ops *ops)

[MTD Interface] NAND write data and/or out-of-band

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t to: offset to write to
  • struct mtd_oob_ops *ops: oob operation description structure

nand_erase() #

int nand_erase(struct mtd_info *mtd, struct erase_info *instr)

[MTD Interface] erase block(s)

Parameters

  • struct mtd_info *mtd: MTD device structure
  • struct erase_info *instr: erase instruction

Description

Erase one ore more blocks.

nand_erase_nand() #

int nand_erase_nand(struct nand_chip *chip, struct erase_info *instr, int allowbbt)

[INTERN] erase block(s)

Parameters

  • struct nand_chip *chip: NAND chip object
  • struct erase_info *instr: erase instruction
  • int allowbbt: allow erasing the bbt area

Description

Erase one ore more blocks.

nand_sync() #

void nand_sync(struct mtd_info *mtd)

[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 nand_block_isbad(struct mtd_info *mtd, loff_t offs)

[MTD Interface] Check if block at offset is bad

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t offs: offset relative to mtd start

nand_block_markbad() #

int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)

[MTD Interface] Mark block at the given offset as bad

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t ofs: offset relative to mtd start

nand_suspend() #

int nand_suspend(struct mtd_info *mtd)

[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 nand_resume(struct mtd_info *mtd)

[MTD Interface] Resume the NAND flash

Parameters

  • struct mtd_info *mtd: MTD device structure

nand_shutdown() #

void nand_shutdown(struct mtd_info *mtd)

[MTD Interface] Finish the current NAND operation and prevent further operations

Parameters

  • struct mtd_info *mtd: MTD device structure

nand_lock() #

int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)

[MTD Interface] Lock the NAND flash

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t ofs: offset byte address
  • uint64_t len: number of bytes to lock (must be a multiple of block/page size)

nand_unlock() #

int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)

[MTD Interface] Unlock the NAND flash

Parameters

  • struct mtd_info *mtd: MTD device structure
  • loff_t ofs: offset byte address
  • uint64_t len: number of bytes to unlock (must be a multiple of block/page size)

nand_scan_ident() #

int nand_scan_ident(struct nand_chip *chip, unsigned int maxchips, struct nand_flash_dev *table)

Scan for the NAND device

Parameters

  • struct nand_chip *chip: NAND chip object
  • unsigned int maxchips: number of chips to scan for
  • struct 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 nand_check_ecc_caps(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)

check the sanity of preset ECC settings

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const struct nand_ecc_caps *caps: ECC caps info structure
  • int 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 nand_match_ecc_req(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)

meet the chip's requirement with least ECC bytes

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const struct nand_ecc_caps *caps: ECC engine caps info structure
  • int 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 nand_maximize_ecc(struct nand_chip *chip, const struct nand_ecc_caps *caps, int oobavail)

choose the max ECC strength available

Parameters

  • struct nand_chip *chip: nand chip info structure
  • const struct nand_ecc_caps *caps: ECC engine caps info structure
  • int 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 nand_scan_tail(struct nand_chip *chip)

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 check_pattern(uint8_t *buf, int len, int paglen, struct nand_bbt_descr *td)

[GENERIC] check if a pattern is in the buffer

Parameters

  • uint8_t *buf: the buffer to search
  • int len: the length of buffer to search
  • int paglen: the pagelength
  • struct 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 check_short_pattern(uint8_t *buf, struct nand_bbt_descr *td)

[GENERIC] check if a pattern is in the buffer

Parameters

  • uint8_t *buf: the buffer to search
  • struct 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 add_marker_len(struct nand_bbt_descr *td)

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 read_bbt(struct nand_chip *this, uint8_t *buf, int page, int num, struct nand_bbt_descr *td, int offs)

[GENERIC] Read the bad block table starting from page

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • int page: the starting page
  • int num: the number of bbt descriptors to read
  • struct nand_bbt_descr *td: the bbt describtion table
  • int offs: block number offset in the table

Description

Read the bad block table starting from page.

read_abs_bbt() #

int read_abs_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, int chip)

[GENERIC] Read the bad block table starting at a given page

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct nand_bbt_descr *td: descriptor for the bad block table
  • int 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 scan_read_oob(struct nand_chip *this, uint8_t *buf, loff_t offs, size_t len)

[GENERIC] Scan data+OOB region to buffer

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • loff_t offs: offset at which to scan
  • size_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 read_abs_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)

[GENERIC] Read the bad block table(s) for all chips starting at a given page

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct nand_bbt_descr *td: descriptor for the bad block table
  • struct 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 create_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd, int chip)

[GENERIC] Create a bad block table by scanning the device

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct nand_bbt_descr *bd: descriptor for the good/bad block search pattern
  • int 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 search_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td)

[GENERIC] scan the device for a specific bad block table

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct 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 search_read_bbts(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md)

[GENERIC] scan the device for bad block table(s)

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct nand_bbt_descr *td: descriptor for the bad block table
  • struct 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_bbt_block(struct nand_chip *this, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chip)

Get the first valid eraseblock suitable to store a BBT

Parameters

  • struct nand_chip *this: the NAND device
  • struct nand_bbt_descr *td: the BBT description
  • struct nand_bbt_descr *md: the mirror BBT descriptor
  • int 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_bbt_block_bad(struct nand_chip *this, struct nand_bbt_descr *td, int chip, int block)

Mark one of the block reserved for BBT bad

Parameters

  • struct nand_chip *this: the NAND device
  • struct nand_bbt_descr *td: the BBT description
  • int chip: the CHIP selector
  • int 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 write_bbt(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *td, struct nand_bbt_descr *md, int chipsel)

[GENERIC] (Re)write the bad block table

Parameters

  • struct nand_chip *this: NAND chip object
  • uint8_t *buf: temporary buffer
  • struct nand_bbt_descr *td: descriptor for the bad block table
  • struct nand_bbt_descr *md: descriptor for the bad block table mirror
  • int chipsel: selector for a specific chip, -1 for all

Description

(Re)write the bad block table.

nand_memory_bbt() #

int nand_memory_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)

[GENERIC] create a memory based bad block table

Parameters

  • struct nand_chip *this: NAND chip object
  • struct 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 check_create(struct nand_chip *this, uint8_t *buf, struct nand_bbt_descr *bd)

[GENERIC] create and write bbt(s) if necessary

Parameters

  • struct nand_chip *this: the NAND device
  • uint8_t *buf: temporary buffer
  • struct 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 nand_update_bbt(struct nand_chip *this, loff_t offs)

update bad block table(s)

Parameters

  • struct nand_chip *this: the NAND device
  • loff_t offs: the offset of the newly marked block

Description

The function updates the bad block table(s).

mark_bbt_region() #

void mark_bbt_region(struct nand_chip *this, struct nand_bbt_descr *td)

[GENERIC] mark the bad block table regions

Parameters

  • struct nand_chip *this: the NAND device
  • struct 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_bbt_descr(struct nand_chip *this, struct nand_bbt_descr *bd)

verify the bad block description

Parameters

  • struct nand_chip *this: the NAND device
  • struct 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_scan_bbt(struct nand_chip *this, struct nand_bbt_descr *bd)

[NAND Interface] scan, find, read and maybe create bad block table(s)

Parameters

  • struct nand_chip *this: the NAND device
  • struct 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 nand_create_badblock_pattern(struct nand_chip *this)

[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_isreserved_bbt(struct nand_chip *this, loff_t offs)

[NAND Interface] Check if a block is reserved

Parameters

  • struct nand_chip *this: NAND chip object
  • loff_t offs: offset in the device

nand_isbad_bbt() #

int nand_isbad_bbt(struct nand_chip *this, loff_t offs, int allowbbt)

[NAND Interface] Check if a block is bad

Parameters

  • struct nand_chip *this: NAND chip object
  • loff_t offs: offset in the device
  • int allowbbt: allow access to bad block table region

nand_markbad_bbt() #

int nand_markbad_bbt(struct nand_chip *this, loff_t offs)

[NAND Interface] Mark a block bad in the BBT

Parameters

  • struct nand_chip *this: NAND chip object
  • loff_t offs: offset of the bad block

Credits #

The following people have contributed to the NAND driver:

  1. Steven J. Hillsjhill@realitydiluted.com

  2. David Woodhousedwmw2@infradead.org

  3. 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:

  1. 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

struct ccw1 {
    __u8 cmd_code;
    __u8 flags;
    __u16 count;
    dma32_t cda;
};

Members

  • cmd_code: command code
  • flags: flags, like IDA addressing, etc.
  • count: byte count
  • cda: 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

struct ccw0 {
    __u8 cmd_code;
    __u32 cda : 24;
    __u8 flags;
    __u8 reserved;
    __u16 count;
};

Members

  • cmd_code: command code
  • cda: data address
  • flags: flags, like IDA addressing, etc.
  • reserved: will be ignored
  • count: byte count

Description

The format-0 ccw structure.

struct erw #

extended report word

Definition

struct erw {
    __u32 res0  : 3;
    __u32 auth  : 1;
    __u32 pvrf  : 1;
    __u32 cpt   : 1;
    __u32 fsavf : 1;
    __u32 cons  : 1;
    __u32 scavf : 1;
    __u32 fsaf  : 1;
    __u32 scnt  : 6;
    __u32 res16 : 16;
};

Members

  • res0: reserved
  • auth: authorization check
  • pvrf: path-verification-required flag
  • cpt: channel-path timeout
  • fsavf: failing storage address validity flag
  • cons: concurrent sense
  • scavf: secondary ccw address validity flag
  • fsaf: failing storage address format
  • scnt: sense count, if cons == 1
  • res16: reserved

struct erw_eadm #

EADM Subchannel extended report word

Definition

struct erw_eadm {
    __u32 : 16;
    __u32 b : 1;
    __u32 r : 1;
    __u32 : 14;
};

Members

  • b: aob error
  • r: arsb error

struct sublog #

subchannel logout area

Definition

struct sublog {
    __u32 res0  : 1;
    __u32 esf   : 7;
    __u32 lpum  : 8;
    __u32 arep  : 1;
    __u32 fvf   : 5;
    __u32 sacc  : 2;
    __u32 termc : 2;
    __u32 devsc : 1;
    __u32 serr  : 1;
    __u32 ioerr : 1;
    __u32 seqc  : 3;
};

Members

  • res0: reserved
  • esf: extended status flags
  • lpum: last path used mask
  • arep: ancillary report
  • fvf: field-validity flags
  • sacc: storage access code
  • termc: termination code
  • devsc: device-status check
  • serr: secondary error
  • ioerr: i/o-error alert
  • seqc: sequence code

struct esw0 #

Format 0 Extended Status Word (ESW)

Definition

struct esw0 {
    struct sublog sublog;
    struct erw erw;
    dma32_t faddr[2];
    dma32_t saddr;
};

Members

  • sublog: subchannel logout
  • erw: extended report word
  • faddr: failing storage address
  • saddr: secondary ccw address

struct esw1 #

Format 1 Extended Status Word (ESW)

Definition

struct esw1 {
    __u8 zero0;
    __u8 lpum;
    __u16 zero16;
    struct erw erw;
    __u32 zeros[3];
};

Members

  • zero0: reserved zeros
  • lpum: last path used mask
  • zero16: reserved zeros
  • erw: extended report word
  • zeros: three fullwords of zeros

struct esw2 #

Format 2 Extended Status Word (ESW)

Definition

struct esw2 {
    __u8 zero0;
    __u8 lpum;
    __u16 dcti;
    struct erw erw;
    __u32 zeros[3];
};

Members

  • zero0: reserved zeros
  • lpum: last path used mask
  • dcti: device-connect-time interval
  • erw: extended report word
  • zeros: three fullwords of zeros

struct esw3 #

Format 3 Extended Status Word (ESW)

Definition

struct esw3 {
    __u8 zero0;
    __u8 lpum;
    __u16 res;
    struct erw erw;
    __u32 zeros[3];
};

Members

  • zero0: reserved zeros
  • lpum: last path used mask
  • res: reserved
  • erw: extended report word
  • zeros: three fullwords of zeros

struct esw_eadm #

EADM Subchannel Extended Status Word (ESW)

Definition

struct esw_eadm {
    __u32 sublog;
    struct erw_eadm erw;
    __u32 : 32;
    __u32 : 32;
    __u32 : 32;
};

Members

  • sublog: subchannel logout
  • erw: extended report word

struct irb #

interruption response block

Definition

struct irb {
    union scsw scsw;
    union {
        struct esw0 esw0;
        struct esw1 esw1;
        struct esw2 esw2;
        struct esw3 esw3;
        struct esw_eadm eadm;
    } esw;
    __u8 ecw[32];
};

Members

  • scsw: subchannel status word
  • esw: extended status word
  • ecw: 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

struct ciw {
    __u32 et       :  2;
    __u32 reserved :  2;
    __u32 ct       :  4;
    __u32 cmd      :  8;
    __u32 count    : 16;
};

Members

  • et: entry type
  • reserved: reserved bits
  • ct: command type
  • cmd: command code
  • count: command count

struct ccw_dev_id #

unique identifier for ccw devices

Definition

struct ccw_dev_id {
    u8 ssid;
    u16 devno;
};

Members

  • ssid: subchannel set id
  • devno: 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 ccw_dev_id_is_equal(struct ccw_dev_id *dev_id1, struct ccw_dev_id *dev_id2)

compare two ccw_dev_ids

Parameters

  • struct ccw_dev_id *dev_id1: a ccw_dev_id
  • struct 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 pathmask_to_pos(u8 mask)

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

struct ccw_device {
    spinlock_t *ccwlock;
    struct ccw_device_id id;
    struct ccw_driver *drv;
    struct device dev;
    int online;
    void (*handler) (struct ccw_device *, unsigned long, struct irb *);
};

Members

  • ccwlock: pointer to device lock
  • id: id of this device
  • drv: ccw driver for this device
  • dev: embedded device structure
  • online: online status of device
  • handler: 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

struct ccw_driver {
    struct ccw_device_id *ids;
    int (*probe) (struct ccw_device *);
    void (*remove) (struct ccw_device *);
    int (*set_online) (struct ccw_device *);
    int (*set_offline) (struct ccw_device *);
    int (*notify) (struct ccw_device *, int);
    void (*path_event) (struct ccw_device *, int *);
    void (*shutdown) (struct ccw_device *);
    enum uc_todo (*uc_handler) (struct ccw_device *, struct irb *);
    struct device_driver driver;
    enum interruption_class int_class;
};

Members

  • ids: ids supported by this driver
  • probe: function called on probe
  • remove: function called on remove
  • set_online: called when setting device online
  • set_offline: called when setting device offline
  • notify: notify driver of device state changes
  • path_event: notify driver of channel path events
  • shutdown: called at device shutdown
  • uc_handler: callback for unit check handler
  • driver: embedded device driver structure
  • int_class: interruption class to use for accounting interrupts

ccw_device_set_offline() #

int ccw_device_set_offline(struct ccw_device *cdev)

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 ccw_device_set_online(struct ccw_device *cdev)

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 * get_ccwdev_by_dev_id(struct ccw_dev_id *dev_id)

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 * get_ccwdev_by_busid(struct ccw_driver *cdrv, const char *bus_id)

obtain device from a bus id

Parameters

  • struct ccw_driver *cdrv: driver the device is owned by
  • const 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 ccw_driver_register(struct ccw_driver *cdriver)

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 ccw_driver_unregister(struct ccw_driver *cdriver)

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 ccw_device_siosl(struct ccw_device *cdev)

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 ccw_device_set_options_mask(struct ccw_device *cdev, unsigned long flags)

set some options and unset the rest

Parameters

  • struct ccw_device *cdev: device for which the options are to be set
  • unsigned 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 ccw_device_set_options(struct ccw_device *cdev, unsigned long flags)

set some options

Parameters

  • struct ccw_device *cdev: device for which the options are to be set
  • unsigned 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 ccw_device_clear_options(struct ccw_device *cdev, unsigned long flags)

clear some options

Parameters

  • struct ccw_device *cdev: device for which the options are to be cleared
  • unsigned long flags: options to be cleared

Description

All flags specified in flags are cleared, the remainder is left untouched.

ccw_device_is_pathgroup() #

int ccw_device_is_pathgroup(struct ccw_device *cdev)

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 ccw_device_is_multipath(struct ccw_device *cdev)

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 ccw_device_clear(struct ccw_device *cdev, unsigned long intparm)

terminate I/O request processing

Parameters

  • struct ccw_device *cdev: target ccw device
  • unsigned 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 ccw_device_start_timeout_key(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, __u8 key, unsigned long flags, int expires)

start a s390 channel program with timeout and key

Parameters

  • struct ccw_device *cdev: target ccw device
  • struct ccw1 *cpa: logical start address of channel program
  • unsigned 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/O
  • 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_start_key() #

int ccw_device_start_key(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, __u8 key, unsigned long flags)

start a s390 channel program with key

Parameters

  • struct ccw_device *cdev: target ccw device
  • struct ccw1 *cpa: logical start address of channel program
  • unsigned 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/O
  • 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() #

int ccw_device_start(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, unsigned long flags)

start a s390 channel program

Parameters

  • struct ccw_device *cdev: target ccw device
  • struct ccw1 *cpa: logical start address of channel program
  • unsigned 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 ccw_device_start_timeout(struct ccw_device *cdev, struct ccw1 *cpa, unsigned long intparm, __u8 lpm, unsigned long flags, int expires)

start a s390 channel program with timeout

Parameters

  • struct ccw_device *cdev: target ccw device
  • struct ccw1 *cpa: logical start address of channel program
  • unsigned 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 ccw_device_halt(struct ccw_device *cdev, unsigned long intparm)

halt I/O request processing

Parameters

  • struct ccw_device *cdev: target ccw device
  • unsigned 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 ccw_device_resume(struct ccw_device *cdev)

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 * ccw_device_get_ciw(struct ccw_device *cdev, __u32 ct)

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 ccw_device_get_path_mask(struct ccw_device *cdev)

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 * ccw_device_get_chp_desc(struct ccw_device *cdev, int chp_idx)

return newly allocated channel-path descriptor

Parameters

  • struct ccw_device *cdev: device to obtain the descriptor for
  • int 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 * ccw_device_get_util_str(struct ccw_device *cdev, int chp_idx)

return newly allocated utility strings

Parameters

  • struct ccw_device *cdev: device to obtain the utility strings for
  • int 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 ccw_device_get_id(struct ccw_device *cdev, struct ccw_dev_id *dev_id)

obtain a ccw device id

Parameters

  • struct ccw_device *cdev: device to obtain the id for
  • struct ccw_dev_id *dev_id: where to fill in the values

ccw_device_tm_start_timeout_key() #

int ccw_device_tm_start_timeout_key(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, u8 key, int expires)

perform start function

Parameters

  • struct ccw_device *cdev: ccw device on which to perform the start function
  • struct tcw *tcw: transport-command word to be started
  • unsigned long intparm: user defined parameter to be passed to the interrupt handler
  • u8 lpm: mask of paths to use
  • u8 key: storage key to use for storage access
  • int 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 ccw_device_tm_start_key(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, u8 key)

perform start function

Parameters

  • struct ccw_device *cdev: ccw device on which to perform the start function
  • struct tcw *tcw: transport-command word to be started
  • unsigned long intparm: user defined parameter to be passed to the interrupt handler
  • u8 lpm: mask of paths to use
  • u8 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 ccw_device_tm_start(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm)

perform start function

Parameters

  • struct ccw_device *cdev: ccw device on which to perform the start function
  • struct tcw *tcw: transport-command word to be started
  • unsigned long intparm: user defined parameter to be passed to the interrupt handler
  • u8 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 ccw_device_tm_start_timeout(struct ccw_device *cdev, struct tcw *tcw, unsigned long intparm, u8 lpm, int expires)

perform start function

Parameters

  • struct ccw_device *cdev: ccw device on which to perform the start function
  • struct tcw *tcw: transport-command word to be started
  • unsigned long intparm: user defined parameter to be passed to the interrupt handler
  • u8 lpm: mask of paths to use
  • int 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 ccw_device_get_mdc(struct ccw_device *cdev, u8 mask)

accumulate max data count

Parameters

  • struct ccw_device *cdev: ccw device for which the max data count is accumulated
  • u8 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 ccw_device_tm_intrg(struct ccw_device *cdev)

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 ccw_device_get_schid(struct ccw_device *cdev, struct subchannel_id *schid)

obtain a subchannel id

Parameters

  • struct ccw_device *cdev: device to obtain the id for
  • struct subchannel_id *schid: where to fill in the values

ccw_device_pnso() #

int ccw_device_pnso(struct ccw_device *cdev, struct chsc_pnso_area *pnso_area, u8 oc, struct chsc_pnso_resume_token resume_token, int cnc)

Perform Network-Subchannel Operation

Parameters

  • struct ccw_device *cdev: device on which PNSO is performed
  • struct chsc_pnso_area *pnso_area: request and response block for the operation
  • u8 oc: Operation Code
  • struct chsc_pnso_resume_token resume_token: resume token for multiblock response
  • int 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 ccw_device_get_cssid(struct ccw_device *cdev, u8 *cssid)

obtain Channel Subsystem ID

Parameters

  • struct ccw_device *cdev: device to obtain the CSSID for
  • u8 *cssid: The resulting Channel Subsystem ID

ccw_device_get_iid() #

int ccw_device_get_iid(struct ccw_device *cdev, u8 *iid)

obtain MIF-image ID

Parameters

  • struct ccw_device *cdev: device to obtain the MIF-image ID for
  • u8 *iid: The resulting MIF-image ID

ccw_device_get_chpid() #

int ccw_device_get_chpid(struct ccw_device *cdev, int chp_idx, u8 *chpid)

obtain Channel Path ID

Parameters

  • struct ccw_device *cdev: device to obtain the Channel Path ID for
  • int chp_idx: Index of the channel path
  • u8 *chpid: The resulting Channel Path ID

ccw_device_get_chid() #

int ccw_device_get_chid(struct ccw_device *cdev, int chp_idx, u16 *chid)

obtain Channel ID associated with specified CHPID

Parameters

  • struct ccw_device *cdev: device to obtain the Channel ID for
  • int chp_idx: Index of the channel path
  • u16 *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

struct cmbdata {
    __u64 size;
    __u64 elapsed_time;
    __u64 ssch_rsch_count;
    __u64 sample_count;
    __u64 device_connect_time;
    __u64 function_pending_time;
    __u64 device_disconnect_time;
    __u64 control_unit_queuing_time;
    __u64 device_active_only_time;
    __u64 device_busy_time;
    __u64 initial_command_response_time;
};

Members

  • size: size of the stored data
  • elapsed_time: time since last sampling
  • ssch_rsch_count: number of ssch and rsch
  • sample_count: number of samples
  • device_connect_time: time of device connect
  • function_pending_time: time of function pending
  • device_disconnect_time: time of device disconnect
  • control_unit_queuing_time: time of control unit queuing
  • device_active_only_time: time of device active only
  • device_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 enable_cmf(struct ccw_device *cdev)

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 disable_cmf(struct ccw_device *cdev)

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 cmf_read(struct ccw_device *cdev, int index)

read one value from the current channel measurement block

Parameters

  • struct ccw_device *cdev: the channel to be read
  • int 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 cmf_readall(struct ccw_device *cdev, struct cmbdata *data)

read the current channel measurement block

Parameters

  • struct ccw_device *cdev: the channel to be read
  • struct 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

struct ccwgroup_device {
    enum {
        CCWGROUP_OFFLINE,
        CCWGROUP_ONLINE,
    } state;
    unsigned int count;
    struct device   dev;
    struct work_struct ungroup_work;
    struct ccw_device *cdev[];
};

Members

  • state: online/offline state
  • count: number of attached slave devices
  • dev: embedded device structure
  • ungroup_work: used to ungroup the ccwgroup device
  • cdev: variable number of slave devices, allocated as needed

struct ccwgroup_driver #

driver for ccw group devices

Definition

struct ccwgroup_driver {
    int (*setup) (struct ccwgroup_device *);
    void (*remove) (struct ccwgroup_device *);
    int (*set_online) (struct ccwgroup_device *);
    int (*set_offline) (struct ccwgroup_device *);
    void (*shutdown)(struct ccwgroup_device *);
    struct device_driver driver;
    struct ccw_driver *ccw_driver;
};

Members

  • setup: function called during device creation to setup the device
  • remove: function called on remove
  • set_online: function called when device is set online
  • set_offline: function called when device is set offline
  • shutdown: function called when device is shut down
  • driver: embedded driver structure
  • ccw_driver: supported ccw_driver (optional)

ccwgroup_set_online() #

int ccwgroup_set_online(struct ccwgroup_device *gdev)

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 ccwgroup_set_offline(struct ccwgroup_device *gdev, bool call_gdrv)

disable a ccwgroup device

Parameters

  • struct ccwgroup_device *gdev: target ccwgroup device
  • bool 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 ccwgroup_create_dev(struct device *parent, struct ccwgroup_driver *gdrv, int num_devices, const char *buf)

create and register a ccw group device

Parameters

  • struct device *parent: parent device for the new device
  • struct ccwgroup_driver *gdrv: driver for the new group device
  • int num_devices: number of slave devices
  • const 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 ccwgroup_driver_register(struct ccwgroup_driver *cdriver)

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 ccwgroup_driver_unregister(struct ccwgroup_driver *cdriver)

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 ccwgroup_probe_ccwdev(struct ccw_device *cdev)

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 ccwgroup_remove_ccwdev(struct ccw_device *cdev)

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(struct airq_struct *airq)

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(struct airq_struct *airq)

unregister adapter interrupt handler

Parameters

  • struct airq_struct *airq: pointer to adapter interrupt descriptor

airq_iv_create() #

struct airq_iv * airq_iv_create(unsigned long bits, unsigned long flags, unsigned long *vec)

create an interrupt vector

Parameters

  • unsigned long bits: number of bits in the interrupt vector
  • unsigned long flags: allocation flags
  • unsigned long *vec: pointer to pinned guest memory if AIRQ_IV_GUESTVEC

Description

Returns a pointer to an interrupt vector structure

airq_iv_release() #

void airq_iv_release(struct airq_iv *iv)

release an interrupt vector

Parameters

  • struct airq_iv *iv: pointer to interrupt vector structure

airq_iv_alloc() #

unsigned long airq_iv_alloc(struct airq_iv *iv, unsigned long num)

allocate irq bits from an interrupt vector

Parameters

  • struct airq_iv *iv: pointer to an interrupt vector structure
  • unsigned 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 airq_iv_free(struct airq_iv *iv, unsigned long bit, unsigned long num)

free irq bits of an interrupt vector

Parameters

  • struct airq_iv *iv: pointer to interrupt vector structure
  • unsigned long bit: number of the first irq bit to free
  • unsigned long num: number of consecutive irq bits to free

airq_iv_scan() #

unsigned long airq_iv_scan(struct airq_iv *iv, unsigned long start, unsigned long end)

scan interrupt vector for non-zero bits

Parameters

  • struct airq_iv *iv: pointer to interrupt vector structure
  • unsigned long start: bit number to start the search
  • unsigned 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 by mmap() to get to the actual device memory. This is important if the device's memory is not page aligned. Remember that pointers returned by mmap() 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 with mmap(). For each mapping you need to fill one of the uio_mem structures. 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 the uio_port structures. 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, set irq to UIO_IRQ_CUSTOM. If you had no interrupt at all, you could set irq to UIO_IRQ_NONE, though this rarely makes sense.

  • unsigned long irq_flags: Required if you've set irq to a hardware interrupt number. The flags given here will be used in the call to request_irq().

  • int (*mmap)(struct uio_info *info, struct vm_area_struct *vma): Optional. If you need a special mmap() function, you can set it here. If this pointer is not NULL, your mmap() 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 own open(), 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 own open(), you will probably also want a custom release() 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 parameter irq_on will 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 to UIO_MEM_PHYS if you have physical memory on your card to be mapped. Use UIO_MEM_LOGICAL for logical memory (e.g. allocated with __get_free_pages() but not kmalloc()). There's also UIO_MEM_VIRTUAL for 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 that addr points to. If size is zero, the mapping is considered unused. Note that you must initialize size with 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 like ioremap(). Addresses returned by this function cannot be mapped to user space, so you must not store it in addr. Use internal_addr instead 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. Use UIO_PORT_X86 for 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. If size is zero, the region is considered unused. Note that you must initialize size with 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 the uio_pdrv_genirq platform 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 in dynamic_region_sizes array.

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:

    1. Channel ring buffers: guest to host and host to guest

    2. Guest to host interrupt signalling pages

    3. Guest to host monitor page

    4. Network receive buffer region

    5. 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 #

  • OSADL homepage.

  • Linutronix homepage.

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 #

  1. See Documentation/driver-api/vfio.rst for more information on VFIO.

  2. struct mdev_driver in include/linux/mdev.h

  3. struct mdev_parent_ops in include/linux/mdev.h

  4. 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 chown examples 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, &reg);

        /* 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.
     */
    
    ....
    
  5. 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.

  6. 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).

Peios Learn — documentation for Peios software.

Built with Trail.