first draft of libgpiod v2.0 API
Subsystems (2)
cover first draft of libgpiod v2.0 API
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenance
The new API is completely documented in include/gpiod.h doxygen comments.
Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
The branch from which this series was generated can be found on my github:
https://github.com/brgl/libgpiod-private/tree/topic/core-lib-API-v2
Bartosz Golaszewski (6):
treewide: rename chip property accessors
core: add refcounting helpers
core: implement line_info objects
core: rework line events
core: rework line requests
core: implement line watch events
bindings/cxx/chip.cpp | 6 +- bindings/python/gpiodmodule.c | 14 +- include/gpiod.h | 1224 +++++++++++++++++--------------- lib/Makefile.am | 15 +- lib/attr.c | 232 ++++++ lib/chip.c | 234 +++++++ lib/config.c | 158 +++++ lib/core.c | 1240 --------------------------------- lib/event.c | 218 ++++++ lib/handle.c | 126 ++++ lib/helpers.c | 302 -------- lib/info.c | 171 +++++ lib/internal.c | 147 ++++ lib/internal.h | 43 ++ lib/mask.c | 43 ++ lib/misc.c | 80 +++ lib/request.c | 118 ++++ lib/watch.c | 96 +++ tests/gpiod-test.h | 5 + tests/tests-chip.c | 33 +- tests/tests-event.c | 470 +++++++++---- tests/tests-line.c | 425 ++++++++--- tools/gpio-tools-test.bats | 12 +- tools/gpiodetect.c | 17 +- tools/gpiofind.c | 3 +- tools/gpioget.c | 57 +- tools/gpioinfo.c | 58 +- tools/gpiomon.c | 130 ++-- tools/gpioset.c | 85 ++- tools/tools-common.c | 8 +- tools/tools-common.h | 2 +- 31 files changed, 3255 insertions(+), 2517 deletions(-) create mode 100644 lib/attr.c create mode 100644 lib/chip.c create mode 100644 lib/config.c delete mode 100644 lib/core.c create mode 100644 lib/event.c create mode 100644 lib/handle.c delete mode 100644 lib/helpers.c create mode 100644 lib/info.c create mode 100644 lib/internal.c create mode 100644 lib/mask.c create mode 100644 lib/request.c create mode 100644 lib/watch.c
Signature · 1 line
2.30.1
RFC 1/6 treewide: rename chip property accessors
In v2 API all getters will be called using the following pattern:
gpiod_<object>_get_<what>
Apply this to already existing getters for gpiod_chip.
--- bindings/cxx/chip.cpp | 6 +++--- bindings/python/gpiodmodule.c | 14 +++++++------- include/gpiod.h | 6 +++--- lib/core.c | 6 +++--- lib/helpers.c | 6 +++--- tests/tests-chip.c | 25 ++++++++++++++----------- tools/gpiodetect.c | 6 +++--- tools/gpiofind.c | 2 +- tools/gpioinfo.c | 4 ++-- 9 files changed, 39 insertions(+), 36 deletions(-)
bindings/cxx/chip.cpp +3 -3
@@ -62,21 +62,21 @@ GPIOD_CXX_API ::std::string chip::name(void) const { this->throw_if_noref(); - return ::std::string(::gpiod_chip_name(this->_m_chip.get())); + return ::std::string(::gpiod_chip_get_name(this->_m_chip.get())); } GPIOD_CXX_API ::std::string chip::label(void) const { this->throw_if_noref(); - return ::std::string(::gpiod_chip_label(this->_m_chip.get())); + return ::std::string(::gpiod_chip_get_label(this->_m_chip.get())); } GPIOD_CXX_API unsigned int chip::num_lines(void) const { this->throw_if_noref(); - return ::gpiod_chip_num_lines(this->_m_chip.get()); + return ::gpiod_chip_get_num_lines(this->_m_chip.get()); } GPIOD_CXX_API line chip::get_line(unsigned int offset) const
bindings/python/gpiodmodule.c +7 -7
@@ -1918,9 +1918,9 @@ static PyObject *gpiod_Chip_repr(gpiod_ChipObject *self)return NULL ;return PyUnicode_FromFormat ("'%s /%s/ %u lines'" , -gpiod_chip_name (self->chip), -gpiod_chip_label (self->chip), -gpiod_chip_num_lines (self->chip)); +gpiod_chip_get_name (self->chip), +gpiod_chip_get_label (self->chip), +gpiod_chip_get_num_lines (self->chip)); } PyDoc_STRVAR(gpiod_Chip_close_doc,
@@ -1971,7 +1971,7 @@ static PyObject *gpiod_Chip_name(gpiod_ChipObject *self,if (gpiod_ChipIsClosed (self))return NULL ; -return PyUnicode_FromFormat ("%s" ,gpiod_chip_name (self->chip)); +return PyUnicode_FromFormat ("%s" ,gpiod_chip_get_name (self->chip)); } PyDoc_STRVAR(gpiod_Chip_label_doc,
@@ -1985,7 +1985,7 @@ static PyObject *gpiod_Chip_label(gpiod_ChipObject *self,if (gpiod_ChipIsClosed (self))return NULL ; -return PyUnicode_FromFormat ("%s" ,gpiod_chip_label (self->chip)); +return PyUnicode_FromFormat ("%s" ,gpiod_chip_get_label (self->chip)); } PyDoc_STRVAR(gpiod_Chip_num_lines_doc,
@@ -1999,7 +1999,7 @@ static PyObject *gpiod_Chip_num_lines(gpiod_ChipObject *self,if (gpiod_ChipIsClosed (self))return NULL ; -return Py_BuildValue ("I" ,gpiod_chip_num_lines (self->chip)); +return Py_BuildValue ("I" ,gpiod_chip_get_num_lines (self->chip)); } static gpiod_LineObject *
@@ -2381,7 +2381,7 @@ static gpiod_LineObject *gpiod_LineIter_next(gpiod_LineIterObject *self) {struct gpiod_line *line; -if (self->offset ==gpiod_chip_num_lines (self->owner->chip)) +if (self->offset ==gpiod_chip_get_num_lines (self->owner->chip))return NULL ;/* Last element. */ line =gpiod_chip_get_line (self->owner->chip, self->offset++);
include/gpiod.h +3 -3
@@ -94,21 +94,21 @@ void gpiod_chip_unref(struct gpiod_chip *chip);* @param chip The GPIO chip object. * @return Pointer to a human-readable string containing the chip name. */ -const char *gpiod_chip_name (struct gpiod_chip *chip); +const char *gpiod_chip_get_name (struct gpiod_chip *chip);/** * @brief Get the GPIO chip label as represented in the kernel. * @param chip The GPIO chip object. * @return Pointer to a human-readable string containing the chip label. */ -const char *gpiod_chip_label (struct gpiod_chip *chip); +const char *gpiod_chip_get_label (struct gpiod_chip *chip);/** * @brief Get the number of GPIO lines exposed by this chip. * @param chip The GPIO chip object. * @return Number of GPIO lines. */ -unsigned int gpiod_chip_num_lines (struct gpiod_chip *chip); +unsigned int gpiod_chip_get_num_lines (struct gpiod_chip *chip);/** * @brief Get the handle to the GPIO line at given offset.
lib/core.c +3 -3
@@ -335,17 +335,17 @@ GPIOD_API void gpiod_chip_unref(struct gpiod_chip *chip)free (chip); } -GPIOD_API const char *gpiod_chip_name(struct gpiod_chip *chip) +GPIOD_API const char *gpiod_chip_get_name(struct gpiod_chip *chip) {return chip->name; } -GPIOD_API const char *gpiod_chip_label(struct gpiod_chip *chip) +GPIOD_API const char *gpiod_chip_get_label(struct gpiod_chip *chip) {return chip->label; } -GPIOD_API unsigned int gpiod_chip_num_lines(struct gpiod_chip *chip) +GPIOD_API unsigned int gpiod_chip_get_num_lines(struct gpiod_chip *chip) {return chip->num_lines; }
lib/helpers.c +3 -3
@@ -45,11 +45,11 @@ gpiod_chip_get_all_lines(struct gpiod_chip *chip)struct gpiod_line *line;unsigned int offset; - bulk =gpiod_line_bulk_new (gpiod_chip_num_lines (chip)); + bulk =gpiod_line_bulk_new (gpiod_chip_get_num_lines (chip));if (!bulk)return NULL ; -for (offset =0 ; offset <gpiod_chip_num_lines (chip); offset++) { +for (offset =0 ; offset <gpiod_chip_get_num_lines (chip); offset++) { line =gpiod_chip_get_line (chip, offset);if (!line) {gpiod_line_bulk_free (bulk);
@@ -68,7 +68,7 @@ GPIOD_API int gpiod_chip_find_line(struct gpiod_chip *chip, const char *name)struct gpiod_line *line;const char *tmp; - num_lines =gpiod_chip_num_lines (chip); + num_lines =gpiod_chip_get_num_lines (chip);for (offset =0 ; offset < num_lines; offset++) { line =gpiod_chip_get_line (chip, offset);
tests/tests-chip.c +14 -11
@@ -63,9 +63,12 @@ GPIOD_TEST_CASE(get_name, 0, { 8, 8, 8})g_assert_nonnull (chip2);gpiod_test_return_if_failed (); - g_assert_cmpstr(gpiod_chip_name(chip0), ==, gpiod_test_chip_name(0)); - g_assert_cmpstr(gpiod_chip_name(chip1), ==, gpiod_test_chip_name(1)); - g_assert_cmpstr(gpiod_chip_name(chip2), ==, gpiod_test_chip_name(2)); + g_assert_cmpstr(gpiod_chip_get_name(chip0), ==, +gpiod_test_chip_name (0 )); + g_assert_cmpstr(gpiod_chip_get_name(chip1), ==, +gpiod_test_chip_name (1 )); + g_assert_cmpstr(gpiod_chip_get_name(chip2), ==, +gpiod_test_chip_name (2 )); } GPIOD_TEST_CASE(get_label, 0, { 8, 8, 8})
@@ -83,9 +86,9 @@ GPIOD_TEST_CASE(get_label, 0, { 8, 8, 8})g_assert_nonnull (chip2);gpiod_test_return_if_failed (); - g_assert_cmpstr(gpiod_chip_label(chip0), ==, "gpio-mockup-A"); - g_assert_cmpstr(gpiod_chip_label(chip1), ==, "gpio-mockup-B"); - g_assert_cmpstr(gpiod_chip_label(chip2), ==, "gpio-mockup-C"); + g_assert_cmpstr(gpiod_chip_get_label(chip0), ==, "gpio-mockup-A"); + g_assert_cmpstr(gpiod_chip_get_label(chip1), ==, "gpio-mockup-B"); + g_assert_cmpstr(gpiod_chip_get_label(chip2), ==, "gpio-mockup-C"); } GPIOD_TEST_CASE(num_lines, 0, { 1, 4, 8, 16, 32 })
@@ -109,11 +112,11 @@ GPIOD_TEST_CASE(num_lines, 0, { 1, 4, 8, 16, 32 })g_assert_nonnull (chip4);gpiod_test_return_if_failed (); - g_assert_cmpuint(gpiod_chip_num_lines(chip0), ==, 1); - g_assert_cmpuint(gpiod_chip_num_lines(chip1), ==, 4); - g_assert_cmpuint(gpiod_chip_num_lines(chip2), ==, 8); - g_assert_cmpuint(gpiod_chip_num_lines(chip3), ==, 16); - g_assert_cmpuint(gpiod_chip_num_lines(chip4), ==, 32); + g_assert_cmpuint(gpiod_chip_get_num_lines(chip0), ==, 1); + g_assert_cmpuint(gpiod_chip_get_num_lines(chip1), ==, 4); + g_assert_cmpuint(gpiod_chip_get_num_lines(chip2), ==, 8); + g_assert_cmpuint(gpiod_chip_get_num_lines(chip3), ==, 16); + g_assert_cmpuint(gpiod_chip_get_num_lines(chip4), ==, 32); } GPIOD_TEST_CASE(get_line, 0, { 16 })
tools/gpiodetect.c +3 -3
@@ -76,9 +76,9 @@ int main(int argc, char **argv) }printf ("%s [%s] (%u lines)\n" , -gpiod_chip_name (chip), -gpiod_chip_label (chip), -gpiod_chip_num_lines (chip)); +gpiod_chip_get_name (chip), +gpiod_chip_get_label (chip), +gpiod_chip_get_num_lines (chip));gpiod_chip_unref (chip);free (entries[i]);
tools/gpiofind.c +1 -1
@@ -76,7 +76,7 @@ int main(int argc, char **argv) offset =gpiod_chip_find_line (chip, argv[0 ]);if (offset >=0 ) {printf ("%s %u\n" , -gpiod_chip_name (chip), offset); +gpiod_chip_get_name (chip), offset);gpiod_chip_unref (chip);return EXIT_SUCCESS ; }
tools/gpioinfo.c +2 -2
@@ -130,9 +130,9 @@ static void list_lines(struct gpiod_chip *chip)int direction;printf ("%s - %u lines:\n" , -gpiod_chip_name (chip),gpiod_chip_num_lines (chip)); +gpiod_chip_get_name (chip),gpiod_chip_get_num_lines (chip)); -for (offset =0 ; offset <gpiod_chip_num_lines (chip); offset++) { +for (offset =0 ; offset <gpiod_chip_get_num_lines (chip); offset++) { line =gpiod_chip_get_line (chip, offset);if (!line)die_perror ("unable to retrieve the line object from chip" );
Signature · 1 line
2.30.1
RFC 2/6 core: add refcounting helpers
In reply to Bartosz GolaszewskiIn v2.0 all objects will be opaque and refcounted. Add a set of helper functions and data structures for refcounting.
--- lib/Makefile.am | 2 +- lib/core.c | 52 ++++++++++++++++++++++++++----------------------- lib/internal.c | 22 +++++++++++++++++++++ lib/internal.h | 19 ++++++++++++++++++ 4 files changed, 70 insertions(+), 25 deletions(-) create mode 100644 lib/internal.c
lib/Makefile.am +1 -1
@@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <[email protected]> lib_LTLIBRARIES = libgpiod.la -libgpiod_la_SOURCES = core.c helpers.c internal.h misc.c uapi/gpio.h +libgpiod_la_SOURCES = core.c helpers.c internal.c internal.h misc.c uapi/gpio.h libgpiod_la_CFLAGS = -Wall -Wextra -g -std=gnu89 libgpiod_la_CFLAGS += -fvisibility=hidden -I$(top_srcdir)/include/ libgpiod_la_CFLAGS += -include $(top_builddir)/config.h
lib/core.c +28 -24
81 lines not on this page · raw message
lib/internal.c new file +22 -0
@@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +// SPDX-FileCopyrightText: 2021 Bartosz Golaszewski <[email protected]> + +#include "internal.h" + +void gpiod_refcount_init (struct gpiod_refcount *refcount, +gpiod_refcount_release release) +{ + refcount->refcnt =1 ; + refcount->release = release; +} + +void gpiod_refcount_ref (struct gpiod_refcount *refcount) +{ + refcount->refcnt++; +} + +void gpiod_refcount_unref (struct gpiod_refcount *refcount) +{ +if (--refcount->refcnt ==0 ) + refcount->release (refcount); +}
lib/internal.h +19 -0
@@ -4,8 +4,27 @@#ifndef __LIBGPIOD_GPIOD_INTERNAL_H__#define __LIBGPIOD_GPIOD_INTERNAL_H__ +#include <stddef.h> +/* For internal library use only. */ #define GPIOD_API __attribute__((visibility("default"))) +#define gpiod_container_of (ptr, type, member) ({ \ + void *__mptr = (void *)(ptr); \ + ((type *)(__mptr - offsetof(type, member))); }) + +struct gpiod_refcount ; +typedef void (*gpiod_refcount_release )(struct gpiod_refcount *); + +struct gpiod_refcount { +unsigned int refcnt; +gpiod_refcount_release release; +}; + +void gpiod_refcount_init (struct gpiod_refcount *refcount, +gpiod_refcount_release release); +void gpiod_refcount_ref (struct gpiod_refcount *refcount); +void gpiod_refcount_unref (struct gpiod_refcount *refcount); +#endif /* __LIBGPIOD_GPIOD_INTERNAL_H__ */
Signature · 1 line
2.30.1
RFC 3/6 core: implement line_info objects
In reply to Bartosz GolaszewskiImplement an opaque object storing a snapshot of a GPIO line's status info and add functions for accessing its fields.
--- include/gpiod.h | 119 ++++++++++--- lib/Makefile.am | 2 +- lib/core.c | 63 ++----- lib/helpers.c | 16 +- lib/info.c | 170 ++++++++++++++++++ lib/internal.h | 6 + tests/gpiod-test.h | 2 + tests/tests-chip.c | 8 +- tests/tests-line.c | 425 ++++++++++++++++++++++++++++++++++++--------- tools/gpioinfo.c | 42 ++--- 10 files changed, 672 insertions(+), 181 deletions(-) create mode 100644 lib/info.c
include/gpiod.h +96 -23
@@ -35,6 +35,7 @@ extern "C" {struct gpiod_chip ;struct gpiod_line ; +struct gpiod_line_info ;struct gpiod_line_bulk ;/**
@@ -110,6 +111,17 @@ const char *gpiod_chip_get_label(struct gpiod_chip *chip);*/ unsigned int gpiod_chip_get_num_lines (struct gpiod_chip *chip); +/** +* @brief Get the current snapshot of information about the line at given +* offset. +* @param chip The GPIO chip object. +* @param offset The offset of the GPIO line. +* @return New GPIO line info object that must be freed using +* ::gpiod_line_info_free or NULL if an error occurred. +*/ +struct gpiod_line_info *gpiod_chip_get_line_info (struct gpiod_chip *chip, +unsigned int offset); +/** * @brief Get the handle to the GPIO line at given offset. * @param chip The GPIO chip object.
@@ -286,6 +298,20 @@ enum {/**< The internal pull-down bias is enabled. */ }; +/** +* @brief Possible edge detection settings. +*/ +enum { +GPIOD_LINE_EDGE_NONE =1 , +/**< Line edge detection is disabled. */ +GPIOD_LINE_EDGE_RISING , +/**< Line detects rising edge events. */ +GPIOD_LINE_EDGE_FALLING , +/**< Line detect falling edge events. */ +GPIOD_LINE_EDGE_BOTH , +/**< Line detects both rising and falling edge events. */ +}; +/** * @brief Read the GPIO line offset. * @param line GPIO line object.
@@ -293,64 +319,111 @@ enum {*/ unsigned int gpiod_line_offset (struct gpiod_line *line); +/** +* @brief Increase the reference count for this line info object. +* @param info GPIO line info object. +* @return Passed reference to the line info object. +*/ +struct gpiod_line_info * +gpiod_line_info_ref (struct gpiod_line_info *info); + +/** +* @brief Decrease the reference count on this line info object. If it reaches +* 0, then free all associated resources. +* @param info GPIO line info object. +*/ +void gpiod_line_info_unref (struct gpiod_line_info *info); + +/** +* @brief Get the hardware offset of the line. +* @param info GPIO line info object. +* @return Offset of the line within the parent chip. +*/ +unsigned int gpiod_line_info_get_offset (struct gpiod_line_info *info); +/** * @brief Read the GPIO line name. -* @param line GPIO line object. +* @param info GPIO line info object. * @return Name of the GPIO line as it is represented in the kernel. This * routine returns a pointer to a null-terminated string or NULL if * the line is unnamed. */ -const char *gpiod_line_name (struct gpiod_line *line); +const char *gpiod_line_get_name (struct gpiod_line_info *info); + +/** +* @brief Check if the line is currently in use. +* @param info GPIO line object. +* @return True if the line is in use, false otherwise. +* +* The user space can't know exactly why a line is busy. It may have been +* requested by another process or hogged by the kernel. It only matters that +* the line is used and we can't request it. +*/ +bool gpiod_line_is_used (struct gpiod_line_info *info);/** * @brief Read the GPIO line consumer name. -* @param line GPIO line object. +* @param info GPIO line info object. * @return Name of the GPIO consumer name as it is represented in the * kernel. This routine returns a pointer to a null-terminated string * or NULL if the line is not used. */ -const char *gpiod_line_consumer (struct gpiod_line *line); +const char *gpiod_line_get_consumer (struct gpiod_line_info *info);/** * @brief Read the GPIO line direction setting. -* @param line GPIO line object. +* @param info GPIO line info object. * @return Returns GPIOD_LINE_DIRECTION_INPUT or GPIOD_LINE_DIRECTION_OUTPUT. */ -int gpiod_line_direction (struct gpiod_line *line); +int gpiod_line_get_direction (struct gpiod_line_info *info);/** * @brief Check if the signal of this line is inverted. -* @param line GPIO line object. +* @param info GPIO line object. * @return True if this line is "active-low", false otherwise. */ -bool gpiod_line_is_active_low (struct gpiod_line *line); +bool gpiod_line_is_active_low (struct gpiod_line_info *info);/** * @brief Read the GPIO line bias setting. -* @param line GPIO line object. +* @param info GPIO line object. * @return Returns GPIOD_LINE_BIAS_PULL_UP, GPIOD_LINE_BIAS_PULL_DOWN, * GPIOD_LINE_BIAS_DISABLE or GPIOD_LINE_BIAS_UNKNOWN. */ -int gpiod_line_bias (struct gpiod_line *line); - -/** -* @brief Check if the line is currently in use. -* @param line GPIO line object. -* @return True if the line is in use, false otherwise. -* -* The user space can't know exactly why a line is busy. It may have been -* requested by another process or hogged by the kernel. It only matters that -* the line is used and we can't request it. -*/ -bool gpiod_line_is_used (struct gpiod_line *line); +int gpiod_line_get_bias (struct gpiod_line_info *info);/** * @brief Read the GPIO line drive setting. -* @param line GPIO line object. +* @param info GPIO line info object. * @return Returns GPIOD_LINE_DRIVE_PUSH_PULL, GPIOD_LINE_DRIVE_OPEN_DRAIN or * GPIOD_LINE_DRIVE_OPEN_SOURCE. */ -int gpiod_line_drive (struct gpiod_line *line); +int gpiod_line_get_drive (struct gpiod_line_info *info); + +/** +* @brief Read the current edge detection setting of this line. +* @param info GPIO line info object. +* @return Returns GPIOD_LINE_EDGE_NONE, GPIOD_LINE_EDGE_RISING, +* GPIOD_LINE_EDGE_FALLING or GPIOD_LINE_EDGE_BOTH. +*/ +int gpiod_line_get_edge_detection (struct gpiod_line_info *info); + +/** +* @brief Check if this line is debounced (either by hardware or by the kernel +* software debouncer). +* @param info GPIO line info object. +* @return True if the line is debounced, false otherwise. +*/ +bool gpiod_line_is_debounced (struct gpiod_line_info *info); + +/** +* @brief Read the current debounce period in microseconds. +* @param info GPIO line info object. +* @return Current debounce period in microseconds, 0 if the line is not +* debounced. +*/ +unsigned long +gpiod_line_get_debounce_period (struct gpiod_line_info *info);/** * @brief Get the handle to the GPIO chip controlling this line.
lib/Makefile.am +1 -1
@@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <[email protected]> lib_LTLIBRARIES = libgpiod.la -libgpiod_la_SOURCES = core.c helpers.c internal.c internal.h misc.c uapi/gpio.h +libgpiod_la_SOURCES = core.c helpers.c internal.c internal.h info.c misc.c uapi/gpio.h libgpiod_la_CFLAGS = -Wall -Wextra -g -std=gnu89 libgpiod_la_CFLAGS += -fvisibility=hidden -I$(top_srcdir)/include/ libgpiod_la_CFLAGS += -include $(top_builddir)/config.h
lib/core.c +16 -47
75 lines not on this page · raw message
lib/helpers.c +10 -6
@@ -65,19 +65,23 @@ gpiod_chip_get_all_lines(struct gpiod_chip *chip) GPIOD_API int gpiod_chip_find_line(struct gpiod_chip *chip, const char *name) {unsigned int offset, num_lines; -struct gpiod_line *line; +struct gpiod_line_info *info;const char *tmp; num_lines =gpiod_chip_get_num_lines (chip);for (offset =0 ; offset < num_lines; offset++) { - line =gpiod_chip_get_line (chip, offset); -if (!line) + info =gpiod_chip_get_line_info (chip, offset); +if (!info)return -1 ; - tmp =gpiod_line_name (line); -if (tmp &&strcmp (tmp, name) ==0 ) -return gpiod_line_offset (line); + tmp =gpiod_line_get_name (info); +if (tmp &&strcmp (tmp, name) ==0 ) { +gpiod_line_info_unref (info); +return offset; + } + +gpiod_line_info_unref (info); } errno =ENOENT ;
lib/info.c new file +170 -0
170 lines not on this page · raw message
lib/internal.h +6 -0
@@ -4,8 +4,11 @@#ifndef __LIBGPIOD_GPIOD_INTERNAL_H__#define __LIBGPIOD_GPIOD_INTERNAL_H__ +#include <gpiod.h> #include <stddef.h> +#include "uapi/gpio.h" +/* For internal library use only. */ #define GPIOD_API __attribute__((visibility("default")))
@@ -27,4 +30,7 @@ void gpiod_refcount_init(struct gpiod_refcount *refcount,void gpiod_refcount_ref (struct gpiod_refcount *refcount);void gpiod_refcount_unref (struct gpiod_refcount *refcount); +struct gpiod_line_info * +gpiod_line_info_from_kernel (struct gpio_v2_line_info *infobuf); +#endif /* __LIBGPIOD_GPIOD_INTERNAL_H__ */
tests/gpiod-test.h +2 -0
@@ -21,9 +21,11 @@*/ typedef struct gpiod_chip gpiod_chip_struct ;typedef struct gpiod_line_bulk gpiod_line_bulk_struct ; +typedef struct gpiod_line_info gpiod_line_info_struct ;G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_chip_struct, gpiod_chip_unref);G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_line_bulk_struct, gpiod_line_bulk_free); +G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_line_info_struct, gpiod_line_info_unref);/* These are private definitions and should not be used directly. */ typedef void (*_gpiod_test_func )(void );
tests/tests-chip.c +4 -4
@@ -195,8 +195,8 @@ GPIOD_TEST_CASE(get_all_lines, 0, { 4 }) GPIOD_TEST_CASE(find_line_good, GPIOD_TEST_FLAG_NAMED_LINES, { 8, 8, 8 }) { +g_autoptr (gpiod_line_info_struct) info =NULL ;g_autoptr (gpiod_chip_struct) chip =NULL ; -struct gpiod_line *line;int offset; chip =gpiod_chip_open (gpiod_test_chip_path (1 ));
@@ -207,11 +207,11 @@ GPIOD_TEST_CASE(find_line_good, GPIOD_TEST_FLAG_NAMED_LINES, { 8, 8, 8 }) g_assert_cmpint(offset, ==, 4);gpiod_test_return_if_failed (); - line =gpiod_chip_get_line (chip,4 ); -g_assert_nonnull (line); + info =gpiod_chip_get_line_info (chip,4 ); +g_assert_nonnull (info);gpiod_test_return_if_failed (); - g_assert_cmpstr(gpiod_line_name(line), ==, "gpio-mockup-B-4"); + g_assert_cmpstr(gpiod_line_get_name(info), ==, "gpio-mockup-B-4"); } GPIOD_TEST_CASE(find_line_unique_not_found,
tests/tests-line.c +345 -80
737 lines not on this page · raw message
tools/gpioinfo.c +22 -20
100 lines not on this page · raw message
Signature · 1 line
2.30.1
RFC 4/6 core: rework line events
In reply to Bartosz GolaszewskiIntroduce opaque event objects: gpiod_line_event and gpiod_line_event_buffer. The latter serves as a container into which multiple events can be read without having to dynamically allocate memory for each one as reading line events should be as fast as possible.
--- include/gpiod.h | 65 +++--- lib/Makefile.am | 9 +- lib/core.c | 98 +-------- lib/event.c | 250 +++++++++++++++++++++++ lib/misc.c | 5 + tests/gpiod-test.h | 3 + tests/tests-event.c | 470 ++++++++++++++++++++++++++++++++------------ tools/gpiomon.c | 45 +++-- 8 files changed, 690 insertions(+), 255 deletions(-) create mode 100644 lib/event.c
include/gpiod.h +43 -22
@@ -6,7 +6,7 @@#include <stdbool.h> #include <stdlib.h> -#include <time.h> +#include <stdint.h> #ifdef __cplusplusextern "C" {
@@ -37,6 +37,8 @@ struct gpiod_chip;struct gpiod_line ;struct gpiod_line_info ;struct gpiod_line_bulk ; +struct gpiod_line_event ; +struct gpiod_line_event_buffer ;/** * @defgroup common Common helper macros
@@ -928,17 +930,35 @@ enum {/**< Falling edge event. */ }; -/** -* @brief Structure holding event info. -*/ -struct gpiod_line_event { -struct timespec ts; -/**< Best estimate of time of event occurrence. */ -int event_type; -/**< Type of the event that occurred. */ -int offset; -/**< Offset of line on which the event occurred. */ -}; +struct gpiod_line_event *gpiod_line_event_ref (struct gpiod_line_event *event); + +void gpiod_line_event_unref (struct gpiod_line_event *event); + +int gpiod_line_event_get_event_type (struct gpiod_line_event *event); + +uint64_t gpiod_line_event_get_timestamp (struct gpiod_line_event *event); + +unsigned int gpiod_line_event_get_line_offset (struct gpiod_line_event *event); + +unsigned int gpiod_line_event_get_global_seqno (struct gpiod_line_event *event); + +unsigned int gpiod_line_event_get_line_seqno (struct gpiod_line_event *event); + +struct gpiod_line_event_buffer * +gpiod_line_event_buffer_new (unsigned int capacity); + +struct gpiod_line_event_buffer * +gpiod_line_event_buffer_ref (struct gpiod_line_event_buffer *buf); + +void gpiod_line_event_buffer_unref (struct gpiod_line_event_buffer *buf); + +struct gpiod_line_event * +gpiod_line_event_buffer_get_event (struct gpiod_line_event_buffer *buf, +unsigned long index); + +struct gpiod_line_event * +gpiod_line_event_buffer_copy_event (struct gpiod_line_event_buffer *buf, +unsigned long index);/** * @brief Wait for an event on a single line.
@@ -947,8 +967,7 @@ struct gpiod_line_event {* @return 0 if wait timed out, -1 if an error occurred, 1 if an event * occurred. */ -int gpiod_line_event_wait (struct gpiod_line *line, -const struct timespec *timeout); +int gpiod_line_event_wait (struct gpiod_line *line,uint64_t timeout);/** * @brief Wait for events on a set of lines.
@@ -959,8 +978,7 @@ int gpiod_line_event_wait(struct gpiod_line *line,* @return 0 if wait timed out, -1 if an error occurred, 1 if at least one * event occurred. */ -int gpiod_line_event_wait_bulk (struct gpiod_line_bulk *bulk, -const struct timespec *timeout, +int gpiod_line_event_wait_bulk (struct gpiod_line_bulk *bulk,uint64_t timeout,struct gpiod_line_bulk *event_bulk);/**
@@ -971,7 +989,7 @@ int gpiod_line_event_wait_bulk(struct gpiod_line_bulk *bulk,* @note This function will block if no event was queued for this line. */ int gpiod_line_event_read (struct gpiod_line *line, -struct gpiod_line_event *event); +struct gpiod_line_event_buffer *buf);/** * @brief Read up to a certain number of events from the GPIO line.
@@ -983,7 +1001,7 @@ int gpiod_line_event_read(struct gpiod_line *line,* failure -1 is returned. */ int gpiod_line_event_read_multiple (struct gpiod_line *line, -struct gpiod_line_event *events, +struct gpiod_line_event_buffer *buf,unsigned int num_events);/**
@@ -1008,19 +1026,20 @@ int gpiod_line_event_get_fd(struct gpiod_line *line);* directly read the event data from it using this routine. This function * translates the kernel representation of the event to the libgpiod format. */ -int gpiod_line_event_read_fd (int fd,struct gpiod_line_event *event); +int gpiod_line_event_read_fd (int fd,struct gpiod_line_event_buffer *buf);/** * @brief Read up to a certain number of events directly from a file descriptor. * @param fd File descriptor. * @param events Buffer to which the event data will be copied. Must hold at * least the amount of events specified in num_events. -* @param num_events Specifies how many events can be stored in the buffer. +* @param max_events Specifies the maximum number of events to read. * @return On success returns the number of events stored in the buffer, on * failure -1 is returned. */ -int gpiod_line_event_read_fd_multiple (int fd,struct gpiod_line_event *events, -unsigned int num_events); +int gpiod_line_event_read_fd_multiple (int fd, +struct gpiod_line_event_buffer *buf, +unsigned int max_events);/** * @}
@@ -1033,6 +1052,8 @@ int gpiod_line_event_read_fd_multiple(int fd, struct gpiod_line_event *events,* Various libgpiod-related functions. */ +uint64_t gpiod_sec_to_nsec (uint64_t sec); +/** * @brief Get the API version of the library as a human-readable string. * @return Human-readable string containing the library version.
lib/Makefile.am +8 -1
@@ -2,7 +2,14 @@ # SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <[email protected]> lib_LTLIBRARIES = libgpiod.la -libgpiod_la_SOURCES = core.c helpers.c internal.c internal.h info.c misc.c uapi/gpio.h +libgpiod_la_SOURCES = core.c \ + event.c \ + helpers.c \ + internal.h \ + internal.c \ + info.c \ + misc.c \ + uapi/gpio.h libgpiod_la_CFLAGS = -Wall -Wextra -g -std=gnu89 libgpiod_la_CFLAGS += -fvisibility=hidden -I$(top_srcdir)/include/ libgpiod_la_CFLAGS += -include $(top_builddir)/config.h
lib/core.c +8 -90
136 lines not on this page · raw message
lib/event.c new file +250 -0
250 lines not on this page · raw message
lib/misc.c +5 -0
@@ -7,6 +7,11 @@#include "internal.h" +GPIOD_API uint64_t gpiod_sec_to_nsec(uint64_t sec) +{ +return sec *1000000000ULL ; +} + GPIOD_API const char *gpiod_version_string(void) {return GPIOD_VERSION_STR ;
tests/gpiod-test.h +3 -0
@@ -22,10 +22,13 @@typedef struct gpiod_chip gpiod_chip_struct ;typedef struct gpiod_line_bulk gpiod_line_bulk_struct ;typedef struct gpiod_line_info gpiod_line_info_struct ; +typedef struct gpiod_line_event_buffer gpiod_line_event_buffer_struct ;G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_chip_struct, gpiod_chip_unref);G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_line_bulk_struct, gpiod_line_bulk_free);G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_line_info_struct, gpiod_line_info_unref); +G_DEFINE_AUTOPTR_CLEANUP_FUNC (gpiod_line_event_buffer_struct, + gpiod_line_event_buffer_unref);/* These are private definitions and should not be used directly. */ typedef void (*_gpiod_test_func )(void );
tests/tests-event.c +345 -125
915 lines not on this page · raw message
tools/gpiomon.c +28 -17
112 lines not on this page · raw message
Signature · 1 line
2.30.1
RFC 6/6 core: implement line watch events
In reply to Bartosz GolaszewskiThis implement support for line status watch events in libgpiod. Unlike line events, these are not expected to happen very often and continuously so there's no need for a dedicated container.
--- include/gpiod.h | 103 ++++++++++++++++++++++++++++++++++++++++++++++++ lib/Makefile.am | 3 +- lib/chip.c | 65 ++++++++++++++++++++++++++---- lib/handle.c | 20 +--------- lib/internal.c | 24 +++++++++++ lib/internal.h | 4 ++ lib/watch.c | 96 ++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 288 insertions(+), 27 deletions(-) create mode 100644 lib/watch.c
include/gpiod.h +103 -0
@@ -41,6 +41,7 @@ extern "C" {struct gpiod_chip ;struct gpiod_line_info ; +struct gpiod_watch_event ;struct gpiod_line_attr ;struct gpiod_line_config ;struct gpiod_request_config ;
@@ -107,6 +108,49 @@ unsigned int gpiod_chip_get_num_lines(struct gpiod_chip *chip);struct gpiod_line_info *gpiod_chip_get_line_info (struct gpiod_chip *chip,unsigned int offset); +/** +* @brief Get the current snapshot of information about the line at given +* offset and start watching it for future changes. +* @param chip GPIO chip object. +* @param offset The offset of the GPIO line. +* @return New GPIO line info object or NULL if an error occurred. +*/ +struct gpiod_line_info *gpiod_chip_watch_line_info (struct gpiod_chip *chip, +unsigned int offset); + +/** +* @brief Stop watching the line at given offset for status changes. +* @param chip GPIO chip object. +* @param offset The offset of the GPIO line. +* @return 0 on success, -1 on failure. +*/ +int gpiod_chip_unwatch_line_info (struct gpiod_chip *chip,unsigned int offset); + +/** +* @brief Get the file descriptor associated with this chip. +* @param chip GPIO chip object. +* @return File descriptor number. This function never fails. +*/ +int gpiod_chip_get_fd (struct gpiod_chip *chip); + +/** +* @brief Wait for line status events on any of the lines associated with +* this chip. +* @param chip GPIO chip object. +* @param timeout Wait time limit in nanoseconds. +* @return 0 if wait timed out, -1 if an error occurred, 1 if an event is +* pending. +*/ +int gpiod_chip_watch_event_wait (struct gpiod_chip *chip,uint64_t timeout); + +/** +* @brief Read a single line status change event from this chip. +* @param chip GPIO chip object. +* @return Newly read watch event object or NULL on error. +* @note If no events are pending, this function will block. +*/ +struct gpiod_watch_event *gpiod_chip_watch_event_read (struct gpiod_chip *chip); +/** * @brief Map a GPIO line's name to its offset within the chip. * @param chip GPIO chip object.
@@ -295,6 +339,65 @@ bool gpiod_line_is_debounced(struct gpiod_line_info *info);unsigned long gpiod_line_get_debounce_period (struct gpiod_line_info *info); +/** +* @} +* +* @defgroup line_watch Line status watch events +* @{ +*/ + +/** +* @brief Possible line status change event types. +*/ +enum { +GPIOD_WATCH_EVENT_LINE_REQUESTED =1 , +/**< Line has been requested. */ +GPIOD_WATCH_EVENT_LINE_RELEASED , +/**< Previously requested line has been released. */ +GPIOD_WATCH_EVENT_LINE_CONFIG_CHANGED , +/**< Line configuration has changed. */ +}; + +/** +* @brief Increase the reference count of this line status watch event. +* @param event Line status watch event. +* @return Passed reference to this line watch event. +*/ +struct gpiod_watch_event * +gpiod_watch_event_ref (struct gpiod_watch_event *event); + +/** +* @brief Decrease the reference count of this line status watch event. If the +* reference count reaches 0, release all associated resources. +* @param event Line status watch event. +*/ +void gpiod_watch_event_unref (struct gpiod_watch_event *event); + +/** +* @brief Get the event type of this status change event. +* @param event Line status watch event. +* @return One of ::GPIOD_WATCH_EVENT_LINE_REQUESTED, +* ::GPIOD_WATCH_EVENT_LINE_RELEASED or +* ::GPIOD_WATCH_EVENT_LINE_CONFIG_CHANGED. +*/ +int gpiod_watch_event_get_event_type (struct gpiod_watch_event *event); + +/** +* @brief Get the line info snapshot at the time of the watch event occurence. +* @param event Line status watch event. +* @return Reference to the line info object whose lifetime must be managed +* by the caller. +*/ +struct gpiod_line_info * +gpiod_watch_event_get_line_info (struct gpiod_watch_event *event); + +/** +* @brief Get the timestamp of the event. +* @param event Line status watch event. +* @return Timestamp in nanoseconds. +*/ +uint64_t gpiod_watch_event_get_timestamp (struct gpiod_watch_event *event); +/** * @} *
lib/Makefile.am +2 -1
@@ -13,7 +13,8 @@ libgpiod_la_SOURCES = attr.c \ mask.c \ misc.c \ request.c \ - uapi/gpio.h + uapi/gpio.h \ + watch.c libgpiod_la_CFLAGS = -Wall -Wextra -g -std=gnu89 libgpiod_la_CFLAGS += -fvisibility=hidden -I$(top_srcdir)/include/
lib/chip.c +58 -7
98 lines not on this page · raw message
lib/handle.c +1 -19
@@ -5,7 +5,6 @@#include <errno.h> #include <gpiod.h> -#include <poll.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h>
@@ -110,24 +109,7 @@ GPIOD_API int gpiod_request_handle_event_wait(struct gpiod_request_handle *handle, uint64_t timeout) { - struct timespec ts; -struct pollfd pfd; -int ret; - -memset (&pfd,0 ,sizeof (pfd)); - pfd.fd = handle->fd; - pfd.events =POLLIN |POLLPRI ; - - ts.tv_sec = timeout /1000000000ULL ; - ts.tv_nsec = timeout %1000000000ULL ; - - ret =ppoll (&pfd,1 , &ts,NULL ); -if (ret <0 ) -return -1 ; -else if (ret ==0 ) -return 0 ; - -return 1 ; +return gpiod_poll_fd (handle->fd, timeout); }GPIOD_API int
lib/internal.c +24 -0
@@ -2,6 +2,8 @@// SPDX-FileCopyrightText: 2021 Bartosz Golaszewski <[email protected]> #include <errno.h> +#include <poll.h> +#include <string.h> #include "internal.h"
@@ -121,3 +123,25 @@ uint64_t gpiod_make_kernel_flags(int request_type, int drive, int bias,return flags; } + +int gpiod_poll_fd (int fd,uint64_t timeout) +{ +struct timespec ts; +struct pollfd pfd; +int ret; + +memset (&pfd,0 ,sizeof (pfd)); + pfd.fd = fd; + pfd.events =POLLIN |POLLPRI ; + + ts.tv_sec = timeout /1000000000ULL ; + ts.tv_nsec = timeout %1000000000ULL ; + + ret =ppoll (&pfd,1 , &ts,NULL ); +if (ret <0 ) +return -1 ; +else if (ret ==0 ) +return 0 ; + +return 1 ; +}
lib/internal.h +4 -0
@@ -42,9 +42,13 @@ void gpiod_line_attr_to_kernel(struct gpiod_line_attr *attr,uint64_t gpiod_make_kernel_flags (int request_type,int drive,int bias,bool active_low,bool clock_realtime);struct gpiod_request_handle *gpiod_request_handle_from_fd (int fd); +struct gpiod_watch_event * +gpiod_watch_event_from_kernel (struct gpio_v2_line_info_changed *evbuf);int gpiod_validate_request_type (int request_type);int gpiod_validate_drive (int drive);int gpiod_validate_bias (int bias); +int gpiod_poll_fd (int fd,uint64_t timeout); +#endif /* __LIBGPIOD_GPIOD_INTERNAL_H__ */
lib/watch.c new file +96 -0
96 lines not on this page · raw message
Signature · 1 line
2.30.1
RFC 5/6 core: rework line requests
In reply to Bartosz GolaszewskiThis introduces the bulk of changes for the v2 API in libgpiod. All objects become opaque. The API supports all features exposed by the v2 of the kernel uAPI.
--- include/gpiod.h | 1023 ++++++++++++++------------------ lib/Makefile.am | 9 +- lib/attr.c | 232 ++++++++ lib/chip.c | 183 ++++++ lib/config.c | 158 +++++ lib/core.c | 1131 ------------------------------------ lib/event.c | 44 +- lib/handle.c | 144 +++++ lib/helpers.c | 306 ---------- lib/info.c | 1 + lib/internal.c | 101 ++++ lib/internal.h | 14 + lib/mask.c | 43 ++ lib/misc.c | 75 +++ lib/request.c | 118 ++++ tests/tests-event.c | 58 +- tools/gpio-tools-test.bats | 12 +- tools/gpiodetect.c | 11 +- tools/gpiofind.c | 1 + tools/gpioget.c | 57 +- tools/gpioinfo.c | 12 +- tools/gpiomon.c | 113 ++-- tools/gpioset.c | 85 ++- tools/tools-common.c | 8 +- tools/tools-common.h | 2 +- 25 files changed, 1722 insertions(+), 2219 deletions(-) create mode 100644 lib/attr.c create mode 100644 lib/chip.c create mode 100644 lib/config.c delete mode 100644 lib/core.c create mode 100644 lib/handle.c delete mode 100644 lib/helpers.c create mode 100644 lib/mask.c create mode 100644 lib/request.c
include/gpiod.h +446 -577
@@ -1,11 +1,11 @@/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <[email protected]> */ +/* SPDX-FileCopyrightText: 2021 Bartosz Golaszewski <[email protected]> */ #ifndef __LIBGPIOD_GPIOD_H__#define __LIBGPIOD_GPIOD_H__#include <stdbool.h> -#include <stdlib.h> #include <stdint.h> #ifdef __cplusplus
@@ -29,48 +29,32 @@ extern "C" {* errno to one of the error values defined in errno.h upon failure. The way * of notifying the caller that an error occurred varies between functions, * but in general a function that returns an int, returns -1 on error, while -* a function returning a pointer bails out on error condition by returning +* a function returning a pointer indicates an error condition by returning * a NULL pointer. +* +* <p>In general libgpiod functions are not NULL-aware and it's expected that +* users pass valid pointers to objects as arguments. +* +* <p>Almost all opaque objects are reference counted. The associated resources +* are released when the reference count reaches 0. */ struct gpiod_chip ; -struct gpiod_line ;struct gpiod_line_info ; -struct gpiod_line_bulk ; +struct gpiod_line_attr ; +struct gpiod_line_config ; +struct gpiod_request_config ; +struct gpiod_request_handle ;struct gpiod_line_event ;struct gpiod_line_event_buffer ;/** -* @defgroup common Common helper macros -* @{ -* -* Commonly used utility macros. -*/ - -/** -* @brief Shift 1 by given offset. -* @param nr Bit position. -* @return 1 shifted by nr. -*/ -#define GPIOD_BIT (nr) (1UL << (nr)) - -/** -* @} -* -* @defgroup chips GPIO chip operations +* @defgroup chips GPIO chips * @{ * -* Functions and data structures dealing with GPIO chips. +* Functions and data structures for manipulating GPIO chips. */ -/** -* @brief Check if the file pointed to by path is a GPIO chip character device. -* @param path Path to check. -* @return True if the file exists and is a GPIO chip character device or a -* symbolic link to it. -*/ -bool gpiod_is_gpiochip_device (const char *path); -/** * @brief Open a gpiochip by path. * @param path Path to the gpiochip device file.
@@ -80,7 +64,7 @@ struct gpiod_chip *gpiod_chip_open(const char *path);/** * @brief Increase the refcount on this GPIO object. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @return Passed reference to the GPIO chip. */ struct gpiod_chip *gpiod_chip_ref (struct gpiod_chip *chip);
@@ -88,27 +72,27 @@ struct gpiod_chip *gpiod_chip_ref(struct gpiod_chip *chip);/** * @brief Decrease the refcount on this GPIO object. If the refcount reaches 0, * close the chip device and free all associated resources. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. */ void gpiod_chip_unref (struct gpiod_chip *chip);/** * @brief Get the GPIO chip name as represented in the kernel. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @return Pointer to a human-readable string containing the chip name. */ const char *gpiod_chip_get_name (struct gpiod_chip *chip);/** * @brief Get the GPIO chip label as represented in the kernel. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @return Pointer to a human-readable string containing the chip label. */ const char *gpiod_chip_get_label (struct gpiod_chip *chip);/** * @brief Get the number of GPIO lines exposed by this chip. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @return Number of GPIO lines. */ unsigned int gpiod_chip_get_num_lines (struct gpiod_chip *chip);
@@ -116,143 +100,34 @@ unsigned int gpiod_chip_get_num_lines(struct gpiod_chip *chip);/** * @brief Get the current snapshot of information about the line at given * offset. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @param offset The offset of the GPIO line. -* @return New GPIO line info object that must be freed using -* ::gpiod_line_info_free or NULL if an error occurred. +* @return New GPIO line info object or NULL if an error occurred. */ struct gpiod_line_info *gpiod_chip_get_line_info (struct gpiod_chip *chip,unsigned int offset); -/** -* @brief Get the handle to the GPIO line at given offset. -* @param chip The GPIO chip object. -* @param offset The offset of the GPIO line. -* @return Pointer to the GPIO line handle or NULL if an error occured. -*/ -struct gpiod_line * -gpiod_chip_get_line (struct gpiod_chip *chip,unsigned int offset); - -/** -* @brief Retrieve a set of lines and store them in a line bulk object. -* @param chip The GPIO chip object. -* @param offsets Array of offsets of lines to retrieve. -* @param num_offsets Number of lines to retrieve. -* @return New line bulk object or NULL on error. -*/ -struct gpiod_line_bulk * -gpiod_chip_get_lines (struct gpiod_chip *chip,unsigned int *offsets, -unsigned int num_offsets); - -/** -* @brief Retrieve all lines exposed by a chip and store them in a bulk object. -* @param chip The GPIO chip object. -* @return New line bulk object or NULL on error. -*/ -struct gpiod_line_bulk * -gpiod_chip_get_all_lines (struct gpiod_chip *chip); -/** * @brief Map a GPIO line's name to its offset within the chip. -* @param chip The GPIO chip object. +* @param chip GPIO chip object. * @param name Name of the GPIO line to map. -* @return Offset of the line within the chip or -1 if a line with given name -* is not exposed by the chip. +* @return Offset of the line within the chip or -1 on error. +* @note If a line with given name is not exposed by the chip, the function +* sets errno to ENOENT. */ int gpiod_chip_find_line (struct gpiod_chip *chip,const char *name);/** -* @} -* -* @defgroup lines GPIO line operations -* @{ -* -* Functions and data structures dealing with GPIO lines. -* -* @defgroup line_bulk Operating on multiple lines -* @{ -* -* Convenience data structures and helper functions for storing and operating -* on multiple lines at once. -*/ - -/** -* @brief Allocate and initialize a new line bulk object. -* @param max_lines Maximum number of lines this object can hold. -* @return New line bulk object or NULL on error. -*/ -struct gpiod_line_bulk *gpiod_line_bulk_new (unsigned int max_lines); - -/** -* @brief Reset a bulk object. Remove all lines and set size to 0. -* @param bulk Bulk object to reset. -*/ -void gpiod_line_bulk_reset (struct gpiod_line_bulk *bulk); - -/** -* @brief Release all resources allocated for this bulk object. -* @param bulk Bulk object to free. -*/ -void gpiod_line_bulk_free (struct gpiod_line_bulk *bulk); - -/** -* @brief Add a single line to a GPIO bulk object. -* @param bulk Line bulk object. -* @param line Line to add. -* @return 0 on success, -1 on error. -* @note The line is added at the next free bulk index. -* -* The function can fail if this bulk already holds its maximum amount of -* lines or if the added line is associated with a different chip than all -* the other lines already held by this object. -*/ -int gpiod_line_bulk_add_line (struct gpiod_line_bulk *bulk, -struct gpiod_line *line); - -/** -* @brief Retrieve the line handle from a line bulk object at given index. -* @param bulk Line bulk object. -* @param index Index of the line to retrieve. -* @return Line handle at given index or NULL if index is greater or equal to -* the number of lines this bulk can hold. -*/ -struct gpiod_line * -gpiod_line_bulk_get_line (struct gpiod_line_bulk *bulk,unsigned int index); - -/** -* @brief Retrieve the number of GPIO lines held by this line bulk object. -* @param bulk Line bulk object. -* @return Number of lines held by this line bulk. -*/ -unsigned int gpiod_line_bulk_num_lines (struct gpiod_line_bulk *bulk); - -/** -* @brief Values returned by the callback passed to -* ::gpiod_line_bulk_foreach_line. +* @brief Request a set of lines for exclusive usage. +* @param chip GPIO chip object. +* @param req_cfg Request config object. +* @param line_cfg Line config object. +* @return New request handle object or NULL if an error occurred. */ -enum { -/**< Continue the loop. */ -GPIOD_LINE_BULK_CB_NEXT =0 , -/**< Stop the loop. */ -GPIOD_LINE_BULK_CB_STOP , -}; - -/** -* @brief Signature of the callback passed to ::gpiod_line_bulk_foreach_line. -* -* Takes the current line and additional user data as arguments. -*/ -typedef int (*gpiod_line_bulk_foreach_cb )(struct gpiod_line *,void *); - -/** -* @brief Iterate over all lines held by this bulk object. -* @param bulk Bulk object to iterate over. -* @param func Callback to be called for each line. -* @param data User data pointer that is passed to the callback. -*/ -void gpiod_line_bulk_foreach_line (struct gpiod_line_bulk *bulk, -gpiod_line_bulk_foreach_cb func, -void *data); +struct gpiod_request_handle * +gpiod_chip_request_lines (struct gpiod_chip *chip, +struct gpiod_request_config *req_cfg, +struct gpiod_line_config *line_cfg);/** * @}
@@ -314,13 +189,6 @@ enum {/**< Line detects both rising and falling edge events. */ }; -/** -* @brief Read the GPIO line offset. -* @param line GPIO line object. -* @return Line offset. -*/ -unsigned int gpiod_line_offset (struct gpiod_line *line); -/** * @brief Increase the reference count for this line info object. * @param info GPIO line info object.
@@ -428,485 +296,460 @@ unsigned long gpiod_line_get_debounce_period(struct gpiod_line_info *info);/** -* @brief Get the handle to the GPIO chip controlling this line. -* @param line The GPIO line object. -* @return Pointer to the GPIO chip handle controlling this line. +* @} +* +* @defgroup line_mask Line mask bitmaps +* @{ +*/ + +/** +* @brief Bitmask used to store values of lines in a single request (up to 64 +* lines) as well as to specify on which lines in a request to act when +* reading/setting values or applying configuration options. +*/ +typedef uint64_t gpiod_line_mask ; + +/** +* @brief Set all bits in the mask. +* @param mask The GPIO line mask. +*/ +void gpiod_line_mask_fill (gpiod_line_mask *mask); + +/** +* @brief Clear all bits in the mask. +* @param mask The GPIO line mask. +*/ +void gpiod_line_mask_zero (gpiod_line_mask *mask); + +/** +* @brief Test a single bit. +* @param mask The GPIO line mask. +* @param offset Offset of the bit to test. +* @return True if the bit is set, false otherwise. +*/ +bool gpiod_line_mask_test_bit (gpiod_line_mask mask,unsigned int offset); + +/** +* @brief Set a single bit. +* @param mask The GPIO line mask. +* @param offset Offset of the bit to set. +*/ +void gpiod_line_mask_set_bit (gpiod_line_mask *mask,unsigned int offset); + +/** +* @brief Clear a single bit. +* @param mask The GPIO line mask. +* @param offset Offset of the bit to clear. +*/ +void gpiod_line_mask_clear_bit (gpiod_line_mask *mask,unsigned int offset); + +/** +* @brief Set or clear a single bit depending on a boolean value. +* @param mask The GPIO line mask. +* @param offset Offset of the bit to assign. +* @param value Boolean value to indicate the value of the bit. */ -struct gpiod_chip *gpiod_line_get_chip (struct gpiod_line *line); +void gpiod_line_mask_assign_bit (gpiod_line_mask *mask, +unsigned int offset,bool value);/** * @} * -* @defgroup line_request Line requests +* @defgroup line_config Line and request configuration objects * @{ * -* Interface for requesting GPIO lines from userspace for both values and -* events. +* Functions for manipulating line attributes and configuration objects. */ /** * @brief Available types of requests. */ enum { -GPIOD_LINE_REQUEST_DIRECTION_AS_IS =1 , +GPIOD_LINE_CONFIG_DIRECTION_AS_IS =1 ,/**< Request the line(s), but don't change current direction. */ -GPIOD_LINE_REQUEST_DIRECTION_INPUT , +GPIOD_LINE_CONFIG_DIRECTION_INPUT ,/**< Request the line(s) for reading the GPIO line state. */ -GPIOD_LINE_REQUEST_DIRECTION_OUTPUT , +GPIOD_LINE_CONFIG_DIRECTION_OUTPUT ,/**< Request the line(s) for setting the GPIO line state. */ -GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE , +GPIOD_LINE_CONFIG_EVENT_FALLING_EDGE ,/**< Only watch falling edge events. */ -GPIOD_LINE_REQUEST_EVENT_RISING_EDGE , +GPIOD_LINE_CONFIG_EVENT_RISING_EDGE ,/**< Only watch rising edge events. */ -GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES , +GPIOD_LINE_CONFIG_EVENT_BOTH_EDGES ,/**< Monitor both types of events. */ };/** -* @brief Miscellaneous GPIO request flags. +* @brief Available drive settings for line requests. */ enum { -GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN =GPIOD_BIT (0 ), -/**< The line is an open-drain port. */ -GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE =GPIOD_BIT (1 ), -/**< The line is an open-source port. */ -GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW =GPIOD_BIT (2 ), -/**< The active state of the line is low (high is the default). */ -GPIOD_LINE_REQUEST_FLAG_BIAS_DISABLED =GPIOD_BIT (3 ), -/**< The line has neither either pull-up nor pull-down resistor. */ -GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_DOWN =GPIOD_BIT (4 ), -/**< The line has pull-down resistor enabled. */ -GPIOD_LINE_REQUEST_FLAG_BIAS_PULL_UP =GPIOD_BIT (5 ), -/**< The line has pull-up resistor enabled. */ +GPIOD_LINE_CONFIG_DRIVE_PUSH_PULL =1 , +/**< Drive setting should be set to push-pull (the default). */ +GPIOD_LINE_CONFIG_DRIVE_OPEN_DRAIN , +/**< Line output should be set to open-drain. */ +GPIOD_LINE_CONFIG_DRIVE_OPEN_SOURCE , +/**< Line output should be set to open-source. */ };/** -* @brief Structure holding configuration of a line request. +* @brief Available internal bias settings for line requests. */ -struct gpiod_line_request_config { -const char *consumer; -/**< Name of the consumer. */ -int request_type; -/**< Request type. */ -int flags; -/**< Other configuration flags. */ +enum { +GPIOD_LINE_CONFIG_BIAS_DISABLED =1 , +/**< The internal bias should be disabled (the default). */ +GPIOD_LINE_CONFIG_BIAS_PULL_UP , +/**< The internal pull-up bias is enabled. */ +GPIOD_LINE_CONFIG_BIAS_PULL_DOWN , +/**< The internal pull-down bias is enabled. */ };/** -* @brief Reserve a single line. -* @param line GPIO line object. -* @param config Request options. -* @param default_val Initial line value - only relevant if we're setting -* the direction to output. -* @return 0 if the line was properly reserved. In case of an error this -* routine returns -1 and sets the last error number. -* -* If this routine succeeds, the caller takes ownership of the GPIO line until -* it's released. +* @brief Available line attribute types. */ -int gpiod_line_request (struct gpiod_line *line, -const struct gpiod_line_request_config *config, -int default_val); +enum { +GPIOD_LINE_ATTR_TYPE_OPTS , +/**< The attribute specifies a set of simple line options. */ +GPIOD_LINE_ATTR_TYPE_OUTPUT_VALUES , +/**< The attribute contains output values for a set of GPIO lines. */ +GPIOD_LINE_ATTR_TYPE_DEBOUNCE , +/**< The attribute defines debounce config. */ +};/** -* @brief Reserve a single line, set the direction to input. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @return 0 if the line was properly reserved, -1 on failure. +* @brief Create a new line attribute. +* @param type Type of this attribute. +* @return New line attribute or NULL on error. */ -int gpiod_line_request_input (struct gpiod_line *line,const char *consumer); +struct gpiod_line_attr *gpiod_line_attr_new (int type);/** -* @brief Reserve a single line, set the direction to output. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param default_val Initial line value. -* @return 0 if the line was properly reserved, -1 on failure. +* @brief Increase the reference count of this object. +* @param attr Line attribute object. +* @return Passed reference to the line attribute. */ -int gpiod_line_request_output (struct gpiod_line *line, -const char *consumer,int default_val); +struct gpiod_line_attr *gpiod_line_attr_ref (struct gpiod_line_attr *attr);/** -* @brief Request rising edge event notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Decrease the reference count to the line attribute. If the refcount +* reaches 0, free all resources associated with this object. +* @param attr Line attribute object. */ -int gpiod_line_request_rising_edge_events (struct gpiod_line *line, -const char *consumer); +void gpiod_line_attr_unref (struct gpiod_line_attr *attr);/** -* @brief Request falling edge event notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the line mask of this attribute. +* @param attr Line attribute object. +* @param mask New line mask. +* +* An attribute can be associated with up to 64 lines (the maximum for a single +* line request). Each bit in the mask bitmap represents a single line from the +* request at the same offset as the bit. If the bit is set, the configuration +* specified in this attribute will apply to the associated line. */ -int gpiod_line_request_falling_edge_events (struct gpiod_line *line, -const char *consumer); +void gpiod_line_attr_set_line_mask (struct gpiod_line_attr *attr, +gpiod_line_mask mask);/** -* @brief Request all event type notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the request type. +* @param attr Line attribute object. +* @param request_type New request type. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type ::GPIOD_LINE_ATTR_TYPE_OPTS. */ -int gpiod_line_request_both_edges_events (struct gpiod_line *line, -const char *consumer); +int gpiod_line_attr_set_request_type (struct gpiod_line_attr *attr, +int request_type);/** -* @brief Reserve a single line, set the direction to input. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the line was properly reserved, -1 on failure. +* @brief Set the drive setting. +* @param attr Line attribute object. +* @param drive New drive setting. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type ::GPIOD_LINE_ATTR_TYPE_OPTS. */ -int gpiod_line_request_input_flags (struct gpiod_line *line, -const char *consumer,int flags); +int gpiod_line_attr_set_drive (struct gpiod_line_attr *attr,int drive);/** -* @brief Reserve a single line, set the direction to output. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @param default_val Initial line value. -* @return 0 if the line was properly reserved, -1 on failure. +* @brief Set the bias setting. +* @param attr Line attribute object. +* @param bias New bias setting. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type ::GPIOD_LINE_ATTR_TYPE_OPTS. */ -int gpiod_line_request_output_flags (struct gpiod_line *line, -const char *consumer,int flags, -int default_val); +int gpiod_line_attr_set_bias (struct gpiod_line_attr *attr,int bias);/** -* @brief Request rising edge event notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the active-low setting. +* @param attr Line attribute object. +* @param active_low New active-low setting. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type ::GPIOD_LINE_ATTR_TYPE_OPTS. */ -int gpiod_line_request_rising_edge_events_flags (struct gpiod_line *line, -const char *consumer, -int flags); +int gpiod_line_attr_set_active_low (struct gpiod_line_attr *attr, +bool active_low);/** -* @brief Request falling edge event notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the realtime clock setting. +* @param attr Line attribute object. +* @param clock_realtime New realtime clock setting. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type ::GPIOD_LINE_ATTR_TYPE_OPTS. +* +* This option can be used to tell the kernel to get the line event timestamps +* from the realtime clock, not the monotonic clock which is the default. */ -int gpiod_line_request_falling_edge_events_flags (struct gpiod_line *line, -const char *consumer, -int flags); +int gpiod_line_attr_set_clock_realtime (struct gpiod_line_attr *attr, +bool clock_realtime);/** -* @brief Request all event type notifications on a single line. -* @param line GPIO line object. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the debounce config. +* @param attr Line attribute object. +* @param debounce Activate or de-activate debouncing. +* @param debounce_period New debounce period in microseconds. +* @return 0 on success, -1 on error. +* @note Can only be used with attributes of type +* ::GPIOD_LINE_ATTR_TYPE_DEBOUNCE. +* */ -int gpiod_line_request_both_edges_events_flags (struct gpiod_line *line, -const char *consumer, -int flags); +int gpiod_line_attr_set_debounce (struct gpiod_line_attr *attr,bool debounce, +unsigned long debounce_period);/** -* @brief Reserve a set of GPIO lines. -* @param bulk Set of GPIO lines to reserve. -* @param config Request options. -* @param default_vals Initial line values - only relevant if we're setting -* the direction to output. -* @return 0 if all lines were properly requested. In case of an error -* this routine returns -1 and sets the last error number. +* @brief Set the output values carried by this attribute. +* @param attr Line attribute object. +* @param values GPIO line mask specifing the output values. +* @return 0 on success +* @note Can only be used with attributes of type +* ::GPIOD_LINE_ATTR_TYPE_OUTPUT_VALUES. * -* If this routine succeeds, the caller takes ownership of the GPIO lines -* until they're released. All the requested lines must be provided by the -* same gpiochip. +* Each bit in the values mask is associated with a line in a request handle. +* If the bit is set, the line should be driven high, if the bit is cleared, +* the line should be driven low. */ -int gpiod_line_request_bulk (struct gpiod_line_bulk *bulk, -const struct gpiod_line_request_config *config, -const int *default_vals); +int gpiod_line_attr_set_output_values (struct gpiod_line_attr *attr, +gpiod_line_mask values);/** -* @brief Reserve a set of GPIO lines, set the direction to input. -* @param bulk Set of GPIO lines to reserve. -* @param consumer Name of the consumer. -* @return 0 if the lines were properly reserved, -1 on failure. +* @brief Create a new line config object. +* @return New line config object or NULL on error. */ -int gpiod_line_request_bulk_input (struct gpiod_line_bulk *bulk, -const char *consumer); +struct gpiod_line_config *gpiod_line_config_new (void );/** -* @brief Reserve a set of GPIO lines, set the direction to output. -* @param bulk Set of GPIO lines to reserve. -* @param consumer Name of the consumer. -* @param default_vals Initial line values. -* @return 0 if the lines were properly reserved, -1 on failure. +* @brief Increase the reference count of this line config object. +* @param config Line config object. +* @return Passed reference to the line config object. */ -int gpiod_line_request_bulk_output (struct gpiod_line_bulk *bulk, -const char *consumer, -const int *default_vals); +struct gpiod_line_config * +gpiod_line_config_ref (struct gpiod_line_config *config);/** -* @brief Request rising edge event notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Decrease the reference count of this line config object. If the +* reference count reaches 0, free all associated resources. +* @param config Line config object. */ -int gpiod_line_request_bulk_rising_edge_events (struct gpiod_line_bulk *bulk, -const char *consumer); +void gpiod_line_config_unref (struct gpiod_line_config *config);/** -* @brief Request falling edge event notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Add a new line attribute to this line config. +* @param config Line config object. +* @param attr Line attribute to add. +* @return 0 on success, -1 on failure. */ -int gpiod_line_request_bulk_falling_edge_events (struct gpiod_line_bulk *bulk, -const char *consumer); +int gpiod_line_config_add_attribute (struct gpiod_line_config *config, +struct gpiod_line_attr *attr);/** -* @brief Request all event type notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Remove all attributes from this config. +* @param config Line config. */ -int gpiod_line_request_bulk_both_edges_events (struct gpiod_line_bulk *bulk, -const char *consumer); +void gpiod_line_config_clear_attrs (struct gpiod_line_config *config);/** -* @brief Reserve a set of GPIO lines, set the direction to input. -* @param bulk Set of GPIO lines to reserve. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the lines were properly reserved, -1 on failure. +* @brief Set the request type. +* @param config Line config. +* @param request_type New request type. +* @return 0 on success, -1 on error. */ -int gpiod_line_request_bulk_input_flags (struct gpiod_line_bulk *bulk, -const char *consumer,int flags); +int gpiod_line_config_set_request_type (struct gpiod_line_config *config, +int request_type);/** -* @brief Reserve a set of GPIO lines, set the direction to output. -* @param bulk Set of GPIO lines to reserve. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @param default_vals Initial line values. -* @return 0 if the lines were properly reserved, -1 on failure. +* @brief Set the drive setting. +* @param config Line config. +* @param drive New drive setting. +* @return 0 on success, -1 on error. */ -int gpiod_line_request_bulk_output_flags (struct gpiod_line_bulk *bulk, -const char *consumer,int flags, -const int *default_vals); +int gpiod_line_config_set_drive (struct gpiod_line_config *config,int drive);/** -* @brief Request rising edge event notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the bias setting. +* @param config Line config. +* @param bias New bias setting. +* @return 0 on success, -1 on error. */ -int gpiod_line_request_bulk_rising_edge_events_flags ( -struct gpiod_line_bulk *bulk, -const char *consumer,int flags); +int gpiod_line_config_set_bias (struct gpiod_line_config *config,int bias);/** -* @brief Request falling edge event notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the active-low setting. +* @param config Line config. +* @param active_low New active-low setting. */ -int gpiod_line_request_bulk_falling_edge_events_flags ( -struct gpiod_line_bulk *bulk, -const char *consumer,int flags); +void gpiod_line_config_set_active_low (struct gpiod_line_config *config, +bool active_low);/** -* @brief Request all event type notifications on a set of lines. -* @param bulk Set of GPIO lines to request. -* @param consumer Name of the consumer. -* @param flags Additional request flags. -* @return 0 if the operation succeeds, -1 on failure. +* @brief Set the realtime clock setting. +* @param config Line config. +* @param clock_realtime New realtime clock setting. +* +* This option can be used to tell the kernel to get the line event timestamps +* from the realtime clock, not the monotonic clock which is the default. */ -int gpiod_line_request_bulk_both_edges_events_flags ( -struct gpiod_line_bulk *bulk, -const char *consumer,int flags); +void +gpiod_line_config_set_event_clock_realtime (struct gpiod_line_config *config, +bool clock_realtime);/** -* @brief Release a previously reserved line. -* @param line GPIO line object. +* @brief Create a new request config object. +* @return New request config object or NULL on error. */ -void gpiod_line_release (struct gpiod_line *line); +struct gpiod_request_config *gpiod_request_config_new (void );/** -* @brief Release a set of previously reserved lines. -* @param bulk Set of GPIO lines to release. -* -* If the lines were not previously requested together, the behavior is -* undefined. +* @brief Increase the reference count of this request config object. +* @param config Request config object. +* @return Passed reference to this request config. */ -void gpiod_line_release_bulk (struct gpiod_line_bulk *bulk); +struct gpiod_request_config * +gpiod_request_config_ref (struct gpiod_request_config *config);/** -* @} -* -* @defgroup line_value Reading & setting line values -* @{ -* -* Functions allowing to read and set GPIO line values for single lines and -* in bulk. +* @brief Decrease the reference count of this request config object. If the +* reference count reaches 0, free all associated resources. +* @param config Request config object. */ +void gpiod_request_config_unref (struct gpiod_request_config *config);/** -* @brief Read current value of a single GPIO line. -* @param line GPIO line object. -* @return 0 or 1 if the operation succeeds. On error this routine returns -1 -* and sets the last error number. +* @brief Set the consumer string. +* @param config Request config object. +* @param consumer Consumer name. +* @return 0 on success, -1 on failure. */ -int gpiod_line_get_value (struct gpiod_line *line); +int gpiod_request_config_set_consumer (struct gpiod_request_config *config, +const char *consumer);/** -* @brief Read current values of a set of GPIO lines. -* @param bulk Set of GPIO lines to reserve. -* @param values An array big enough to hold line_bulk->num_lines values. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -* -* If succeeds, this routine fills the values array with a set of values in -* the same order, the lines are added to line_bulk. If the lines were not -* previously requested together, the behavior is undefined. +* @brief Set line offsets for this request. +* @param config Request config object. +* @param num_lines Number of offsets. +* @param offsets Array of line offsets. +* @return 0 on success, -1 on failure. */ -int gpiod_line_get_value_bulk (struct gpiod_line_bulk *bulk,int *values); +int gpiod_request_config_set_offsets (struct gpiod_request_config *config, +unsigned int num_lines, +unsigned int *offsets);/** -* @brief Set the value of a single GPIO line. -* @param line GPIO line object. -* @param value New value. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. +* @brief Set the size of the kernel event buffer. +* @param config Request config object. +* @param event_buffer_size New event buffer size. +* @return 0 on success, -1 on failure. */ -int gpiod_line_set_value (struct gpiod_line *line,int value); +int +gpiod_request_config_set_event_buffer_size (struct gpiod_request_config *config, +unsigned int event_buffer_size);/** -* @brief Set the values of a set of GPIO lines. -* @param bulk Set of GPIO lines to reserve. -* @param values An array holding line_bulk->num_lines new values for lines. -* A NULL pointer is interpreted as a logical low for all lines. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. +* @} * -* If the lines were not previously requested together, the behavior is -* undefined. +* @defgroup request_handle Line request handle operations +* @{ */ -int gpiod_line_set_value_bulk (struct gpiod_line_bulk *bulk,const int *values);/** -* @} -* -* @defgroup line_config Setting line configuration -* @{ -* -* Functions allowing modification of config options of GPIO lines requested -* from user-space. -*/ - -/** -* @brief Update the configuration of a single GPIO line. -* @param line GPIO line object. -* @param direction Updated direction which may be one of -* GPIOD_LINE_REQUEST_DIRECTION_AS_IS, -* GPIOD_LINE_REQUEST_DIRECTION_INPUT, or -* GPIOD_LINE_REQUEST_DIRECTION_OUTPUT. -* @param flags Replacement flags. -* @param value The new output value for the line when direction is -* GPIOD_LINE_REQUEST_DIRECTION_OUTPUT. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -*/ -int gpiod_line_set_config (struct gpiod_line *line,int direction, -int flags,int value); - -/** -* @brief Update the configuration of a set of GPIO lines. -* @param bulk Set of GPIO lines. -* @param direction Updated direction which may be one of -* GPIOD_LINE_REQUEST_DIRECTION_AS_IS, -* GPIOD_LINE_REQUEST_DIRECTION_INPUT, or -* GPIOD_LINE_REQUEST_DIRECTION_OUTPUT. -* @param flags Replacement flags. -* @param values An array holding line_bulk->num_lines new logical values -* for lines when direction is -* GPIOD_LINE_REQUEST_DIRECTION_OUTPUT. -* A NULL pointer is interpreted as a logical low for all lines. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -* -* If the lines were not previously requested together, the behavior is -* undefined. +* @brief Increase the reference count of this request handle. +* @param handle GPIO request handle. +* @return Passed reference to this request handle. */ -int gpiod_line_set_config_bulk (struct gpiod_line_bulk *bulk, -int direction,int flags,const int *values); +struct gpiod_request_handle * +gpiod_request_handle_ref (struct gpiod_request_handle *handle); +/** +* @brief Decrease the reference count of this request handle. If the reference +* count reaches 0, close the associated file descriptor and release +* all allocated resources. +* @param handle GPIO request handle. +*/ +void gpiod_request_handle_unref (struct gpiod_request_handle *handle);/** -* @brief Update the configuration flags of a single GPIO line. -* @param line GPIO line object. -* @param flags Replacement flags. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. +* @brief Read values of lines associated with this request handle. +* @param handle GPIO request handle. +* @param values Address of the bitmap to store values in. +* @param mask Mask of the lines to read values from. +* @return 0 on success, -1 on failure. +* @note The bits in the values and mask bitmaps represent the lines associated +* with this request handle at the same offsets. Only values of lines +* for which the relevant bits in mask are set will be read. */ -int gpiod_line_set_flags (struct gpiod_line *line,int flags); +int gpiod_request_handle_get_values (struct gpiod_request_handle *handle, +gpiod_line_mask *values, +gpiod_line_mask mask);/** -* @brief Update the configuration flags of a set of GPIO lines. -* @param bulk Set of GPIO lines. -* @param flags Replacement flags. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -* -* If the lines were not previously requested together, the behavior is -* undefined. +* @brief Set values of lines associated with this request handle. +* @param handle GPIO request handle. +* @param values Mask of line values to set. +* @param mask Mask of the lines to set values for. +* @return 0 on success, -1 on failure. +* @note The bits in the values and mask bitmaps represent the lines associated +* with this request handle at the same offsets. Only values of lines +* for which the relevant bits in mask are set will be modified. */ -int gpiod_line_set_flags_bulk (struct gpiod_line_bulk *bulk,int flags); +int gpiod_request_handle_set_values (struct gpiod_request_handle *handle, +gpiod_line_mask values, +gpiod_line_mask mask);/** -* @brief Set the direction of a single GPIO line to input. -* @param line GPIO line object. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. +* @brief Update the configuration of lines associated with this request handle. +* @param handle GPIO request handle. +* @param config New line config to apply. +* @return 0 on success, -1 on failure. */ -int gpiod_line_set_direction_input (struct gpiod_line *line); +int gpiod_request_handle_set_config (struct gpiod_request_handle *handle, +struct gpiod_line_config *config);/** -* @brief Set the direction of a set of GPIO lines to input. -* @param bulk Set of GPIO lines. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -* -* If the lines were not previously requested together, the behavior is -* undefined. +* @brief Get the file descriptor associated with this request handle. +* @param handle GPIO request handle. +* @return Number of the file descriptor associated with this request. This +* function never fails. */ -int -gpiod_line_set_direction_input_bulk (struct gpiod_line_bulk *bulk); +int gpiod_request_handle_get_fd (struct gpiod_request_handle *handle);/** -* @brief Set the direction of a single GPIO line to output. -* @param line GPIO line object. -* @param value The logical value output on the line. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. +* @brief Wait for line events on any of the lines associated with this handle. +* @param handle GPIO request handle. +* @param timeout Wait time limit in nanoseconds. +* @return 0 if wait timed out, -1 if an error occurred, 1 if an event is +* pending. */ -int gpiod_line_set_direction_output (struct gpiod_line *line,int value); +int gpiod_request_handle_event_wait (struct gpiod_request_handle *handle, +uint64_t timeout);/** -* @brief Set the direction of a set of GPIO lines to output. -* @param bulk Set of GPIO lines. -* @param values An array holding line_bulk->num_lines new logical values -* for lines. A NULL pointer is interpreted as a logical low -* for all lines. -* @return 0 is the operation succeeds. In case of an error this routine -* returns -1 and sets the last error number. -* -* If the lines were not previously requested together, the behavior is -* undefined. +* @brief Read a number of line events from a request handle. +* @param handle GPIO request handle. +* @param buf Line event buffer. +* @param max_events Maximum number of events to read. +* @return On success returns the number of events read from the file +* descriptor, on failure return -1. +* @note This function will block if no event was queued for this line. */ -int gpiod_line_set_direction_output_bulk (struct gpiod_line_bulk *bulk, -const int *values); +int gpiod_request_handle_event_read (struct gpiod_request_handle *handle, +struct gpiod_line_event_buffer *buf, +unsigned int max_events);/** * @}
@@ -930,120 +773,133 @@ enum {/**< Falling edge event. */ }; +/** +* @brief Increase the reference count of this line event. +* @param event GPIO line event. +* @return Passed reference to the event object. +* @note Must not be used with events held by the event buffer (retrieved +* using ::gpiod_line_event_buffer_get_event. Only event objects +* created by ::gpiod_line_event_buffer_copy_event are refcounted. +*/ struct gpiod_line_event *gpiod_line_event_ref (struct gpiod_line_event *event); +/** +* @brief Decrease the reference count of this line event. If the reference +* count reaches zero, free all associated resources. +* @param event GPIO line event. +*/ void gpiod_line_event_unref (struct gpiod_line_event *event); +/** +* @brief Get the event type. +* @param event GPIO line event. +* @return The event type (::GPIOD_LINE_EVENT_RISING_EDGE or +* ::GPIOD_LINE_EVENT_FALLING_EDGE). +*/ int gpiod_line_event_get_event_type (struct gpiod_line_event *event); +/** +* @brief Get the timestamp of the event. +* @param event GPIO line event. +* @return Timestamp in nanoseconds. +*/ uint64_t gpiod_line_event_get_timestamp (struct gpiod_line_event *event); +/** +* @brief Get the hardware offset of the line on which the event was triggered. +* @param event GPIO line event. +* @return Line offset. +*/ unsigned int gpiod_line_event_get_line_offset (struct gpiod_line_event *event); +/** +* @brief Get the global sequence number of this event. +* @param event GPIO line event. +* @return Sequence number of the event relative to all lines in the associated +* line request. +*/ unsigned int gpiod_line_event_get_global_seqno (struct gpiod_line_event *event); +/** +* @brief Get the event sequence number specific to this line. +* @param event GPIO line event. +* @return Sequence number of the event relative to this line within the +* lifetime of the associated line request. +*/ unsigned int gpiod_line_event_get_line_seqno (struct gpiod_line_event *event); +/** +* @brief Create a new line event buffer. +* @param capacity Number of events this buffer can store (min = 1, max = 1024). +* @return New line event buffer or NULL on error. +*/ struct gpiod_line_event_buffer *gpiod_line_event_buffer_new (unsigned int capacity); +/** +* @brief Increase the reference count of this event buffer. +* @param buf Line event buffer. +* @return Passed reference to the event buffer. +*/ struct gpiod_line_event_buffer *gpiod_line_event_buffer_ref (struct gpiod_line_event_buffer *buf); +/** +* @brief Decrease the reference count of this event buffer. If the reference +* count reaches 0, free all associated resources. +* @param buf Line event buffer. +*/ void gpiod_line_event_buffer_unref (struct gpiod_line_event_buffer *buf); +/** +* @brief Get a weak reference to an event in the buffer. +* @param buf Line event buffer. +* @param index Index of the event in the buffer. +* @return Pointer to an event stored in the buffer. The lifetime of this +* event is tied to the buffer object. Users must not call event +* reference counting functions on pointers retrieved using this +* function. +*/ struct gpiod_line_event *gpiod_line_event_buffer_get_event (struct gpiod_line_event_buffer *buf,unsigned long index); +/** +* @brief Get a copy of a line event. +* @param buf Line event buffer. +* @param index Index of the event in the buffer. +* @return Returns a copy of the line event stored in this buffer. The event's +* lifetime is managed by the caller. The event's reference count must +* be decreases using ::gpiod_line_event_unref. +*/ struct gpiod_line_event *gpiod_line_event_buffer_copy_event (struct gpiod_line_event_buffer *buf,unsigned long index);/** -* @brief Wait for an event on a single line. -* @param line GPIO line object. -* @param timeout Wait time limit. -* @return 0 if wait timed out, -1 if an error occurred, 1 if an event -* occurred. -*/ -int gpiod_line_event_wait (struct gpiod_line *line,uint64_t timeout); - -/** -* @brief Wait for events on a set of lines. -* @param bulk Set of GPIO lines to monitor. -* @param timeout Wait time limit. -* @param event_bulk Bulk object in which to store the line handles on which -* events occurred. Can be NULL. -* @return 0 if wait timed out, -1 if an error occurred, 1 if at least one -* event occurred. -*/ -int gpiod_line_event_wait_bulk (struct gpiod_line_bulk *bulk,uint64_t timeout, -struct gpiod_line_bulk *event_bulk); - -/** -* @brief Read next pending event from the GPIO line. -* @param line GPIO line object. -* @param event Buffer to which the event data will be copied. -* @return 0 if the event was read correctly, -1 on error. -* @note This function will block if no event was queued for this line. -*/ -int gpiod_line_event_read (struct gpiod_line *line, -struct gpiod_line_event_buffer *buf); - -/** -* @brief Read up to a certain number of events from the GPIO line. -* @param line GPIO line object. -* @param events Buffer to which the event data will be copied. Must hold at -* least the amount of events specified in num_events. -* @param num_events Specifies how many events can be stored in the buffer. -* @return On success returns the number of events stored in the buffer, on -* failure -1 is returned. -*/ -int gpiod_line_event_read_multiple (struct gpiod_line *line, -struct gpiod_line_event_buffer *buf, -unsigned int num_events); - -/** -* @brief Get the event file descriptor. -* @param line GPIO line object. -* @return Number of the event file descriptor or -1 if the user tries to -* retrieve the descriptor from a line that wasn't configured for -* event monitoring. -* -* Users may want to poll the event file descriptor on their own. This routine -* allows to access it. +* @brief Get the number of events this buffers stores. +* @param buf Line event buffer. +* @return Number of events stored in this buffer. */ -int gpiod_line_event_get_fd (struct gpiod_line *line); +unsigned int +gpiod_line_event_buffer_num_events (struct gpiod_line_event_buffer *buf);/** -* @brief Read the last GPIO event directly from a file descriptor. +* @brief Read GPIO line events directly from a file descriptor. * @param fd File descriptor. -* @param event Buffer in which the event data will be stored. -* @return 0 if the event was read correctly, -1 on error. +* @param buf Line event buffer. +* @param max_events Maximum number of events to read. +* @return On success returns the number of events read from the file +* descriptor, on failure return -1. * * Users who directly poll the file descriptor for incoming events can also * directly read the event data from it using this routine. This function * translates the kernel representation of the event to the libgpiod format. */ -int gpiod_line_event_read_fd (int fd,struct gpiod_line_event_buffer *buf); - -/** -* @brief Read up to a certain number of events directly from a file descriptor. -* @param fd File descriptor. -* @param events Buffer to which the event data will be copied. Must hold at -* least the amount of events specified in num_events. -* @param max_events Specifies the maximum number of events to read. -* @return On success returns the number of events stored in the buffer, on -* failure -1 is returned. -*/ -int gpiod_line_event_read_fd_multiple (int fd, -struct gpiod_line_event_buffer *buf, -unsigned int max_events); +int gpiod_line_event_buffer_read_fd (int fd,struct gpiod_line_event_buffer *buf, +unsigned int max_events);/** -* @} -* * @} * * @defgroup misc Stuff that didn't fit anywhere else
@@ -1052,6 +908,19 @@ int gpiod_line_event_read_fd_multiple(int fd,* Various libgpiod-related functions. */ +/** +* @brief Check if the file pointed to by path is a GPIO chip character device. +* @param path Path to check. +* @return True if the file exists and is a GPIO chip character device or a +* symbolic link to it. +*/ +bool gpiod_is_gpiochip_device (const char *path); + +/** +* @brief Convert seconds to nanoseconds. +* @param sec Number of seconds to convert. +* @return The same duration in nanoseconds. +*/ uint64_t gpiod_sec_to_nsec (uint64_t sec);/**
lib/Makefile.am +7 -2
@@ -2,14 +2,19 @@ # SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <[email protected]> lib_LTLIBRARIES = libgpiod.la -libgpiod_la_SOURCES = core.c \ +libgpiod_la_SOURCES = attr.c \ + chip.c \ + config.c \ event.c \ - helpers.c \ + handle.c \ internal.h \ internal.c \ info.c \ + mask.c \ misc.c \ + request.c \ uapi/gpio.h + libgpiod_la_CFLAGS = -Wall -Wextra -g -std=gnu89 libgpiod_la_CFLAGS += -fvisibility=hidden -I$(top_srcdir)/include/ libgpiod_la_CFLAGS += -include $(top_builddir)/config.h
lib/attr.c new file +232 -0
232 lines not on this page · raw message
lib/chip.c new file +183 -0
183 lines not on this page · raw message
lib/config.c new file +158 -0
158 lines not on this page · raw message
lib/core.c deleted +0 -1131
1,100 lines not on this page · raw message
lib/event.c +6 -38
44 lines not on this page · raw message
lib/handle.c new file +144 -0
144 lines not on this page · raw message
lib/helpers.c deleted +0 -306
306 lines not on this page · raw message
lib/internal.c +101 -0
101 lines not on this page · raw message
lib/mask.c new file +43 -0
43 lines not on this page · raw message
lib/misc.c +75 -0
75 lines not on this page · raw message
lib/request.c new file +118 -0
118 lines not on this page · raw message
tests/tests-event.c +29 -29
58 lines not on this page · raw message
tools/gpioget.c +34 -23
57 lines not on this page · raw message
tools/gpiomon.c +54 -59
113 lines not on this page · raw message
tools/gpioset.c +58 -27
85 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.30.1
Part of the diff is not shown here. View the raw message.
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenance
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
e.g. gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?
Similarly gpiod_line_get_consumer() - who owns the returned pointer and what is it's lifetime?
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. So gpiod_chip would have open()/close(), gpiod_request_handle would have request()/release(), and the others would all be new()/free()d.
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop the gpiod_line_attr, and instead provide accessors and mutators on the gpiod_line_config for each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.
Not sure I like merging the direction and edge into the request_type. I would tend to keep those separate, with set_direction and set_edge_detection functions, with the latter forcing input direction.
I would rename gpiod_request_config to gpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion with gpiod_line_config.
gpiod_line_mask should highlight that the bits correspond to lines on the request, in the order provided to gpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps the gpiod_request_config or the gpiod_request_handle should provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then the gpiod_line_mask can be opaque as well.
I would rename gpiod_request_handle to gpiod_line_request. And request.c to options.c, and handle.c to request.c.
gpiod_line_attr_set_debounce() can use a zero period to identify disabling debounce, so the debounce flag is redundant.
Cheers,
Kent.
Hi Kent!
Thanks a lot for looking at this.
Quoted 26 lines · Kent Gibson
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenance
Quoted 7 lines
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
Just to clarify why I did certain things the way I did: there are certain semi-standardized guidelines to creating low-level C libraries for linux user-space interfaces. They are gathered in a sample project called libabc[1][2][3]. Most plumbing-layer libraries follow these guidelines more or less rigorously. Many low-level programmers will make certain assumptions based on their previous experiences when working with libraries and it's good to be as little confusing as possible.
Quoted 10 lines
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
Interesting because in my mind reference counting actually simplifies the life-time of objects - everytime someone (the caller or another object) stores the address of the object, the reference count is increased.
Reference counting is a de-facto standard in C libraries. Look at libkmod, libudev, libpulse, all the systemd libraries, the whole of GLib.
Reference counting makes higher-level programming easier. An object lives as long as there's at least one user. In C++ bindings the objects were refcounted using shared_ptr which causes some issues. Now with refcounting implemented at the C library level, we'll be able to use the PImpl pattern with unique_ptr and still keep the objects copyable.
To summarize: I don't see many disadvantages to using reference counting other than the fact that my documentation is not yet very detailed and lacks some general information about how reference counting works in libgpiod and needs some clarification.
Quoted 5 lines
e.g.
gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?
Yes, it becomes shared. Its reference count is now 2. If the user modifies it, the config will use a modified value at the time of the request. To give you a real-life example of such behavior: in GLib where all GObjects are reference counted, if you pass a reference to a GFile to another user, then set its (GFile's) attribute, they'll be changed for the user sharing the object too. Same with how Python or Java handle references, except you don't need to manage them yourself.
Quoted 2 lines
Similarly
gpiod_line_get_consumer()- who owns the returned pointer and what is it's lifetime?
Since simple strings can't be refcounted and this function returns a pointer to a constant string, the life-time of the string is obviously tied to that of the line_info object. The doc should probably say:
Returns a pointer to the string stored in the line_info object.
Quoted 8 lines
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. Sogpiod_chipwould have open()/close(),gpiod_request_handlewould have request()/release(), and the others would all be new()/free()d.
This makes you use a different set of resource management functions depending on the object. Additionally some objects can't be created - only retrieved from other objects.
Having a simple ref/unref pair for all opaque data types looks more elegant to me. Another real-life example from yesterday: I'm working on a small library to go with the new gpio-sim module (meant as a replacement for libgpio-mockup) and when I tried to use libmount (to verify if configfs is mounted and where) I was super confused by its resource management which is similar to what you suggest but also some resources need to be freed and some transfer their ownership to other objects (without reference counting) and while it's all documented and you can find info on that eventually, I still spent time debugging strange double-free and other corruptions before I got things right. I find libudev and libkmod with their consistent reference counting much more instinctive to use.
Quoted 6 lines
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop thegpiod_line_attr, and instead provide accessors and
Quoted 9 lines
mutators on the
gpiod_line_configfor each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.
I had exactly this in mind initially but couldn't find an elegant interface.
There are two options I see:
gpiod_line_config_set_drive(cfg, drive); gpiod_line_config_set_drive_index(cfg, drive, index);
or:
gpiod_line_config_set_drive(cfg, drive); unsigned int indices[] = { 0, 3, 4, 6 }; gpiod_line_config_set_drive_index(cfg, drive, indices);
The former would require a separate function call for each line, the former needs a lot of boilerplate code because we'll usually have to alloc & fill the indices array. Eventually I decided to go with attributes but if you have some ideas/suggestions for that, they're welcome!
Quoted 4 lines
Not sure I like merging the direction and edge into the
request_type. I would tend to keep those separate, withset_directionandset_edge_detectionfunctions, with the latter forcing input direction.
If there's no way we can use output with edge detection, why even bother with allowing the user to try to set output mode for edge_detection or vice-versa? It's just more error checking for no benefit, right? The user will still find out that the line is in input mode with the line_info.
Quoted 4 lines
I would rename
gpiod_request_configtogpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion withgpiod_line_config.
Not sure about this one. With the current naming, it's being made clear that we have two separate things to configure, the line(s) and the request itself. Naming both "_config" makes a clear distinction.
Also: the request config can be reused too for separate requests.
Quoted 7 lines
gpiod_line_maskshould highlight that the bits correspond to lines on the request, in the order provided togpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps thegpiod_request_configor thegpiod_request_handleshould provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then thegpiod_line_maskcan be opaque as well.
Yes, this is one of those things I struggled with. I wasn't sure which one's better because if the user wants to request 64 lines, then set a separate config for 20 of them, it's a lot of function calls if we allow to set line config by offset of a single line, or we get a complicated API with allowing arrays of offsets.
Agreed for the line map functions, it's probably the most confusing element of this new API. I'll come up with something.
Quoted 6 lines
I would rename
gpiod_request_handletogpiod_line_request. Andrequest.ctooptions.c, andhandle.ctorequest.c.
gpiod_line_attr_set_debounce()can use a zero period to identify disabling debounce, so the debounce flag is redundant.
Sounds good.
Bart
Quoted 2 lines
Cheers,
Kent.
[1] http://0pointer.de/blog/projects/libabc.html
[2] https://git.kernel.org/pub/scm/linux/kernel/git/kay/libabc.git
[3] https://git.kernel.org/pub/scm/linux/kernel/git/kay/libabc.git/plain/README
Quoted 39 lines · Bartosz Golaszewski
Hi Kent!
Thanks a lot for looking at this.
Quoted 26 lines · Kent Gibson
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenanceQuoted 7 lines
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
Quoted 9 lines
Just to clarify why I did certain things the way I did: there are certain semi-standardized guidelines to creating low-level C libraries for linux user-space interfaces. They are gathered in a sample project called libabc[1][2][3]. Most plumbing-layer libraries follow these guidelines more or less rigorously. Many low-level programmers will make certain assumptions based on their previous experiences when working with libraries and it's good to be as little confusing as possible.
Fair enough, though I don't see anything in libabc that conflicts with my suggestions, nor that require some of your design choices.
Quoted 11 lines
Quoted 10 lines
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
Quoted 9 lines
Interesting because in my mind reference counting actually simplifies the life-time of objects - everytime someone (the caller or another object) stores the address of the object, the reference count is increased.
Reference counting is a de-facto standard in C libraries. Look at libkmod, libudev, libpulse, all the systemd libraries, the whole of GLib.
I don't doubt that reference counting is out there, I question whether it is necessary here.
In my mind reference counting is a tool to be used when you need to share objects and it isn't clear who is responsible for freeing them. I don't see any need for sharing here at all - for all objects (excluding the gpiod_line_attr that I would remove) it is pretty clear who is responsible for them at all times.
Quoted 7 lines
Reference counting makes higher-level programming easier. An object lives as long as there's at least one user. In C++ bindings the objects were refcounted using
shared_ptrwhich causes some issues. Now with refcounting implemented at the C library level, we'll be able to use the PImpl pattern withunique_ptrand still keep the objects copyable.
That still sounds to me like you are sharing objects that shouldn't be shared. Or copied.
Quoted 5 lines
To summarize: I don't see many disadvantages to using reference counting other than the fact that my documentation is not yet very detailed and lacks some general information about how reference counting works in libgpiod and needs some clarification.
I understand your argument - which is exactly what I had presumed. But I still find the idea of having _unref() acting as the universal free function to be distasteful.
Quoted 6 lines
Quoted 5 lines
e.g.
gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?
Quoted 8 lines
Yes, it becomes shared. Its reference count is now 2. If the user modifies it, the config will use a modified value at the time of the request. To give you a real-life example of such behavior: in GLib where all GObjects are reference counted, if you pass a reference to a GFile to another user, then set its (GFile's) attribute, they'll be changed for the user sharing the object too. Same with how Python or Java handle references, except you don't need to manage them yourself.
This is all mute if you drop gpiod_line_attr, but I still don't see why sharing is preferable in this case. It feels like the worst of both worlds - I need to alloc an attr for every add, and I need to unref them as well.
Quoted 8 lines
Quoted 2 lines
Similarly
gpiod_line_get_consumer()- who owns the returned pointer and what is it's lifetime?Since simple strings can't be refcounted and this function returns a pointer to a constant string, the life-time of the string is obviously tied to that of the
line_infoobject. The doc should probably say:
Returns a pointer to the string stored in theline_infoobject.
I would dispute the "obviously", particularly since you seem to expect everything else to be unref()ed.
Quoted 9 lines
Quoted 8 lines
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. Sogpiod_chipwould have open()/close(),gpiod_request_handlewould have request()/release(), and the others would all be new()/free()d.
Quoted 4 lines
This makes you use a different set of resource management functions depending on the object. Additionally some objects can't be created - only retrieved from other objects.
Yup, different objects have different lifecycles - even your way.
Quoted 4 lines
Having a simple ref/unref pair for all opaque data types looks more elegant to me. Another real-life example from yesterday: I'm working on a small library to go with the new gpio-sim module (meant as a replacement for libgpio-mockup) and when I tried to use libmount (to
Quoted 9 lines
verify if configfs is mounted and where) I was super confused by its resource management which is similar to what you suggest but also some resources need to be freed and some transfer their ownership to other objects (without reference counting) and while it's all documented and you can find info on that eventually, I still spent time debugging strange double-free and other corruptions before I got things right. I find libudev and libkmod with their consistent reference counting much more instinctive to use.
I find dealing with repeated frees preferable to dealing with issues related to unexpected side-effects when ownership is unclear.
Quoted 29 lines
Quoted 6 lines
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop thegpiod_line_attr, and instead provide accessors andQuoted 9 lines
mutators on the
gpiod_line_configfor each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.I had exactly this in mind initially but couldn't find an elegant interface.
There are two options I see:
gpiod_line_config_set_drive(cfg, drive);gpiod_line_config_set_drive_index(cfg, drive, index);or:
gpiod_line_config_set_drive(cfg, drive); unsigned int indices[] = { 0, 3, 4, 6 };gpiod_line_config_set_drive_index(cfg, drive, indices);
Quoted 6 lines
The former would require a separate function call for each line, the former needs a lot of boilerplate code because we'll usually have to alloc & fill the indices array. Eventually I decided to go with attributes but if you have some ideas/suggestions for that, they're welcome!
I generally avoid variadic functions, but this might be an application where they make sense. i.e. make your indices variadic. Oh, and make them offsets ;-).
Quoted 11 lines
Quoted 4 lines
Not sure I like merging the direction and edge into the
request_type. I would tend to keep those separate, withset_directionandset_edge_detectionfunctions, with the latter forcing input direction.If there's no way we can use output with edge detection, why even bother with allowing the user to try to set output mode for
edge_detectionor vice-versa? It's just more error checking for no benefit, right? The user will still find out that the line is in input mode with theline_info.
You are adding another concept for the user to grok - the request_type. They will need to understand direction and edge detection anyway, why add a new concept to the mix?
Oh, and wrt error checking, in my Go library, and as I suggest above, setting edge detection overrides any previous direction setting and forces input. Similarly setting output direction cancels any edge detection. So the config presented to the kernel will always be consistent and never trigger an EINVAL. And that is all documented in the corresponding config functions.
Similarly the drive settings.
The library policy is last-in-wins, which it can be as there are distinct calls for each attribute, whereas at the uAPI they are merged into flags.
Quoted 10 lines
Quoted 4 lines
I would rename
gpiod_request_configtogpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion withgpiod_line_config.Not sure about this one. With the current naming, it's being made clear that we have two separate things to configure, the line(s) and the request itself. Naming both "
_config" makes a clear distinction.
Also: the request config can be reused too for separate requests.
I meant one-off wrt a single request. i.e. changing the options after the lines have been requested can never impact the request, whereas a changed config can be applied with the set_config().
Quoted 8 lines
Quoted 7 lines
gpiod_line_maskshould highlight that the bits correspond to lines on the request, in the order provided togpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps thegpiod_request_configor thegpiod_request_handleshould provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then thegpiod_line_maskcan be opaque as well.
Quoted 9 lines
Yes, this is one of those things I struggled with. I wasn't sure which one's better because if the user wants to request 64 lines, then set a separate config for 20 of them, it's a lot of function calls if we allow to set line config by offset of a single line, or we get a complicated API with allowing arrays of offsets.
Agreed for the line map functions, it's probably the most confusing element of this new API. I'll come up with something.
Ideally I would like to avoid the gpiod_line_mask totally, and always deal in chip offsets.
The API should be simplest for the most common use cases. Those far corner cases can be a pain to use, but must still be possible. I would put the priority on handling the most common cases:
A. all lines
B. one line
C. a subset of lines
I would expect A to be the most common by far - that was all that the previous API supported, then B and then C.
I had suggested providing A and C, with B being a special case of C. But I could live with C being implemented as multiple calls to B.
A variadic function could manage all three, with no offsets meaning all lines? Though in practice I would probably provide distinct functions for A and B, and reserve the variadic for C.
Cheers,
Kent.
Quoted 128 lines · Kent Gibson
Quoted 39 lines · Bartosz Golaszewski
Hi Kent!
Thanks a lot for looking at this.
Quoted 26 lines · Kent Gibson
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenanceQuoted 7 lines
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
Quoted 9 lines
Just to clarify why I did certain things the way I did: there are certain semi-standardized guidelines to creating low-level C libraries for linux user-space interfaces. They are gathered in a sample project called libabc[1][2][3]. Most plumbing-layer libraries follow these guidelines more or less rigorously. Many low-level programmers will make certain assumptions based on their previous experiences when working with libraries and it's good to be as little confusing as possible.
Fair enough, though I don't see anything in libabc that conflicts with my suggestions, nor that require some of your design choices.
Quoted 11 lines
Quoted 10 lines
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
Quoted 9 lines
Interesting because in my mind reference counting actually simplifies the life-time of objects - everytime someone (the caller or another object) stores the address of the object, the reference count is increased.
Reference counting is a de-facto standard in C libraries. Look at libkmod, libudev, libpulse, all the systemd libraries, the whole of GLib.
I don't doubt that reference counting is out there, I question whether it is necessary here.
In my mind reference counting is a tool to be used when you need to share objects and it isn't clear who is responsible for freeing them. I don't see any need for sharing here at all - for all objects (excluding the
gpiod_line_attrthat I would remove) it is pretty clear who is responsible for them at all times.Quoted 7 lines
Reference counting makes higher-level programming easier. An object lives as long as there's at least one user. In C++ bindings the objects were refcounted using
shared_ptrwhich causes some issues. Now with refcounting implemented at the C library level, we'll be able to use the PImpl pattern withunique_ptrand still keep the objects copyable.That still sounds to me like you are sharing objects that shouldn't be shared. Or copied.
Quoted 5 lines
To summarize: I don't see many disadvantages to using reference counting other than the fact that my documentation is not yet very detailed and lacks some general information about how reference counting works in libgpiod and needs some clarification.
I understand your argument - which is exactly what I had presumed. But I still find the idea of having
_unref()acting as the universal free function to be distasteful.Quoted 6 lines
Quoted 5 lines
e.g.
gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?Quoted 8 lines
Yes, it becomes shared. Its reference count is now 2. If the user modifies it, the config will use a modified value at the time of the request. To give you a real-life example of such behavior: in GLib where all GObjects are reference counted, if you pass a reference to a GFile to another user, then set its (GFile's) attribute, they'll be changed for the user sharing the object too. Same with how Python or Java handle references, except you don't need to manage them yourself.
This is all mute if you drop
gpiod_line_attr, but I still don't see why sharing is preferable in this case. It feels like the worst of both worlds - I need to alloc an attr for every add, and I need to unref them as well.Quoted 3 lines
Quoted 2 lines
Similarly
gpiod_line_get_consumer()- who owns the returned pointer and what is it's lifetime?
Quoted 9 lines
Quoted 5 lines
Since simple strings can't be refcounted and this function returns a pointer to a constant string, the life-time of the string is obviously tied to that of the
line_infoobject. The doc should probably say:
Returns a pointer to the string stored in theline_infoobject.I would dispute the "obviously", particularly since you seem to expect everything else to be unref()ed.
No, the ref/unref mechanism is customary for opaque structures. Const string pointers are always stored in some other object because passing const char * to free will result in a warning. In libc all functions that return a malloc()'ed string return char *.
Quoted 150 lines
Quoted 9 lines
Quoted 8 lines
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. Sogpiod_chipwould have open()/close(),gpiod_request_handlewould have request()/release(), and the others would all be new()/free()d.Quoted 4 lines
This makes you use a different set of resource management functions depending on the object. Additionally some objects can't be created - only retrieved from other objects.
Yup, different objects have different lifecycles - even your way.
Quoted 4 lines
Having a simple ref/unref pair for all opaque data types looks more elegant to me. Another real-life example from yesterday: I'm working on a small library to go with the new gpio-sim module (meant as a replacement for libgpio-mockup) and when I tried to use libmount (to
Quoted 9 lines
verify if configfs is mounted and where) I was super confused by its resource management which is similar to what you suggest but also some resources need to be freed and some transfer their ownership to other objects (without reference counting) and while it's all documented and you can find info on that eventually, I still spent time debugging strange double-free and other corruptions before I got things right. I find libudev and libkmod with their consistent reference counting much more instinctive to use.
I find dealing with repeated frees preferable to dealing with issues related to unexpected side-effects when ownership is unclear.
Quoted 29 lines
Quoted 6 lines
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop thegpiod_line_attr, and instead provide accessors andQuoted 9 lines
mutators on the
gpiod_line_configfor each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.I had exactly this in mind initially but couldn't find an elegant interface.
There are two options I see:
gpiod_line_config_set_drive(cfg, drive);gpiod_line_config_set_drive_index(cfg, drive, index);or:
gpiod_line_config_set_drive(cfg, drive); unsigned int indices[] = { 0, 3, 4, 6 };gpiod_line_config_set_drive_index(cfg, drive, indices);Quoted 6 lines
The former would require a separate function call for each line, the former needs a lot of boilerplate code because we'll usually have to alloc & fill the indices array. Eventually I decided to go with attributes but if you have some ideas/suggestions for that, they're welcome!
I generally avoid variadic functions, but this might be an application where they make sense. i.e. make your indices variadic. Oh, and make them offsets ;-).
Quoted 11 lines
Quoted 4 lines
Not sure I like merging the direction and edge into the
request_type. I would tend to keep those separate, withset_directionandset_edge_detectionfunctions, with the latter forcing input direction.If there's no way we can use output with edge detection, why even bother with allowing the user to try to set output mode for
edge_detectionor vice-versa? It's just more error checking for no benefit, right? The user will still find out that the line is in input mode with theline_info.You are adding another concept for the user to grok - the
request_type. They will need to understand direction and edge detection anyway, why add a new concept to the mix?Oh, and wrt error checking, in my Go library, and as I suggest above, setting edge detection overrides any previous direction setting and forces input. Similarly setting output direction cancels any edge detection. So the config presented to the kernel will always be consistent and never trigger an EINVAL. And that is all documented in the corresponding config functions.
Similarly the drive settings.
The library policy is last-in-wins, which it can be as there are distinct calls for each attribute, whereas at the uAPI they are merged into flags.
Quoted 10 lines
Quoted 4 lines
I would rename
gpiod_request_configtogpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion withgpiod_line_config.Not sure about this one. With the current naming, it's being made clear that we have two separate things to configure, the line(s) and the request itself. Naming both "
_config" makes a clear distinction.
Also: the request config can be reused too for separate requests.I meant one-off wrt a single request. i.e. changing the options after the lines have been requested can never impact the request, whereas a changed config can be applied with the
set_config().Quoted 8 lines
Quoted 7 lines
gpiod_line_maskshould highlight that the bits correspond to lines on the request, in the order provided togpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps thegpiod_request_configor thegpiod_request_handleshould provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then thegpiod_line_maskcan be opaque as well.Quoted 9 lines
Yes, this is one of those things I struggled with. I wasn't sure which one's better because if the user wants to request 64 lines, then set a separate config for 20 of them, it's a lot of function calls if we allow to set line config by offset of a single line, or we get a complicated API with allowing arrays of offsets.
Agreed for the line map functions, it's probably the most confusing element of this new API. I'll come up with something.
Ideally I would like to avoid the
gpiod_line_masktotally, and always deal in chip offsets.The API should be simplest for the most common use cases. Those far corner cases can be a pain to use, but must still be possible. I would put the priority on handling the most common cases:
A. all lines
B. one line
C. a subset of linesI would expect A to be the most common by far - that was all that the previous API supported, then B and then C.
I had suggested providing A and C, with B being a special case of C. But I could live with C being implemented as multiple calls to B.
Quoted 7 lines
A variadic function could manage all three, with no offsets meaning all lines? Though in practice I would probably provide distinct functions for A and B, and reserve the variadic for C.
Cheers,
Kent.
Thank you for your insight and suggestions. You are right about how the config should be handled and the example with priorities is spot-on. I'm still not sure about the naming for config structures but that's a minor detail.
I was on the fence wrt reference counting but then realized that in C++ or Python we still need to provide a mechanism for unconditional closing of chips and releasing of requests. For the former it's because otherwise we'd need to make the object go out of scope manually (probably by storing it in another object that would be "closed" -> pointless abstraction) and in the latter case: Python doesn't even guarantee that the destructor will be called at any specific point.
So it seems that it is the right way to go after all and these objects simply will not be shared. In C++ this will be addressed by providing move constructors and operators, in Python reference counting is natural so there's no problem. Same for GLib bindings I want to implement before providing the dbus API.
You haven't commented on the line & watch events. I would love to hear your opinion on that too.
For v2 I intend to apply the renaming of chip accessors to master and then squash all patches adding the new API into one because splitting them doesn't make the reviewing any easier. Except maybe for the line watch patch which is logically separate.
Best regards,
Bartosz Golaszewski
Quoted 298 lines · Bartosz Golaszewski
Quoted 128 lines · Kent Gibson
Quoted 39 lines · Bartosz Golaszewski
Hi Kent!
Thanks a lot for looking at this.
Quoted 26 lines · Kent Gibson
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenanceQuoted 7 lines
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
Quoted 9 lines
Just to clarify why I did certain things the way I did: there are certain semi-standardized guidelines to creating low-level C libraries for linux user-space interfaces. They are gathered in a sample project called libabc[1][2][3]. Most plumbing-layer libraries follow these guidelines more or less rigorously. Many low-level programmers will make certain assumptions based on their previous experiences when working with libraries and it's good to be as little confusing as possible.
Fair enough, though I don't see anything in libabc that conflicts with my suggestions, nor that require some of your design choices.
Quoted 11 lines
Quoted 10 lines
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
Quoted 9 lines
Interesting because in my mind reference counting actually simplifies the life-time of objects - everytime someone (the caller or another object) stores the address of the object, the reference count is increased.
Reference counting is a de-facto standard in C libraries. Look at libkmod, libudev, libpulse, all the systemd libraries, the whole of GLib.
I don't doubt that reference counting is out there, I question whether it is necessary here.
In my mind reference counting is a tool to be used when you need to share objects and it isn't clear who is responsible for freeing them. I don't see any need for sharing here at all - for all objects (excluding the
gpiod_line_attrthat I would remove) it is pretty clear who is responsible for them at all times.Quoted 7 lines
Reference counting makes higher-level programming easier. An object lives as long as there's at least one user. In C++ bindings the objects were refcounted using
shared_ptrwhich causes some issues. Now with refcounting implemented at the C library level, we'll be able to use the PImpl pattern withunique_ptrand still keep the objects copyable.That still sounds to me like you are sharing objects that shouldn't be shared. Or copied.
Quoted 5 lines
To summarize: I don't see many disadvantages to using reference counting other than the fact that my documentation is not yet very detailed and lacks some general information about how reference counting works in libgpiod and needs some clarification.
I understand your argument - which is exactly what I had presumed. But I still find the idea of having
_unref()acting as the universal free function to be distasteful.Quoted 6 lines
Quoted 5 lines
e.g.
gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?Quoted 8 lines
Yes, it becomes shared. Its reference count is now 2. If the user modifies it, the config will use a modified value at the time of the request. To give you a real-life example of such behavior: in GLib where all GObjects are reference counted, if you pass a reference to a GFile to another user, then set its (GFile's) attribute, they'll be changed for the user sharing the object too. Same with how Python or Java handle references, except you don't need to manage them yourself.
This is all mute if you drop
gpiod_line_attr, but I still don't see why sharing is preferable in this case. It feels like the worst of both worlds - I need to alloc an attr for every add, and I need to unref them as well.Quoted 3 lines
Quoted 2 lines
Similarly
gpiod_line_get_consumer()- who owns the returned pointer and what is it's lifetime?Quoted 9 lines
Quoted 5 lines
Since simple strings can't be refcounted and this function returns a pointer to a constant string, the life-time of the string is obviously tied to that of the
line_infoobject. The doc should probably say:
Returns a pointer to the string stored in theline_infoobject.I would dispute the "obviously", particularly since you seem to expect everything else to be unref()ed.
No, the ref/unref mechanism is customary for opaque structures. Const string pointers are always stored in some other object because passing const char * to free will result in a warning. In libc all functions that return a malloc()'ed string return char *.
Quoted 154 lines
Quoted 9 lines
Quoted 8 lines
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. Sogpiod_chipwould have open()/close(),gpiod_request_handlewould have request()/release(), and the others would all be new()/free()d.Quoted 4 lines
This makes you use a different set of resource management functions depending on the object. Additionally some objects can't be created - only retrieved from other objects.
Yup, different objects have different lifecycles - even your way.
Quoted 4 lines
Having a simple ref/unref pair for all opaque data types looks more elegant to me. Another real-life example from yesterday: I'm working on a small library to go with the new gpio-sim module (meant as a replacement for libgpio-mockup) and when I tried to use libmount (to
Quoted 9 lines
verify if configfs is mounted and where) I was super confused by its resource management which is similar to what you suggest but also some resources need to be freed and some transfer their ownership to other objects (without reference counting) and while it's all documented and you can find info on that eventually, I still spent time debugging strange double-free and other corruptions before I got things right. I find libudev and libkmod with their consistent reference counting much more instinctive to use.
I find dealing with repeated frees preferable to dealing with issues related to unexpected side-effects when ownership is unclear.
Quoted 29 lines
Quoted 6 lines
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop thegpiod_line_attr, and instead provide accessors andQuoted 9 lines
mutators on the
gpiod_line_configfor each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.I had exactly this in mind initially but couldn't find an elegant interface.
There are two options I see:
gpiod_line_config_set_drive(cfg, drive);gpiod_line_config_set_drive_index(cfg, drive, index);or:
gpiod_line_config_set_drive(cfg, drive); unsigned int indices[] = { 0, 3, 4, 6 };gpiod_line_config_set_drive_index(cfg, drive, indices);Quoted 6 lines
The former would require a separate function call for each line, the former needs a lot of boilerplate code because we'll usually have to alloc & fill the indices array. Eventually I decided to go with attributes but if you have some ideas/suggestions for that, they're welcome!
I generally avoid variadic functions, but this might be an application where they make sense. i.e. make your indices variadic. Oh, and make them offsets ;-).
Quoted 11 lines
Quoted 4 lines
Not sure I like merging the direction and edge into the
request_type. I would tend to keep those separate, withset_directionandset_edge_detectionfunctions, with the latter forcing input direction.If there's no way we can use output with edge detection, why even bother with allowing the user to try to set output mode for
edge_detectionor vice-versa? It's just more error checking for no benefit, right? The user will still find out that the line is in input mode with theline_info.You are adding another concept for the user to grok - the
request_type. They will need to understand direction and edge detection anyway, why add a new concept to the mix?Oh, and wrt error checking, in my Go library, and as I suggest above, setting edge detection overrides any previous direction setting and forces input. Similarly setting output direction cancels any edge detection. So the config presented to the kernel will always be consistent and never trigger an EINVAL. And that is all documented in the corresponding config functions.
Similarly the drive settings.
The library policy is last-in-wins, which it can be as there are distinct calls for each attribute, whereas at the uAPI they are merged into flags.
Quoted 10 lines
Quoted 4 lines
I would rename
gpiod_request_configtogpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion withgpiod_line_config.Not sure about this one. With the current naming, it's being made clear that we have two separate things to configure, the line(s) and the request itself. Naming both "
_config" makes a clear distinction.
Also: the request config can be reused too for separate requests.I meant one-off wrt a single request. i.e. changing the options after the lines have been requested can never impact the request, whereas a changed config can be applied with the
set_config().Quoted 8 lines
Quoted 7 lines
gpiod_line_maskshould highlight that the bits correspond to lines on the request, in the order provided togpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps thegpiod_request_configor thegpiod_request_handleshould provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then thegpiod_line_maskcan be opaque as well.Quoted 9 lines
Yes, this is one of those things I struggled with. I wasn't sure which one's better because if the user wants to request 64 lines, then set a separate config for 20 of them, it's a lot of function calls if we allow to set line config by offset of a single line, or we get a complicated API with allowing arrays of offsets.
Agreed for the line map functions, it's probably the most confusing element of this new API. I'll come up with something.
Ideally I would like to avoid the
gpiod_line_masktotally, and always deal in chip offsets.The API should be simplest for the most common use cases. Those far corner cases can be a pain to use, but must still be possible. I would put the priority on handling the most common cases:
A. all lines
B. one line
C. a subset of linesI would expect A to be the most common by far - that was all that the previous API supported, then B and then C.
I had suggested providing A and C, with B being a special case of C. But I could live with C being implemented as multiple calls to B.A variadic function could manage all three, with no offsets meaning all lines? Though in practice I would probably provide distinct functions for A and B, and reserve the variadic for C.
Quoted 9 lines
Quoted 3 lines
Cheers,
Kent.Thank you for your insight and suggestions. You are right about how the config should be handled and the example with priorities is spot-on. I'm still not sure about the naming for config structures but that's a minor detail.
I forgot to add that wrt the config mutators, you need to allow overriding of existing config, rather than returning an error on conflict, so that you can change config for the set_config ioctl(). Hence the last-in-wins approach. And as a consequence the mutator is always right and so needs no return code.
And you might want to add a copy() for config to allow the user to easily create two slightly different configurations.
Quoted 9 lines
I was on the fence wrt reference counting but then realized that in C++ or Python we still need to provide a mechanism for unconditional closing of chips and releasing of requests. For the former it's because otherwise we'd need to make the object go out of scope manually (probably by storing it in another object that would be "closed" -> pointless abstraction) and in the latter case: Python doesn't even guarantee that the destructor will be called at any specific point.
Hmmm, ok, I was assuming the C++ bindings would wrap the C objects in C++ objects, and the C++ destructor would release any associated resources.
For Python I would probably go with an explicit close() or equivalent. My Go library has to use that approach as there are no destructors in Go.
Quoted 9 lines
So it seems that it is the right way to go after all and these objects simply will not be shared. In C++ this will be addressed by providing move constructors and operators, in Python reference counting is natural so there's no problem. Same for GLib bindings I want to implement before providing the dbus API.
You haven't commented on the line & watch events. I would love to hear your opinion on that too.
Didn't have any major problems with them on the first pass - nothing worth commenting on anyway.
I presume that the info events don't get a buffer as they are expected to be low rate.
A zero timeout in the wait() will not block, and just return the event availability?
Perhaps the wait() and read() should be strictly orthogonal, i.e. the read() should never block (blocking functions are bad, as per libabc). At least the wait() will eventually timeout (assuming a zero timeout doesn't block forever).
Or the two could be combined?
Oh, and in the @return for gpiod_line_event_buffer_copy_event(), "decreases" should be "decreased".
Quoted 5 lines
For v2 I intend to apply the renaming of chip accessors to master and then squash all patches adding the new API into one because splitting them doesn't make the reviewing any easier. Except maybe for the line watch patch which is logically separate.
Fair enough. In this case I applied all the patches and looked at the resulting gpiod.h, as I wasn't terribly interested in the changes - only the final result.
Cheers,
Kent.
Quoted 2 lines
Best regards,
Bartosz Golaszewski
Quoted 310 lines · Kent Gibson
Quoted 298 lines · Bartosz Golaszewski
Quoted 128 lines · Kent Gibson
Quoted 39 lines · Bartosz Golaszewski
Hi Kent!
Thanks a lot for looking at this.
Quoted 26 lines · Kent Gibson
Quoted 24 lines · Bartosz Golaszewski
This series introduces an entirely reworked API for the core C part of libgpiod. It's not fully functional as the bindings are not modified, and starting from patch 5, even the tests stop working. This is on purpose as I'd like to reach an agreement on the interface before spending time on reworking the tests.
My plan for the development of v2.0 is to keep the changes in a separate branch until all bits & pieces are complete and then rearrange them into a bisectable series that will be merged into the master branch.
A couple points regarding the design of the new API:
- all objects have become opaque and can only be accessed using dedicated functions
- line objects as well as bulk containers have been removed
- line requests are now configured using three types of structures: attributes, line config and request config structures, which follows the kernel API
- line request handles have now a lifetime separate from the parent chips to leverage the separation of chip and request file descriptors
- line events are now opaque but they can be stored in a dedicated container so that memory allocations are not necessary everytime an event is read from the kernel
- the library code has been split into several compilation units for easier maintenanceQuoted 7 lines
Quoted 6 lines
The new API is completely documented in
include/gpiod.hdoxygen comments.Please let me know what you think. I am aware that these patches are huge and difficult to review but I'm really only expecting a general API review - all other implementation details can be improved later.
Quoted 9 lines
Just to clarify why I did certain things the way I did: there are certain semi-standardized guidelines to creating low-level C libraries for linux user-space interfaces. They are gathered in a sample project called libabc[1][2][3]. Most plumbing-layer libraries follow these guidelines more or less rigorously. Many low-level programmers will make certain assumptions based on their previous experiences when working with libraries and it's good to be as little confusing as possible.
Fair enough, though I don't see anything in libabc that conflicts with my suggestions, nor that require some of your design choices.
Quoted 11 lines
Quoted 10 lines
In that vein, I'll lump my comments here, rather than scattering them throughout the patches...
Overall it feels much tighter and clearer than the old API, though that could just be personal bias, as it is also closer to the new uAPI.
I find the ownership and lifetime of objects confusing. I presume you want to use the reference counting to simplify the object lifecycle, but that just formalises the possibility that objects are shared - further confusing the ownership issue.
Quoted 9 lines
Interesting because in my mind reference counting actually simplifies the life-time of objects - everytime someone (the caller or another object) stores the address of the object, the reference count is increased.
Reference counting is a de-facto standard in C libraries. Look at libkmod, libudev, libpulse, all the systemd libraries, the whole of GLib.
I don't doubt that reference counting is out there, I question whether it is necessary here.
In my mind reference counting is a tool to be used when you need to share objects and it isn't clear who is responsible for freeing them. I don't see any need for sharing here at all - for all objects (excluding the
gpiod_line_attrthat I would remove) it is pretty clear who is responsible for them at all times.Quoted 7 lines
Reference counting makes higher-level programming easier. An object lives as long as there's at least one user. In C++ bindings the objects were refcounted using
shared_ptrwhich causes some issues. Now with refcounting implemented at the C library level, we'll be able to use the PImpl pattern withunique_ptrand still keep the objects copyable.That still sounds to me like you are sharing objects that shouldn't be shared. Or copied.
Quoted 5 lines
To summarize: I don't see many disadvantages to using reference counting other than the fact that my documentation is not yet very detailed and lacks some general information about how reference counting works in libgpiod and needs some clarification.
I understand your argument - which is exactly what I had presumed. But I still find the idea of having
_unref()acting as the universal free function to be distasteful.Quoted 6 lines
Quoted 5 lines
e.g.
gpiod_line_config_add_attribute()
- who owns the attr after the call? What happens if it is subsequently modified? Is the attr copied or does ownership pass to the config? As written it is neither - the attr becomes shared. How is that preferable?Quoted 8 lines
Yes, it becomes shared. Its reference count is now 2. If the user modifies it, the config will use a modified value at the time of the request. To give you a real-life example of such behavior: in GLib where all GObjects are reference counted, if you pass a reference to a GFile to another user, then set its (GFile's) attribute, they'll be changed for the user sharing the object too. Same with how Python or Java handle references, except you don't need to manage them yourself.
This is all mute if you drop
gpiod_line_attr, but I still don't see why sharing is preferable in this case. It feels like the worst of both worlds - I need to alloc an attr for every add, and I need to unref them as well.Quoted 3 lines
Quoted 2 lines
Similarly
gpiod_line_get_consumer()- who owns the returned pointer and what is it's lifetime?Quoted 9 lines
Quoted 5 lines
Since simple strings can't be refcounted and this function returns a pointer to a constant string, the life-time of the string is obviously tied to that of the
line_infoobject. The doc should probably say:
Returns a pointer to the string stored in theline_infoobject.I would dispute the "obviously", particularly since you seem to expect everything else to be unref()ed.
No, the ref/unref mechanism is customary for opaque structures. Const string pointers are always stored in some other object because passing const char * to free will result in a warning. In libc all functions that return a malloc()'ed string return char *.
Quoted 154 lines
Quoted 9 lines
Quoted 8 lines
I would prefer the opaque objects to be able to be free()d normally, and for any calls that involve a change of ownership to explicitly document that fact.
For objects that require additional setup/cleanup, try to make use of open()/close() or request()/release() function name pairings. Sogpiod_chipwould have open()/close(),gpiod_request_handlewould have request()/release(), and the others would all be new()/free()d.Quoted 4 lines
This makes you use a different set of resource management functions depending on the object. Additionally some objects can't be created - only retrieved from other objects.
Yup, different objects have different lifecycles - even your way.
Quoted 4 lines
Having a simple ref/unref pair for all opaque data types looks more elegant to me. Another real-life example from yesterday: I'm working on a small library to go with the new gpio-sim module (meant as a replacement for libgpio-mockup) and when I tried to use libmount (to
Quoted 9 lines
verify if configfs is mounted and where) I was super confused by its resource management which is similar to what you suggest but also some resources need to be freed and some transfer their ownership to other objects (without reference counting) and while it's all documented and you can find info on that eventually, I still spent time debugging strange double-free and other corruptions before I got things right. I find libudev and libkmod with their consistent reference counting much more instinctive to use.
I find dealing with repeated frees preferable to dealing with issues related to unexpected side-effects when ownership is unclear.
Quoted 29 lines
Quoted 6 lines
Conceptually the config for each line can be considered to be independent
- the uAPI encoding using attributes and masks is only there to keep the uAPI structs to a manageable size.
At this level you can model it as config per line, and only map between the uAPI structures when calling the ioctl()s.
So I would drop thegpiod_line_attr, and instead provide accessors andQuoted 9 lines
mutators on the
gpiod_line_configfor each attr type.
That removes the whole lifecycle issue for attributes, and allows you to provide a simpler abstraction of the config than that provided in the uAPI.
For the mutators there can be two flavours, one that sets the config for the whole set, and another that accepts a subset of applicable lines. Accessors would provide the config attr for a particular line. Both accessor and mutator would use chip offsets to identify the lines.I had exactly this in mind initially but couldn't find an elegant interface.
There are two options I see:
gpiod_line_config_set_drive(cfg, drive);gpiod_line_config_set_drive_index(cfg, drive, index);or:
gpiod_line_config_set_drive(cfg, drive); unsigned int indices[] = { 0, 3, 4, 6 };gpiod_line_config_set_drive_index(cfg, drive, indices);Quoted 6 lines
The former would require a separate function call for each line, the former needs a lot of boilerplate code because we'll usually have to alloc & fill the indices array. Eventually I decided to go with attributes but if you have some ideas/suggestions for that, they're welcome!
I generally avoid variadic functions, but this might be an application where they make sense. i.e. make your indices variadic. Oh, and make them offsets ;-).
Quoted 11 lines
Quoted 4 lines
Not sure I like merging the direction and edge into the
request_type. I would tend to keep those separate, withset_directionandset_edge_detectionfunctions, with the latter forcing input direction.If there's no way we can use output with edge detection, why even bother with allowing the user to try to set output mode for
edge_detectionor vice-versa? It's just more error checking for no benefit, right? The user will still find out that the line is in input mode with theline_info.You are adding another concept for the user to grok - the
request_type. They will need to understand direction and edge detection anyway, why add a new concept to the mix?Oh, and wrt error checking, in my Go library, and as I suggest above, setting edge detection overrides any previous direction setting and forces input. Similarly setting output direction cancels any edge detection. So the config presented to the kernel will always be consistent and never trigger an EINVAL. And that is all documented in the corresponding config functions.
Similarly the drive settings.
The library policy is last-in-wins, which it can be as there are distinct calls for each attribute, whereas at the uAPI they are merged into flags.
Quoted 10 lines
Quoted 4 lines
I would rename
gpiod_request_configtogpiod_request_options. Config is long lived and can be modified, whereas options are one-off. And it would reduce any chance of confusion withgpiod_line_config.Not sure about this one. With the current naming, it's being made clear that we have two separate things to configure, the line(s) and the request itself. Naming both "
_config" makes a clear distinction.
Also: the request config can be reused too for separate requests.I meant one-off wrt a single request. i.e. changing the options after the lines have been requested can never impact the request, whereas a changed config can be applied with the
set_config().Quoted 8 lines
Quoted 7 lines
gpiod_line_maskshould highlight that the bits correspond to lines on the request, in the order provided togpiod_request_config_set_offsets(), not line offsets on the chip. Perhaps thegpiod_request_configor thegpiod_request_handleshould provide the mask functions for a given a qchip offset, rather than require the user to track the mapping? Then thegpiod_line_maskcan be opaque as well.Quoted 9 lines
Yes, this is one of those things I struggled with. I wasn't sure which one's better because if the user wants to request 64 lines, then set a separate config for 20 of them, it's a lot of function calls if we allow to set line config by offset of a single line, or we get a complicated API with allowing arrays of offsets.
Agreed for the line map functions, it's probably the most confusing element of this new API. I'll come up with something.
Ideally I would like to avoid the
gpiod_line_masktotally, and always deal in chip offsets.The API should be simplest for the most common use cases. Those far corner cases can be a pain to use, but must still be possible. I would put the priority on handling the most common cases:
A. all lines
B. one line
C. a subset of linesI would expect A to be the most common by far - that was all that the previous API supported, then B and then C.
I had suggested providing A and C, with B being a special case of C. But I could live with C being implemented as multiple calls to B.A variadic function could manage all three, with no offsets meaning all lines? Though in practice I would probably provide distinct functions for A and B, and reserve the variadic for C.
Quoted 9 lines
Quoted 3 lines
Cheers,
Kent.Thank you for your insight and suggestions. You are right about how the config should be handled and the example with priorities is spot-on. I'm still not sure about the naming for config structures but that's a minor detail.
Quoted 6 lines
I forgot to add that wrt the config mutators, you need to allow overriding of existing config, rather than returning an error on conflict, so that you can change config for the
set_configioctl(). Hence the last-in-wins approach. And as a consequence the mutator is always right and so needs no return code.
This sounds good in theory but how do we handle a situation that requires more than 10 attributes? Override the first one? The last one? What if the line offsets passed to the request config repeat themselves? I think some sanitization of input is in order.
Regarding offsets: I was thinking about how to approach referring to lines in configs and requests by offsets only (in order to hide the whole masking logic) and while for a request (for example: when setting/reading line) this is straightforward (as long as we make sure the offsets are never duplicated), the line config structure doesn't really know the concept of offsets. So when we set a config option for a specific line, we need to carry the offset information somehow in the structure until the request is actually made. How do you deal with this in your library? Did you expose any of the bitmap details in your API? Can we really avoid dealing with indexing of lines in a request?
Quoted 13 lines
And you might want to add a
copy()for config to allow the user to easily create two slightly different configurations.Quoted 9 lines
I was on the fence wrt reference counting but then realized that in C++ or Python we still need to provide a mechanism for unconditional closing of chips and releasing of requests. For the former it's because otherwise we'd need to make the object go out of scope manually (probably by storing it in another object that would be "closed" -> pointless abstraction) and in the latter case: Python doesn't even guarantee that the destructor will be called at any specific point.
Quoted 3 lines
Hmmm, ok, I was assuming the C++ bindings would wrap the C objects in C++ objects, and the C++ destructor would release any associated resources.
Yes, but what if the user wants to close the chip or release the request without the underlying object going out of scope? I think we need to keep that possibility.
Quoted 13 lines
For Python I would probably go with an explicit
close()or equivalent. My Go library has to use that approach as there are no destructors in Go.Quoted 9 lines
So it seems that it is the right way to go after all and these objects simply will not be shared. In C++ this will be addressed by providing move constructors and operators, in Python reference counting is natural so there's no problem. Same for GLib bindings I want to implement before providing the dbus API.
You haven't commented on the line & watch events. I would love to hear your opinion on that too.
Quoted 6 lines
Didn't have any major problems with them on the first pass - nothing worth commenting on anyway.
I presume that the info events don't get a buffer as they are expected to be low rate.
Indeed.
Quoted 3 lines
A zero timeout in the
wait()will not block, and just return the event availability?
Yes.
Quoted 6 lines
Perhaps the
wait()andread()should be strictly orthogonal, i.e. theread()should never block (blocking functions are bad, as per libabc). At least thewait()will eventually timeout (assuming a zero timeout doesn't block forever).
Or the two could be combined?
Good point, but I'd prefer to keep that logic separate. I've never seen a combined poll()/read() in any lib. I will see about that non-blocking read() though.
Bart
Quoted 18 lines
Oh, and in the @return for
gpiod_line_event_buffer_copy_event(), "decreases" should be "decreased".Quoted 5 lines
For v2 I intend to apply the renaming of chip accessors to master and then squash all patches adding the new API into one because splitting them doesn't make the reviewing any easier. Except maybe for the line watch patch which is logically separate.
Fair enough. In this case I applied all the patches and looked at the resulting
gpiod.h, as I wasn't terribly interested in the changes - only the final result.Cheers,
Kent.Quoted 2 lines
Best regards,
Bartosz Golaszewski
Quoted 2 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip!]
Quoted 8 lines
Quoted 7 lines
I forgot to add that wrt the config mutators, you need to allow overriding of existing config, rather than returning an error on conflict, so that you can change config for the
set_configioctl(). Hence the last-in-wins approach. And as a consequence the mutator is always right and so needs no return code.
Quoted 5 lines
This sounds good in theory but how do we handle a situation that requires more than 10 attributes? Override the first one? The last one? What if the line offsets passed to the request config repeat themselves? I think some sanitization of input is in order.
Repeating of lines is equivalent to repeatedly setting a bit, so the subsequent instances are ignored. In practice I don't even need to check
- if the user includes the line multiple times then it gets set multiple times - to the same thing.
The case where a complex config can't be mapped to the uAPI, e.g. due to too many attributes on too many lines, is handled at the time of the request_lines() or set_config() itself when that mapping is performed. Those will return an "overly complex config" error.
Quoted 11 lines
Regarding offsets: I was thinking about how to approach referring to lines in configs and requests by offsets only (in order to hide the whole masking logic) and while for a request (for example: when setting/reading line) this is straightforward (as long as we make sure the offsets are never duplicated), the line config structure doesn't really know the concept of offsets. So when we set a config option for a specific line, we need to carry the offset information somehow in the structure until the request is actually made. How do you deal with this in your library? Did you expose any of the bitmap details in your API? Can we really avoid dealing with indexing of lines in a request?
In the request config I use a map of offset to line config to avoid duplication. A config change that alters any existing setting just overwrites the old.
The line config is similar to your struct gpiod_line_config. The line config for a particular line is only created and added to the map if there is a config change specific to that line.
Each attribute has a "not set" value, in which case the request-wide default is used.
The request-wide default config is stored separately from the map. And there is a function to reset a line config back to the default, i.e. drop that line config from the map.
The request_lines() and set_config(), that accept the config, also have the list of offsets available (provided to the request_lines() and subsequently stored as part of the request struct for the set_config()) and so can map from offsets to indices to build the bitmap. The bitmap and indices themselves are never exposed.
That is a high level description - the details are actually a little different as the Go implementation uses functional options, so the initial config settings become parameters to the request, and bundles the config into the request object itself.
Quoted 13 lines
Quoted 13 lines
And you might want to add a
copy()for config to allow the user to easily create two slightly different configurations.Quoted 9 lines
I was on the fence wrt reference counting but then realized that in C++ or Python we still need to provide a mechanism for unconditional closing of chips and releasing of requests. For the former it's because otherwise we'd need to make the object go out of scope manually (probably by storing it in another object that would be "closed" -> pointless abstraction) and in the latter case: Python doesn't even guarantee that the destructor will be called at any specific point.
Quoted 8 lines
Quoted 3 lines
Hmmm, ok, I was assuming the C++ bindings would wrap the C objects in C++ objects, and the C++ destructor would release any associated resources.
Yes, but what if the user wants to close the chip or release the request without the underlying object going out of scope? I think we need to keep that possibility.
Then you also provide a close() method. They aren't mutually exclusive.
Cheers,
Kent.
Quoted 1 line · Kent Gibson
[snip -> long discussion on the libgpiod C API]
Hi Kent,
I was working on the next iteration of the code and I'm struggling with the implementation of some elements without the concept of attributes.
So I initially liked the idea of variadic functions but they won't work for language bindings so that's a no go. On that note: I wanted to get some inspiration from your go library but your elegant API makes use of go features (like interfaces) we don't have in C.
The problem we have is basically about implementing primary and secondary line configuration objects - where the primary contains the default config for all requested lines and the secondary can override certain config options (should zeroed values for enumerated types mean
- don't override?) for certain lines.
The basic line config structure (let's call it struct gpiod_line_config) can be very simple and have the following mutators:
struct gpiod_line_config *cfg = gpiod_line_config_new();
gpiod_line_config_set_direction(cfg, GPIOD_LINE_CONFIG_DIRECTION_OUTPUT); gpiod_line_config_set_active_low(cfg, true);
and so on for for drive, bias, edge, debounce, realtime clock.
Output values would be set like this:
unsigned int values[] = { 0, 1, 1, 0 }, num_lines = 4; gpiod_line_config_set_output_values(cfg, num_lines, values);
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);
Where req_cfg configures request-specific options, and line_cfg contains the above line config. I'm still not convinced that gpiod_request_options is the better name, I think I prefer the juxtaposition of the two names: line_config and request_config.
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
One idea I have is to add a new object called struct gpiod_line_config_ext (for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:
struct gpiod_line_config_ext *ext_cfg = gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };
/* Add the default config for this request. */ gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */ gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);
Does this make sense? I'm worried about the resource management here. Who should be responsible for freeing the config structures? Should the extended config take ownership? Should the user remain responsible? Back to reference counting for these objects? Is this even a good idea?
Please let me know what you think, I could use some advice.
Best Regards,
Bartosz
Quoted 7 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip -> long discussion on the libgpiod C API]
Hi Kent,
Quoted 9 lines
I was working on the next iteration of the code and I'm struggling with the implementation of some elements without the concept of attributes.
So I initially liked the idea of variadic functions but they won't work for language bindings so that's a no go. On that note: I wanted to get some inspiration from your go library but your elegant API makes use of go features (like interfaces) we don't have in C.
It is the functional options that is the big difference between my Go implementation and what I would do in C. I happen to use interfaces to implement those options. You could do something similar in C (cos what can't you do in C) but it would be weird, so lets not go there.
You can still provide the variadic forms for C users. And couldn't the language bindings use the "v" variant, as libabc suggests?:
"Be careful with variadic functions
- It's great if you provide them, but you must accompany them with "v" variants (i.e. functions taking a va_arg object), and provide non-variadic variants as well. This is important to get language wrappers right."
Quoted 6 lines
The problem we have is basically about implementing primary and secondary line configuration objects - where the primary contains the default config for all requested lines and the secondary can override certain config options (should zeroed values for enumerated types mean
- don't override?) for certain lines.
Yep, use the 0 value to mean "defaulted".
For the secondary that means use the primary value.
For the primary that means use the kernel default, so the primary is initialised with the kernel defaults.
Note that accessors, if provided, generally wouldn't return the 0 value to the user - they follow the secondary -> primary chain and return the effective setting.
Quoted 3 lines
The basic line config structure (let's call it struct
gpiod_line_config) can be very simple and have the following mutators:
This is where you are immediately off into the weeds, so I obviously didn't communicate my suggestion very well...
.
The opaque config object presented to the user is not the simple line config object - it is the container for the whole request config (which is different from the request options - which is exactly why I would like the options not to be called request_config).
The user never sees the simple line config, which is internal, only the request config.
The accessors always work on the request config at attribute level, and there is never a need to apply or return the whole config for a particular line. You could - but it is not necessary for core functionality, so for now don't.
I realise this makes the internal modelling of config much more complicated, but the goal is to provide a simplified interface for the user - so it should be expected that the majority of the complexity will end up in the library rather than user code.
In my Go implementation I merge the request config into the request object itself. You could also do that, though the semantics might be clearer if you keep them separate (more on that later).
Quoted 3 lines
struct
gpiod_line_config*cfg =gpiod_line_config_new();
gpiod_line_config_set_active_low(cfg, true);
I would provide two functions for active level - set_active_high() and set_active_low(). Even if you don't, the function here should be set_active_level(), in case you want to add them later.
Quoted 2 lines
gpiod_line_config_set_direction(cfg, GPIOD_LINE_CONFIG_DIRECTION_OUTPUT);
That is the A case, i.e. the whole request. How would you name the B and C cases?
_set_<attr>_line and _set_<attr>_lines?
or _set_line_<attr> and _set_lines_<attr>?
or something else?
It might be worthwhile providing separate set_input() and set_output() functions - as the output case requires the initial value. You could have the user call set_output_values(), but why force them to make another call?
Quoted 7 lines
and so on for for drive, bias, edge, debounce, realtime clock.
Output values would be set like this:
unsigned int values[] = { 0, 1, 1, 0 },
num_lines= 4;gpiod_line_config_set_output_values(cfg, num_lines, values);
I don't like the implicit identification of lines based on request ordering here. I realise my Go API does that, but that is an option to the request itself, so the requested lines are also present and visible to the casual reader, whereas this is a standalone call.
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named set_output(value) (that is the A case, btw).
Quoted 9 lines
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);Where
req_cfgconfigures request-specific options, andline_cfgcontains the above line config. I'm still not convinced thatgpiod_request_optionsis the better name, I think I prefer the juxtaposition of the two names:line_configandrequest_config.
That's ok - I'm pretty sure you'll get there eventually ;-).
Quoted 3 lines
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
As above, the req_cfg is the composite line config, so
req = gpiod_chip_request_lines(chip, req_options, req_cfg);
Or if you were to merge the request config, and even the options, into the request:
unsigned int lines[] = { 0, 4, 12, 54 }, num_lines = 4;
req = gpiod_line_request_new(num_lines, lines); // also variadic forms?? // call req option and config mutators here... gpiod_line_request_set_active_low(req); gpiod_line_request_set_output(req, 1); gpiod_line_request_set_line_input(req, 12); gpiod_line_request_set_event_buffer_size(req, 42);
...
// then actually request the lines...
err = gpiod_chip_request_lines(chip, req);
which may error for various reasons, such as lines already being requested or overly complex config.
Merging everything into the request means fewer opaque objects and interactions for the user to have to deal with, which is always a good thing.
The downside is that changes to options and config, such as the gpiod_line_request_set_active_low() etc here, are not applied until either the gpiod_chip_request_lines() or the set_config() call, which could be confusing. Though the more I think about it the more I think the resulting simplification of the API wins out. i.e. these objects:
struct gpiod_line_attr;
struct gpiod_line_config;
struct gpiod_request_config;
struct gpiod_request_handle;
all get collapsed into:
struct gpiod_line_request;
which significantly reduces the cognitive load on the user.
The set_config() would probably be called something like:
err = gpiod_line_request_reconfigure(req)
to distinguish it from the mutators which use the _set_ naming. (and it would also align with my Go library ;-)
Quoted 8 lines
One idea I have is to add a new object called struct
gpiod_line_config_ext(for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:struct
gpiod_line_config_ext*ext_cfg=gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };
Quoted 7 lines
/* Add the default config for this request. */
gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);
Please, no _ext objects - that is an admission of failure right there.
Quoted 6 lines
Does this make sense? I'm worried about the resource management here. Who should be responsible for freeing the config structures? Should the extended config take ownership? Should the user remain responsible? Back to reference counting for these objects? Is this even a good idea?
The user is responsible for freeing the request config.
The request config is responsible for freeing the line configs, if there are any - the user isn't even aware of them so they obviously can't.
Similarly if you merge the config into the request.
Quoted 1 line
Please let me know what you think, I could use some advice.
Hopefully I've communicated my meaning a little more clearly this time?
Cheers,
Kent.
Quoted 28 lines · Kent Gibson
Quoted 7 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip -> long discussion on the libgpiod C API]
Hi Kent,
Quoted 9 lines
I was working on the next iteration of the code and I'm struggling with the implementation of some elements without the concept of attributes.
So I initially liked the idea of variadic functions but they won't work for language bindings so that's a no go. On that note: I wanted to get some inspiration from your go library but your elegant API makes use of go features (like interfaces) we don't have in C.
It is the functional options that is the big difference between my Go implementation and what I would do in C. I happen to use interfaces to implement those options. You could do something similar in C (cos what can't you do in C) but it would be weird, so lets not go there.
You can still provide the variadic forms for C users. And couldn't the language bindings use the "v" variant, as libabc suggests?:
Quoted 6 lines
"Be careful with variadic functions
- It's great if you provide them, but you must accompany them with "v" variants (i.e. functions taking ava_argobject), and provide non-variadic variants as well. This is important to get language wrappers right."
The "v" functions do nothing for language bindings - you can't construct the required va_list out of thin air. What you do usually is this (example taken from GLib):
gpointer
g_object_new(GType object_type,
const gchar *first_property_name,
...);
has a non-variadic counterpart:
GObject *
g_object_new_with_properties(GType object_type,
guint n_properties,
const char *names[],
const GValue values[]);I would prefer to simply not do variadic functions. The low-level API should in general be wrapped in high-level languages. Most people that mail me on libgpiod seem to use Python anyway.
Quoted 35 lines
Quoted 6 lines
The problem we have is basically about implementing primary and secondary line configuration objects - where the primary contains the default config for all requested lines and the secondary can override certain config options (should zeroed values for enumerated types mean
- don't override?) for certain lines.Yep, use the 0 value to mean "defaulted".
For the secondary that means use the primary value.
For the primary that means use the kernel default, so the primary is initialised with the kernel defaults.Note that accessors, if provided, generally wouldn't return the 0 value to the user - they follow the secondary -> primary chain and return the effective setting.
Quoted 3 lines
The basic line config structure (let's call it struct
gpiod_line_config) can be very simple and have the following mutators:This is where you are immediately off into the weeds, so I obviously didn't communicate my suggestion very well...
.
The opaque config object presented to the user is not the simple line config object - it is the container for the whole request config (which is different from the request options - which is exactly why I would like the options not to be calledrequest_config).The user never sees the simple line config, which is internal, only the request config.
The accessors always work on the request config at attribute level, and there is never a need to apply or return the whole config for a particular line. You could - but it is not necessary for core functionality, so for now don't.
Quoted 5 lines
I realise this makes the internal modelling of config much more complicated, but the goal is to provide a simplified interface for the user - so it should be expected that the majority of the complexity will end up in the library rather than user code.
Yeah, I understood this alright but I figured that this will bloat the library interface with three variants of mutators per every config option (or more if we provide two functions for direction and active level) more than having simpler config objects and applying them globally or per line.
Quoted 4 lines
In my Go implementation I merge the request config into the request object itself. You could also do that, though the semantics might be clearer if you keep them separate (more on that later).
My goal was to logically split the config into elements that can be reconfigured and those that cannot. More on that later.
Quoted 11 lines
Quoted 3 lines
struct
gpiod_line_config*cfg =gpiod_line_config_new();
gpiod_line_config_set_active_low(cfg, true);I would provide two functions for active level -
set_active_high()andset_active_low(). Even if you don't, the function here should beset_active_level(), in case you want to add them later.Quoted 2 lines
gpiod_line_config_set_direction(cfg, GPIOD_LINE_CONFIG_DIRECTION_OUTPUT);
Quoted 9 lines
That is the A case, i.e. the whole request. How would you name the B and C cases?
_set_<attr>_line and _set_<attr>_lines?
or _set_line_<attr> and _set_lines_<attr>?
or something else?
These are what I had in mind and also: _offset and _offsets.
Quoted 18 lines
It might be worthwhile providing separate
set_input()andset_output()functions - as the output case requires the initial value. You could have the user callset_output_values(), but why force them to make another call?Quoted 7 lines
and so on for for drive, bias, edge, debounce, realtime clock.
Output values would be set like this:
unsigned int values[] = { 0, 1, 1, 0 },
num_lines= 4;gpiod_line_config_set_output_values(cfg, num_lines, values);I don't like the implicit identification of lines based on request ordering here. I realise my Go API does that, but that is an option to the request itself, so the requested lines are also present and visible to the casual reader, whereas this is a standalone call.
Quoted 6 lines
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named
set_output(value)(that is the A case, btw).
I can imagine the B case like:
gpiod_line_config_set_output_value(config, offset, value);
But how would exactly the call for the A case look like? Two arrays with offset -> value mapping?
unsigned int offsets[] = { 0, 2, 5 }, values[] = { 0, 1 ,1 }; gpiod_line_config_set_output_values_offsets(config, 3, offsets, values);
?
Quoted 53 lines
Quoted 9 lines
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);Where
req_cfgconfigures request-specific options, andline_cfgcontains the above line config. I'm still not convinced thatgpiod_request_optionsis the better name, I think I prefer the juxtaposition of the two names:line_configandrequest_config.That's ok - I'm pretty sure you'll get there eventually ;-).
Quoted 3 lines
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
As above, the
req_cfgis the composite line config, soreq =
gpiod_chip_request_lines(chip, req_options, req_cfg);Or if you were to merge the request config, and even the options, into the request:
unsigned int lines[] = { 0, 4, 12, 54 },
num_lines= 4;
req =gpiod_line_request_new(num_lines, lines); // also variadic forms?? // call req option and config mutators here...gpiod_line_request_set_active_low(req);gpiod_line_request_set_output(req, 1);gpiod_line_request_set_line_input(req, 12);gpiod_line_request_set_event_buffer_size(req, 42);
...
// then actually request the lines...
err =gpiod_chip_request_lines(chip, req);which may error for various reasons, such as lines already being requested or overly complex config.
Merging everything into the request means fewer opaque objects and interactions for the user to have to deal with, which is always a good thing.
The downside is that changes to options and config, such as thegpiod_line_request_set_active_low()etc here, are not applied until either thegpiod_chip_request_lines()or theset_config()call, which could be confusing. Though the more I think about it the more I think the resulting simplification of the API wins out. i.e. these objects:struct
gpiod_line_attr;
structgpiod_line_config;
structgpiod_request_config;
structgpiod_request_handle;all get collapsed into:
Quoted 8 lines
struct
gpiod_line_request;which significantly reduces the cognitive load on the user.
The
set_config()would probably be called something like:err =
gpiod_line_request_reconfigure(req)
This lack of splitting of options into configurable and constant ones visually suggests that you can change all request options later on which is not true. I think that at least for the C API, we should split the responsibilities of objects and keep the division into request config, line config *and* the line handle whose lifetime is from the moment the lines get requested until they're released.
Quoted 16 lines
to distinguish it from the mutators which use the _set_ naming. (and it would also align with my Go library ;-)
Quoted 13 lines
One idea I have is to add a new object called struct
gpiod_line_config_ext(for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:struct
gpiod_line_config_ext*ext_cfg=gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };/* Add the default config for this request. */
gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);
Quoted 5 lines
Quoted 2 lines
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);Please, no
_extobjects - that is an admission of failure right there.
I wanted to protest but then realized that if you need _ext interfaces then it means your non-extended, initial design is already flawed. :)
Ok so let's try again.
How about:
Three structs:
struct gpiod_line_config;
struct gpiod_request_config;
struct gpiod_line_request;
The first one holds the composite of primary and secondary configs and is modified using mutators according to this scheme:
gpiod_line_config_set_<attr>(config, attr); gpiod_line_config_set_<attr>_offset(config, attr, offset); gpiod_line_config_set_<attr>_offsets(config, attr, num_offsets, offsets);
With notable exceptions for:
gpiod_line_config_set_[input|active_low|active_high](config); gpiod_line_config_set_[input|active_low|active_high]_offset(config, offset); gpiod_line_config_set_[input|active_low|active_high]_offsets(config,
num_offsets, offsets);
and:
gpiod_line_config_set_output(config, num_lines, offsets, values); gpiod_line_config_set_output_offset(config, offset, value);
The request function takes a single line config and a request config and returns a new gpiod_line_request like in the first iteration.
Then the lines can be set like this:
// num_lines refers to the number of lines to set, not the number of // lines in the request gpiod_line_request_set_values(req, num_lines, offsets, values);
Bartosz
Quoted 19 lines
Quoted 6 lines
Does this make sense? I'm worried about the resource management here. Who should be responsible for freeing the config structures? Should the extended config take ownership? Should the user remain responsible? Back to reference counting for these objects? Is this even a good idea?
The user is responsible for freeing the request config.
The request config is responsible for freeing the line configs, if there are any - the user isn't even aware of them so they obviously can't.Similarly if you merge the config into the request.
Quoted 1 line
Please let me know what you think, I could use some advice.
Hopefully I've communicated my meaning a little more clearly this time?
Cheers,
Kent.
Quoted 36 lines · Bartosz Golaszewski
Quoted 28 lines · Kent Gibson
Quoted 7 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip -> long discussion on the libgpiod C API]
Hi Kent,
Quoted 9 lines
I was working on the next iteration of the code and I'm struggling with the implementation of some elements without the concept of attributes.
So I initially liked the idea of variadic functions but they won't work for language bindings so that's a no go. On that note: I wanted to get some inspiration from your go library but your elegant API makes use of go features (like interfaces) we don't have in C.
It is the functional options that is the big difference between my Go implementation and what I would do in C. I happen to use interfaces to implement those options. You could do something similar in C (cos what can't you do in C) but it would be weird, so lets not go there.
You can still provide the variadic forms for C users. And couldn't the language bindings use the "v" variant, as libabc suggests?:
Quoted 6 lines
"Be careful with variadic functions
- It's great if you provide them, but you must accompany them with "v" variants (i.e. functions taking ava_argobject), and provide non-variadic variants as well. This is important to get language wrappers right."
Quoted 4 lines
The "v" functions do nothing for language bindings - you can't construct the required
va_listout of thin air. What you do usually is this (example taken from GLib):
You are right - I was thinking you could build and pass in the the va_list like Python args and kwargs, but you can only use it to decode an existing call stack :-|.
[snip]
Quoted 7 lines
Quoted 6 lines
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named
set_output(value)(that is the A case, btw).
Quoted 7 lines
I can imagine the B case like:
gpiod_line_config_set_output_value(config, offset, value);But how would exactly the call for the A case look like? Two arrays with offset -> value mapping?
No - the A case sets ALL lines to one value.
B is one line to one value.
C is a set of lines to one value.
A set of lines to a set of values is a new case. And yes - two arrays as per your set_values() below.
Quoted 62 lines
unsigned int offsets[] = { 0, 2, 5 }, values[] = { 0, 1 ,1 };
gpiod_line_config_set_output_values_offsets(config, 3, offsets, values);?
Quoted 57 lines
Quoted 9 lines
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);Where
req_cfgconfigures request-specific options, andline_cfgcontains the above line config. I'm still not convinced thatgpiod_request_optionsis the better name, I think I prefer the juxtaposition of the two names:line_configandrequest_config.That's ok - I'm pretty sure you'll get there eventually ;-).
Quoted 3 lines
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
As above, the
req_cfgis the composite line config, soreq =
gpiod_chip_request_lines(chip, req_options, req_cfg);Or if you were to merge the request config, and even the options, into the request:
unsigned int lines[] = { 0, 4, 12, 54 },
num_lines= 4;
req =gpiod_line_request_new(num_lines, lines); // also variadic forms?? // call req option and config mutators here...gpiod_line_request_set_active_low(req);gpiod_line_request_set_output(req, 1);gpiod_line_request_set_line_input(req, 12);gpiod_line_request_set_event_buffer_size(req, 42);
...
// then actually request the lines...
err =gpiod_chip_request_lines(chip, req);which may error for various reasons, such as lines already being requested or overly complex config.
Merging everything into the request means fewer opaque objects and interactions for the user to have to deal with, which is always a good thing.
The downside is that changes to options and config, such as thegpiod_line_request_set_active_low()etc here, are not applied until either thegpiod_chip_request_lines()or theset_config()call, which could be confusing. Though the more I think about it the more I think the resulting simplification of the API wins out. i.e. these objects:struct
gpiod_line_attr;
structgpiod_line_config;
structgpiod_request_config;
structgpiod_request_handle;all get collapsed into:
struct
gpiod_line_request;which significantly reduces the cognitive load on the user.
Quoted 8 lines
Quoted 4 lines
The
set_config()would probably be called something like:err =
gpiod_line_request_reconfigure(req)This lack of splitting of options into configurable and constant ones visually suggests that you can change all request options later on which is not true.
Yup, as I said, the semantics for the unified object are more confusing.
In the Go implementation, the request options can be passed to the request_lines(), but not the set_config(), cos interfaces.
There is no good way to flag that in C at compile time. For a runtime check you could add a return code to the option mutators and return an error if the lines have already been requested.
Quoted 32 lines
I think that at least for the C API, we should
split the responsibilities of objects and keep the division into request config, line config *and* the line handle whose lifetime is from the moment the lines get requested until they're released.Quoted 16 lines
to distinguish it from the mutators which use the _set_ naming. (and it would also align with my Go library ;-)
Quoted 13 lines
One idea I have is to add a new object called struct
gpiod_line_config_ext(for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:struct
gpiod_line_config_ext*ext_cfg=gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };/* Add the default config for this request. */
gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);Quoted 5 lines
Quoted 2 lines
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);Please, no
_extobjects - that is an admission of failure right there.I wanted to protest but then realized that if you need
_extinterfaces then it means your non-extended, initial design is already flawed. :)Ok so let's try again.
Quoted 8 lines
How about:
Three structs:
struct
gpiod_line_config;
structgpiod_request_config;
structgpiod_line_request;
The user manages the lifecycle of all three?
I can live with that, though I would probably still lean towards the unified object approach - with the option mutators getting return codes.
Quoted 3 lines
The first one holds the composite of primary and secondary configs and is modified using mutators according to this scheme:
Which is why it should be called request_config, not line_config. line_config is misleading - it says line but its scope is request.
And of course request_config should be request_options ;-).
Quoted 4 lines
gpiod_line_config_set_<attr>(config, attr); gpiod_line_config_set_<attr>_offset(config, attr, offset); gpiod_line_config_set_<attr>_offsets(config, attr,
num_offsets, offsets);
I personally prefer the _set_line_<attr> style as it reads better, but I can live with this - I know you prefer suffixes for variants.
Quoted 7 lines
With notable exceptions for:
gpiod_line_config_set_[input|active_low|active_high](config); gpiod_line_config_set_[input|active_low|active_high]_offset(config, offset); gpiod_line_config_set_[input|active_low|active_high]_offsets(config,
num_offsets, offsets);
Quoted 8 lines
and:
gpiod_line_config_set_output(config, num_lines, offsets, values);gpiod_line_config_set_output_offset(config, offset, value);The request function takes a single line config and a request config and returns a new
gpiod_line_requestlike in the first iteration.
Where are the set of requested lines specified?
Do null config ptrs result in something useful, but guaranteed harmless, such as requesting lines as input? Or are they required non-null?
Quoted 6 lines
Then the lines can be set like this:
//
num_linesrefers to the number of lines to set, not the number of // lines in the requestgpiod_line_request_set_values(req, num_lines, offsets, values);
At first glance that feels a bit odd, being on the request while the others all operate on the config, but it maps to the SET_VALUES ioctl(), not the SET_CONFIG, so that makes sense.
There is a corresponding get_values(req, num_lines, offsets, values)?
And a reconfigure(req, cfg)?
Cheers,
Kent.
Quoted 1 line · Kent Gibson
[snip]
Quoted 10 lines
Quoted 10 lines
Quoted 7 lines
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named
set_output(value)(that is the A case, btw).I can imagine the B case like:
Quoted 7 lines
Quoted 5 lines
gpiod_line_config_set_output_value(config, offset, value);But how would exactly the call for the A case look like? Two arrays with offset -> value mapping?
No - the A case sets ALL lines to one value.
Apart from a single line request - what could possibly be the use-case for that?
Quoted 2 lines
B is one line to one value.
C is a set of lines to one value.
This makes a bit more sense but ...
Quoted 4 lines
A set of lines to a set of values is a new case. And yes - two arrays as per your
set_values()below.
... to me this and B are the most sensible options. Do we really need A & C for line reading and setting? Do you find use for that in your Go lib?
Quoted 71 lines
Quoted 62 lines
unsigned int offsets[] = { 0, 2, 5 }, values[] = { 0, 1 ,1 };
gpiod_line_config_set_output_values_offsets(config, 3, offsets, values);?
Quoted 57 lines
Quoted 9 lines
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);Where
req_cfgconfigures request-specific options, andline_cfgcontains the above line config. I'm still not convinced thatgpiod_request_optionsis the better name, I think I prefer the juxtaposition of the two names:line_configandrequest_config.That's ok - I'm pretty sure you'll get there eventually ;-).
Quoted 3 lines
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
As above, the
req_cfgis the composite line config, soreq =
gpiod_chip_request_lines(chip, req_options, req_cfg);Or if you were to merge the request config, and even the options, into the request:
unsigned int lines[] = { 0, 4, 12, 54 },
num_lines= 4;
req =gpiod_line_request_new(num_lines, lines); // also variadic forms?? // call req option and config mutators here...gpiod_line_request_set_active_low(req);gpiod_line_request_set_output(req, 1);gpiod_line_request_set_line_input(req, 12);gpiod_line_request_set_event_buffer_size(req, 42);
...
// then actually request the lines...
err =gpiod_chip_request_lines(chip, req);which may error for various reasons, such as lines already being requested or overly complex config.
Merging everything into the request means fewer opaque objects and interactions for the user to have to deal with, which is always a good thing.
The downside is that changes to options and config, such as thegpiod_line_request_set_active_low()etc here, are not applied until either thegpiod_chip_request_lines()or theset_config()call, which could be confusing. Though the more I think about it the more I think the resulting simplification of the API wins out. i.e. these objects:struct
gpiod_line_attr;
structgpiod_line_config;
structgpiod_request_config;
structgpiod_request_handle;all get collapsed into:
struct
gpiod_line_request;which significantly reduces the cognitive load on the user.
Quoted 8 lines
Quoted 4 lines
The
set_config()would probably be called something like:err =
gpiod_line_request_reconfigure(req)This lack of splitting of options into configurable and constant ones visually suggests that you can change all request options later on which is not true.
Quoted 9 lines
Yup, as I said, the semantics for the unified object are more confusing.
In the Go implementation, the request options can be passed to the
request_lines(), but not theset_config(), cos interfaces.There is no good way to flag that in C at compile time. For a runtime check you could add a return code to the option mutators and return an error if the lines have already been requested.
I agree that it doesn't map well to C and this is why I think it would be less confusing if we went with two structs instead.
Quoted 34 lines
Quoted 34 lines
I think that at least for the C API, we should
split the responsibilities of objects and keep the division into request config, line config *and* the line handle whose lifetime is from the moment the lines get requested until they're released.Quoted 16 lines
to distinguish it from the mutators which use the _set_ naming. (and it would also align with my Go library ;-)
Quoted 13 lines
One idea I have is to add a new object called struct
gpiod_line_config_ext(for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:struct
gpiod_line_config_ext*ext_cfg=gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };/* Add the default config for this request. */
gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);Quoted 5 lines
Quoted 2 lines
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);Please, no
_extobjects - that is an admission of failure right there.I wanted to protest but then realized that if you need
_extinterfaces then it means your non-extended, initial design is already flawed. :)Ok so let's try again.
How about:
Quoted 8 lines
Quoted 6 lines
Three structs:
struct
gpiod_line_config;
structgpiod_request_config;
structgpiod_line_request;The user manages the lifecycle of all three?
Yes.
Quoted 11 lines
I can live with that, though I would probably still lean towards the unified object approach - with the option mutators getting return codes.
Quoted 3 lines
The first one holds the composite of primary and secondary configs and is modified using mutators according to this scheme:
Which is why it should be called
request_config, notline_config.line_configis misleading - it says line but its scope is request.
It depends on how you look at it really. Its scope are *the lines* in the request, not the request itself (unlike the event buffer size or line offsets). It says line because gpiod_lines_config would look bizarre.
Quoted 1 line
And of course
request_configshould berequest_options;-).
I'm still not there yet.
Quoted 18 lines
Quoted 5 lines
gpiod_line_config_set_<attr>(config, attr); gpiod_line_config_set_<attr>_offset(config, attr, offset); gpiod_line_config_set_<attr>_offsets(config, attr,
num_offsets, offsets);I personally prefer the _set_line_<attr> style as it reads better, but I can live with this - I know you prefer suffixes for variants.
Quoted 9 lines
With notable exceptions for:
gpiod_line_config_set_[input|active_low|active_high](config); gpiod_line_config_set_[input|active_low|active_high]_offset(config, offset); gpiod_line_config_set_[input|active_low|active_high]_offsets(config,
num_offsets, offsets);and:
Quoted 9 lines
Quoted 6 lines
gpiod_line_config_set_output(config, num_lines, offsets, values);gpiod_line_config_set_output_offset(config, offset, value);The request function takes a single line config and a request config and returns a new
gpiod_line_requestlike in the first iteration.Where are the set of requested lines specified?
They map the uAPI in that the offsets are set in struct gpiod_request_config:
gpiod_request_config_set_line_offsets(config, num_lines, offsets); :)
or
gpiod_request_options_set_line_offsets(config, num_lines, offsets); :(
Quoted 3 lines
Do null config ptrs result in something useful, but guaranteed harmless, such as requesting lines as input? Or are they required non-null?
I normally expect users to pass a valid pointer and don't make the functions null aware. In this case - it's a good question. I'm wondering if it is useful at all? The user should IMO specify what they want to do with the lines? I would lean towards non-null line configfs.
Quoted 7 lines
Quoted 6 lines
Then the lines can be set like this:
//
num_linesrefers to the number of lines to set, not the number of // lines in the requestgpiod_line_request_set_values(req, num_lines, offsets, values);
Quoted 6 lines
At first glance that feels a bit odd, being on the request while the others all operate on the config, but it maps to the
SET_VALUESioctl(), not theSET_CONFIG, so that makes sense.There is a corresponding
get_values(req, num_lines, offsets, values)?
Sure, just didn't include it in the example.
Quoted 2 lines
And a
reconfigure(req, cfg)?
Sure, just haven't decided on the name yet. gpiod_line_request_reconfigure() would be what you're suggesting but it sounds like it would reconfigure the request and not modify the line configuration. I would prefer something closer to gpiod_line_request_set_line_config() which is as verbose as it gets. Maybe even gpiod_line_request_change_line_config()? Or gpiod_line_request_modify_line_config()?
Bartosz
Quoted 3 lines
Cheers,
Kent.
Quoted 17 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip]
Quoted 12 lines
Quoted 12 lines
Quoted 7 lines
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named
set_output(value)(that is the A case, btw).I can imagine the B case like:
gpiod_line_config_set_output_value(config, offset, value);
Quoted 8 lines
Quoted 5 lines
Quoted 3 lines
But how would exactly the call for the A case look like? Two arrays with offset -> value mapping?
No - the A case sets ALL lines to one value.
Apart from a single line request - what could possibly be the use-case for that?
The A, B, C nomenclature originated for attributes, for which blanket sets (A) make more sense.
The case for using A for outputs would be if the vast majority of your lines default to one value. You would then only have to use the other (B, C or whatever) for the non-default lines.
Quoted 9 lines
Quoted 2 lines
B is one line to one value.
C is a set of lines to one value.This makes a bit more sense but ...
Quoted 4 lines
A set of lines to a set of values is a new case. And yes - two arrays as per your
set_values()below.
For future reference, lets call this case D.
Quoted 5 lines
... to me this and B are the most sensible options. Do we really need A & C for line reading and setting? Do you find use for that in your Go lib?
No need for all four - two would be sufficient - probably B and D as you suggest.
The Go interface is a little different because it is being passed as options. It doesn't provide all four. It provides D. And setting all offsets in the request to specific values as part of the request contructor - similar to the set in your initial draft. And it defaults lines to inactive if not specified otherwise.
For gets and sets it only supports all the requested lines. Strictly speaking it can request a subset of the lines - but only the first n lines not a sparse subset. It could be extended to the D case, but so far no one has asked.
Quoted 76 lines
Quoted 76 lines
Quoted 62 lines
unsigned int offsets[] = { 0, 2, 5 }, values[] = { 0, 1 ,1 };
gpiod_line_config_set_output_values_offsets(config, 3, offsets, values);?
Quoted 57 lines
Quoted 9 lines
One can imagine a simple request with the same config for all lines as:
gpiod_chip_request_lines(chip, req_cfg, line_cfg);Where
req_cfgconfigures request-specific options, andline_cfgcontains the above line config. I'm still not convinced thatgpiod_request_optionsis the better name, I think I prefer the juxtaposition of the two names:line_configandrequest_config.That's ok - I'm pretty sure you'll get there eventually ;-).
Quoted 3 lines
Now how do we pass a composite line config with overridden values in C without interfaces etc.?
As above, the
req_cfgis the composite line config, soreq =
gpiod_chip_request_lines(chip, req_options, req_cfg);Or if you were to merge the request config, and even the options, into the request:
unsigned int lines[] = { 0, 4, 12, 54 },
num_lines= 4;
req =gpiod_line_request_new(num_lines, lines); // also variadic forms?? // call req option and config mutators here...gpiod_line_request_set_active_low(req);gpiod_line_request_set_output(req, 1);gpiod_line_request_set_line_input(req, 12);gpiod_line_request_set_event_buffer_size(req, 42);
...
// then actually request the lines...
err =gpiod_chip_request_lines(chip, req);which may error for various reasons, such as lines already being requested or overly complex config.
Merging everything into the request means fewer opaque objects and interactions for the user to have to deal with, which is always a good thing.
The downside is that changes to options and config, such as thegpiod_line_request_set_active_low()etc here, are not applied until either thegpiod_chip_request_lines()or theset_config()call, which could be confusing. Though the more I think about it the more I think the resulting simplification of the API wins out. i.e. these objects:struct
gpiod_line_attr;
structgpiod_line_config;
structgpiod_request_config;
structgpiod_request_handle;all get collapsed into:
struct
gpiod_line_request;which significantly reduces the cognitive load on the user.
Quoted 8 lines
Quoted 4 lines
The
set_config()would probably be called something like:err =
gpiod_line_request_reconfigure(req)This lack of splitting of options into configurable and constant ones visually suggests that you can change all request options later on which is not true.
Yup, as I said, the semantics for the unified object are more confusing.
In the Go implementation, the request options can be passed to the
request_lines(), but not theset_config(), cos interfaces.
Quoted 8 lines
Quoted 4 lines
There is no good way to flag that in C at compile time. For a runtime check you could add a return code to the option mutators and return an error if the lines have already been requested.
I agree that it doesn't map well to C and this is why I think it would be less confusing if we went with two structs instead.
I know.
My concern is that the simplest get use case is 7 function calls:
1. create request_config
2. create line_config
3. request lines
4. do the actual work
5. release request
6. free line_config
7. free request_config
And that is ignoring the chip open/close functions.
Quoted 94 lines
Quoted 34 lines
Quoted 34 lines
I think that at least for the C API, we should
split the responsibilities of objects and keep the division into request config, line config *and* the line handle whose lifetime is from the moment the lines get requested until they're released.Quoted 16 lines
to distinguish it from the mutators which use the _set_ naming. (and it would also align with my Go library ;-)
Quoted 13 lines
One idea I have is to add a new object called struct
gpiod_line_config_ext(for extended) that would take one primary config and an arbitrary number of secondary configs with the following example use-case:struct
gpiod_line_config_ext*ext_cfg=gpiod_line_config_ext_new(); unsigned int offsets[] = { 2, 3 };/* Add the default config for this request. */
gpiod_line_config_ext_set_primary_config(ext_cfg, line_cfg);
/* Add a secondary config for 2 lines with offsets: 2 and 3. */gpiod_line_config_ext_add_secondary_config(ext_cfg, other_line_cfg, 2, offsets);Quoted 5 lines
Quoted 2 lines
gpiod_chip_request_lines_ext(chip, req_cfg, ext_cfg);Please, no
_extobjects - that is an admission of failure right there.I wanted to protest but then realized that if you need
_extinterfaces then it means your non-extended, initial design is already flawed. :)Ok so let's try again.
How about:
Quoted 8 lines
Quoted 6 lines
Three structs:
struct
gpiod_line_config;
structgpiod_request_config;
structgpiod_line_request;The user manages the lifecycle of all three?
Yes.
Quoted 11 lines
I can live with that, though I would probably still lean towards the unified object approach - with the option mutators getting return codes.
Quoted 3 lines
The first one holds the composite of primary and secondary configs and is modified using mutators according to this scheme:
Which is why it should be called
request_config, notline_config.line_configis misleading - it says line but its scope is request.It depends on how you look at it really. Its scope are *the lines* in the request, not the request itself (unlike the event buffer size or line offsets). It says line because
gpiod_lines_configwould look bizarre.Quoted 1 line
And of course
request_configshould berequest_options;-).I'm still not there yet.
Quoted 18 lines
Quoted 5 lines
gpiod_line_config_set_<attr>(config, attr); gpiod_line_config_set_<attr>_offset(config, attr, offset); gpiod_line_config_set_<attr>_offsets(config, attr,
num_offsets, offsets);I personally prefer the _set_line_<attr> style as it reads better, but I can live with this - I know you prefer suffixes for variants.
Quoted 9 lines
With notable exceptions for:
gpiod_line_config_set_[input|active_low|active_high](config); gpiod_line_config_set_[input|active_low|active_high]_offset(config, offset); gpiod_line_config_set_[input|active_low|active_high]_offsets(config,
num_offsets, offsets);and:
Quoted 9 lines
Quoted 6 lines
gpiod_line_config_set_output(config, num_lines, offsets, values);gpiod_line_config_set_output_offset(config, offset, value);The request function takes a single line config and a request config and returns a new
gpiod_line_requestlike in the first iteration.Where are the set of requested lines specified?
Quoted 8 lines
They map the uAPI in that the offsets are set in struct
gpiod_request_config:
gpiod_request_config_set_line_offsets(config, num_lines, offsets); :)or
gpiod_request_options_set_line_offsets(config, num_lines, offsets); :(
Alternatively it could be in one of the constructors - gpiod_request_config_new(), gpiod_line_config_new() or gpiod_chip_request_lines()?
Quoted 10 lines
Quoted 3 lines
Do null config ptrs result in something useful, but guaranteed harmless, such as requesting lines as input? Or are they required non-null?
I normally expect users to pass a valid pointer and don't make the functions null aware. In this case - it's a good question. I'm wondering if it is useful at all? The user should IMO specify what they want to do with the lines? I would lean towards non-null line configfs.
Sure doesn't if you have to set the offsets in the config. But might do if you provide them to the gpiod_chip_request_lines().
The null case could then request the lines as-is?
There seems to be a bit of interest in as-is of late, and the simplest case would then be three function calls.
Quoted 19 lines
Quoted 7 lines
Quoted 6 lines
Then the lines can be set like this:
//
num_linesrefers to the number of lines to set, not the number of // lines in the requestgpiod_line_request_set_values(req, num_lines, offsets, values);Quoted 6 lines
At first glance that feels a bit odd, being on the request while the others all operate on the config, but it maps to the
SET_VALUESioctl(), not theSET_CONFIG, so that makes sense.There is a corresponding
get_values(req, num_lines, offsets, values)?Sure, just didn't include it in the example.
Quoted 2 lines
And a
reconfigure(req, cfg)?
Quoted 8 lines
Sure, just haven't decided on the name yet.
gpiod_line_request_reconfigure()would be what you're suggesting but it sounds like it would reconfigure the request and not modify the line configuration. I would prefer something closer togpiod_line_request_set_line_config()which is as verbose as it gets. Maybe evengpiod_line_request_change_line_config()? Orgpiod_line_request_modify_line_config()?
gpiod_line_request_reconfigure(req, cfg) is not modifying the line_config
- it is modifying the request WITH the modified config.
If gpiod_line_request_<splat>_line_config(req, cfg) works better for you then I'd prefer something along the lines of _apply_ or _commit_, as it is taking the line_config, modified by sets, and applying it to the requested lines.
Cheers,
Kent.
Quoted 48 lines · Kent Gibson
Quoted 17 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip]
Quoted 12 lines
Quoted 12 lines
Quoted 7 lines
So it should require the list of lines that you are setting the values for. i.e. it is the mutator for a subset of lines, so the C case.
And it implicitly sets those lines to outputs, so it can be more clearly named
set_output(value)(that is the A case, btw).I can imagine the B case like:
gpiod_line_config_set_output_value(config, offset, value);Quoted 8 lines
Quoted 5 lines
Quoted 3 lines
But how would exactly the call for the A case look like? Two arrays with offset -> value mapping?
No - the A case sets ALL lines to one value.
Apart from a single line request - what could possibly be the use-case for that?
The A, B, C nomenclature originated for attributes, for which blanket sets (A) make more sense.
The case for using A for outputs would be if the vast majority of your lines default to one value. You would then only have to use the other (B, C or whatever) for the non-default lines.
Quoted 9 lines
Quoted 2 lines
B is one line to one value.
C is a set of lines to one value.This makes a bit more sense but ...
Quoted 4 lines
A set of lines to a set of values is a new case. And yes - two arrays as per your
set_values()below.For future reference, lets call this case D.
Quoted 1 line
Quoted 8 lines
Quoted 4 lines
... to me this and B are the most sensible options. Do we really need A & C for line reading and setting? Do you find use for that in your Go lib?
No need for all four - two would be sufficient - probably B and D as you suggest.
Agreed.
[snip]
Quoted 30 lines
Quoted 10 lines
Quoted 10 lines
Quoted 4 lines
This lack of splitting of options into configurable and constant ones visually suggests that you can change all request options later on which is not true.
Yup, as I said, the semantics for the unified object are more confusing.
In the Go implementation, the request options can be passed to the
request_lines(), but not theset_config(), cos interfaces.Quoted 8 lines
Quoted 4 lines
There is no good way to flag that in C at compile time. For a runtime check you could add a return code to the option mutators and return an error if the lines have already been requested.
I agree that it doesn't map well to C and this is why I think it would be less confusing if we went with two structs instead.
I know.
My concern is that the simplest get use case is 7 function calls:
1. createrequest_config
2. createline_config
3. request lines
4. do the actual work
5. release request
6. freeline_config
7. freerequest_config
Quoted 2 lines
And that is ignoring the chip open/close functions.
This doesn't bother me all that much. This is the low-level C API. It's supposed to be a bit clunky. It'll get way simpler in the high-level bindings.
In Python a simple case would look something like this:
with gpiod.Chip("/dev/gpiochip0") as chip:
with chip.request_lines(gpiod.RequestConfig(offsets=( 0, 2, 3 )),
gpiod.LineConfig(direction=gpiod.DIRECTION_INPUT)) as req:
values = req.get_values() # Read all values
values = req.get_values(offsets=( 2, 3)) # Read values of specific lines
[snip]
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Where are the set of requested lines specified?
They map the uAPI in that the offsets are set in struct
gpiod_request_config:
gpiod_request_config_set_line_offsets(config, num_lines, offsets); :)
Quoted 9 lines
Quoted 4 lines
or
gpiod_request_options_set_line_offsets(config, num_lines, offsets); :(Alternatively it could be in one of the constructors -
gpiod_request_config_new(),gpiod_line_config_new()orgpiod_chip_request_lines()?
I want to make the struct reusable/modifiable so setting it only in the constructor would disallow it and having both would be redundant. And the last one: the less function arguments the better IMO. So I'm for having it in the request_config.
Quoted 11 lines
Quoted 10 lines
Quoted 3 lines
Do null config ptrs result in something useful, but guaranteed harmless, such as requesting lines as input? Or are they required non-null?
I normally expect users to pass a valid pointer and don't make the functions null aware. In this case - it's a good question. I'm wondering if it is useful at all? The user should IMO specify what they want to do with the lines? I would lean towards non-null line configfs.
Quoted 8 lines
Sure doesn't if you have to set the offsets in the config. But might do if you provide them to the
gpiod_chip_request_lines().The null case could then request the lines as-is?
There seems to be a bit of interest in as-is of late, and the simplest case would then be three function calls.
Ok, makes sense. Null line-config -> request lines as is.
Quoted 28 lines
Quoted 19 lines
Quoted 7 lines
Quoted 6 lines
Then the lines can be set like this:
//
num_linesrefers to the number of lines to set, not the number of // lines in the requestgpiod_line_request_set_values(req, num_lines, offsets, values);Quoted 6 lines
At first glance that feels a bit odd, being on the request while the others all operate on the config, but it maps to the
SET_VALUESioctl(), not theSET_CONFIG, so that makes sense.There is a corresponding
get_values(req, num_lines, offsets, values)?Sure, just didn't include it in the example.
Quoted 2 lines
And a
reconfigure(req, cfg)?Quoted 8 lines
Sure, just haven't decided on the name yet.
gpiod_line_request_reconfigure()would be what you're suggesting but it sounds like it would reconfigure the request and not modify the line configuration. I would prefer something closer togpiod_line_request_set_line_config()which is as verbose as it gets. Maybe evengpiod_line_request_change_line_config()? Orgpiod_line_request_modify_line_config()?
Quoted 8 lines
gpiod_line_request_reconfigure(req, cfg)is not modifying theline_config
- it is modifying the request WITH the modified config.If gpiod_line_request_<splat>_line_config(req, cfg) works better for you then I'd prefer something along the lines of _apply_ or _commit_, as it is taking the
line_config, modified by sets, and applying it to the requested lines.
How about gpiod_line_request_reconfigure_lines()?
Bart
Quoted 6 lines · Bartosz Golaszewski
Quoted 5 lines · Kent Gibson
Quoted 3 lines · Bartosz Golaszewski
Quoted 1 line · Kent Gibson
[snip]
Quoted 9 lines
Quoted 6 lines
If gpiod_line_request_<splat>_line_config(req, cfg) works better for you then I'd prefer something along the lines of _apply_ or _commit_, as it is taking the
line_config, modified by sets, and applying it to the requested lines.How about
gpiod_line_request_reconfigure_lines()?
That works for me.
Cheers,
Kent.