Linux kernel Gpiolib__linux

Source: Internet
Author: User
Identify ports-------------
Gpio uses an integer ID between 0~max_int and cannot use negative numbers. Use the following function to check the legality of a port number: int gpio_is_valid (int number);
using GpioThe first step-------------using IO is to allocate ports, using Gpio_request (). The next thing to do is to mark its direction.  /* Set to input or output, successfully return 0 or failure to return negative error value */int gpio_direction_input (unsigned gpio); int gpio_direction_output (unsigned gpio, int value); Typically, you should check their return values. It is generally assumed that the two interfaces will be invoked in the thread context. However, Gpio for spin lock security can also be used between early initialization before a thread appears.
For the gpio of the output, the supplied value is used as the initial value of the output.
GPIO using spin lock security----------------------------------most GPIO controllers can be accessed using memory read-write instructions that do not require sleep and can be accessed at the interrupt context.
For gpio_cansleep return fake Gpio can use the following interface access:/* Read input, return 0 or not 0 */int gpio_get_value (unsigned gpio); /* Output/void Gpio_set_value (unsigned gpio, int value); The returned value is a Boolean value, and 0 represents a low, not 0-level. When reading the value of the output pin, the return value should be the actual state on the pin, which is not necessarily equal to the configured output value, because it takes a certain amount of time to signal stability from the set signal.
Not all platforms can read the output pin values, and these platforms cannot always return zeros. Using these two functions to access gpio that cannot be safely accessed in a sleep context will be an error.
Gpio that can be accessed in the hibernation context----------------------------------------------some GPIO controllers must use information based buses, such as I2C and SPI. Commands that read and write Gpio values need to wait in the queue. Manipulating these gpio may sleep and cannot be invoked in an interrupt context.
A platform that supports this gpio in order to differentiate other types of gpio by returning zero in this function (requires a GPIO number that has already been applied gpio_request): int gpio_cansleep (unsigned gpio);
To access these ports, another set of function interfaces is defined:/* Input port: return 0 or Non-zero, possibly sleep/int gpio_get_value_cansleep (unsigned gpio); /* Output port: May sleep/void gpio_set_value_cansleep (unsigned gpio, int value); These ports can be accessed only in contexts where sleep is allowed, such as in threaded interrupts, which must be used instead of a spin-lock security interface without a cansleep prefix.
In addition to the fact that these interfaces may sleep, they manipulate the ports that cannot be accessed in the interrupt handler function, and the performance of these calls is consistent with the invocation of the spin lock security.
In addition: invoking the installation and configuration of such gpio must be in a restful context because they may need access to the GPIO controller. Gpio_direction_input () Gpio_direction_output () gpio_request ()
# # Gpio_request_one () # # Gpio_request_array () # # Gpio_free_array () #
Gpio_free () gpio_set_debounce ()

application and release of Gpio------------------------to get a system configuration error, two calls are defined:/* request Gpio, return 0 or negative error value * Non-empty lables pointers help diagnose/int gpio_request (unsigned gpio, const char *label); /* release of gpio*/void Gpio_free (unsigned gpio) previously requested; It should be assumed that these two functions are called in the context of the process, but gpio for spin-lock security can also be invoked from an earlier boot process prior to the process's establishment.
Given that in most cases gpio will need to be configured immediately after the application, the following three interfaces are responsible for these tasks:
/* Request a separate GPIO, using "flag" as the initial configuration parameter
/int gpio_request_one (unsigned gpio, unsigned long flags, const char *label);

/* Request multiple gpio*/
int gpio_request_array (struct gpio *array, size_t num) in one call;

/* Free Multiple ports *
/void Gpio_free_array (struct gpio *array, size_t num);


"Flag" is used to configure the following features: * gpiof_dir_in-Configuration direction for input * gpiof_dir_out-Configuration direction for output * G Piof_init_low-Do output pins, output low level * Gpiof_init_high-do output pins, output high level
In order to handle multiple gpio at the same time, a specialized structure is defined: struct Gpio {unsigned gpio;                  unsigned long flags;          const char *label; };

Typical use is as follows:

static struct Gpio leds_gpios[] = {{*,
                Gpiof_out_init_high, "Power LED"},/* default to ON * *
                , Gpiof_out_ Init_low,  "Green led"},/* default to OFF * *,
                Gpiof_out_init_low,  "Red led"   },/* default to OFF */< c7/>{, Gpiof_out_init_low,  "Blue LED"  },/* default to OFF *
                /{...},
        };

        Err = Gpio_request_one (To, gpiof_in, "Reset button");
        if (err) ...

        Err = Gpio_request_array (Leds_gpios, Array_size (Leds_gpios));
        if (err) ...
                

        

Gpio map to IRQ

------------------------

 
/* Map GPIO numbers to IRQ numbers *
   /int Gpio_to_irq (unsigned GPIO);

/* Map IRQ numbers to GPIO numbers (avoid using this) * *
   

The return value is the corresponding number or a negative error code. Using an GPIO number that is not installed with gpio_direction_input () or an interrupt number that is not obtained from GPIO_TO_IRQ () is an error that will not be checked by Gpio.
The interrupt number returned by GPIO_TO_IRQ () can be passed to REQUEST_IRQ () and FREE_IRQ (). The GPIO number returned by Irq_to_gpio () is typically used to invoke Gpio_get_value (), such as the state of the pin being fetched along a triggered interrupt. Some platforms do not support this mapping and should avoid calling mapping functions.
Analog leaky electrode open circuit------------------Gpio may or may not support open drain output. If the hardware is not supported, you can simulate the input or output of the open drain output: low:gpio_direction_output (gpio, 0) ignores the pull resistor. High:gpio_direction_input (GPIO) closes the output and pulls the resistance control signal. If the drive outputs a high level but gpio_get_value (GPIO) reports a low level (after a certain delay), it can be concluded that the other parts are outputting low levels on the signal line.
GPIO Framework (optional)The =============== GPIO framework is implemented in Gpiolib. If the Debugfs can be made, the/sys/kernel/debug/gpio file will appear under the system. The status of all the controllers registered within the framework and the GPIO currently in use will be listed in this file.
Controller driver: gpio_chip-------------------------------use "struct gpio_chip" in the GPIO framework to represent all of the information for each controller:--the way to set the gpio direction--the way to access the GPIO state--to indicate whether the sign of sleep -optional Debugfs Method-Diagnostic label lable (char pointer) Of course, there are unique data for each instance (possibly from Dev.platform_data), number of the first Gpio, and number of Gpio to manage.
Gpiolib supports instances of multiple GPIO controllers, registers using Gpiochip_add (), and logs out using Gpiochip_remove (). The Debugfs method of Gpio_chip will ignore gpio that have not been applied. Using gpiochip_is_requested () will return Null (not requested) or lable (has been requested)
Platform Support------------to support the GPIO framework, you must select the options in Kconfig: Arch_require_gpiolib or Arch_want_optional_gpiolib. and include <asm-generic/gpio.h&gt in <asm/gpio.h>, and define three functions: Gpio_get_value (), Gpio_set_value (), and Gpio_cansleep ( ). The Arch_nr_gpios definition can also be provided to reflect the number of GPIO supported by the platform.
Arch_require_gpiolib indicates that gpiolib code is always compiled into the kernel. Arch_want_optional_gpiolib means that Gpiolib is closed by default, but the user can make it and compile it into the kernel. If neither of these options is selected, Gpiolib cannot be enabled by the user.
Typically, the three function interfaces can be used to directly use the code within the framework (called Via Gpio_chip): #define Gpio_get_value __gpio_get_value GP #define Io_set_value __gpio_set_value #define GPIO_CANSLEEP __gpio_cansleep

SYSFS Interface for user space (optional)==================
The path under Sysfs---------------------has three types of entrances under/sys/class/gpio:----User Space Control Gpio interface (first category)--corresponds to specific gpio --gpio Controller (instance of "Gpio_chip") (third Class) The above interfaces do not include standard "device" files and their links.
Control Interface (First Class) is written only:             /sys/class/gpio/                           "Export" User space to request the kernel to export control of a gpio to user space by writing the GPIO number                                  such as "Echo > Export" A node "GPIO19" will be created for number 19th Gpio, provided the port is not requested within and code.                           "Unexport" is the opposite of the export effect.                                       for example "Echo > Unexport" will remove "gpio19" thisNodes. The path to the Gpio pin is similar to the/sys/class/gpio/gpio42/(for Gpio #42) and has the following writable properties:              /sys/class/gpio/gpioN/   (Type II)                           " Direction "The read result is" in "or" out ". You can also write to it. Write ' out ' defaults to initialize the PIN value to low.                                       Write "Low" or "high" can initialize the initial value as output.                                       This property will not exist if the kernel does not support it or if the kernel code is unwilling.                           "value" read the result is 0 (low level) or 1 (High level). If the GPIO is configured for output, this value is writable,                                        any Non-zero value will output a high level.                                       If a pin can and has been configured to generate interrupts, it can invoke poll (2) on its node and poll (2) will return after the interrupt trigger.                                       If you use Poll (2), set the event type to Pollpri and Pollerr. If you use Sellect (2), add the file descriptor to the Exceptfds.                                       after poll (2) return, you can use Lseek (2) Move to the beginning of the file to read the new value or close it and reopen the read new value.                           "Edge"     read change node will get the following values: "None", "Rising", "falling", or   Both ". Writing such as these strings to this node will select                                        wake up the signal along the poll (2) on "value".                                       This file node only exists when the PIN can be configured to enter an interrupt pin.                         &nbsP; " Active_low Read value is 0 (false) or 1 (true). Writing any Non-zero value reverses the read and write values in "value".                                       The "rasing" and "Falling" values of "edge" nodes that have been used and then used poll (2) will be affected by "Active_low".                                       (Your own understanding: This value actually turns the height into 0, the low to 1.) That is, to achieve a logical reversal. )
The path to the Gpio controller is similar to the/sys/class/gpio/gpiochip42/(the minimum port for this controller is 42) and has the following read-write properties:/sys/class/gpio/gpiochipn/                         "Base" is the same as N, which is the smallest port number managed by the controller. The "lable" diagnostics use flags (not always unique) the number of ports managed by the "Ngpio" Controller (port range is: N ~ n+ngpio-1)

exporting from kernel spaceThe------------------------kernel can explicitly manage the export of Gpio that has been gpio_request () requested. /* Export Gpio to User space Sysfs, when allowing user space to modify the direction of Gpio, the second parameter is true/int gpio_export (unsigned gpio, bool direction_may_change);

/* Undo Gpio Export/void Gpio_unexport ();

/* Create SYSFS link to export Gpio, the first parameter is created under which Dev, the second parameter name, the third is gpio number */int gpio_export_link (struct device *dev, const C Har *name, unsigned gpio)

/* Change the polarity of the Gpio node in the Sysfs, that is, the logic inversion of the high-low level. can be done before and after export. The Enabled Poll (2) previously set will also change the/int gpio_sysfs_set_active_low (unsigned gpio, int value) accordingly;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ above is the content of the kernel document, the following analysis of the content of gpio_chip, this is a controller.   48/**   struct Gpio_chip-a GPIO controller abstract   x @label: Diagnostic label (name)   @dev: Optional Device structure   @owner: Owner module Pointer   @request: Optional activation callback function, just like the power management interface. Can sleep   @free: Optional release callback function, can sleep.   * @direction_input: Configure an offset corresponding to the port for the input pin, may return an error.   @get: Returns the value of the corresponding offset pin; If it is an output pin, the state of the output pin is returned or zero is returned.   * @direction_output: Configure output values for output pins, or return error   @set: Sets the output value of the specified pin.   @to_irq: Optional callback function, which supports non-static GPIO_TO_IRQ () mappings, and can not sleep;   * @dbg_show: Optional DEBUGFS interface; If not set, the kernel uses the default function to assign the pointer.   @base: The number of the first gpio managed by gpiogpio_chip; If the registration period is negative, a value will be dynamically requested.   @ngpio: The number of IO Gpio controller management, and the last IO number is   (base + ngpio-1).   @can_sleep: If the Get ()/set () method sleeps this flag must be set   @names: If this member is set, it must be an array of character pointers of ngpio size, Each member can point to the specific name of the corresponding PIN, or it can be empty.              name affects Exportgpio to SYSFS, if not set the name is "Gpion" (n is the number of IO corresponding))。               Of course this member can not initialize.
Gpio_chip uses offset (0~ (ngpio-1)) to distinguish between pins.
struct Gpio_chip {const char *label;
        struct device *dev;

        struct module *owner; Int (*request) (struct gpio_chip *chip, unsigned offset
        );

        void (*free) (struct gpio_chip *chip, unsigned offset);
                                                Int (*direction_input) (struct gpio_chip *chip,
        unsigned offset);
        Int (*get) (struct gpio_chip *chip, unsigned offset);
                                                Int (*direction_output) (struct gpio_chip *chip,
        unsigned offset, int value); Int (*set_debounce) (struct gpio_chip *chip, unsigned o

        Ffset, unsigned debounce);    void                (*set)

        (struct gpio_chip *chip, unsigned offset, int value); Int (*TO_IRQ) (struct gpio_chip *chip, unsigned offset)

        ; void (*dbg_show) (struct seq_file *s, struct gpio_chip *
        CHIP);
        int base;
        U16 Ngpio;
        const char *const *names;
        unsigned can_sleep:1;

unsigned exported:1;
         #if defined (CONFIG_OF_GPIO)/* If CONFIG_OF is enabled, then all GPIO controllers described in the
        * Device automatically may have of translation * * struct device_node *of_node;
        int of_gpio_n_cells;
Int (*of_xlate) (struct gpio_chip *gc, struct device_node *np, const void *gpio_spec, U32 *flags); #ENDIF};          
Gpio_chip Interface:
extern const char *gpiochip_is_requested (struct gpio_chip *chip, unsigned offset); Returns null if the OFFET corresponding Gpio has been applied, or returns a lable pointer or ".. ”


extern int __must_check gpiochip_reserve (int start, int ngpio);
Keep the Ngpio number of start
This function is to reserve a number in the global scope for future use by a gpio_chip.

Attached Gpiolib frame chart (based on s5pv210):



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.