Interact with QEMU GPIO models via gpiodev
Subsystems (2)
cover Interact with QEMU GPIO models via gpiodev
While vhost-user-gpio-pci is a good solution to pass gpios inside guest it still doesn't cover the following cases:
- AFAIK the board needs to have a PCI bus;
- we add new hot-plugged gpios instead of re-using the existing ones;
- we can't connect it to existing gpio models;
This functionality is quite desired (numerous emails observed since i released https://github.com/maquefel/virtual_gpio_basic which is ivshmem based and have same disadvantages as above) - the ability to manipulate existing gpios, including MMIO mmaped like aspeed or bcm2835/bcm2838 gpios.
This becomes even more important for MCUs where virtio gpio application is limited.
For example:
https://stackoverflow.com/questions/76834038/qemu-gpio-connect
https://stackoverflow.com/questions/60764018/how-to-connect-gpio-in-qemu-emulated-machine-to-an-object-in-host
And so on.
So the most obvious thing is to create something similar to existing chardev, to provide common interface for models to interact with.
I propose new gpiodev, which consists of gpiodev itself, frontend and backends just like chardev does.
It provides the abilities which mostly replicate the current state of Linux GPIO UAPI, i.e.:
- getting GPIO chip/line info;
- monitoring line state change externally on rising/falling events;
- monitoring configuration change (output swith to input and vise-versa);
- setting/getting gpio pins;
The interface for GPIO Models is described in qemu/include/gpiodev/gpio-fe.h.
The model should provide callbacks for the following:
- LineInfoHandler to provide info aboud line specified by offset;
- LineGetValueHandler to get gpio line value specified by offset;
- LineGetValueHandler to set gpio line value specified by offset;
Also the model can notify the Gpiodev and connected back about:
- line value;
- line config;
changed by the guest witch qemu_gpio_fe_line_event()/qemu_gpio_fe_config_event().
A nice choice for demonstation purpose as heavily used and, maybe, the most full board simulation in QEMU.
It seems to have some flaws in GPIO model hovewer (not sure if it's really a flaw through).
Andrew provided some clarification on Linux driver implementation, and agreed that it might be a bug in QEMU model.
First write to pin has no effect to gpiomon/gpio-event-mon as direction is set AFTER pin value which results in qemu_gpio_fe_line_event() not called in aspeed_gpio_update(), so qemu_set_irq() won't be called for the same reason by the way.
``` aspeed # gpioset 0 8=1 aspeed_gpio_write offset: 0x1c value 0x100 aspeed_gpio_write offset: 0x0 value 0x100 <-- VALUE aspeed_gpio_write offset: 0x4 value 0x100 <-- DIRECTION ```
Also ast2600 machine was modified to set DEVICE()->id for gpios, as ASPEED gpio relies on this to connect to gpiodev.
A simple backend over any chadev transport, while this solution seems good at first glance, it lacks solid protocol (currently used Linux GPIO UAPI structs) and I couldn't find any suitable/standardized solution, something like MOXA uses for ioLogik devices for example. So using this backend requires specials tools like qemu-gpio-tools (just Linux gpio tools with some modification for demo purpose).
I someone can propose a ready protocol or an idea please do so.
Some demo interacting with ASPEED:
``` host $ build-qemu/qemu-system-arm -M ast2600-evb,bmc-console=uart5 -kernel buildroot/output/build/linux-6.6.14/arch/arm/boot/zImage \ -dtb buildroot/output/build/linux-6.6.14/arch/arm/boot/dts/aspeed/aspeed-ast2600-evb.dtb \ -initrd buildroot/output/images/rootfs.cpio -nographic -serial mon:stdio \ -gpiodev chardev,id=aspeed-gpio0,chardev=gpio0 -chardev socket,path=/tmp/gpio0,id=gpio0,server=on,wait=off ```
```
host $ qemu-gpio-tools/lsgpio -n /tmp/gpio0
sending 0x8044b401
GPIO chip: aspeed-gpio0, "ASPEED GPIO", 208 GPIO lines
line 0: "gpioA0" unused [input]
line 1: "gpioA1" unused [input]
line 2: "gpioA2" unused [input]
line 3: "gpioA3" unused [input]
line 4: "gpioA4" unused [input]
line 5: "gpioA5" unused [input]
line 6: "gpioA6" unused [input]
line 7: "gpioA7" unused [input]
line 8: "gpioB0" unused [input]
[...]
line 200: "gpioZ0" unused [input]
line 201: "gpioZ1" unused [input]
line 202: "gpioZ2" unused [input]
line 203: "gpioZ3" unused [input]
line 204: "gpioZ4" unused [input]
line 205: "gpioZ5" unused [input]
line 206: "gpioZ6" unused [input]
line 207: "gpioZ7" unused [input]
```I did some experiments with CUSE, but it lacks the most important functionality,
creating new file descriptors (creating new file could also do). While it's quite simple
to implement something like sysfs GPIO i don't think it's a good solution (hehehehehe, Bartosz and Linus i hope you appreciate this), so i decided to make something similiar to CUSE.
The price is high:
- a kernel module (also kernel modifitions are also required to make it pretty - export fuse_mknod function for example);
- new guse bindings for libfuse;
- libgpiod modification (a small one to allow "/sys/class/guse" in gpiod_check_gpiochip_device());
- and the QEMU of course;
But i was obsessed with the idea of using the same tools like in Linux (libgpiod for example ;)), and still it was a fun thing to do.
With this we can have a FULL support of Linux GPIO UAPI.
Module ony test with 6.11.*, v6.13.*+ (pages replaced with folio) under KSAN, kmemleak.
``` $ sudo insmod guse/guse.ko ```
``` sudo build-qemu/qemu-system-arm -M ast2600-evb,bmc-console=uart5 -kernel buildroot/output/build/linux-6.6.14/arch/arm/boot/zImage \ -dtb buildroot/output/build/linux-6.6.14/arch/arm/boot/dts/aspeed/aspeed-ast2600-evb.dtb \ -initrd buildroot/output/images/rootfs.cpio -nographic -serial mon:stdio -gpiodev guse,id=aspeed-gpio0,devname=gpiochip10 ```
``` aspeed # gpioset 0 8=1 aspeed # gpioget 0 8 ```
``` host $ sudo libgpiod/tools/gpionotify -c 10 8 1741686422.149345616 reconfigured aspeed-gpio0 8 1741686430.466103054 reconfigured aspeed-gpio0 8 ```
``` aspeed # gpioset 0 8=1 aspeed # gpioset 0 8=0 ```
``` $ sudo libgpiod/tools/gpiomon -c 10 8 1741687220.025006346 rising aspeed-gpio0 8 1741687222.634353601 falling aspeed-gpio0 8 ```
gpio-sim also can serve as a backend, but the only thing we can get from it is monitoring lines set by QEMU guest. So i didn't bother implementing it yet.
I prepare a suite with whing nessary if someone wants to test/tinker with current series:
---
Nikita Shubin (7):
QAPI: gpio JSON
Add gpiodev dummy
gpiodev: Add GPIO device frontend
gpiodev: Add GPIO backend over chardev
hw/gpio/aspeed: Add gpiodev support
hw/arm: ast2600: set id for gpio
gpiodev: Add gpiobackend over GUSE
gpiodev/gpio-chardev.c | 479 +++++++++++++++++++++++++++ gpiodev/gpio-fe.c | 103 ++++++ gpiodev/gpio-guse.c | 747 ++++++++++++++++++++++++++++++++++++++++++ gpiodev/gpio.c | 399 ++++++++++++++++++++++ gpiodev/meson.build | 8 + hw/arm/aspeed_ast2600.c | 2 + hw/gpio/aspeed_gpio.c | 127 +++++++ include/gpiodev/gpio-fe.h | 122 +++++++ include/gpiodev/gpio.h | 233 +++++++++++++ include/hw/gpio/aspeed_gpio.h | 3 + meson.build | 11 +- qapi/gpio.json | 93 ++++++ qapi/meson.build | 1 + qapi/qapi-schema.json | 1 + qemu-options.hx | 9 + qom/object.c | 1 + system/vl.c | 25 ++ 17 files changed, 2363 insertions(+), 1 deletion(-)
---
base-commit: 98c7362b1efe651327385a25874a73e008c6549e
change-id: 20250313-gpiodev-d24e6d9be90d
Best regards,
Signature · 1 line
Nikita Shubin <[email protected]>
PATCH 1/7 QAPI: gpio JSON
From: Nikita Shubin <[email protected]>
--- qapi/gpio.json | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ qapi/meson.build | 1 + qapi/qapi-schema.json | 1 + 3 files changed, 70 insertions(+)
qapi/gpio.json new file +68 -0
@@ -0,0 +1,68 @@ +# -*- Mode: Python -*- +# vim: filetype=python +# + +## +# = Gpio devices +## + +## +# @GpiodevInfo: +# +# Information about a gpio device. +# +# @label: the label of the gpio device +# +# Since: 9.2 +## +{ 'struct': 'GpiodevInfo', + 'data': { 'label': 'str' } } + +## +# @GpiodevBackendKind: +# +# @chardev: chardevs +# +# Since: 9.2 +## +{ 'enum': 'GpiodevBackendKind', + 'data': [ 'chardev' ] } + +## +# @GpiodevChardev: +# +# Configuration info for chardev gpiodevs. +# +# @chardev: chardev id +# +# @size: buffer size, default is 65536 +# +# Since: 9.2 +## + { 'struct': 'GpiodevChardev', + 'data': { 'chardev': 'str', + '*size': 'int' } } + +## +# @GpiodevChardevWrapper: +# +# @data: Configuration info for chardev gpiodevs +# +# Since: 9.2 +## +{ 'struct': 'GpiodevChardevWrapper', + 'data': { 'data': 'GpiodevChardev' } } + +## +# @GpiodevBackend: +# +# Configuration info for the new chardev backend. +# +# @type: backend type +# +# Since: 9.2 +## +{ 'union': 'GpiodevBackend', + 'base': { 'type': 'GpiodevBackendKind' }, + 'discriminator': 'type', + 'data': { 'chardev': 'GpiodevChardevWrapper' } }
qapi/meson.build +1 -0
@@ -35,6 +35,7 @@ qapi_all_modules = [ 'dump', 'ebpf', 'error', + 'gpio', 'introspect', 'job', 'machine-common',
qapi/qapi-schema.json +1 -0
@@ -52,6 +52,7 @@ { 'include': 'block-export.json' } { 'include': 'char.json' } { 'include': 'dump.json' } +{ 'include': 'gpio.json' } { 'include': 'net.json' } { 'include': 'ebpf.json' } { 'include': 'rocker.json' }
Signature · 1 line
2.45.2
Re: [PATCH PoC 1/7] QAPI: gpio JSON
Quoted 73 lines · On Wed, Mar 19, 2025 at 10:57:51AM +0300, Nikita Shubin via B4 Relay wrote:
From: Nikita Shubin <[email protected]>
Signed-off-by Nikita Shubin <[email protected]>--- qapi/gpio.json | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ qapi/meson.build | 1 + qapi/qapi-schema.json | 1 + 3 files changed, 70 insertions(+)qapi/gpio.json new file +58
-0@@ -0,0 +1,68 @@ +# -*- Mode: Python -*- +# vim: filetype=python +# + +## +# = Gpio devices +## + +## +# @GpiodevInfo: +# +# Information about a gpio device. +# +# @label: the label of the gpio device +# +# Since: 9.2 +## +{ 'struct': 'GpiodevInfo', + 'data': { 'label': 'str' } } + +## +# @GpiodevBackendKind: +# +# @chardev: chardevs +# +# Since: 9.2 +## +{ 'enum': 'GpiodevBackendKind', + 'data': [ 'chardev' ] } + +## +# @GpiodevChardev: +# +# Configuration info for chardev gpiodevs. +# +# @chardev: chardev id +# +# @size: buffer size, default is 65536 +# +# Since: 9.2 +## + { 'struct': 'GpiodevChardev', + 'data': { 'chardev': 'str', + '*size': 'int' } } + +## +# @GpiodevChardevWrapper: +# +# @data: Configuration info for chardev gpiodevs +# +# Since: 9.2 +## +{ 'struct': 'GpiodevChardevWrapper', + 'data': { 'data': 'GpiodevChardev' } } + +## +# @GpiodevBackend: +#
qapi/gpio.json line 68
Quoted 10 lines
qapi/gpio.json new file +10
-0+# Configuration info for the new chardev backend. +# +# @type: backend type +# +# Since: 9.2 +## +{ 'union': 'GpiodevBackend', + 'base': { 'type': 'GpiodevBackendKind' }, + 'discriminator': 'type', + 'data': { 'chardev': 'GpiodevChardevWrapper' } }
While historically we've just wired things up to chardevs in QEMU, in most cases this is just a hack to get the ability too configure a socket, with the other chardev backends being never used. The downside of this is that chardev APIs internally are not very nice to work with, especally if you want/need to be aware of client connection establishment/closure.
These days we've got common socket APIs and QAPI schema available and can bypass the chardevs (which have a pretty unpleasant internal API) if all we need is a socket backend connecting to an external server. This would let code directly work with the QIOChannelSocket object, instead of that object being hidden behind the chardev APIs.
{ 'enum': 'GpiodevBackendKind',
'data': [ 'socket' ] }
{ 'struct': 'GpiodevSocket',
'data': { 'addr': 'SocketAddress',
'*size': 'int'} }
{ 'struct': 'GpiodevSocketWrapper',
'data': { 'data': 'GpiodevSocket' } }
{ 'union': 'GpiodevBackend',
'base': { 'type': 'GpiodevBackendKind' },
'discriminator': 'type',
'data': { 'socket': 'GpiodevSocketWrapper' } }
if you need to switch between client/server mode some further additions would be needed.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH PoC 1/7] QAPI: gpio JSON
Quoted 4 lines · Daniel P. Berrangé
Quoted 3 lines · On Wed, Mar 19, 2025 at 10:57:51AM +0300, Nikita Shubin via B4 Relay wrote:
From: Nikita Shubin <[email protected]>
Signed-off-by Nikita Shubin <[email protected]>
The commit message should briefly explain the purpose of the change.
Quoted 6 lines
Quoted 6 lines
--- qapi/gpio.json | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ qapi/meson.build | 1 + qapi/qapi-schema.json | 1 + 3 files changed, 70 insertions(+)
Quoted 12 lines
qapi/gpio.json line 6
Quoted 12 lines
qapi/gpio.json new file +6
-0@@ -0,0 +1,68 @@ +# -*- Mode: Python -*- +# vim: filetype=python +# + +## +# = Gpio devices
Spell it GPIO in doc text, because it's an acronym.
Quoted 10 lines
qapi/gpio.json line 16
Quoted 10 lines
qapi/gpio.json new file +10
-0+## + +## +# @GpiodevInfo: +# +# Information about a gpio device. +# +# @label: the label of the gpio device +# +# Since: 9.2
Make that 10.1 everywhere.
Quoted 14 lines
Quoted 14 lines
qapi/gpio.json new file +14
-0+## +{ 'struct': 'GpiodevInfo', + 'data': { 'label': 'str' } } + +## +# @GpiodevBackendKind: +# +# @chardev: chardevs +# +# Since: 9.2 +## +{ 'enum': 'GpiodevBackendKind', + 'data': [ 'chardev' ] } +
Quoted 8 lines
qapi/gpio.json line 38
Quoted 8 lines
qapi/gpio.json new file +8
-0+## +# @GpiodevChardev: +# +# Configuration info for chardev gpiodevs. +# +# @chardev: chardev id +# +# @size: buffer size, default is 65536
What buffer is being sized here?
Quoted 6 lines
qapi/gpio.json line 44
Quoted 6 lines
qapi/gpio.json new file +6
-0+# +# Since: 9.2 +## + { 'struct': 'GpiodevChardev', + 'data': { 'chardev': 'str', + '*size': 'int' } }
Use 'size' instead of 'int' for byte counts, please.
Quoted 16 lines
Quoted 16 lines
qapi/gpio.json new file +16
-0+ +## +# @GpiodevChardevWrapper: +# +# @data: Configuration info for chardev gpiodevs +# +# Since: 9.2 +## +{ 'struct': 'GpiodevChardevWrapper', + 'data': { 'data': 'GpiodevChardev' } } + +## +# @GpiodevBackend: +# +# Configuration info for the new chardev backend. +#
Quoted 8 lines
qapi/gpio.json line 68
Quoted 8 lines
qapi/gpio.json new file +8
-0+# @type: backend type +# +# Since: 9.2 +## +{ 'union': 'GpiodevBackend', + 'base': { 'type': 'GpiodevBackendKind' }, + 'discriminator': 'type', + 'data': { 'chardev': 'GpiodevChardevWrapper' } }
Why GpiodevChardevWrapper? Consistency with similar existing things?
The wrapper types are remnants of "simple" unions. New code should avoid them, unless avoiding them would make things hard to use. For instance, when adding a new branch to a union where the existing branches are of such wrapper types, use a wrapper for the new one to keep things consistent.
What other backend types do you have in mind?
Quoted 7 lines
While historically we've just wired things up to chardevs in QEMU, in most cases this is just a hack to get the ability too configure a socket, with the other chardev backends being never used. The downside of this is that chardev APIs internally are not very nice to work with, especally if you want/need to be aware of client connection establishment/closure.
Quoted 6 lines
These days we've got common socket APIs and QAPI schema available and can bypass the chardevs (which have a pretty unpleasant internal API) if all we need is a socket backend connecting to an external server. This would let code directly work with the QIOChannelSocket object, instead of that object being hidden behind the chardev APIs.
Good point. Nikita, do you see a use for chardevs other than sockets?
[...]
PATCH 2/7 Add gpiodev dummy
In reply to Nikita ShubinAdd gpiodev stub with single help option.
--- gpiodev/gpio.c | 145 +++++++++++++++++++++++++++++++++++++++++++++++++ gpiodev/meson.build | 5 ++ include/gpiodev/gpio.h | 34 ++++++++++++ meson.build | 11 +++- qemu-options.hx | 9 +++ system/vl.c | 25 +++++++++ 6 files changed, 228 insertions(+), 1 deletion(-)
gpiodev/gpio.c new file +145 -0
@@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* QEMU GPIO device. +* +* Author: 2025 Nikita Shubin <[email protected]> +* +*/ +#include "qemu/osdep.h" + +#include "qapi/error.h" +#include "qemu/config-file.h" +#include "qemu/option.h" +#include "qemu/qemu-print.h" +#include "qemu/help_option.h" + +#include "gpiodev/gpio.h" + +static Object *get_gpiodevs_root (void ) +{ +return object_get_container ("gpiodevs" ); +} + +static const TypeInfo gpiodev_types_info[] = { + { + .name =TYPE_GPIODEV , + .parent =TYPE_OBJECT , + .instance_size =sizeof (Gpiodev), + .abstract = true, + }, +}; + +DEFINE_TYPES (gpiodev_types_info); + +static Gpiodev *gpiodev_new (const char *id, +GMainContext *gcontext, +Error **errp) +{ +Object *obj; +Gpiodev *gpio =NULL ; + +assert (id); + + obj =object_new (TYPE_GPIODEV ); + gpio =GPIODEV (obj); + gpio->gcontext = gcontext; + +return gpio; +} + +static Gpiodev *qemu_gpiodev_new (const char *id, +GMainContext *gcontext, +Error **errp) +{ +Gpiodev *gpio; + + gpio =gpiodev_new (id, gcontext, errp); +if (!gpio) { +return NULL ; + } + +if (!object_property_try_add_child (get_gpiodevs_root (), id,OBJECT (gpio), + errp)) { +object_unref (OBJECT (gpio)); +return NULL ; + } + +object_unref (OBJECT (gpio)); + +return gpio; +} + +typedef struct GpiodevClassFE { +void (*fn)(const char *name,void *opaque); +void *opaque; +}GpiodevClassFE ; + +static void +gpiodev_class_foreach (ObjectClass *klass,void *opaque) +{ +GpiodevClassFE *fe = opaque; + +assert (g_str_has_prefix (object_class_get_name (klass),"gpiodev-" )); + fe->fn (object_class_get_name (klass) +8 , fe->opaque); +} + +static void +gpiodev_name_foreach (void (*fn)(const char *name,void *opaque), +void *opaque) +{ +GpiodevClassFE fe = { .fn = fn, .opaque = opaque }; + +object_class_foreach (gpiodev_class_foreach,TYPE_GPIODEV , false, &fe); +} + +static void +help_string_append (const char *name,void *opaque) +{ +GString *str = opaque; + +g_string_append_printf (str,"\n %s" , name); +} + +Gpiodev *qemu_gpiodev_add (QemuOpts *opts,GMainContext *context, +Error **errp) +{ +const char *id =qemu_opts_id (opts); +const char *name =qemu_opt_get (opts,"backend" ); + +if (name &&is_help_option (name)) { +GString *str =g_string_new ("" ); + +gpiodev_name_foreach (help_string_append, str); + +qemu_printf ("Available chardev backend types: %s\n" , str->str); +g_string_free (str, true); +return NULL ; + } + +if (id ==NULL ) { +error_setg (errp,"gpiodev: no id specified" ); +return NULL ; + } + +return qemu_gpiodev_new (id, context, errp); +} + +static QemuOptsList qemu_gpiodev_opts = { + .name ="gpiodev" , + .implied_opt_name ="backend" , + .head =QTAILQ_HEAD_INITIALIZER (qemu_gpiodev_opts.head), + .desc = { + { + .name ="backend" , + .type =QEMU_OPT_STRING , + }, + {/* end of list */ } + }, +}; + +static void gpiodev_register_config (void ) +{ +qemu_add_opts (&qemu_gpiodev_opts); +} + +opts_init (gpiodev_register_config);
gpiodev/meson.build new file +5 -0
@@ -0,0 +1,5 @@ +gpiodev_ss.add(files( + 'gpio.c', +)) + +gpiodev_ss = gpiodev_ss.apply({})
include/gpiodev/gpio.h new file +34 -0
@@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* QEMU GPIO device. +* +* Author: 2025 Nikita Shubin <[email protected]> +* +*/ +#ifndef QEMU_GPIO_H +#define QEMU_GPIO_H + +#include "qom/object.h" + +/* gpio back-end device */ +typedef struct GpioBackend GpioBackend ; + +struct Gpiodev { +Object parent_obj; + +GpioBackend *be; + +GMainContext *gcontext; +}; + +struct GpiodevClass { +ObjectClass parent_class; +}; + +#define TYPE_GPIODEV "gpiodev" +OBJECT_DECLARE_TYPE (Gpiodev, GpiodevClass,GPIODEV ) + +Gpiodev *qemu_gpiodev_add(QemuOpts *opts, GMainContext *context, + Error **errp); + +#endif /* QEMU_GPIO_H */
meson.build +10 -1
@@ -3646,6 +3646,7 @@ block_ss = ss.source_set() chardev_ss = ss.source_set() common_ss = ss.source_set() crypto_ss = ss.source_set() +gpiodev_ss = ss.source_set() hwcore_ss = ss.source_set() io_ss = ss.source_set() qmp_ss = ss.source_set()
@@ -3735,6 +3736,7 @@ subdir('io') subdir('chardev') subdir('fsdev') subdir('dump') +subdir('gpiodev') if have_block block_ss.add(files(
@@ -4023,11 +4025,18 @@ libhwcore = static_library('hwcore', sources: hwcore_ss.sources() + genh, hwcore = declare_dependency(objects: libhwcore.extract_all_objects(recursive: false)) common_ss.add(hwcore) +libgpiodev = static_library('gpiodev', gpiodev_ss.sources() + genh, + dependencies: gpiodev_ss.dependencies(), + build_by_default: false) + +gpiodev = declare_dependency(objects: libgpiodev.extract_all_objects(recursive: false), + dependencies: gpiodev_ss.dependencies()) + ########### # Targets # ########### -system_ss.add(authz, blockdev, chardev, crypto, io, qmp) +system_ss.add(authz, blockdev, chardev, crypto, gpiodev, io, qmp) common_ss.add(qom, qemuutil) common_ss.add_all(when: 'CONFIG_SYSTEM_ONLY', if_true: [system_ss])
qemu-options.hx +9 -0
@@ -4081,6 +4081,15 @@ ERST DEFHEADING() +DEFHEADING(GPIO device options:) + +DEF("gpiodev", HAS_ARG, QEMU_OPTION_gpiodev, + "-gpiodev help\n" + , QEMU_ARCH_ALL +) + +DEFHEADING() + #ifdef CONFIG_TPM DEFHEADING(TPM device options:)
system/vl.c +25 -0
@@ -73,6 +73,7 @@#include "gdbstub/enums.h" #include "qemu/timer.h" #include "chardev/char.h" +#include "gpiodev/gpio.h" #include "qemu/bitmap.h" #include "qemu/log.h" #include "system/blockdev.h"
@@ -1230,6 +1231,20 @@ static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)return 0 ; } +static int gpiodev_init_func (void *opaque,QemuOpts *opts,Error **errp) +{ +Error *local_err =NULL ; + +if (!qemu_gpiodev_add (opts,NULL , &local_err)) { +if (local_err) { +error_propagate (errp, local_err); +return -1 ; + } +exit (0 ); + } +return 0 ; +} +#ifdef CONFIG_VIRTFS static int fsdev_init_func (void *opaque,QemuOpts *opts,Error **errp) {
@@ -2053,6 +2068,9 @@ static void qemu_create_early_backends(void)qemu_opts_foreach (qemu_find_opts ("chardev" ), chardev_init_func,NULL , &error_fatal); +qemu_opts_foreach (qemu_find_opts ("gpiodev" ), + gpiodev_init_func,NULL , &error_fatal); +#ifdef CONFIG_VIRTFS qemu_opts_foreach (qemu_find_opts ("fsdev" ), fsdev_init_func,NULL , &error_fatal);
@@ -3241,6 +3259,13 @@ void qemu_init(int argc, char **argv)exit (1 ); }break ; +case QEMU_OPTION_gpiodev: + opts =qemu_opts_parse_noisily (qemu_find_opts ("gpiodev" ), + optarg, true); +if (!opts) { +exit (1 ); + } +break ;case QEMU_OPTION_fsdev: olist =qemu_find_opts ("fsdev" );if (!olist) {
Signature · 1 line
2.45.2
PATCH 3/7 gpiodev: Add GPIO device frontend
In reply to Nikita ShubinAdd GPIO device front end with helper functions to provide information about GPIO Port to Backends and to allow Frontend to set data.
To use it GPIO device should register with qemu_gpio_fe_init() and provide handlers with qemu_gpio_fe_set_handlers().
Notifications about config and changed value events should be done with qemu_gpio_fe_line_event() and qemu_gpio_fe_config_event().
--- gpiodev/gpio-fe.c | 103 ++++++++++++++++++ gpiodev/gpio.c | 264 +++++++++++++++++++++++++++++++++++++++++++++- gpiodev/meson.build | 1 + include/gpiodev/gpio-fe.h | 122 +++++++++++++++++++++ include/gpiodev/gpio.h | 200 ++++++++++++++++++++++++++++++++++- qom/object.c | 1 + 6 files changed, 684 insertions(+), 7 deletions(-)
gpiodev/gpio-fe.c new file +103 -0
@@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* QEMU GPIO device frontend. +* +* Author: 2025 Nikita Shubin <[email protected]> +* +*/ +#include "qemu/osdep.h" +#include "qemu/error-report.h" +#include "qapi/error.h" +#include "qapi/qmp/qerror.h" + +#include "gpiodev/gpio-fe.h" + +bool qemu_gpio_fe_init (GpioBackend *b,Gpiodev *s,uint32_t nlines, +const char *name,const char *label, +Error **errp) +{ +if (s->be) { + goto unavailable; + }else { + s->be = b; + } + +qemu_gpiodev_set_info (s, nlines, name, label); + b->gpio = s; + +return true; + +unavailable: +error_setg (errp,"chardev '%s' is already in use" , s->label); +return false; +} + +void qemu_gpio_fe_set_handlers (GpioBackend *b, +LineInfoHandler *line_info, +LineGetValueHandler *get_value, +LineSetValueHandler *set_value, +void *opaque) +{ +Gpiodev *s; + + s = b->gpio; +if (!s) { +return ; + } + + b->line_info = line_info; + b->get_value = get_value; + b->set_value = set_value; + b->opaque = opaque; +} + +bool qemu_gpio_fe_line_event (GpioBackend *b,uint32_t offset, +QEMUGpioLineEvent event) +{ +Gpiodev *gpio = b->gpio; + +if (!gpio) { +return false; + } + +qemu_gpio_line_event (gpio, offset, event); + +return true; +} + +bool qemu_gpio_fe_config_event (GpioBackend *b,uint32_t offset, +QEMUGpioConfigEvent event) +{ +Gpiodev *gpio = b->gpio; + +if (!gpio) { +return false; + } + +qemu_gpio_config_event (gpio, offset, event); + +return true; +} + +void qemu_gpio_fe_deinit (GpioBackend *b,bool del) +{ +assert (b); + +if (b->gpio) { +qemu_gpio_fe_set_handlers (b,NULL ,NULL ,NULL ,NULL ); +if (b->gpio->be == b) { + b->gpio->be =NULL ; + } + +if (del) { +Object *obj =OBJECT (b->gpio); +if (obj->parent) { +object_unparent (obj); + }else { +object_unref (obj); + } + } + + b->gpio =NULL ; + } +}
gpiodev/gpio.c +259 -5
335 lines not on this page · raw message
gpiodev/meson.build +1 -0
@@ -1,4 +1,5 @@ gpiodev_ss.add(files( + 'gpio-fe.c', 'gpio.c', ))
include/gpiodev/gpio-fe.h new file +122 -0
122 lines not on this page · raw message
include/gpiodev/gpio.h +198 -2
223 lines not on this page · raw message
qom/object.c +1 -0
@@ -1730,6 +1730,7 @@ const char *object_property_get_type(Object *obj, const char *name, Error **errpstatic const char *const root_containers[] = {"chardevs" , +"gpiodevs" ,"objects" ,"backend" };
Signature · 1 line
2.45.2
PATCH 4/7 gpiodev: Add GPIO backend over chardev
In reply to Nikita ShubinCurrently based on passing linux GPIO UAPI structs over UNIX socket.
This is more a PoC than a real application, still this is something to start with.
--- gpiodev/gpio-chardev.c | 479 +++++++++++++++++++++++++++++++++++++++++++++++++ gpiodev/meson.build | 1 + include/gpiodev/gpio.h | 2 + 3 files changed, 482 insertions(+)
gpiodev/gpio-chardev.c new file +479 -0
@@ -0,0 +1,479 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* QEMU GPIO Chardev based backend. +* +* Author: 2025 Nikita Shubin <[email protected]> +* +*/ +#include "qemu/osdep.h" +#include "qemu/module.h" +#include "qemu/option.h" +#include "qemu/log.h" +#include "qapi/error.h" +#include "gpiodev/gpio.h" +#include "chardev/char.h" +#include "chardev/char-fe.h" + +#include <linux/gpio.h> + +/* Taken from include/linux/circ_buf.h */ + +/* +* Return count in buffer. +*/ +#define CIRC_CNT (head, tail, size) (((head) - (tail)) & ((size) - 1)) + +/* +* Return space available, 0..size-1. We always leave one free char +* as a completely full buffer has head == tail, which is the same as +* empty. +*/ +#define CIRC_SPACE (head, tail, size) CIRC_CNT((tail), ((head) + 1), (size)) + +/* +* Return count up to the end of the buffer. Carefully avoid +* accessing head and tail more than once, so they can change +* underneath us without returning inconsistent results. +*/ +#define CIRC_CNT_TO_END (head, tail, size) \ + ({int end = (size) - (tail); \ + int n = ((head) + end) & ((size) - 1); \ + n < end ? n : end; }) + +/* +* Return space available up to the end of the buffer. +*/ +#define CIRC_SPACE_TO_END (head, tail, size) \ + ({int end = (size) - 1 - (head); \ + int n = (end + (tail)) & ((size) - 1); \ + n <= end ? n : end + 1; }) + + +typedef struct ChardevGpiodev { +Gpiodev parent; + +CharBackend chardev; +size_t size; +size_t prod; +size_t cons; +uint8_t *cbuf; + +struct gpio_v2_line_request last_request; +uint64_t mask; +}ChardevGpiodev ; + +DECLARE_INSTANCE_CHECKER (ChardevGpiodev,GPIODEV_CHARDEV , + TYPE_GPIODEV_CHARDEV) + +static void gpio_chardev_line_event (Gpiodev *g,uint32_t offset, +QEMUGpioLineEvent event) +{ +ChardevGpiodev *d =GPIODEV_CHARDEV (g); +struct gpio_v2_line_event changed = {0 }; +int ret; + + changed.timestamp_ns =qemu_clock_get_ns (QEMU_CLOCK_VIRTUAL ); + changed.id = event; + changed.offset = offset; + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&changed,sizeof (changed)); +if (ret !=sizeof (changed)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } +} + +static void gpio_chardev_config_event (Gpiodev *g,uint32_t offset, +QEMUGpioConfigEvent event) +{ +ChardevGpiodev *d =GPIODEV_CHARDEV (g); +struct gpio_v2_line_info_changed changed = {0 }; +int ret; + + changed.timestamp_ns =qemu_clock_get_ns (QEMU_CLOCK_VIRTUAL ); + changed.event_type = event; + changed.info.offset = offset; + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&changed,sizeof (changed)); +if (ret !=sizeof (changed)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } +} + +static int gpio_chardev_can_read (void *opaque) +{ +ChardevGpiodev *s =GPIODEV_CHARDEV (opaque); + +return CIRC_SPACE (s->prod, s->cons, s->size); +} + +static int gpio_chardev_send_chip_info (ChardevGpiodev *d) +{ +struct gpiochip_info info = {0 }; +int ret; + +qemu_gpio_chip_info (&d->parent, &info.lines, info.name, info.label); + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&info,sizeof (info)); +if (ret !=sizeof (info)) { +qemu_log_mask (LOG_GUEST_ERROR , +"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return 8 ; +} + +static int gpio_chardev_unwatch_line (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +uint32_t offset; + +memcpy (&offset, &buf[8 ],sizeof (offset)); +qemu_gpio_clear_event_watch (&d->parent, offset,-1ULL ); + +return 8 +4 ; +} + +static int gpio_chardev_send_line_info (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +struct gpio_v2_line_info info = {0 }; +gpio_line_info req = {0 }; +int ret; + +if (len <sizeof (info) +8 ) { +return -EAGAIN ; + } + +memcpy (&info, &buf[8 ],sizeof (info)); + req.offset = info.offset; +qemu_gpio_line_info (&d->parent, &req); + +g_strlcpy (info.name, req.name,GPIO_MAX_NAME_SIZE ); + info.flags = req.flags; + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&info,sizeof (info)); +if (ret !=sizeof (info)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return sizeof (info) +8 ; +} + +static int gpio_chardev_line_watch (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +struct gpio_v2_line_info info = {0 }; +int ret; + +if (len <sizeof (info) +8 ) { +return -EAGAIN ; + } + +memcpy (&info, &buf[8 ],sizeof (info)); +qemu_gpio_add_config_watch (&d->parent, info.offset); + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&info,sizeof (info)); +if (ret !=sizeof (info)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return sizeof (info) +8 ; +} + +static uint64_t gpio_chardev_get_flags (const struct gpio_v2_line_request *request) +{ +uint64_t req_flags = request->config.flags; +uint64_t flags =0 ; + +if (req_flags &GPIO_V2_LINE_FLAG_EDGE_RISING ) { + flags |=GPIO_EVENT_RISING_EDGE ; + } + +if (req_flags &GPIO_V2_LINE_FLAG_EDGE_FALLING ) { + flags |=GPIO_EVENT_FALLING_EDGE ; + } + +return flags; +} + +static int gpio_chardev_line_request (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +struct gpio_v2_line_request *req = &d->last_request; +uint64_t flags; +int ret, i; + +if (len <sizeof (*req) +8 ) { +return -EAGAIN ; + } + +/* unwatch lines before proccessing new request */ + d->mask =0 ; +for (i =0 ; i < req->num_lines; i++) { +qemu_gpio_clear_event_watch (&d->parent, req->offsets[i],-1ULL ); + } + +memcpy (req, &buf[8 ],sizeof (*req)); + flags =gpio_chardev_get_flags (req); +for (i =0 ; i < req->num_lines; i++) { +qemu_gpio_add_event_watch (&d->parent, req->offsets[i], flags); + d->mask |=BIT_ULL (req->offsets[i]); + } + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)req,sizeof (*req)); +if (ret !=sizeof (*req)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return sizeof (*req) +8 ; +} + +static int gpio_chardev_get_line_values (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +struct gpio_v2_line_request *req = &d->last_request; +struct gpio_v2_line_values values = {0 }; +int ret, idx; + +if (len < (sizeof (values) +8 )) { +return -EAGAIN ; + } + +memcpy (&values, &buf[8 ],sizeof (values)); + idx =find_first_bit ((unsigned long *)&values.mask, req->num_lines); +while (idx < req->num_lines) { + values.bits |=qemu_gpio_get_line_value (&d->parent, req->offsets[idx]); + idx =find_next_bit ((unsigned long *)&values.mask, req->num_lines, idx +1 ); + } + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&values,sizeof (values)); +if (ret !=sizeof (values)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return sizeof (values) +8 ; +} + +static int gpio_chardev_set_line_values (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +struct gpio_v2_line_request *req = &d->last_request; +struct gpio_v2_line_values values = {0 }; +int ret, idx; + +if (len <sizeof (values) +8 ) { +return -EAGAIN ; + } + +memcpy (&values, &buf[8 ],sizeof (values)); + idx =find_first_bit ((unsigned long *)&values.mask, req->num_lines); +while (idx < req->num_lines) { +qemu_gpio_set_line_value (&d->parent, req->offsets[idx], +test_bit (idx, (unsigned long *)&values.bits)); + idx =find_next_bit ((unsigned long *)&values.mask, req->num_lines, idx +1 ); + } + + ret =qemu_chr_fe_write (&d->chardev, (uint8_t *)&values,sizeof (values)); +if (ret !=sizeof (values)) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: failed writing %d bytes\n" , + __func__, ret); + } + +return sizeof (values) +8 ; +} + +static int gpio_chardev_consume_one (ChardevGpiodev *d,const uint8_t *buf, +size_t len) +{ +unsigned long ctl; +int ret; + +if (len <8 ) { +return -EAGAIN ; + } + +memcpy (&ctl, buf,8 ); +switch (ctl) { +case GPIO_GET_CHIPINFO_IOCTL : + ret =gpio_chardev_send_chip_info (d); +break ; +case GPIO_GET_LINEINFO_UNWATCH_IOCTL : + ret =gpio_chardev_unwatch_line (d, buf, len); +break ; +case GPIO_V2_GET_LINEINFO_IOCTL : + ret =gpio_chardev_send_line_info (d, buf, len); +break ; +case GPIO_V2_GET_LINEINFO_WATCH_IOCTL : + ret =gpio_chardev_line_watch (d, buf, len); +break ; +case GPIO_V2_GET_LINE_IOCTL : + ret =gpio_chardev_line_request (d, buf, len); +break ; +case GPIO_V2_LINE_GET_VALUES_IOCTL : + ret =gpio_chardev_get_line_values (d, buf, len); +break ; +case GPIO_V2_LINE_SET_VALUES_IOCTL : + ret =gpio_chardev_set_line_values (d, buf, len); +break ; +case GPIO_V2_LINE_SET_CONFIG_IOCTL : +default : +qemu_log_mask (LOG_GUEST_ERROR ,"%s: unknow ctl=%lx\n" , + __func__, ctl); +return -EINVAL ; + }; + +return ret; +} + +static void gpio_chardev_consume (ChardevGpiodev *d,size_t len) +{ + g_autofree guint8 *buf; +size_t t_cons = d->cons; +int i, ret, pos =0 ; +size_t left = len; + + buf =g_malloc (len); + +for (i =0 ; i < len && t_cons != d->prod; i++) { + buf[i] = d->cbuf[t_cons++ & (d->size -1 )]; + } + +do { + ret =gpio_chardev_consume_one (d, &buf[pos], left); +if (ret >0 ) { + left -= ret; + pos += ret; + } + }while (ret >0 ); + +/* advance */ + d->cons += pos; +qemu_chr_fe_accept_input (&d->chardev); +} + +static void gpio_chardev_read (void *opaque,const uint8_t *buf,int len) +{ +ChardevGpiodev *d =GPIODEV_CHARDEV (opaque); +int i; + +if (!buf || (len <0 )) { +return ; + } + +for (i =0 ; i < len; i++) { + d->cbuf[d->prod++ & (d->size -1 )] = buf[i]; +if (d->prod - d->cons > d->size) { + d->cons = d->prod - d->size; + } + } + +gpio_chardev_consume (d,CIRC_CNT (d->prod, d->cons, d->size)); +} + +static void gpio_chardev_event (void *opaque,QEMUChrEvent event) +{ +ChardevGpiodev *d =GPIODEV_CHARDEV (opaque); + +if (event ==CHR_EVENT_OPENED ) { + d->prod =0 ; + d->cons =0 ; + +/* remove watches */ +qemu_gpio_clear_watches (&d->parent); + } +} + +static void gpio_chardev_open (Gpiodev *gpio,GpiodevBackend *backend, +Error **errp) +{ +GpiodevChardev *opts = backend->u.chardev.data; +ChardevGpiodev *d =GPIODEV_CHARDEV (gpio); +Object *chr_backend; +Chardev *chr =NULL ; + + d->size = opts->has_size ? opts->size :65536 ; + +/* The size must be power of 2 */ +if (d->size & (d->size -1 )) { +error_setg (errp,"size of ringbuf chardev must be power of two" ); +return ; + } + + chr_backend =object_resolve_path_type (opts->chardev,TYPE_CHARDEV ,NULL ); +if (chr_backend) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: %s got backend\n" , + __func__, opts->chardev); + chr =qemu_chr_find (opts->chardev); + } + +if (!chr) { +error_setg (errp,"gpiodev: chardev: no chardev %s not found" , opts->chardev); +return ; + } + + d->cbuf =g_malloc0 (d->size); + +qemu_chr_fe_init (&d->chardev, chr,NULL ); +qemu_chr_fe_set_handlers (&d->chardev, + gpio_chardev_can_read, + gpio_chardev_read, + gpio_chardev_event,NULL , d,NULL , true); +} + +static void gpio_chardev_parse (QemuOpts *opts,GpiodevBackend *backend, +Error **errp) +{ +const char *chardev =qemu_opt_get (opts,"chardev" ); +GpiodevChardev *gchardev; +int val; + +if (chardev ==NULL ) { +error_setg (errp,"gpiodev: chardev: no chardev id given" ); +return ; + } + + backend->type =GPIODEV_BACKEND_KIND_CHARDEV ; + gchardev = backend->u.chardev.data =g_new0 (GpiodevChardev,1 ); + val =qemu_opt_get_size (opts,"size" ,0 ); +if (val !=0 ) { + gchardev->has_size = true; + gchardev->size = val; + } + gchardev->chardev =g_strdup (chardev); +} + +static void gpio_chardev_finalize (Object *obj) +{ +ChardevGpiodev *d =GPIODEV_CHARDEV (obj); + +g_free (d->cbuf); +} + +static void gpio_chardev_class_init (ObjectClass *oc,void *data) +{ +GpiodevClass *cc =GPIODEV_CLASS (oc); + + cc->parse = &gpio_chardev_parse; + cc->open = &gpio_chardev_open; + cc->line_event = &gpio_chardev_line_event; + cc->config_event = &gpio_chardev_config_event; +} + +static const TypeInfo gpio_chardev_type_info[] = { + { + .name =TYPE_GPIODEV_CHARDEV , + .parent =TYPE_GPIODEV , + .class_init = gpio_chardev_class_init, + .instance_size =sizeof (ChardevGpiodev), + .instance_finalize = gpio_chardev_finalize, + }, +}; + +DEFINE_TYPES (gpio_chardev_type_info); +
gpiodev/meson.build +1 -0
@@ -1,4 +1,5 @@ gpiodev_ss.add(files( + 'gpio-chardev.c', 'gpio-fe.c', 'gpio.c', ))
include/gpiodev/gpio.h +2 -0
@@ -55,6 +55,8 @@ struct Gpiodev {#define TYPE_GPIODEV "gpiodev" OBJECT_DECLARE_TYPE(Gpiodev, GpiodevClass, GPIODEV) +#define TYPE_GPIODEV_CHARDEV "gpiodev-chardev" +struct GpiodevClass {ObjectClass parent_class;
Signature · 1 line
2.45.2
PATCH 5/7 hw/gpio/aspeed: Add gpiodev support
In reply to Nikita ShubinAdd gpiodev support for:
- getting line info
- getting/setting lines
- monitoring line events
- monitoting config events
Binding is done via id, i.e.:
... -gpiodev chardev,id=aspeed-gpio0
--- hw/gpio/aspeed_gpio.c | 127 ++++++++++++++++++++++++++++++++++++++++++ include/hw/gpio/aspeed_gpio.h | 3 + 2 files changed, 130 insertions(+)
hw/gpio/aspeed_gpio.c +127 -0
@@ -291,6 +291,8 @@ static int aspeed_evaluate_irq(GPIOSets *regs, int gpio_prev_high, int gpio)return 0 ; } +static void aspeed_gpio_line_event (AspeedGPIOState *s,uint32_t set_idx,uint32_t pin_idx); +#define nested_struct_index (ta, pa, m, tb, pb) \ (pb - ((tb *)(((char *)pa) + offsetof(ta, m))))
@@ -337,6 +339,9 @@ static void aspeed_gpio_update(AspeedGPIOState *s, GPIOSets *regs,/* ...trigger the line-state IRQ */ ptrdiff_t set =aspeed_gpio_set_idx (s, regs);qemu_set_irq (s->gpios[set][gpio], !!(new & mask)); + +/* ...notify gpio backend if any */ +aspeed_gpio_line_event (s, set, gpio); }else {/* ...otherwise if we meet the line's current IRQ policy... */ if (aspeed_evaluate_irq (regs, old & mask, gpio)) {
@@ -360,6 +365,18 @@ static bool aspeed_gpio_get_pin_level(AspeedGPIOState *s, uint32_t set_idx,return !!(reg_val & pin_mask); } +static void aspeed_gpio_line_event (AspeedGPIOState *s,uint32_t set_idx,uint32_t pin_idx) +{ +uint32_t offset = set_idx *ASPEED_GPIOS_PER_SET + pin_idx; +QEMUGpioLineEvent event =GPIO_EVENT_FALLING_EDGE ; + +if (aspeed_gpio_get_pin_level (s, set_idx, pin_idx)) { + event =GPIO_EVENT_RISING_EDGE ; + } + +qemu_gpio_fe_line_event (&s->gpiodev, offset, event); +} +static void aspeed_gpio_set_pin_level (AspeedGPIOState *s,uint32_t set_idx,uint32_t pin,bool level) {
@@ -659,6 +676,13 @@ static uint64_t aspeed_gpio_read(void *opaque, hwaddr offset, uint32_t size)return value; } +static void aspeed_gpio_config_event (AspeedGPIOState *s,uint32_t set_idx,uint32_t pin_idx) +{ +uint32_t offset = set_idx *ASPEED_GPIOS_PER_SET + pin_idx; + +qemu_gpio_fe_config_event (&s->gpiodev, offset,GPIO_LINE_CHANGED_CONFIG ); +} +static void aspeed_gpio_write_index_mode (void *opaque,hwaddr offset,uint64_t data,uint32_t size) {
@@ -674,6 +698,7 @@ static void aspeed_gpio_write_index_mode(void *opaque, hwaddr offset,uint32_t group_idx = pin_idx /GPIOS_PER_GROUP ;uint32_t reg_value =0 ;uint32_t pending =0 ; +uint32_t old_direction; set = &s->sets[set_idx]; props = &agc->props[set_idx];
@@ -711,8 +736,12 @@ static void aspeed_gpio_write_index_mode(void *opaque, hwaddr offset,* data = ( data | ~input) & output; */ reg_value = (reg_value | ~props->input) & props->output; + old_direction = set->direction; set->direction =update_value_control_source (set, set->direction, reg_value); +if (set->direction != old_direction) { +aspeed_gpio_config_event (s, set_idx, pin_idx); + }break ;case gpio_reg_idx_interrupt: reg_value = set->int_enable;
@@ -813,6 +842,7 @@ static void aspeed_gpio_write(void *opaque, hwaddr offset, uint64_t data,const AspeedGPIOReg *reg;GPIOSets *set;uint32_t cleared; +uint32_t old_direction;trace_aspeed_gpio_write (offset, data);
@@ -867,7 +897,17 @@ static void aspeed_gpio_write(void *opaque, hwaddr offset, uint64_t data,* data = ( data | ~input) & output; */ data = (data | ~props->input) & props->output; + old_direction = set->direction; set->direction =update_value_control_source (set, set->direction, data); +qemu_log ("gpio_reg_direction: 0x%x 0x%x\n" , set->direction, old_direction); +if (set->direction != old_direction) { +unsigned long changed = set->direction ^ old_direction; +int idx =find_first_bit (&changed,ASPEED_GPIOS_PER_SET ); +while (idx <ASPEED_GPIOS_PER_SET ) { +aspeed_gpio_config_event (s, reg->set_idx, idx); + idx =find_next_bit (&changed,ASPEED_GPIOS_PER_SET , idx +1 ); + } + }break ;case gpio_reg_int_enable: set->int_enable = update_value_control_source(set, set->int_enable,
@@ -1392,11 +1432,85 @@ static void aspeed_gpio_reset(DeviceState *dev)memset (s->sets,0 ,sizeof (s->sets)); } +static void aspeed_gpio_line_info (void *opaque,gpio_line_info *info) +{ +AspeedGPIOState *s =ASPEED_GPIO (opaque); +AspeedGPIOClass *agc =ASPEED_GPIO_GET_CLASS (s); +uint32_t group_idx =0 , pin_idx =0 , idx =0 ; +uint32_t offset = info->offset; +const GPIOSetProperties *props; +bool direction; +const char *group; +int i, set_idx, grp_idx, pin; + +for (i =0 ; i <ASPEED_GPIO_MAX_NR_SETS ; i++) { + props = &agc->props[i]; +uint32_t skip = ~(props->input | props->output); +for (int j =0 ; j <ASPEED_GPIOS_PER_SET ; j++) { +if (skip >> j &1 ) { +continue ; + } + + group_idx = j /GPIOS_PER_GROUP ; + pin_idx = j %GPIOS_PER_GROUP ; +if (idx == offset) { + goto found; + } + + idx++; + } + } + +return ; + +found: + group = &props->group_label[group_idx][0 ]; + set_idx =get_set_idx (s, group, &grp_idx); +snprintf (info->name,sizeof (info->name),"gpio%s%d" , group, pin_idx); + pin = pin_idx + group_idx *GPIOS_PER_GROUP ; + direction = !!(s->sets[set_idx].direction &BIT_ULL (pin)); + +if (direction) { + info->flags |=GPIO_LINE_FLAG_OUTPUT ; + }else { + info->flags |=GPIO_LINE_FLAG_INPUT ; + } + +qemu_log ("%u: %s: set_idx=%d, grp_idx=%d, group_idx=%u, pin_idx=%u\n" , offset, info->name, set_idx, grp_idx, group_idx, pin_idx); +} + +static int aspeed_gpio_get_line (void *opaque,uint32_t offset) +{ +AspeedGPIOState *s =ASPEED_GPIO (opaque); +int set_idx, pin_idx; + + set_idx = offset /ASPEED_GPIOS_PER_SET ; + pin_idx = offset %ASPEED_GPIOS_PER_SET ; + +return aspeed_gpio_get_pin_level (s, set_idx, pin_idx); +} + +static int aspeed_gpio_set_line (void *opaque,uint32_t offset,uint8_t value) +{ +AspeedGPIOState *s =ASPEED_GPIO (opaque); +int set_idx, pin_idx; + + set_idx = offset /ASPEED_GPIOS_PER_SET ; + pin_idx = offset %ASPEED_GPIOS_PER_SET ; + +aspeed_gpio_set_pin_level (s, set_idx, pin_idx, value); + +return 0 ; +} +static void aspeed_gpio_realize (DeviceState *dev,Error **errp) {AspeedGPIOState *s =ASPEED_GPIO (dev);SysBusDevice *sbd =SYS_BUS_DEVICE (dev);AspeedGPIOClass *agc =ASPEED_GPIO_GET_CLASS (s); +DeviceState *d =DEVICE (s); +Object *backend; +Gpiodev *gpio;/* Interrupt parent line */ sysbus_init_irq (sbd, &s->irq);
@@ -1417,6 +1531,19 @@ static void aspeed_gpio_realize(DeviceState *dev, Error **errp) TYPE_ASPEED_GPIO, agc->mem_size);sysbus_init_mmio (sbd, &s->iomem); + +/* NOTE: or we can create one per set */ +if (d->id) { + backend =object_resolve_path_type (d->id,TYPE_GPIODEV ,NULL ); +if (backend) { + gpio =GPIODEV (backend); +qemu_gpio_fe_init (&s->gpiodev, gpio, agc->nr_gpio_pins, d->id, +"ASPEED GPIO" ,NULL ); +qemu_gpio_fe_set_handlers (&s->gpiodev, aspeed_gpio_line_info, + aspeed_gpio_get_line, + aspeed_gpio_set_line, s); + } + } }static void aspeed_gpio_init (Object *obj)
include/hw/gpio/aspeed_gpio.h +3 -0
@@ -12,6 +12,8 @@#include "hw/sysbus.h" #include "qom/object.h" +#include "gpiodev/gpio.h" +#include "gpiodev/gpio-fe.h" #define TYPE_ASPEED_GPIO "aspeed.gpio"OBJECT_DECLARE_TYPE (AspeedGPIOState, AspeedGPIOClass,ASPEED_GPIO )
@@ -85,6 +87,7 @@ struct AspeedGPIOState {SysBusDevice parent;/*< public >*/ +GpioBackend gpiodev;MemoryRegion iomem;int pending;qemu_irq irq;
Signature · 1 line
2.45.2
PATCH 6/7 hw/arm: ast2600: set id for gpio
In reply to Nikita ShubinSet device id for gpios to allow gpiodev binding.
--- hw/arm/aspeed_ast2600.c | 2 ++ 1 file changed, 2 insertions(+)
hw/arm/aspeed_ast2600.c +2 -0
@@ -537,6 +537,7 @@ static void aspeed_soc_ast2600_realize(DeviceState *dev, Error **errp) aspeed_soc_get_irq(s, ASPEED_DEV_XDMA));/* GPIO */ +DEVICE (&s->gpio)->id =g_strdup ("aspeed-gpio0" );if (!sysbus_realize (SYS_BUS_DEVICE (&s->gpio), errp)) {return ; }
@@ -545,6 +546,7 @@ static void aspeed_soc_ast2600_realize(DeviceState *dev, Error **errp)sysbus_connect_irq (SYS_BUS_DEVICE (&s->gpio),0 ,aspeed_soc_get_irq (s,ASPEED_DEV_GPIO )); +DEVICE (&s->gpio_1_8v)->id =g_strdup ("aspeed-gpio1" );if (!sysbus_realize (SYS_BUS_DEVICE (&s->gpio_1_8v), errp)) {return ; }
Signature · 1 line
2.45.2
PATCH 7/7 gpiodev: Add gpiobackend over GUSE
In reply to Nikita ShubinAdd GUSE (FUSE based kernel module similiar to CUSE) based backend.
This allows transparent usage of Linux GPIO UAPI based tools like in kernel tools/gpio or libgpiod.
libgpiod requires some modification to allow "/sys/class/guse" in gpiod_check_gpiochip_device().
It requires guse module to be loaded and providing DEVICE()->id for GPIO module, for example:
```
DEVICE(&s->gpio)->id = g_strdup("aspeed-gpio0");
```The id should be provided to gpiodev with any devname that doesn't exists in /dev:
``` -gpiodev guse,id=aspeed-gpio0,devname=gpiochip10 ```
That /dev/gpiochip10 can be used in the same way we usually operate with gpiochip's.
--- gpiodev/gpio-guse.c | 747 +++++++++++++++++++++++++++++++++++++++++++++++++ gpiodev/meson.build | 1 + include/gpiodev/gpio.h | 1 + qapi/gpio.json | 31 +- 4 files changed, 777 insertions(+), 3 deletions(-)
gpiodev/gpio-guse.c new file +747 -0
@@ -0,0 +1,747 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* QEMU GPIO GUSE based backend. +* +* Author: 2025 Nikita Shubin <[email protected]> +* +*/ +#include "qemu/osdep.h" +#include "qemu/module.h" +#include "qemu/option.h" +#include "qemu/log.h" +#include "qemu/lockable.h" +#include "qapi/error.h" +#include "gpiodev/gpio.h" +#include "chardev/char.h" +#include "chardev/char-fe.h" + +#define FUSE_USE_VERSION 31 +#include <fuse.h> +#include <fuse_lowlevel.h> +#include <guse_lowlevel.h> +#undef FUSE_USE_VERSION + +#include <poll.h> +#include <linux/gpio.h> + +#define GUSE_DEVICE_INODE_FLAG BIT_ULL(63) +#define GUSE_MAX_WATCH 64 +#define GUSE_MAX_EVENTS 64 + +typedef struct GusedevLineWatch { +uint64_t i_node; +struct fuse_pollhandle *ph; + +/* since we can have multiply requests per device we need own masks */ +struct { +unsigned long risen; +unsigned long fallen; + +/* special for GPIO_V2_LINE_FLAG_OUTPUT */ +unsigned long mask; + } mask; + +/* required to match mask with actual offsets */ +uint32_t num_lines; +uint32_t offsets[GPIO_V2_LINES_MAX ]; + +QemuMutex event_lock; +uint32_t num_events; +struct gpio_v2_line_event events[GUSE_MAX_EVENTS ]; + +QSIMPLEQ_ENTRY (GusedevLineWatch) next; +}GusedevLineWatch ; + +typedef struct GusedevConfigWatch { +uint64_t i_node; +struct fuse_pollhandle *ph; + +unsigned long *mask; + +uint32_t num_events; +struct gpio_v2_line_info_changed events[GUSE_MAX_EVENTS ]; +QSIMPLEQ_ENTRY (GusedevConfigWatch) next; +}GusedevConfigWatch ; + +typedef struct GusedevGpiodev { +Gpiodev parent; + +char *devname; +struct fuse_session *fuse_session; +struct fuse_buf fuse_buf; + +QemuMutex linereq_lock; + QSIMPLEQ_HEAD(, GusedevLineWatch) linereq; + +QemuMutex configreq_lock; + QSIMPLEQ_HEAD(, GusedevConfigWatch) configreq; +}GusedevGpiodev ; + +DECLARE_INSTANCE_CHECKER (GusedevGpiodev,GPIODEV_GUSEDEV , + TYPE_GPIODEV_GUSEDEV) + +static GusedevLineWatch *gpio_gusedev_find_linereq (GusedevGpiodev *d,uint64_t i_node) +{ +GusedevLineWatch *e; + + QSIMPLEQ_FOREACH(e, &d->linereq, next) { +if (e->i_node == i_node) { +return e; + } + } + +return NULL ; +} + +static GusedevLineWatch *gpio_gusedev_allocate_linereq (GusedevGpiodev *d,uint64_t i_node) +{ +GusedevLineWatch *e =g_new0 (GusedevLineWatch,1 ); + + e->i_node = i_node; + +QSIMPLEQ_INSERT_TAIL (&d->linereq, e, next); + +return e; +} + +static void gpio_gusedev_free_linereq (GusedevGpiodev *d,GusedevLineWatch *w) +{ +GusedevLineWatch *entry, *next; + + QSIMPLEQ_FOREACH_SAFE(entry, &d->linereq, next, next) { +if (entry->i_node == w->i_node) { +QSIMPLEQ_REMOVE (&d->linereq, entry, GusedevLineWatch, next); +if (entry->ph) { +fuse_pollhandle_destroy (entry->ph); + } +g_free (entry); + } + } +} + +static GusedevConfigWatch *gpio_gusedev_find_configreq (GusedevGpiodev *d,uint64_t i_node) +{ +GusedevConfigWatch *e; + + QSIMPLEQ_FOREACH(e, &d->configreq, next) { +if (e->i_node == i_node) { +return e; + } + } + +return NULL ; +} + +static GusedevConfigWatch *gpio_gusedev_allocate_configreq (GusedevGpiodev *d, +uint64_t i_node) +{ +GusedevConfigWatch *e =g_new0 (GusedevConfigWatch,1 ); + + e->i_node = i_node; + e->mask =bitmap_new (d->parent.lines); + +QSIMPLEQ_INSERT_TAIL (&d->configreq, e, next); + +return e; +} + +static void gpio_gusedev_free_configreq (GusedevGpiodev *d, +GusedevConfigWatch *w) +{ +GusedevConfigWatch *entry, *next; + + QSIMPLEQ_FOREACH_SAFE(entry, &d->configreq, next, next) { +if (entry->i_node == w->i_node) { +QSIMPLEQ_REMOVE (&d->configreq, entry, GusedevConfigWatch, next); +if (entry->ph) { +fuse_pollhandle_destroy (entry->ph); + } +g_free (entry->mask); +g_free (entry); + } + } +} + +static inline uint64_t timespec_to_ns (struct timespec ts) +{ +return (uint64_t )ts.tv_nsec +1000000000ULL * (uint64_t )ts.tv_sec; +} + +static void gpio_gusedev_push_config (GusedevGpiodev *d,uint32_t offset, +enum gpio_v2_line_changed_type event) +{ +GusedevConfigWatch *e; +struct timespec ts; +uint64_t ts_ns; + +timespec_get (&ts,TIME_UTC ); + ts_ns =timespec_to_ns (ts); + +QEMU_LOCK_GUARD (&d->configreq_lock); + QSIMPLEQ_FOREACH(e, &d->configreq, next) { +if (test_bit (offset, e->mask)) { +struct gpio_v2_line_info_changed *changed; +uint32_t num_events = e->num_events; +if (++num_events >GUSE_MAX_EVENTS ) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: max config events number exeeded\n" , + __func__); +continue ; + } + + changed = &e->events[e->num_events]; + changed->timestamp_ns = ts_ns; + changed->event_type = event; + changed->info.offset = offset; + + e->num_events = num_events; + +if (e->ph) { +fuse_notify_poll (e->ph); +fuse_pollhandle_destroy (e->ph); + e->ph =NULL ; + } + } + } +} + +static void gpio_gusedev_push_event (GusedevGpiodev *d,uint32_t offset, +enum gpio_v2_line_event_id event) +{ +GusedevLineWatch *e; +struct timespec ts; +uint64_t ts_ns; + +timespec_get (&ts,TIME_UTC ); + ts_ns =timespec_to_ns (ts); + +QEMU_LOCK_GUARD (&d->linereq_lock); + QSIMPLEQ_FOREACH(e, &d->linereq, next) { +bool notify = false; +if ((event &GPIO_V2_LINE_EVENT_RISING_EDGE ) + &&test_bit (offset, &e->mask.risen)) { + notify = true; + } + +if ((event &GPIO_V2_LINE_EVENT_FALLING_EDGE ) + &&test_bit (offset, &e->mask.fallen)) { + notify = true; + } + +if (notify) { +struct gpio_v2_line_event *info; +uint32_t num_events = e->num_events; +if (++num_events >GUSE_MAX_EVENTS ) { +qemu_log_mask (LOG_GUEST_ERROR ,"%s: max config events number exeeded\n" , + __func__); +continue ; + } + + info = &e->events[e->num_events]; + info->timestamp_ns = ts_ns; + info->id = event; + info->offset = offset; + + e->num_events = num_events; + +if (e->ph) { +fuse_notify_poll (e->ph); +fuse_pollhandle_destroy (e->ph); + e->ph =NULL ; + } + } + } +} + +static void gpio_gusedev_line_event (Gpiodev *g,uint32_t offset, +QEMUGpioLineEvent event) +{ +GusedevGpiodev *d =GPIODEV_GUSEDEV (g); + +gpio_gusedev_push_event (d, offset, (enum gpio_v2_line_event_id )event); +} + +static void gpio_gusedev_config_event (Gpiodev *g,uint32_t offset, +QEMUGpioConfigEvent event) +{ +GusedevGpiodev *d =GPIODEV_GUSEDEV (g); + +gpio_gusedev_push_config (d, offset, (enum gpio_v2_line_changed_type )event); +} + +static void gusedev_init (void *userdata,struct fuse_conn_info *conn) +{ + (void )userdata; + +/* Disable the receiving and processing of FUSE_INTERRUPT requests */ + conn->no_interrupt =1 ; +} + +static void gusedev_destroy (void *private_data) +{ + (void )private_data; +} + +static void gusedev_open (fuse_req_t req,fuse_ino_t ino, +struct fuse_file_info *fi) +{ +fuse_reply_open (req, fi); +} + +static void gusedev_release (fuse_req_t req,fuse_ino_t ino, +struct fuse_file_info *fi) +{ +GusedevGpiodev *d =fuse_req_userdata (req); + +if (ino &GUSE_DEVICE_INODE_FLAG ) { +GusedevConfigWatch *e; + + e =gpio_gusedev_find_configreq (d, ino); +if (e) { +gpio_gusedev_free_configreq (d, e); + } + }else { +GusedevLineWatch *e; + + e =gpio_gusedev_find_linereq (d, ino); +if (e) { +gpio_gusedev_free_linereq (d, e); + } + } + +fuse_reply_err (req,0 ); +} + +static void gusedev_read (fuse_req_t req,fuse_ino_t ino,size_t size,off_t off, +struct fuse_file_info *fi) +{ +GusedevGpiodev *d =fuse_req_userdata (req); + +if (ino &GUSE_DEVICE_INODE_FLAG ) { +GusedevConfigWatch *e; + + e =gpio_gusedev_find_configreq (d, ino); +if (e && e->num_events) { +fuse_reply_buf (req, (char *)&e->events,sizeof (e->events[0 ]) * e->num_events); + e->num_events =0 ; +return ; + } + }else { +GusedevLineWatch *e; + + e =gpio_gusedev_find_linereq (d, ino); +if (e && e->num_events) { +fuse_reply_buf (req, (char *)&e->events,sizeof (e->events[0 ]) * e->num_events); + e->num_events =0 ; +return ; + } + } + +fuse_reply_buf (req,NULL ,0 ); +} + +static void gusedev_poll_config (fuse_req_t req,fuse_ino_t ino,struct fuse_file_info *fi, +struct fuse_pollhandle *ph) +{ +GusedevGpiodev *d =fuse_req_userdata (req); +GusedevConfigWatch *e; + +QEMU_LOCK_GUARD (&d->configreq_lock); + e =gpio_gusedev_find_configreq (d, ino); +if (!e) { +fuse_reply_poll (req,POLLERR ); +return ; + } + +if (ph) { +if (e->ph) { +fuse_pollhandle_destroy (e->ph); + } + + e->ph = ph; + } + +if (e->num_events) { +fuse_reply_poll (req,POLLIN ); + }else { +fuse_reply_poll (req,0 ); + } +} + +static void gusedev_poll_line (fuse_req_t req,fuse_ino_t ino,struct fuse_file_info *fi, +struct fuse_pollhandle *ph) +{ +GusedevGpiodev *d =fuse_req_userdata (req); +GusedevLineWatch *e; + +QEMU_LOCK_GUARD (&d->linereq_lock); + e =gpio_gusedev_find_linereq (d, ino); +if (!e) { +fuse_reply_poll (req,POLLERR ); +return ; + } + +if (ph) { +if (e->ph) { +fuse_pollhandle_destroy (e->ph); + } + + e->ph = ph; + } + +if (e->num_events) { +fuse_reply_poll (req,POLLIN ); + }else { +fuse_reply_poll (req,0 ); + } +} + +static void gusedev_poll (fuse_req_t req,fuse_ino_t ino,struct fuse_file_info *fi, +struct fuse_pollhandle *ph) +{ +if (ino &GUSE_DEVICE_INODE_FLAG ) { +gusedev_poll_config (req, ino, fi, ph); + }else { +gusedev_poll_line (req, ino, fi, ph); + } +} + +static int gusedev_chipinfo (fuse_req_t req) +{ +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpiochip_info info = {0 }; + +qemu_gpio_chip_info (&d->parent, &info.lines, info.name, info.label); + +return fuse_reply_ioctl (req,0 , &info,sizeof (info)); +} + +static int gusedev_lineinfo (fuse_req_t req,const void *in_buf) +{ +struct gpio_v2_line_info *in = (struct gpio_v2_line_info *)in_buf; +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpio_v2_line_info reply = {0 }; +uint32_t offset = in->offset; +gpio_line_info info = {0 }; + +if (offset > d->parent.lines) { +return fuse_reply_err (req,EINVAL ); + } + + info.offset = offset; +qemu_gpio_line_info (&d->parent, &info); +g_strlcpy (reply.name, info.name,GPIO_MAX_NAME_SIZE ); + reply.flags = info.flags; + +return fuse_reply_ioctl (req,0 , &reply,sizeof (reply)); +} + +static int gusedev_linerequest (fuse_req_t req,fuse_ino_t ino, +const void *in_buf) +{ +struct gpio_v2_line_request *in = (struct gpio_v2_line_request *)in_buf; +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpio_v2_line_request reply; +GusedevLineWatch *watch; +int i; + +/* line request not available for device inode */ +if (ino &GUSE_DEVICE_INODE_FLAG ) { +return fuse_reply_err (req,EINVAL ); + } + + watch =gpio_gusedev_allocate_linereq (d, ino); +if (!watch) { +return fuse_reply_err (req,ENOMEM ); + } + +for (i =0 ; i < in->num_lines; i++) { +bool notify = false; + +if (in->config.flags &GPIO_V2_LINE_FLAG_INPUT ) { +if (in->config.flags &GPIO_V2_LINE_FLAG_EDGE_RISING ) { + watch->mask.risen |=BIT_ULL (in->offsets[i]); +qemu_gpio_add_event_watch (&d->parent, in->offsets[i], +GPIO_EVENT_RISING_EDGE ); + notify = true; + } + +if (in->config.flags &GPIO_V2_LINE_FLAG_EDGE_FALLING ) { + watch->mask.fallen |=BIT_ULL (in->offsets[i]); +qemu_gpio_add_event_watch (&d->parent, in->offsets[i], +GPIO_EVENT_FALLING_EDGE ); + notify = true; + } +/* TODO: check if lines are input and don't allow to change direction */ + }else if (in->config.flags &GPIO_V2_LINE_FLAG_OUTPUT ) { + watch->mask.mask |=BIT_ULL (in->offsets[i]); + } + +/* dispatch config change event */ +if (notify) { +gpio_gusedev_push_config (d, in->offsets[i], +GPIO_V2_LINE_CHANGED_REQUESTED ); + } + } + +memcpy (&reply, in_buf,sizeof (reply)); + +return fuse_reply_ioctl (req,0 , &reply,sizeof (reply)); +} + +static int gusedev_get_line_values (fuse_req_t req,fuse_ino_t ino, +const void *in_buf) +{ +struct gpio_v2_line_values *values = (struct gpio_v2_line_values *)in_buf; +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpio_v2_line_values reply = {0 }; +GusedevLineWatch *e; +int idx; + + e =gpio_gusedev_find_linereq (d, ino); +if (!e) { +return fuse_reply_err (req,EINVAL ); + } + + idx =find_first_bit ((unsigned long *)values->mask, e->num_lines); +while (idx < e->num_lines) { + reply.bits |=qemu_gpio_get_line_value (&d->parent, e->offsets[idx]); + idx =find_next_bit ((unsigned long *)values->mask, e->num_lines, idx +1 ); + } + + reply.mask = values->mask; + +return fuse_reply_ioctl (req,0 , &reply,sizeof (reply)); +} + +/* TODO: merge with gusedev_set_line_values() */ +static int gusedev_set_line_values (fuse_req_t req,fuse_ino_t ino, +const void *in_buf) +{ +struct gpio_v2_line_values *values = (struct gpio_v2_line_values *)in_buf; +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpio_v2_line_values reply = {0 }; +GusedevLineWatch *e; +int idx; + + e =gpio_gusedev_find_linereq (d, ino); +if (!e) { +return fuse_reply_err (req,EINVAL ); + } + + idx =find_first_bit ((unsigned long *)&values->mask, e->num_lines); +while (idx < e->num_lines) { +uint8_t bit =test_bit (idx, (unsigned long *)&values->bits); +qemu_gpio_set_line_value (&d->parent, e->offsets[idx], bit); + idx =find_next_bit ((unsigned long *)&values->mask, e->num_lines, idx +1 ); + } + + reply.bits = values->bits; + reply.mask = values->mask; + +return fuse_reply_ioctl (req,0 , &reply,sizeof (reply)); +} + +static int gusedev_set_line_watch (fuse_req_t req,fuse_ino_t ino, +const void *in_buf,bool watch) +{ +struct gpio_v2_line_info *info = (struct gpio_v2_line_info *)in_buf; +GusedevGpiodev *d =fuse_req_userdata (req); +struct gpio_v2_line_info reply = {0 }; +GusedevConfigWatch *e; + + e =gpio_gusedev_find_configreq (d, ino); + +/* +* If not found allocate it, because unlike linereq configreq is added separately +* per each line. +*/ +if (!e) { + e =gpio_gusedev_allocate_configreq (d, ino); + } + +if (watch) { +qemu_gpio_add_config_watch (&d->parent, info->offset); +set_bit (info->offset, e->mask); + }else { +qemu_gpio_clear_config_watch (&d->parent, info->offset); +clear_bit (info->offset, e->mask); + } + +memcpy (&reply, info,sizeof (reply)); + +return fuse_reply_ioctl (req,0 , &reply,sizeof (reply)); +} + +static void gusedev_ioctl (fuse_req_t req,fuse_ino_t ino,unsigned int cmd, +void *arg,struct fuse_file_info *fi,unsigned flags, +const void *in_buf,size_t in_bufsz,size_t out_bufsz) +{ +bool add_watch = false; +int ret; + +if (flags &FUSE_IOCTL_COMPAT ) { +fuse_reply_err (req,ENOSYS ); +return ; + } + +switch (cmd) { +case GPIO_GET_CHIPINFO_IOCTL : + ret =gusedev_chipinfo (req); +break ; +case GPIO_V2_GET_LINEINFO_IOCTL : + ret =gusedev_lineinfo (req, in_buf); +break ; +/* GPIO_V2_GET_LINE_IOCTL is also processed by guse module. */ +case GPIO_V2_GET_LINE_IOCTL : + ret =gusedev_linerequest (req, ino, in_buf); +break ; +case GPIO_V2_LINE_GET_VALUES_IOCTL : + ret =gusedev_get_line_values (req, ino, in_buf); +break ; +case GPIO_V2_LINE_SET_VALUES_IOCTL : + ret =gusedev_set_line_values (req, ino, in_buf); +break ; +case GPIO_V2_GET_LINEINFO_WATCH_IOCTL : + add_watch = true; +/* fallthrough */ +case GPIO_GET_LINEINFO_UNWATCH_IOCTL : + ret =gusedev_set_line_watch (req, ino, in_buf, add_watch); +break ; +case GPIO_V2_LINE_SET_CONFIG_IOCTL : +default : + ret =fuse_reply_err (req,EINVAL ); + } + +if (ret) { +qemu_log_mask (LOG_GUEST_ERROR ,"gusedev_ioctl() failed with %d\n" , + ret); + } +} + +static const struct guse_cdev_lowlevel_ops gusedev_glop = { + .init = gusedev_init, + .destroy = gusedev_destroy, + .open = gusedev_open, + .release = gusedev_release, + .read = gusedev_read, + .poll = gusedev_poll, + .ioctl = gusedev_ioctl, +}; + +static void read_from_fuse_export (void *opaque) +{ +GusedevGpiodev *guse = opaque; +int ret; + +do { + ret =fuse_session_receive_buf (guse->fuse_session, &guse->fuse_buf); + }while (ret == -EINTR ); + +if (ret <0 ) { +return ; + } + +fuse_session_process_buf (guse->fuse_session, &guse->fuse_buf); +} + +static int setup_guse_export (GusedevGpiodev *guse,Error **errp) +{ +char dev_name[128 ] ="DEVNAME=" ; +const char *dev_info_argv[] = { dev_name }; +char *curdir =get_current_dir_name (); +struct fuse_session *session =NULL ; +const char *argv[3 ]; +struct guse_info ci; +int multithreaded; +AioContext *ctx; + +strncat (dev_name, guse->devname,sizeof (dev_name) -sizeof ("DEVNAME=" )); + + argv[0 ] ="" ;/* Dummy program name */ + argv[1 ] ="-d" ; + argv[2 ] =NULL ; + + ci.dev_major =0 ; + ci.dev_minor =0 ; + ci.dev_info_argc =1 ; + ci.dev_info_argv = dev_info_argv; + + session =guse_lowlevel_setup (ARRAY_SIZE (argv) -1 , (char **)argv, &ci, &gusedev_glop, + &multithreaded, guse); +if (session ==NULL ) { +error_setg (errp,"guse_lowlevel_setup failed" ); + errno =EINVAL ; +return -1 ; + } + +/* FIXME: fuse_daemonize() calls chdir("/") */ +chdir (curdir); +g_free (curdir); + + ctx =iohandler_get_aio_context (); + +aio_set_fd_handler (ctx,fuse_session_fd (session), + read_from_fuse_export,NULL , +NULL ,NULL , guse); + + guse->fuse_session = session; + +return 0 ; +} + +static void gpio_gusedev_open (Gpiodev *gpio,GpiodevBackend *backend, +Error **errp) +{ +GpiodevGusedev *opts = backend->u.gusedev.data; +GusedevGpiodev *d =GPIODEV_GUSEDEV (gpio); + + d->devname =g_strdup (opts->devname); + +QSIMPLEQ_INIT (&d->linereq); +QSIMPLEQ_INIT (&d->configreq); + +qemu_mutex_init (&d->linereq_lock); +qemu_mutex_init (&d->configreq_lock); + +setup_guse_export (d, errp); +} + +static void gpio_gusedev_parse (QemuOpts *opts,GpiodevBackend *backend, +Error **errp) +{ +const char *devname =qemu_opt_get (opts,"devname" ); +/* TODO: add bool debug for fuse debug */ +GpiodevGusedev *ggusedev; + +if (devname ==NULL ) { +error_setg (errp,"gpiodev: gusedev: no devname given" ); +return ; + } + + backend->type =GPIODEV_BACKEND_KIND_GUSEDEV ; + ggusedev = backend->u.gusedev.data =g_new0 (GpiodevGusedev,1 ); + ggusedev->devname =g_strdup (devname); +} + +static void gpio_gusedev_class_init (ObjectClass *oc,void *data) +{ +GpiodevClass *cc =GPIODEV_CLASS (oc); + + cc->parse = &gpio_gusedev_parse; + cc->open = &gpio_gusedev_open; + cc->line_event = &gpio_gusedev_line_event; + cc->config_event = &gpio_gusedev_config_event; +} + +static const TypeInfo gpio_gusedev_type_info[] = { + { + .name =TYPE_GPIODEV_GUSEDEV , + .parent =TYPE_GPIODEV , + .class_init = gpio_gusedev_class_init, + .instance_size =sizeof (GusedevGpiodev), +/* .instance_finalize = gpio_gusedev_finalize, */ + }, +}; + +DEFINE_TYPES (gpio_gusedev_type_info); +
gpiodev/meson.build +1 -0
@@ -4,4 +4,5 @@ gpiodev_ss.add(files( 'gpio.c', )) +gpiodev_ss.add(when: fuse, if_true: files('gpio-guse.c')) gpiodev_ss = gpiodev_ss.apply({})
include/gpiodev/gpio.h +1 -0
@@ -56,6 +56,7 @@ struct Gpiodev { OBJECT_DECLARE_TYPE(Gpiodev, GpiodevClass, GPIODEV)#define TYPE_GPIODEV_CHARDEV "gpiodev-chardev" +#define TYPE_GPIODEV_GUSEDEV "gpiodev-guse"struct GpiodevClass {ObjectClass parent_class;
qapi/gpio.json +28 -3
@@ -21,12 +21,36 @@ ## # @GpiodevBackendKind: # -# @chardev: chardevs +# @chardev: Gpio dev over chardev backend +# @gusedev: Gpio dev over GUSE FUSE module # # Since: 9.2 ## { 'enum': 'GpiodevBackendKind', - 'data': [ 'chardev' ] } + 'data': [ 'chardev', + { 'name': 'gusedev', 'if': 'CONFIG_LINUX' } ] } + +## +# @GpiodevGusedev: +# +# Configuration info for guse gpiodevs. +# +# @devname: Name of device created in /dev +# +# Since: 9.2 +## + { 'struct': 'GpiodevGusedev', + 'data': { 'devname': 'str' } } + +## +# @GpiodevGusedevWrapper: +# +# @data: Configuration info for chardev gpiodevs +# +# Since: 9.2 +## +{ 'struct': 'GpiodevGusedevWrapper', + 'data': { 'data': 'GpiodevGusedev' } } ## # @GpiodevChardev:
@@ -65,4 +89,5 @@ { 'union': 'GpiodevBackend', 'base': { 'type': 'GpiodevBackendKind' }, 'discriminator': 'type', - 'data': { 'chardev': 'GpiodevChardevWrapper' } } + 'data': { 'chardev': 'GpiodevChardevWrapper', + 'gusedev': { 'type': 'GpiodevGusedevWrapper', 'if': 'CONFIG_LINUX' } } }
Signature · 1 line
2.45.2
Re: [PATCH PoC 7/7] gpiodev: Add gpiobackend over GUSE
Nikita Shubin via B4 Relay <[email protected]>
Quoted 31 lines · writes:
From: Nikita Shubin <[email protected]>
Add GUSE (FUSE based kernel module similiar to CUSE) based backend.
This allows transparent usage of Linux GPIO UAPI based tools like in kernel
tools/gpioor libgpiod.libgpiod requires some modification to allow "
/sys/class/guse" ingpiod_check_gpiochip_device().It requires guse module to be loaded and providing DEVICE()->id for GPIO module, for example:
``` DEVICE(&s->gpio)->id = g_strdup("aspeed-gpio0"); ```The id should be provided to gpiodev with any
devnamethat doesn't exists in /dev:``` -gpiodev guse,id=aspeed-gpio0,devname=gpiochip10 ```That
/dev/gpiochip10can be used in the same way we usually operate with gpiochip's.
[...]
qapi/gpio.json line 27
Quoted 13 lines
qapi/gpio.json +2
-1@@ -21,12 +21,36 @@ ## # @GpiodevBackendKind: # -# @chardev: chardevs +# @chardev: Gpio dev over chardev backend +# @gusedev: Gpio dev over GUSE FUSE module # # Since: 9.2
10.1
qapi/gpio.json line 38
Quoted 12 lines
qapi/gpio.json +9
-1## { 'enum': 'GpiodevBackendKind', - 'data': [ 'chardev' ] } + 'data': [ 'chardev', + { 'name': 'gusedev', 'if': 'CONFIG_LINUX' } ] } + +## +# @GpiodevGusedev: +# +# Configuration info for guse gpiodevs. +# +# @devname: Name of device created in /dev
Existing names for similar things elsewhere:
* @dev in AudiodevAlsaPerDirectionOptions
* @device in ChardevHostdev
* @devname in NetdevNetmapOptions
* @vhostdev in NetdevVhostUserOptions
* @sev-device in SevCommonProperties
* @filename in RngRandomProperties
* @path in BlockdevOptionsNvmeIoUring, BlockdevOptionsVirtioBlkVhostVdpa, TPMPassthroughOptions
What a mess.
@filename and @path are clearly bad.
I'd prefer @device or @gpio-device, or maybe @dev.
Quoted 5 lines
qapi/gpio.json +5
-0+# +# Since: 9.2 +## + { 'struct': 'GpiodevGusedev', + 'data': { 'devname': 'str' } }
qapi/gpio.json line 53
Quoted 10 lines
qapi/gpio.json +10
-0+ +## +# @GpiodevGusedevWrapper: +# +# @data: Configuration info for chardev gpiodevs +# +# Since: 9.2 +## +{ 'struct': 'GpiodevGusedevWrapper', + 'data': { 'data': 'GpiodevGusedev' } }
Avoid the wrapper?
qapi/gpio.json line 93
Quoted 12 lines
qapi/gpio.json +2
-1## # @GpiodevChardev:@@ -65,4 +89,5 @@ { 'union': 'GpiodevBackend', 'base': { 'type': 'GpiodevBackendKind' }, 'discriminator': 'type', - 'data': { 'chardev': 'GpiodevChardevWrapper' } } + 'data': { 'chardev': 'GpiodevChardevWrapper', + 'gusedev': { 'type': 'GpiodevGusedevWrapper', 'if': 'CONFIG_LINUX' } } }
Please add a newline at the end of the file.