Uthreads
Subsystems (4)
v2 cover Uthreads
This series introduces threads and uses them to improve the performance of the USB bus scanning code and to implement background jobs in the shell via two new commands: 'spawn' and 'wait'.
The threading framework is called 'uthread' and is inspired from the barebox threads [1]. setjmp() and longjmp() are used to save and restore contexts, as well as a non-standard extension called initjmp(). This new function is added in several patches, one for each architecture that supports HAVE_SETJMP. A new symbol is defined:HAVE_INITJMP. Two tests, one for initjmp() and one for the uthread scheduling, are added to the lib suite. NOTE: the SANDBOX version of initjmp() appears to have problems and needs to be worked on.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
After introducing threads and making schedule() and udelay() a thread re-scheduling point, the USB stack initialization is modified to benefit from concurrency when UTHREAD is enabled, where uthreads are used in usb_init() to initialize and scan multiple busses at the same time. The code was tested on arm64 and arm QEMU with 4 simulated XHCI buses and some devices. On this platform the USB scan takes 2.2 s instead of 5.6 s. Tested on i.MX93 EVK with two USB hubs, one ethernet adapter and one webcam on each, "usb start" takes 2.4 s instead of 4.6 s.
Finally, the spawn and wait commands are introduced, allowing the use of threads from the shell. Tested on the i.MX93 EVK with a spinning HDD connected to USB1 and the network connected to ENET1. The USB plus DHCP init sequence "spawn usb start; spawn dhcp; wait" takes 4.5 seconds instead of 8 seconds for "usb start; dhcp".
Changes in v2:
- Rewrite the cover letter, do not mention the older coroutines series
- Rebased onto next
- UTHREAD_STACK_SIZE is set to 32768 (32 KiB) instead of 32178
- Remove uthread_free_all() and let threads be freed as they terminate by uthread_schedule()
- Add function descriptions
- Add documentation (doc/develop/uthread.rst)
- Explain initjmp() in the description of "arch: introduce symbol HAVE_INITJMP".
- Add thread groups (uthread_grp_new_id() and uthread_grp_done())
- Add the spawn and wait commands
Jerome Forissier (14):
arch: introduce symbol HAVE_INITJMP
arm: add initjmp()
riscv: add initjmp()
sandbox: add initjmp()
test: lib: add initjmp() test
uthread: add cooperative multi-tasking interface
cyclic: invoke uthread_schedule() from schedule()
lib: time: hook uthread_schedule() into udelay()
doc: develop: add documentation for uthreads
test: lib: add uthread test
dm: usb: move bus initialization into new static function
usb_init_bus()
dm: usb: initialize and scan multiple buses simultaneously with
uthread
cmd: add spawn and wait commands
test: dm: add test for spawn and wait commands
arch/Kconfig | 8 ++ arch/arm/include/asm/setjmp.h | 1 + arch/arm/lib/setjmp.S | 11 ++ arch/arm/lib/setjmp_aarch64.S | 9 ++ arch/riscv/include/asm/setjmp.h | 1 + arch/riscv/lib/setjmp.S | 10 ++ arch/sandbox/cpu/Makefile | 11 +- arch/sandbox/cpu/initjmp.c | 172 +++++++++++++++++++++++++++++ arch/sandbox/include/asm/setjmp.h | 5 + cmd/Kconfig | 17 +++ cmd/Makefile | 2 + cmd/spawn.c | 176 +++++++++++++++++++++++++++++ common/console.c | 2 + common/cyclic.c | 3 + doc/develop/index.rst | 1 + doc/develop/uthread.rst | 136 +++++++++++++++++++++++ drivers/usb/host/usb-uclass.c | 168 +++++++++++++++++++--------- include/u-boot/schedule.h | 3 + include/uthread.h | 44 ++++++++ lib/Kconfig | 21 ++++ lib/Makefile | 2 + lib/time.c | 10 +- lib/uthread.c | 178 ++++++++++++++++++++++++++++++ test/boot/bootdev.c | 14 +-- test/boot/bootflow.c | 2 +- test/cmd/Makefile | 1 + test/cmd/spawn.c | 33 ++++++ test/lib/Makefile | 2 + test/lib/initjmp.c | 72 ++++++++++++ test/lib/uthread.c | 68 ++++++++++++ 30 files changed, 1122 insertions(+), 61 deletions(-) create mode 100644 arch/sandbox/cpu/initjmp.c create mode 100644 cmd/spawn.c create mode 100644 doc/develop/uthread.rst create mode 100644 include/uthread.h create mode 100644 lib/uthread.c create mode 100644 test/cmd/spawn.c create mode 100644 test/lib/initjmp.c create mode 100644 test/lib/uthread.c
Signature · 1 line
2.43.0
PATCH v2 1/14 arch: introduce symbol HAVE_INITJMP
HAVE_INIJMP will be set by architectures that support initjmp(), a non-standard extension to setjmp()/longjmp() allowing to initialize a jump buffer with a function pointer and a stack pointer. This will be useful to later introduce threads. With this new function it becomes possible to longjmp() to a particular function pointer (rather than to a point previously reached during program execution as is the case with setjmp()), and with a custom stack. Both things are needed to spin off a new thread. Then the usual setjmp()/ longjmp() pair is enough to save and restore a context, i.e., switch thread.
--- arch/Kconfig | 6 ++++++ 1 file changed, 6 insertions(+)
arch/Kconfig +6 -0
@@ -13,6 +13,12 @@ config HAVE_SETJMP help The architecture supports setjmp() and longjmp(). +config HAVE_INITJMP + bool + help + The architecture supports initjmp(), a non-standard companion to + setjmp() and longjmp(). + config SUPPORT_BIG_ENDIAN bool
Signature · 1 line
2.43.0
Re: [PATCH v2 01/14] arch: introduce symbol HAVE_INITJMP
Hi Jerome,
Quoted 34 lines · Jerome Forissier
HAVE_INIJMPwill be set by architectures that supportinitjmp(), a non-standard extension to setjmp()/longjmp() allowing to initialize a jump buffer with a function pointer and a stack pointer. This will be useful to later introduce threads. With this new function it becomes possible tolongjmp()to a particular function pointer (rather than to a point previously reached during program execution as is the case withsetjmp()), and with a custom stack. Both things are needed to spin off a new thread. Then the usual setjmp()/longjmp()pair is enough to save and restore a context, i.e., switch thread.Signed-off-by Jerome Forissier <[email protected]>--- arch/Kconfig | 6 ++++++ 1 file changed, 6 insertions(+)arch/Kconfig +6
-1@@ -13,6 +13,12 @@ config HAVE_SETJMP help The architecture supports setjmp() and longjmp(). +config HAVE_INITJMP + bool + help + The architecture supports initjmp(), a non-standard companion to + setjmp() and longjmp(). + config SUPPORT_BIG_ENDIAN bool --
Quoted 2 lines
2.43.0
\
Re: [PATCH v2 01/14] arch: introduce symbol HAVE_INITJMP
In reply to Jerome ForissierQuoted 20 lines · Jerome Forissier
HAVE_INIJMPwill be set by architectures that supportinitjmp(), a non-standard extension to setjmp()/longjmp() allowing to initialize a jump buffer with a function pointer and a stack pointer. This will be useful to later introduce threads. With this new function it becomes possible tolongjmp()to a particular function pointer (rather than to a point previously reached during program execution as is the case withsetjmp()), and with a custom stack. Both things are needed to spin off a new thread. Then the usual setjmp()/longjmp()pair is enough to save and restore a context, i.e., switch thread.Signed-off-by Jerome Forissier <[email protected]>--- arch/Kconfig | 6 ++++++ 1 file changed, 6 insertions(+)arch/Kconfig +0
-0
arch/Kconfig config HAVE_SETJMP · line 17
Quoted 5 lines
arch/Kconfig +2
-0@@ -13,6 +13,12 @@ config HAVE_SETJMP help The architecture supports setjmp() and longjmp(). +config HAVE_INITJMP + bool
HAVE_SETJMP controls if /arch/<arch>/lib/setjmp.S is compiled.
Please, add the missing dependency.
depends HAVE_SETJMP
Best regards
Heinrich
Quoted 7 lines
arch/Kconfig +4
-0+ help + The architecture supports initjmp(), a non-standard companion to + setjmp() and longjmp(). + config SUPPORT_BIG_ENDIAN bool
Re: [PATCH v2 01/14] arch: introduce symbol HAVE_INITJMP
Quoted 24 lines · Heinrich Schuchardt
Quoted 23 lines · Jerome Forissier
HAVE_INIJMPwill be set by architectures that supportinitjmp(), a non-standard extension to setjmp()/longjmp() allowing to initialize a jump buffer with a function pointer and a stack pointer. This will be useful to later introduce threads. With this new function it becomes possible tolongjmp()to a particular function pointer (rather than to a point previously reached during program execution as is the case withsetjmp()), and with a custom stack. Both things are needed to spin off a new thread. Then the usual setjmp()/longjmp()pair is enough to save and restore a context, i.e., switch thread.Signed-off-by Jerome Forissier <[email protected]>---
arch/Kconfig| 6 ++++++1 file changed, 6 insertions(+)arch/Kconfig +0
-0@@ -13,6 +13,12 @@ config HAVE_SETJMPhelp
The architecture supportssetjmp()andlongjmp().
Quoted 8 lines
Quoted 2 lines
+config
HAVE_INITJMP
+ bool
HAVE_SETJMPcontrols if /arch/<arch>/lib/setjmp.S is compiled.Please, add the missing dependency.
depends
HAVE_SETJMP
Ack.
Thanks,
Signature · 1 line
Jerome
Quoted 12 lines
Best regards
Heinrich
Quoted 7 lines
+ help
+ The architecture supportsinitjmp(), a non-standard companion to +setjmp()andlongjmp().
+
configSUPPORT_BIG_ENDIAN
bool
PATCH v2 2/14 arm: add initjmp()
In reply to Jerome ForissierImplement initjmp() for Arm.
--- arch/Kconfig | 1 + arch/arm/include/asm/setjmp.h | 1 + arch/arm/lib/setjmp.S | 11 +++++++++++ arch/arm/lib/setjmp_aarch64.S | 9 +++++++++ 4 files changed, 22 insertions(+)
arch/Kconfig +1 -0
@@ -94,6 +94,7 @@ config ARC config ARM bool "ARM architecture" select HAVE_SETJMP + select HAVE_INITJMP select ARCH_SUPPORTS_LTO select CREATE_ARCH_SYMLINK select HAVE_PRIVATE_LIBGCC if !ARM64
arch/arm/include/asm/setjmp.h +1 -0
@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1];int setjmp (jmp_buf jmp);void longjmp (jmp_buf jmp,int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);#endif /* _SETJMP_H_ */
arch/arm/lib/setjmp.S +11 -0
@@ -34,3 +34,14 @@ ENTRY(longjmp) ret lr ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + stm a1, {v1-v8} + /* a2: entry point address, a3: stack top */ + str a3, [a1, #32] /* where setjmp would save sp */ + str a2, [a1, #36] /* where setjmp would save lr */ + mov a1, #0 + ret lr +ENDPROC(initjmp) +.popsection
arch/arm/lib/setjmp_aarch64.S +9 -0
@@ -39,3 +39,12 @@ ENTRY(longjmp) ret ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + /* x1: entry point address, x2: stack top */ + stp x1, x2, [x0,#88] + mov x0, #0 + ret +ENDPROC(initjmp) +.popsection
Signature · 1 line
2.43.0
Re: [PATCH v2 02/14] arm: add initjmp()
Quoted 71 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>--- arch/Kconfig | 1 + arch/arm/include/asm/setjmp.h | 1 + arch/arm/lib/setjmp.S | 11 +++++++++++ arch/arm/lib/setjmp_aarch64.S | 9 +++++++++ 4 files changed, 22 insertions(+)arch/Kconfig +1
-0@@ -94,6 +94,7 @@ config ARC config ARM bool "ARM architecture" select HAVE_SETJMP + select HAVE_INITJMP select ARCH_SUPPORTS_LTO select CREATE_ARCH_SYMLINK select HAVE_PRIVATE_LIBGCC if !ARM64arch/arm/include/asm/setjmp.h +1
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1];int setjmp (jmp_buf jmp);void longjmp (jmp_buf jmp,int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);#endif /* _SETJMP_H_ */ arch/arm/lib/setjmp.S +11
-0@@ -34,3 +34,14 @@ ENTRY(longjmp) ret lr ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + stm a1, {v1-v8} + /* a2: entry point address, a3: stack top */ + str a3, [a1, #32] /* where setjmp would save sp */ + str a2, [a1, #36] /* where setjmp would save lr */ + mov a1, #0 + ret lr +ENDPROC(initjmp) +.popsectionarch/arm/lib/setjmp_aarch64.S +9
-1@@ -39,3 +39,12 @@ ENTRY(longjmp) ret ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + /* x1: entry point address, x2: stack top */ + stp x1, x2, [x0,#88] + mov x0, #0 + ret +ENDPROC(initjmp) +.popsection --
Quoted 2 lines
2.43.0
Re: [PATCH v2 02/14] arm: add initjmp()
In reply to Jerome ForissierQuoted 27 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>--- arch/Kconfig | 1 + arch/arm/include/asm/setjmp.h | 1 + arch/arm/lib/setjmp.S | 11 +++++++++++ arch/arm/lib/setjmp_aarch64.S | 9 +++++++++ 4 files changed, 22 insertions(+)arch/Kconfig +1
-0@@ -94,6 +94,7 @@ config ARC config ARM bool "ARM architecture" select HAVE_SETJMP + select HAVE_INITJMP select ARCH_SUPPORTS_LTO select CREATE_ARCH_SYMLINK select HAVE_PRIVATE_LIBGCC if !ARM64arch/arm/include/asm/setjmp.h +0
-0
arch/arm/include/asm/setjmp.h typedef struct jmp_buf_data jmp_buf[1]; · line 26
Quoted 4 lines
arch/arm/include/asm/setjmp.h +1
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1];int setjmp (jmp_buf jmp);void longjmp (jmp_buf jmp,int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);
As this is not a standard function we cannot expect developers to know what it does and how to use it.
Please, provide Sphinx style documentation with the necessary information.
Best regards
Heinrich
Quoted 38 lines
arch/arm/include/asm/setjmp.h +0
-0#endif /* _SETJMP_H_ */ arch/arm/lib/setjmp.S +11
-0@@ -34,3 +34,14 @@ ENTRY(longjmp) ret lr ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + stm a1, {v1-v8} + /* a2: entry point address, a3: stack top */ + str a3, [a1, #32] /* where setjmp would save sp */ + str a2, [a1, #36] /* where setjmp would save lr */ + mov a1, #0 + ret lr +ENDPROC(initjmp) +.popsectionarch/arm/lib/setjmp_aarch64.S +9
-0@@ -39,3 +39,12 @@ ENTRY(longjmp) ret ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + /* x1: entry point address, x2: stack top */ + stp x1, x2, [x0,#88] + mov x0, #0 + ret +ENDPROC(initjmp) +.popsection
Re: [PATCH v2 02/14] arm: add initjmp()
Quoted 29 lines · Heinrich Schuchardt
Quoted 28 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>---
arch/Kconfig | 1 +
arch/arm/include/asm/setjmp.h| 1 +
arch/arm/lib/setjmp.S | 11 +++++++++++
arch/arm/lib/setjmp_aarch64.S| 9 +++++++++4 files changed, 22 insertions(+)arch/Kconfig +0
-0@@ -94,6 +94,7 @@ config ARCconfig ARM
bool "ARM architecture"
selectHAVE_SETJMP
+ selectHAVE_INITJMP
selectARCH_SUPPORTS_LTO
selectCREATE_ARCH_SYMLINK
selectHAVE_PRIVATE_LIBGCCif !ARM64arch/arm/include/asm/setjmp.h +0
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1];
Quoted 8 lines
arch/arm/include/asm/setjmp.h typedef struct jmp_buf_data jmp_buf[1]; · line 26
Quoted 3 lines
arch/arm/include/asm/setjmp.h +1
-0int setjmp(jmp_buf jmp); void longjmp(jmp_buf jmp, int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);As this is not a standard function we cannot expect developers to know what it does and how to use it.
Please, provide Sphinx style documentation with the necessary information.
I agree on principle, but if I add documentation here then I should add the same for all architectures. That being said the prototypes are already duplicated so maybe consolidation is a question for another time. I will add Shpinx style doc to all 3 commits "{arm,riscv,sandbox}: add initjmp()".
As for usage, I think the best documentation is test/lib/initjmp.c added by "test: lib: add initjmp() test".
Thanks,
Signature · 1 line
Jerome
Quoted 44 lines
Best regards
Heinrich
Quoted 38 lines
arch/arm/include/asm/setjmp.h +0
-0#endif /* _SETJMP_H_ */arch/arm/lib/setjmp.S +0
-0@@ -34,3 +34,14 @@ ENTRY(longjmp)ret lr
ENDPROC(longjmp)
.popsectionarch/arm/lib/setjmp.S +11
-0+ +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + stm a1, {v1-v8} + /* a2: entry point address, a3: stack top */ + str a3, [a1, #32] /* where setjmp would save sp */ + str a2, [a1, #36] /* where setjmp would save lr */ + mov a1, #0 + ret lr +ENDPROC(initjmp) +.popsectionarch/arm/lib/setjmp_aarch64.S +0
-0@@ -39,3 +39,12 @@ ENTRY(longjmp)ret
ENDPROC(longjmp)
.popsectionarch/arm/lib/setjmp_aarch64.S +9
-0+ +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + /* x1: entry point address, x2: stack top */ + stp x1, x2, [x0,#88] + mov x0, #0 + ret +ENDPROC(initjmp) +.popsection
Re: [PATCH v2 02/14] arm: add initjmp()
Quoted 39 lines · Jerome Forissier
Quoted 36 lines · Heinrich Schuchardt
Quoted 27 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>--- arch/Kconfig | 1 + arch/arm/include/asm/setjmp.h | 1 + arch/arm/lib/setjmp.S | 11 +++++++++++ arch/arm/lib/setjmp_aarch64.S | 9 +++++++++ 4 files changed, 22 insertions(+)arch/Kconfig +1
-0@@ -94,6 +94,7 @@ config ARC config ARM bool "ARM architecture" select HAVE_SETJMP + select HAVE_INITJMP select ARCH_SUPPORTS_LTO select CREATE_ARCH_SYMLINK select HAVE_PRIVATE_LIBGCC if !ARM64arch/arm/include/asm/setjmp.h +0
-0arch/arm/include/asm/setjmp.h typedef struct jmp_buf_data jmp_buf[1]; · line 26
Quoted 4 lines
arch/arm/include/asm/setjmp.h +1
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1]; int setjmp(jmp_buf jmp); void longjmp(jmp_buf jmp, int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);As this is not a standard function we cannot expect developers to know what it does and how to use it.
Quoted 6 lines
Quoted 1 line
Please, provide Sphinx style documentation with the necessary information.
I agree on principle, but if I add documentation here then I should add the same for all architectures. That being said the prototypes are already duplicated so maybe consolidation is a question for another time. I will add Shpinx style doc to all 3 commits "{arm,riscv,sandbox}: add
initjmp()".
Yes, this was not designed correctly:
We should move setjmp.h to include/asm-generic and include an architecture specific setjmp_bits.h from there.
setjmp_bits.h would provide the struct jmp_buf_data definition.
Quoted 3 lines
As for usage, I think the best documentation is
test/lib/initjmp.cadded by "test: lib: addinitjmp()test".
Example code is valuable but does not replace documentation.
Best regards
Heinrich
Re: [PATCH v2 02/14] arm: add initjmp()
Quoted 47 lines · Heinrich Schuchardt
Quoted 39 lines · Jerome Forissier
Quoted 36 lines · Heinrich Schuchardt
Quoted 27 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>---
arch/Kconfig | 1 +
arch/arm/include/asm/setjmp.h| 1 +
arch/arm/lib/setjmp.S | 11 +++++++++++
arch/arm/lib/setjmp_aarch64.S| 9 +++++++++4 files changed, 22 insertions(+)arch/Kconfig +0
-0@@ -94,6 +94,7 @@ config ARCconfig ARM
bool "ARM architecture"
selectHAVE_SETJMP
+ selectHAVE_INITJMP
selectARCH_SUPPORTS_LTO
selectCREATE_ARCH_SYMLINK
selectHAVE_PRIVATE_LIBGCCif !ARM64arch/arm/include/asm/setjmp.h +0
-0arch/arm/include/asm/setjmp.h typedef struct jmp_buf_data jmp_buf[1]; · line 26
Quoted 4 lines
arch/arm/include/asm/setjmp.h +1
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1]; int setjmp(jmp_buf jmp); void longjmp(jmp_buf jmp, int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);As this is not a standard function we cannot expect developers to know what it does and how to use it.
Quoted 6 lines
Quoted 1 line
Please, provide Sphinx style documentation with the necessary information.
I agree on principle, but if I add documentation here then I should add the same for all architectures. That being said the prototypes are already duplicated so maybe consolidation is a question for another time. I will add Shpinx style doc to all 3 commits "{arm,riscv,sandbox}: add
initjmp()".
Quoted 6 lines
Yes, this was not designed correctly:
We should move
setjmp.htoinclude/asm-genericand include an architecture specificsetjmp_bits.hfrom there.
setjmp_bits.hwould provide the structjmp_buf_datadefinition.
Makes sense. I'll rework in v3.
Quoted 6 lines
Quoted 4 lines
As for usage, I think the best documentation is
test/lib/initjmp.cadded by "test: lib: addinitjmp()test".Example code is valuable but does not replace documentation.
Should I provide a stripped-down example in the Sphinx doc? Or do you have another location in mind? (doc/develop/initjmp.rst?).
Thanks,
Signature · 1 line
Jerome
Quoted 4 lines
Best regards
Heinrich
Re: [PATCH v2 02/14] arm: add initjmp()
Quoted 61 lines · Jerome Forissier
Quoted 47 lines · Heinrich Schuchardt
Quoted 39 lines · Jerome Forissier
Quoted 36 lines · Heinrich Schuchardt
Quoted 27 lines · Jerome Forissier
Implement
initjmp()for Arm.Signed-off-by Jerome Forissier <[email protected]>---
arch/Kconfig | 1 +
arch/arm/include/asm/setjmp.h| 1 +
arch/arm/lib/setjmp.S | 11 +++++++++++
arch/arm/lib/setjmp_aarch64.S| 9 +++++++++4 files changed, 22 insertions(+)arch/Kconfig +0
-0@@ -94,6 +94,7 @@ config ARCconfig ARM
bool "ARM architecture"
selectHAVE_SETJMP
+ selectHAVE_INITJMP
selectARCH_SUPPORTS_LTO
selectCREATE_ARCH_SYMLINK
selectHAVE_PRIVATE_LIBGCCif !ARM64arch/arm/include/asm/setjmp.h +0
-0arch/arm/include/asm/setjmp.h typedef struct jmp_buf_data jmp_buf[1]; · line 26
Quoted 4 lines
arch/arm/include/asm/setjmp.h +1
-0@@ -23,5 +23,6 @@ typedef struct jmp_buf_data jmp_buf[1]; int setjmp(jmp_buf jmp); void longjmp(jmp_buf jmp, int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);As this is not a standard function we cannot expect developers to know what it does and how to use it.
Quoted 6 lines
Quoted 1 line
Please, provide Sphinx style documentation with the necessary information.
I agree on principle, but if I add documentation here then I should add the same for all architectures. That being said the prototypes are already duplicated so maybe consolidation is a question for another time. I will add Shpinx style doc to all 3 commits "{arm,riscv,sandbox}: add
initjmp()".Quoted 6 lines
Yes, this was not designed correctly:
We should move
setjmp.htoinclude/asm-genericand include an architecture specificsetjmp_bits.hfrom there.
setjmp_bits.hwould provide the structjmp_buf_datadefinition.Makes sense. I'll rework in v3.
Quoted 2 lines
Quoted 2 lines
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
As for usage, I think the best documentation is
test/lib/initjmp.cadded by "test: lib: addinitjmp()test".Example code is valuable but does not replace documentation.
Should I provide a stripped-down example in the Sphinx doc? Or do you have another location in mind? (
doc/develop/initjmp.rst?).
We should have doc/api/initjmp.rst and if test/lib/initjmp.c is commented correctly / well enough it can be referenced in the rST via '.. kernel-doc::test/lib/initjmp.c' I think.
Signature · 1 line
Tom
PATCH v2 3/14 riscv: add initjmp()
In reply to Jerome ForissierImplement initjmp() for RISC-V.
--- arch/Kconfig | 1 + arch/riscv/include/asm/setjmp.h | 1 + arch/riscv/lib/setjmp.S | 10 ++++++++++ 3 files changed, 12 insertions(+)
arch/Kconfig +1 -0
@@ -152,6 +152,7 @@ config RISCV bool "RISC-V architecture" select CREATE_ARCH_SYMLINK select HAVE_SETJMP + select HAVE_INITJMP select SUPPORT_ACPI select SUPPORT_LITTLE_ENDIAN select SUPPORT_OF_CONTROL
arch/riscv/include/asm/setjmp.h +1 -0
@@ -21,5 +21,6 @@ typedef struct jmp_buf_data jmp_buf[1];int setjmp (jmp_buf jmp);void longjmp (jmp_buf jmp,int ret); +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);#endif /* _SETJMP_H_ */
arch/riscv/lib/setjmp.S +10 -0
@@ -59,3 +59,13 @@ ENTRY(longjmp) ret ENDPROC(longjmp) .popsection + +.pushsection .text.initjmp, "ax" +ENTRY(initjmp) + /* a1: entry point address, a2: stack top */ + STORE_IDX(a1, 12) + STORE_IDX(a2, 13) + li a0, 0 + ret +ENDPROC(initjmp) +.popsection
Signature · 1 line
2.43.0
PATCH v2 4/14 sandbox: add initjmp()
In reply to Jerome ForissierAdd ininijmp() to sandbox. The implementation is taken verbatim from barebox [1]. It is quite complex because contrary to U-Boot platform code we don't know how the system's C library implements the jump buffer, so we can't just write the function and stack pointers into it.
FIXME: this patch should make SANDBOX select HAVE_INITJMP (in arch/Kconfig). It does not due to the following error detected by CI:
_________________________ test_ut[ut_lib_lib_initjmp] __________________________ test/py/tests/test_ut.py:608: in test_ut
output = u_boot_console.run_command('ut ' + ut_subtest)
test/py/u_boot_console_base.py:334: in run_command
m = self.p.expect([self.prompt_compiled] + self.bad_patterns)
test/py/u_boot_spawn.py:296: in expect
c = self.receive(1024)
test/py/u_boot_spawn.py:235: in receive
raise err
test/py/u_boot_spawn.py:227: in receive
c = os.read(self.fd, num_bytes).decode(errors='replace')
E OSError: [Errno 5] Input/output error
----------------------------- Captured stdout call -----------------------------
=> ut lib lib_initjmp
Test: lib_initjmp: initjmp.c
Failures: 0
common/dlmalloc.c:796: do_check_free_chunk: Assertion next == top || inuse(next)' failed.common/dlmalloc.c:796: do_check_free_chunk: Assertion next == top || inuse(next)' failed. ---------------- generated xml file: /tmp/sandbox64/results.xml ----------------
On x86 the dmalloc error is not printed but the I/O error is still there.
[1] https://github.com/barebox/barebox/blob/b2a15c383ddc/arch/sandbox/os/setjmp.c
--- arch/sandbox/cpu/Makefile | 11 +- arch/sandbox/cpu/initjmp.c | 172 ++++++++++++++++++++++++++++++ arch/sandbox/include/asm/setjmp.h | 5 + 3 files changed, 187 insertions(+), 1 deletion(-) create mode 100644 arch/sandbox/cpu/initjmp.c
arch/sandbox/cpu/Makefile +10 -1
@@ -5,7 +5,7 @@ # (C) Copyright 2000-2003 # Wolfgang Denk, DENX Software Engineering, [email protected]. -obj-y := cache.o cpu.o state.o +obj-y := cache.o cpu.o state.o initjmp.o extra-y := start.o os.o extra-$(CONFIG_SANDBOX_SDL) += sdl.o obj-$(CONFIG_XPL_BUILD) += spl.o
@@ -29,6 +29,15 @@ cmd_cc_eth-raw-os.o = $(CC) $(filter-out -nostdinc, \ $(obj)/eth-raw-os.o: $(src)/eth-raw-os.c FORCE $(call if_changed_dep,cc_eth-raw-os.o) +# initjmp.c is build in the system environment, so needs standard includes +# CFLAGS_REMOVE_initjmp.o cannot be used to drop header include path +quiet_cmd_cc_initjmp.o = CC $(quiet_modtag) $@ +cmd_cc_initjmp.o = $(CC) $(filter-out -nostdinc, \ + $(patsubst -I%,-idirafter%,$(c_flags))) -c -o $@ $< + +$(obj)/initjmp.o: $(src)/initjmp.c FORCE + $(call if_changed_dep,cc_initjmp.o) + # sdl.c fails to build with -fshort-wchar using musl cmd_cc_sdl.o = $(CC) $(filter-out -nostdinc -fshort-wchar, \ $(patsubst -I%,-idirafter%,$(c_flags))) -fno-lto -c -o $@ $<
arch/sandbox/cpu/initjmp.c new file +172 -0
172 lines not on this page · raw message
arch/sandbox/include/asm/setjmp.h +5 -0
@@ -31,5 +31,10 @@ typedef struct jmp_buf_data jmp_buf[1];*/ int setjmp (jmp_buf jmp);__noreturn void longjmp (jmp_buf jmp,int ret); +/* +* initjmp() is non-standard, still it has to play well with the system versions +* of setjmp()/longjmp(). +*/ +int initjmp (jmp_buf jmp,void __noreturn (*func)(void ),void *stack_top);#endif /* _SETJMP_H_ */
Signature · 1 line
2.43.0
PATCH v2 5/14 test: lib: add initjmp() test
In reply to Jerome ForissierTest the initjmp() function when HAVE_INITJMP is set.
--- test/lib/Makefile | 1 + test/lib/initjmp.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 test/lib/initjmp.c
test/lib/Makefile +1 -0
@@ -14,6 +14,7 @@ obj-y += hexdump.o obj-$(CONFIG_SANDBOX) += kconfig.o obj-y += lmb.o obj-$(CONFIG_HAVE_SETJMP) += longjmp.o +obj-$(CONFIG_HAVE_INITJMP) += initjmp.o obj-$(CONFIG_CONSOLE_RECORD) += test_print.o obj-$(CONFIG_SSCANF) += sscanf.o obj-$(CONFIG_$(PHASE_)STRTO) += str.o
test/lib/initjmp.c new file +72 -0
72 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v2 05/14] test: lib: add initjmp() test
Quoted 101 lines · Jerome Forissier
Test the
initjmp()function whenHAVE_INITJMPis set.Signed-off-by Jerome Forissier <[email protected]>--- test/lib/Makefile | 1 + test/lib/initjmp.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 test/lib/initjmp.ctest/lib/Makefile +1
-0@@ -14,6 +14,7 @@ obj-y += hexdump.o obj-$(CONFIG_SANDBOX) += kconfig.o obj-y += lmb.o obj-$(CONFIG_HAVE_SETJMP) += longjmp.o +obj-$(CONFIG_HAVE_INITJMP) += initjmp.o obj-$(CONFIG_CONSOLE_RECORD) += test_print.o obj-$(CONFIG_SSCANF) += sscanf.o obj-$(CONFIG_$(PHASE_)STRTO) += str.otest/lib/initjmp.c new file +72
-1@@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* +* Copyright 2025 Linaro Limited +* +* Unit test for initjmp() +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <stdbool.h> +#include <test/lib.h> +#include <test/ut.h> +#include <vsprintf.h> + +static bool ep_entered; +static jmp_buf return_buf; + +static void __noreturn entrypoint (void ) +{ + ep_entered = true; + +/* Jump back to the main routine */ +longjmp (return_buf,1 ); + +/* Not reached */ +panic ("longjmp failed\n" ); +} + +static int lib_initjmp (struct unit_test_state *uts) +{ +int ret; +void *stack; +jmp_buf buf; +int stack_sz =1024 ; + + ep_entered = false; + + stack =malloc (stack_sz); +ut_assertnonnull (stack); + +ut_assert (!ep_entered); + +/* +* Prepare return_buf so that entrypoint may jump back just after the +* if() +*/ +if (!setjmp (return_buf)) { +/* return_buf initialized, entrypoint not yet called */ + +/* +* Prepare another jump buffer to jump into entrypoint with the +* given stack +*/ + ret =initjmp (buf, entrypoint, stack + stack_sz); +ut_assertok (ret); + +/* Jump into entrypoint */ +longjmp (buf,1 ); +/* +* Not reached since entrypoint is expected to branch after +* the if() +*/ +ut_assert (false); + } + +ut_assert (ep_entered); + +free (stack); + +return 0 ; +} +LIB_TEST (lib_initjmp,0 ); --
Quoted 2 lines
2.43.0
Re: [PATCH v2 05/14] test: lib: add initjmp() test
In reply to Jerome ForissierQuoted 27 lines · Jerome Forissier
Test the
initjmp()function whenHAVE_INITJMPis set.Signed-off-by Jerome Forissier <[email protected]>--- test/lib/Makefile | 1 + test/lib/initjmp.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+)create mode 100644
test/lib/initjmp.ctest/lib/Makefile +1
-0@@ -14,6 +14,7 @@ obj-y += hexdump.o obj-$(CONFIG_SANDBOX) += kconfig.o obj-y += lmb.o obj-$(CONFIG_HAVE_SETJMP) += longjmp.o +obj-$(CONFIG_HAVE_INITJMP) += initjmp.o obj-$(CONFIG_CONSOLE_RECORD) += test_print.o obj-$(CONFIG_SSCANF) += sscanf.o obj-$(CONFIG_$(PHASE_)STRTO) += str.otest/lib/initjmp.c new file +0
-0
test/lib/initjmp.c line 1
Quoted 1 line
test/lib/initjmp.c new file +1
-0@@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0+
GPL-2.0-or-later
Best regards
Heinrich
Quoted 71 lines
test/lib/initjmp.c new file +71
-0+/* +* Copyright 2025 Linaro Limited +* +* Unit test for initjmp() +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <stdbool.h> +#include <test/lib.h> +#include <test/ut.h> +#include <vsprintf.h> + +static bool ep_entered; +static jmp_buf return_buf; + +static void __noreturn entrypoint (void ) +{ + ep_entered = true; + +/* Jump back to the main routine */ +longjmp (return_buf,1 ); + +/* Not reached */ +panic ("longjmp failed\n" ); +} + +static int lib_initjmp (struct unit_test_state *uts) +{ +int ret; +void *stack; +jmp_buf buf; +int stack_sz =1024 ; + + ep_entered = false; + + stack =malloc (stack_sz); +ut_assertnonnull (stack); + +ut_assert (!ep_entered); + +/* +* Prepare return_buf so that entrypoint may jump back just after the +* if() +*/ +if (!setjmp (return_buf)) { +/* return_buf initialized, entrypoint not yet called */ + +/* +* Prepare another jump buffer to jump into entrypoint with the +* given stack +*/ + ret =initjmp (buf, entrypoint, stack + stack_sz); +ut_assertok (ret); + +/* Jump into entrypoint */ +longjmp (buf,1 ); +/* +* Not reached since entrypoint is expected to branch after +* the if() +*/ +ut_assert (false); + } + +ut_assert (ep_entered); + +free (stack); + +return 0 ; +} +LIB_TEST (lib_initjmp,0 );
Re: [PATCH v2 05/14] test: lib: add initjmp() test
Quoted 23 lines · Heinrich Schuchardt
Quoted 22 lines · Jerome Forissier
Test the
initjmp()function whenHAVE_INITJMPis set.Signed-off-by Jerome Forissier <[email protected]>---
test/lib/Makefile | 1 +
test/lib/initjmp.c| 72 ++++++++++++++++++++++++++++++++++++++++++++++2 files changed, 73 insertions(+)create mode 100644
test/lib/initjmp.ctest/lib/Makefile +0
-0@@ -14,6 +14,7 @@ obj-y += hexdump.oobj-$(CONFIG_SANDBOX) += kconfig.o
obj-y += lmb.o
obj-$(CONFIG_HAVE_SETJMP) += longjmp.o
+obj-$(CONFIG_HAVE_INITJMP) += initjmp.o
obj-$(CONFIG_CONSOLE_RECORD) += test_print.o
obj-$(CONFIG_SSCANF) += sscanf.o
obj-$(CONFIG_$(PHASE_)STRTO) += str.otest/lib/initjmp.c +0
-0
Quoted 8 lines
test/lib/initjmp.c line 1
Quoted 6 lines
new file mode 100644
index 00000000000..52bbda8cc60test/lib/initjmp.c new file +1
-0@@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0+ GPL-2.0-or-later
Ack.
Thanks,
Signature · 1 line
Jerome
Quoted 77 lines
Best regards
Heinrich
Quoted 71 lines
test/lib/initjmp.c new file +71
-0+/* +* Copyright 2025 Linaro Limited +* +* Unit test for initjmp() +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <stdbool.h> +#include <test/lib.h> +#include <test/ut.h> +#include <vsprintf.h> + +static bool ep_entered; +static jmp_buf return_buf; + +static void __noreturn entrypoint (void ) +{ + ep_entered = true; + + /* Jump back to the main routine */ + longjmp(return_buf, 1); + + /* Not reached */ + panic("longjmp failed\n"); +} + +static int lib_initjmp (struct unit_test_state *uts) +{ + int ret; + void *stack; + jmp_buf buf; + int stack_sz = 1024; + + ep_entered = false; + + stack = malloc(stack_sz); + ut_assertnonnull(stack); + + ut_assert(!ep_entered); + + /* + * Prepare return_buf so that entrypoint may jump back just after the + * if() + */ + if (!setjmp(return_buf)) { + /* return_buf initialized, entrypoint not yet called */ + + /* + * Prepare another jump buffer to jump into entrypoint with the + * given stack + */ + ret = initjmp(buf, entrypoint, stack + stack_sz); + ut_assertok(ret); + + /* Jump into entrypoint */ + longjmp(buf, 1); + /* + * Not reached since entrypoint is expected to branch after + * the if() + */ + ut_assert(false); + } + + ut_assert(ep_entered); + + free(stack); + + return 0; +} +LIB_TEST (lib_initjmp,0 );
PATCH v2 6/14 uthread: add cooperative multi-tasking interface
In reply to Jerome ForissierAdd an new internal API called uthread (Kconfig symbol: UTHREAD) which provides cooperative multi-tasking. The goal is to be able to improve the performance of some parts of U-Boot by overlapping lengthy operations, and also implement background jobs in the U-Boot shell. Each uthread has its own stack allocated on the heap. The default stack size is defined by the UTHREAD_STACK_SIZE symbol and is used when uthread_create() receives zero for the stack_sz argument.
The implementation is based on context-switching via initjmp()/setjmp()/ longjmp() and is inspired from barebox threads [1]. A notion of thread group helps with dependencies, such as when a thread needs to block until a number of other threads have returned.
The name "uthread" comes from "user-space threads" because the scheduling happens with no help from a higher privileged mode, contrary to more complex models where kernel threads are defined. But the 'u' may as well stand for 'U-Boot' since the bootloader may actually be running at any privilege level and the notion of user vs. kernel may not make much sense in this context.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
--- include/uthread.h | 44 ++++++++++++ lib/Kconfig | 21 ++++++ lib/Makefile | 2 + lib/uthread.c | 178 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+) create mode 100644 include/uthread.h create mode 100644 lib/uthread.c
include/uthread.h new file +44 -0
@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* +* Copyright 2025 Linaro Limited +*/ + +#include <linux/types.h> + +#ifndef _UTHREAD_H_ +#define _UTHREAD_H_ + +#ifdef CONFIG_UTHREAD + +int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id); +bool uthread_schedule (void ); +unsigned int uthread_grp_new_id (void ); +bool uthread_grp_done (unsigned int grp_id); + +#else + +static inline int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id) +{ +fn (arg); +return 0 ; +} + +static inline bool uthread_schedule (void ) +{ +return false; +} + +static inline unsigned int uthread_grp_new_id (void ) +{ +return 0 ; +} + +static inline bool uthread_grp_done (unsigned int grp_id) +{ +return true; +} + +#endif /* CONFIG_UTHREAD */ +#endif /* _UTHREAD_H_ */
lib/Kconfig +21 -0
@@ -1255,6 +1255,27 @@ config PHANDLE_CHECK_SEQ enable this config option to distinguish them using phandles in fdtdec_get_alias_seq() function. +config UTHREAD + bool "Enable thread support" + depends on HAVE_INITJMP + help + Implement a simple form of cooperative multi-tasking based on + context-switching via initjmp(), setjmp() and longjmp(). The + uthread_ interface enables the main thread of execution to create + one or more secondary threads and schedule them until they all have + returned. At any point a thread may suspend its execution and + schedule another thread, which allows for the efficient multiplexing + of leghthy operations. + +config UTHREAD_STACK_SIZE + int "Default uthread stack size" + depends on UTHREAD + default 32768 + help + The default stak size for uthreads. Each uthread has its own stack. + When the stack_sz argument to uthread_create() is zero then this + value is used. + endmenu source "lib/fwu_updates/Kconfig"
lib/Makefile +2 -0
@@ -164,6 +164,8 @@ obj-$(CONFIG_LIB_ELF) += elf.o obj-$(CONFIG_$(PHASE_)SEMIHOSTING) += semihosting.o +obj-$(CONFIG_UTHREAD) += uthread.o + # # Build a fast OID lookup registry from include/linux/oid_registry.h #
lib/uthread.c new file +178 -0
178 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v2 06/14] uthread: add cooperative multi-tasking interface
Hi Jerome,
Quoted 2 lines · Jerome Forissier
Add an new
'a'
Quoted 98 lines
internal API called uthread (
Kconfigsymbol: UTHREAD) which
provides cooperative multi-tasking. The goal is to be able to improve the performance of some parts of U-Boot by overlapping lengthy operations, and also implement background jobs in the U-Boot shell. Each uthread has its own stack allocated on the heap. The default stack size is defined by theUTHREAD_STACK_SIZEsymbol and is used whenuthread_create()receives zero for thestack_szargument.The implementation is based on context-switching via initjmp()/setjmp()/
longjmp()and is inspired from barebox threads [1]. A notion of thread group helps with dependencies, such as when a thread needs to block until a number of other threads have returned.The name "uthread" comes from "user-space threads" because the scheduling happens with no help from a higher privileged mode, contrary to more complex models where kernel threads are defined. But the 'u' may as well stand for 'U-Boot' since the bootloader may actually be running at any privilege level and the notion of user vs. kernel may not make much sense in this context.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
Signed-off-by Jerome Forissier <[email protected]>--- include/uthread.h | 44 ++++++++++++ lib/Kconfig | 21 ++++++ lib/Makefile | 2 + lib/uthread.c | 178 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+) create mode 100644 include/uthread.h create mode 100644 lib/uthread.cinclude/uthread.h new file +44
-0@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* +* Copyright 2025 Linaro Limited +*/ + +#include <linux/types.h> + +#ifndef _UTHREAD_H_ +#define _UTHREAD_H_ + +#ifdef CONFIG_UTHREAD + +int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id); +bool uthread_schedule (void ); +unsigned int uthread_grp_new_id (void ); +bool uthread_grp_done (unsigned int grp_id); + +#else + +static inline int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id) +{ +fn (arg); +return 0 ; +} + +static inline bool uthread_schedule (void ) +{ +return false; +} + +static inline unsigned int uthread_grp_new_id (void ) +{ +return 0 ; +} + +static inline bool uthread_grp_done (unsigned int grp_id) +{ +return true; +} + +#endif /* CONFIG_UTHREAD */ +#endif /* _UTHREAD_H_ */ lib/Kconfig +8
-0@@ -1255,6 +1255,27 @@ config PHANDLE_CHECK_SEQ enable this config option to distinguish them using phandles in fdtdec_get_alias_seq() function. +config UTHREAD + bool "Enable thread support" + depends on HAVE_INITJMP + help + Implement a simple form of cooperative multi-tasking based on + context-switching via initjmp(), setjmp() and longjmp(). The + uthread_ interface enables the main thread of execution to create + one or more secondary threads and schedule them until they all have
lib/Kconfig config PHANDLE_CHECK_SEQ · line 1275
Quoted 10 lines
lib/Kconfig +10
-0+ returned. At any point a thread may suspend its execution and + schedule another thread, which allows for the efficient multiplexing + of leghthy operations. + +config UTHREAD_STACK_SIZE + int "Default uthread stack size" + depends on UTHREAD + default 32768 + help + The default stak size for uthreads. Each uthread has its own stack.
stack size
Quoted 51 lines
lib/Kconfig +3
-0+ When the stack_sz argument to uthread_create() is zero then this + value is used. + endmenu source "lib/fwu_updates/Kconfig"lib/Makefile +2
-0@@ -164,6 +164,8 @@ obj-$(CONFIG_LIB_ELF) += elf.o obj-$(CONFIG_$(PHASE_)SEMIHOSTING) += semihosting.o +obj-$(CONFIG_UTHREAD) += uthread.o + # # Build a fast OID lookup registry from include/linux/oid_registry.h #lib/uthread.c new file +26
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright (C) 2021 Ahmad Fatoum, Pengutronix +* Copyright (C) 2025 Linaro Limited +* +* An implementation of cooperative multi-tasking inspired from barebox threads +* https://github.com/barebox/barebox/blob/master/common/bthread.c +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <malloc.h> +#include <stdint.h> +#include <uthread.h> + +static struct uthread { +void (*fn)(void *); +void *arg; +jmp_buf ctx; +void *stack; +bool done; +unsigned int grp_id; +struct list_head list; +} main_thread = {
lib/uthread.c line 36
Quoted 10 lines
lib/uthread.c new file +10
-0+ .list = LIST_HEAD_INIT(main_thread.list), +}; + +static struct uthread *current = &main_thread; + +/** +* uthread_trampoline() - Call the current thread's entry point then resume the +* main thread. +* +* This is a helper function which is used as the @func argument to the inijmp()
initjump
Quoted 21 lines
lib/uthread.c new file +21
-0+* function, and ultimately invoked via setjmp(). It does not return, but +* instead longjmp()'s back to the main thread. +*/ +static void __noreturn uthread_trampoline (void ) +{ +struct uthread *curr = current; + + curr->fn (curr->arg); + curr->done = true; + current = &main_thread; +longjmp (current->ctx,1 ); +/* Not reached */ +while (true) + ; +} + +/** +* uthread_free() - Free memory used by a uthread object. +*/ +static void uthread_free (struct uthread *uthread) +{
lib/uthread.c line 67
Quoted 10 lines
lib/uthread.c new file +10
-0+if (!uthread) +return ; +free (uthread->stack); +free (uthread); +} + +/** +* uthread_create() - Create a uthread object and make it ready for execution +* +* Threads are automatically deleted when then return from their entry point.
when they
[...]
lib/uthread.c line 159
Quoted 11 lines
lib/uthread.c new file +11
-0+/** +* uthread_grp_new_id() - return a new ID for a thread group +* +* Return: the new thread group ID +*/ +unsigned int uthread_grp_new_id (void ) +{ +static unsigned int id =0 ; + +return ++id; +}
This seems a bit weird. Why do we need this function?
Quoted 20 lines
lib/uthread.c new file +19
-1+ +/** +* uthread_grp_done() - test if all threads in a group are done +* +* @grp: the ID of the thread group that should be considered +* Return: false if the group contains at least one runnable thread (i.e., one +* thread which entry point has not returned yet), true otherwise +*/ +bool uthread_grp_done (unsigned int grp_id) +{ +struct uthread *next; + +list_for_each_entry (next, &main_thread.list, list) { +if (next->grp_id == grp_id && !next->done) +return false; + } + +return true; +} --
Quoted 2 lines
2.43.0
Apart from the minor typos and the function that I can't figure out why we need this look pretty clean
Thnaks
/Ilias
Re: [PATCH v2 06/14] uthread: add cooperative multi-tasking interface
Quoted 8 lines · Ilias Apalodimas
Hi Jerome,
Quoted 2 lines · Jerome Forissier
Add an new
'a'
Fixed in v3
Quoted 103 lines
Quoted 103 lines
internal API called uthread (
Kconfigsymbol: UTHREAD) which
provides cooperative multi-tasking. The goal is to be able to improve the performance of some parts of U-Boot by overlapping lengthy operations, and also implement background jobs in the U-Boot shell. Each uthread has its own stack allocated on the heap. The default stack size is defined by theUTHREAD_STACK_SIZEsymbol and is used whenuthread_create()receives zero for thestack_szargument.The implementation is based on context-switching via initjmp()/setjmp()/
longjmp()and is inspired from barebox threads [1]. A notion of thread group helps with dependencies, such as when a thread needs to block until a number of other threads have returned.The name "uthread" comes from "user-space threads" because the scheduling happens with no help from a higher privileged mode, contrary to more complex models where kernel threads are defined. But the 'u' may as well stand for 'U-Boot' since the bootloader may actually be running at any privilege level and the notion of user vs. kernel may not make much sense in this context.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
Signed-off-by Jerome Forissier <[email protected]>--- include/uthread.h | 44 ++++++++++++ lib/Kconfig | 21 ++++++ lib/Makefile | 2 + lib/uthread.c | 178 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+) create mode 100644 include/uthread.h create mode 100644 lib/uthread.cinclude/uthread.h new file +44
-0@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* +* Copyright 2025 Linaro Limited +*/ + +#include <linux/types.h> + +#ifndef _UTHREAD_H_ +#define _UTHREAD_H_ + +#ifdef CONFIG_UTHREAD + +int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id); +bool uthread_schedule (void ); +unsigned int uthread_grp_new_id (void ); +bool uthread_grp_done (unsigned int grp_id); + +#else + +static inline int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id) +{ +fn (arg); +return 0 ; +} + +static inline bool uthread_schedule (void ) +{ +return false; +} + +static inline unsigned int uthread_grp_new_id (void ) +{ +return 0 ; +} + +static inline bool uthread_grp_done (unsigned int grp_id) +{ +return true; +} + +#endif /* CONFIG_UTHREAD */ +#endif /* _UTHREAD_H_ */ lib/Kconfig +12
-0@@ -1255,6 +1255,27 @@ config PHANDLE_CHECK_SEQ enable this config option to distinguish them using phandles in fdtdec_get_alias_seq() function. +config UTHREAD + bool "Enable thread support" + depends on HAVE_INITJMP + help + Implement a simple form of cooperative multi-tasking based on + context-switching via initjmp(), setjmp() and longjmp(). The + uthread_ interface enables the main thread of execution to create + one or more secondary threads and schedule them until they all have + returned. At any point a thread may suspend its execution and + schedule another thread, which allows for the efficient multiplexing + of leghthy operations. +
Quoted 8 lines
lib/Kconfig config PHANDLE_CHECK_SEQ · line 1275
Quoted 6 lines
lib/Kconfig +6
-0+config UTHREAD_STACK_SIZE + int "Default uthread stack size" + depends on UTHREAD + default 32768 + help + The default stak size for uthreads. Each uthread has its own stack.stack size
Fixed in v3
Quoted 90 lines
Quoted 52 lines
lib/Kconfig +3
-0+ When the stack_sz argument to uthread_create() is zero then this + value is used. + endmenu source "lib/fwu_updates/Kconfig"lib/Makefile +2
-0@@ -164,6 +164,8 @@ obj-$(CONFIG_LIB_ELF) += elf.o obj-$(CONFIG_$(PHASE_)SEMIHOSTING) += semihosting.o +obj-$(CONFIG_UTHREAD) += uthread.o + # # Build a fast OID lookup registry from include/linux/oid_registry.h #lib/uthread.c new file +26
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright (C) 2021 Ahmad Fatoum, Pengutronix +* Copyright (C) 2025 Linaro Limited +* +* An implementation of cooperative multi-tasking inspired from barebox threads +* https://github.com/barebox/barebox/blob/master/common/bthread.c +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <malloc.h> +#include <stdint.h> +#include <uthread.h> + +static struct uthread { +void (*fn)(void *); +void *arg; +jmp_buf ctx; +void *stack; +bool done; +unsigned int grp_id; +struct list_head list; +} main_thread = {lib/uthread.c line 36
Quoted 10 lines
lib/uthread.c new file +10
-0+ .list = LIST_HEAD_INIT(main_thread.list), +}; + +static struct uthread *current = &main_thread; + +/** +* uthread_trampoline() - Call the current thread's entry point then resume the +* main thread. +* +* This is a helper function which is used as the @func argument to the inijmp() initjump
Quoted 25 lines
lib/uthread.c new file +25
-0+* function, and ultimately invoked via setjmp(). It does not return, but +* instead longjmp()'s back to the main thread. +*/ +static void __noreturn uthread_trampoline (void ) +{ +struct uthread *curr = current; + + curr->fn (curr->arg); + curr->done = true; + current = &main_thread; +longjmp (current->ctx,1 ); +/* Not reached */ +while (true) + ; +} + +/** +* uthread_free() - Free memory used by a uthread object. +*/ +static void uthread_free (struct uthread *uthread) +{ +if (!uthread) +return ; +free (uthread->stack); +free (uthread);
Quoted 8 lines
lib/uthread.c line 67
Quoted 6 lines
lib/uthread.c new file +6
-0+} + +/** +* uthread_create() - Create a uthread object and make it ready for execution +* +* Threads are automatically deleted when then return from their entry point. when they
Fixed in v3
Quoted 15 lines
[...]
lib/uthread.c line 159
Quoted 11 lines
lib/uthread.c new file +11
-0+/** +* uthread_grp_new_id() - return a new ID for a thread group +* +* Return: the new thread group ID +*/ +unsigned int uthread_grp_new_id (void ) +{ +static unsigned int id =0 ; + +return ++id; +}This seems a bit weird. Why do we need this function?
As it should appear clearly in the subsequent patches, it is to help with dependencies. Suppose the main thread creates a thread to perform the "usb start" command. At this point we have two threads: let's call them main and usb_start. The latter enumerates the busses and creates one thread per bus to do the actual device scan. Let's assume we have two busses, then usb_start creates scan1 and scan2.
The main thread needs to do:
while (!done(usb_start))
uthread_schedule();
The usb_start on the other hand is only interested in is own two threads, scan1 and scan2. It has to wait until both are done, and only those two:
while (!done(scan1) || !done(scan2))
uthread_schedule();
This can easily be written if threads can be assigned group IDs:
/* Main */usb_start_id = uthread_new_grp_id(); uthread_create(..., usb_start, NULL, usb_start_id); while (!uthread_grp_done(usb_start_id))
uthread_schedule();
/* usb_start() */scan_id = uthread_new_grp_id();uthread_create(..., usb_start, bus1, scan_id);uthread_create(..., usb_start, bus2, scan_id);
while (!uthread_grp_done(scan_id))
uthread_schedule();
Quoted 19 lines
Quoted 19 lines
lib/uthread.c new file +18
-0+ +/** +* uthread_grp_done() - test if all threads in a group are done +* +* @grp: the ID of the thread group that should be considered +* Return: false if the group contains at least one runnable thread (i.e., one +* thread which entry point has not returned yet), true otherwise +*/ +bool uthread_grp_done (unsigned int grp_id) +{ +struct uthread *next; + +list_for_each_entry (next, &main_thread.list, list) { +if (next->grp_id == grp_id && !next->done) +return false; + } + +return true;
Quoted 8 lines
Quoted 4 lines
+}
--
2.43.0Apart from the minor typos and the function that I can't figure out why we need this look pretty clean
Thanks!
Cheers,
Signature · 1 line
Jerome
Quoted 3 lines
Thnaks
/Ilias
Re: [PATCH v2 06/14] uthread: add cooperative multi-tasking interface
In reply to Jerome ForissierQuoted 1 line · Jerome Forissier
Add an new internal API called uthread (
Kconfigsymbol: UTHREAD) which
nits:
%s/an/a/
Quoted 41 lines
provides cooperative multi-tasking. The goal is to be able to improve the performance of some parts of U-Boot by overlapping lengthy operations, and also implement background jobs in the U-Boot shell. Each uthread has its own stack allocated on the heap. The default stack size is defined by the
UTHREAD_STACK_SIZEsymbol and is used whenuthread_create()receives zero for thestack_szargument.The implementation is based on context-switching via initjmp()/setjmp()/
longjmp()and is inspired from barebox threads [1]. A notion of thread group helps with dependencies, such as when a thread needs to block until a number of other threads have returned.The name "uthread" comes from "user-space threads" because the scheduling happens with no help from a higher privileged mode, contrary to more complex models where kernel threads are defined. But the 'u' may as well stand for 'U-Boot' since the bootloader may actually be running at any privilege level and the notion of user vs. kernel may not make much sense in this context.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
Signed-off-by Jerome Forissier <[email protected]>--- include/uthread.h | 44 ++++++++++++ lib/Kconfig | 21 ++++++ lib/Makefile | 2 + lib/uthread.c | 178 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+)create mode 100644
include/uthread.h
create mode 100644lib/uthread.cinclude/uthread.h new file +4
-0@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* +* Copyright 2025 Linaro Limited +*/
include/uthread.h line 14
Quoted 10 lines
include/uthread.h new file +10
-0+ +#include <linux/types.h> + +#ifndef _UTHREAD_H_ +#define _UTHREAD_H_ + +#ifdef CONFIG_UTHREAD + +int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id);
Every function needs a Shinx style documentation.
Quoted 96 lines
include/uthread.h new file +30
-0+bool uthread_schedule (void ); +unsigned int uthread_grp_new_id (void ); +bool uthread_grp_done (unsigned int grp_id); + +#else + +static inline int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id) +{ +fn (arg); +return 0 ; +} + +static inline bool uthread_schedule (void ) +{ +return false; +} + +static inline unsigned int uthread_grp_new_id (void ) +{ +return 0 ; +} + +static inline bool uthread_grp_done (unsigned int grp_id) +{ +return true; +} + +#endif /* CONFIG_UTHREAD */ +#endif /* _UTHREAD_H_ */ lib/Kconfig +21
-0@@ -1255,6 +1255,27 @@ config PHANDLE_CHECK_SEQ enable this config option to distinguish them using phandles in fdtdec_get_alias_seq() function. +config UTHREAD + bool "Enable thread support" + depends on HAVE_INITJMP + help + Implement a simple form of cooperative multi-tasking based on + context-switching via initjmp(), setjmp() and longjmp(). The + uthread_ interface enables the main thread of execution to create + one or more secondary threads and schedule them until they all have + returned. At any point a thread may suspend its execution and + schedule another thread, which allows for the efficient multiplexing + of leghthy operations. + +config UTHREAD_STACK_SIZE + int "Default uthread stack size" + depends on UTHREAD + default 32768 + help + The default stak size for uthreads. Each uthread has its own stack. + When the stack_sz argument to uthread_create() is zero then this + value is used. + endmenu source "lib/fwu_updates/Kconfig"lib/Makefile +2
-0@@ -164,6 +164,8 @@ obj-$(CONFIG_LIB_ELF) += elf.o obj-$(CONFIG_$(PHASE_)SEMIHOSTING) += semihosting.o +obj-$(CONFIG_UTHREAD) += uthread.o + # # Build a fast OID lookup registry from include/linux/oid_registry.h #lib/uthread.c new file +15
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright (C) 2021 Ahmad Fatoum, Pengutronix +* Copyright (C) 2025 Linaro Limited +* +* An implementation of cooperative multi-tasking inspired from barebox threads +* https://github.com/barebox/barebox/blob/master/common/bthread.c +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <malloc.h> +#include <stdint.h>
lib/uthread.c line 25
Quoted 10 lines
lib/uthread.c new file +10
-0+#include <uthread.h> + +static struct uthread { + void (*fn)(void *); + void *arg; + jmp_buf ctx; + void *stack; + bool done; + unsigned int grp_id; + struct list_head list;
The structure and all its components need to be documented.
Quoted 40 lines
lib/uthread.c new file +40
-0+} main_thread = { + .list = LIST_HEAD_INIT(main_thread.list), +}; + +static struct uthread *current = &main_thread; + +/** +* uthread_trampoline() - Call the current thread's entry point then resume the +* main thread. +* +* This is a helper function which is used as the @func argument to the inijmp() +* function, and ultimately invoked via setjmp(). It does not return, but +* instead longjmp()'s back to the main thread. +*/ +static void __noreturn uthread_trampoline (void ) +{ +struct uthread *curr = current; + + curr->fn (curr->arg); + curr->done = true; + current = &main_thread; +longjmp (current->ctx,1 ); +/* Not reached */ +while (true) + ; +} + +/** +* uthread_free() - Free memory used by a uthread object. +*/ +static void uthread_free (struct uthread *uthread) +{ +if (!uthread) +return ; +free (uthread->stack); +free (uthread); +} + +/** +* uthread_create() - Create a uthread object and make it ready for execution
lib/uthread.c line 75
Quoted 10 lines
lib/uthread.c new file +10
-0+* +* Threads are automatically deleted when then return from their entry point. +* +* @fn: the thread's entry point +* @arg: argument passed to the thread's entry point +* @stack_sz: stack size for the new thread (in bytes). The stack is allocated +* on the heap. +* @grp_id: an optional thread group ID that the new thread should belong to +* (zero for no group) +*/
This documentation should be move to the include and the include needs to be added to doc/api/.
lib/uthread.c line 77
Quoted 2 lines
lib/uthread.c new file +2
-0+int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, +unsigned int grp_id)
We should model the functions more like pthreads.
Let the caller provide struct uthread(). This will allow us to implement pthread_cancel() and phthread_join().
Best regards
Heinrich
Quoted 101 lines
lib/uthread.c new file +101
-0+{ +struct uthread *uthread; + +if (!stack_sz) + stack_sz =CONFIG_UTHREAD_STACK_SIZE ; + + uthread =calloc (1 ,sizeof (*uthread)); +if (!uthread) +return -1 ; + + uthread->stack =memalign (16 , stack_sz); +if (!uthread->stack) + goto err; + + uthread->fn = fn; + uthread->arg = arg; + uthread->grp_id = grp_id; + +list_add_tail (&uthread->list, ¤t->list); + +initjmp (uthread->ctx, uthread_trampoline, uthread->stack + stack_sz); + +return 0 ; +err: +uthread_free (uthread); +return -1 ; +} + +/** +* uthread_resume() - switch execution to a given thread +* +* @uthread: the thread object that should be resumed +*/ +static void uthread_resume (struct uthread *uthread) +{ +if (!setjmp (current->ctx)) { + current = uthread; +longjmp (uthread->ctx,1 ); + } +} + +/** +* uthread_schedule() - yield the CPU to the next runnable thread +* +* This function is called either by the main thread or any secondary thread +* (that is, any thread created via uthread_create()) to switch execution to +* the next runnable thread. +* +* Return: true if a thread was scheduled, false if no runnable thread was found +*/ +bool uthread_schedule (void ) +{ +struct uthread *next; +struct uthread *tmp; + +if (list_empty (¤t->list)) +return false; + +list_for_each_entry_safe (next, tmp, ¤t->list, list) { +if (!next->done) { +uthread_resume (next); +return true; + }else { +/* Found a 'done' thread, free its resources */ +list_del (&next->list); +uthread_free (next); + } + } +return false; +} + +/** +* uthread_grp_new_id() - return a new ID for a thread group +* +* Return: the new thread group ID +*/ +unsigned int uthread_grp_new_id (void ) +{ +static unsigned int id =0 ; + +return ++id; +} + +/** +* uthread_grp_done() - test if all threads in a group are done +* +* @grp: the ID of the thread group that should be considered +* Return: false if the group contains at least one runnable thread (i.e., one +* thread which entry point has not returned yet), true otherwise +*/ +bool uthread_grp_done (unsigned int grp_id) +{ +struct uthread *next; + +list_for_each_entry (next, &main_thread.list, list) { +if (next->grp_id == grp_id && !next->done) +return false; + } + +return true; +}
Re: [PATCH v2 06/14] uthread: add cooperative multi-tasking interface
Quoted 6 lines · Heinrich Schuchardt
Quoted 1 line · Jerome Forissier
Add an new internal API called uthread (
Kconfigsymbol: UTHREAD) whichnits:
%s/an/a/
Fixed in v3
Quoted 46 lines
Quoted 46 lines
provides cooperative multi-tasking. The goal is to be able to improve the performance of some parts of U-Boot by overlapping lengthy operations, and also implement background jobs in the U-Boot shell. Each uthread has its own stack allocated on the heap. The default stack size is defined by the
UTHREAD_STACK_SIZEsymbol and is used whenuthread_create()receives zero for thestack_szargument.The implementation is based on context-switching via initjmp()/setjmp()/
longjmp()and is inspired from barebox threads [1]. A notion of thread group helps with dependencies, such as when a thread needs to block until a number of other threads have returned.The name "uthread" comes from "user-space threads" because the scheduling happens with no help from a higher privileged mode, contrary to more complex models where kernel threads are defined. But the 'u' may as well stand for 'U-Boot' since the bootloader may actually be running at any privilege level and the notion of user vs. kernel may not make much sense in this context.
[1] https://github.com/barebox/barebox/blob/master/common/bthread.c
Signed-off-by Jerome Forissier <[email protected]>---
include/uthread.h| 44 ++++++++++++
lib/Kconfig | 21 ++++++
lib/Makefile | 2 +
lib/uthread.c | 178 ++++++++++++++++++++++++++++++++++++++++++++++4 files changed, 245 insertions(+)create mode 100644
include/uthread.h
create mode 100644lib/uthread.cinclude/uthread.h new file +8
-0@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* +* Copyright 2025 Linaro Limited +*/ + +#include <linux/types.h> + +#ifndef _UTHREAD_H_
Quoted 8 lines
include/uthread.h line 14
Quoted 6 lines
include/uthread.h new file +6
-0+#define _UTHREAD_H_ + +#ifdef CONFIG_UTHREAD + +int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, + unsigned int grp_id);Every function needs a Shinx style documentation.
Ack.
Quoted 101 lines
Quoted 101 lines
include/uthread.h new file +30
-0+bool uthread_schedule (void ); +unsigned int uthread_grp_new_id (void ); +bool uthread_grp_done (unsigned int grp_id); + +#else + +static inline int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, + unsigned int grp_id) +{ + fn(arg); + return 0; +} + +static inline bool uthread_schedule (void ) +{ + return false; +} + +static inline unsigned int uthread_grp_new_id (void ) +{ + return 0; +} + +static inline bool uthread_grp_done (unsigned int grp_id) +{ + return true; +} + +#endif /* CONFIG_UTHREAD */ +#endif /* _UTHREAD_H_ */ lib/Kconfig +0
-0@@ -1255,6 +1255,27 @@ config PHANDLE_CHECK_SEQenable this config option to distinguish them using phandles in
fdtdec_get_alias_seq()function.lib/Kconfig +21
-0+config UTHREAD + bool "Enable thread support" + depends on HAVE_INITJMP + help + Implement a simple form of cooperative multi-tasking based on + context-switching via initjmp(), setjmp() and longjmp(). The + uthread_ interface enables the main thread of execution to create + one or more secondary threads and schedule them until they all have + returned. At any point a thread may suspend its execution and + schedule another thread, which allows for the efficient multiplexing + of leghthy operations. + +config UTHREAD_STACK_SIZE + int "Default uthread stack size" + depends on UTHREAD + default 32768 + help + The default stak size for uthreads. Each uthread has its own stack. + When the stack_sz argument to uthread_create() is zero then this + value is used. +endmenu
source "
lib/fwu_updates/Kconfig"lib/Makefile +0
-0@@ -164,6 +164,8 @@ obj-$(CONFIG_LIB_ELF) += elf.oobj-$(CONFIG_$(PHASE_)SEMIHOSTING) += semihosting.o
lib/Makefile +2
-0+obj-$(CONFIG_UTHREAD) += uthread.o +#
# Build a fast OID lookup registry frominclude/linux/oid_registry.h#lib/uthread.c new file +19
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Copyright (C) 2021 Ahmad Fatoum, Pengutronix +* Copyright (C) 2025 Linaro Limited +* +* An implementation of cooperative multi-tasking inspired from barebox threads +* https://github.com/barebox/barebox/blob/master/common/bthread.c +*/ + +#include <compiler.h> +#include <asm/setjmp.h> +#include <linux/kernel.h> +#include <linux/list.h> +#include <malloc.h> +#include <stdint.h> +#include <uthread.h> + +static struct uthread { + void (*fn)(void *);
Quoted 8 lines
lib/uthread.c line 25
Quoted 6 lines
lib/uthread.c new file +6
-0+ void *arg; + jmp_buf ctx; + void *stack; + bool done; + unsigned int grp_id; + struct list_head list;The structure and all its components need to be documented.
Ack.
Quoted 46 lines
Quoted 46 lines
lib/uthread.c new file +45
-0+} main_thread = { + .list = LIST_HEAD_INIT(main_thread.list), +}; + +static struct uthread *current = &main_thread; + +/** +* uthread_trampoline() - Call the current thread's entry point then resume the +* main thread. +* +* This is a helper function which is used as the @func argument to the inijmp() +* function, and ultimately invoked via setjmp(). It does not return, but +* instead longjmp()'s back to the main thread. +*/ +static void __noreturn uthread_trampoline (void ) +{ + struct uthread *curr = current; + + curr->fn(curr->arg); + curr->done = true; + current = &main_thread; + longjmp(current->ctx, 1); + /* Not reached */ + while (true) + ; +} + +/** +* uthread_free() - Free memory used by a uthread object. +*/ +static void uthread_free (struct uthread *uthread) +{ + if (!uthread) + return; + free(uthread->stack); + free(uthread); +} + +/** +* uthread_create() - Create a uthread object and make it ready for execution +* +* Threads are automatically deleted when then return from their entry point. +* +* @fn: the thread's entry point +* @arg: argument passed to the thread's entry point
Quoted 8 lines
lib/uthread.c line 75
Quoted 5 lines
lib/uthread.c new file +5
-0+* @stack_sz: stack size for the new thread (in bytes). The stack is allocated +* on the heap. +* @grp_id: an optional thread group ID that the new thread should belong to +* (zero for no group) +*/ This documentation should be move to the include and the include needs to be added to doc/api/.
OK.
Quoted 8 lines
lib/uthread.c line 77
Quoted 3 lines
lib/uthread.c new file +2
-0+int uthread_create (void (*fn)(void *),void *arg,size_t stack_sz, + unsigned int grp_id)We should model the functions more like pthreads.
Let the caller provide struct
uthread(). This will allow us to implementpthread_cancel()andphthread_join().
I'd like to keep the ability to let the framework do as much as possible and the notion of grp_id already allows to wait and could be used to cancel too. That said, the uthread struct would be helpful to get the return status. I can do:
int uthread_create(struct uthread *uthread, void (*fn)(void *), void *arg,
size_t stack_sz, unsigned int grp_id);
...with uthread being optional (NULL allowed). Would that work for you?
Regards,
Signature · 1 line
Jerome
Quoted 107 lines
Best regards
Heinrich
Quoted 101 lines
lib/uthread.c new file +101
-0+{ + struct uthread *uthread; + + if (!stack_sz) + stack_sz = CONFIG_UTHREAD_STACK_SIZE; + + uthread = calloc(1, sizeof(*uthread)); + if (!uthread) + return -1; + + uthread->stack = memalign(16, stack_sz); + if (!uthread->stack) + goto err; + + uthread->fn = fn; + uthread->arg = arg; + uthread->grp_id = grp_id; + + list_add_tail(&uthread->list, ¤t->list); + + initjmp(uthread->ctx, uthread_trampoline, uthread->stack + stack_sz); + + return 0; +err: + uthread_free(uthread); + return -1; +} + +/** +* uthread_resume() - switch execution to a given thread +* +* @uthread: the thread object that should be resumed +*/ +static void uthread_resume (struct uthread *uthread) +{ + if (!setjmp(current->ctx)) { + current = uthread; + longjmp(uthread->ctx, 1); + } +} + +/** +* uthread_schedule() - yield the CPU to the next runnable thread +* +* This function is called either by the main thread or any secondary thread +* (that is, any thread created via uthread_create()) to switch execution to +* the next runnable thread. +* +* Return: true if a thread was scheduled, false if no runnable thread was found +*/ +bool uthread_schedule (void ) +{ + struct uthread *next; + struct uthread *tmp; + + if (list_empty(¤t->list)) + return false; + + list_for_each_entry_safe(next, tmp, ¤t->list, list) { + if (!next->done) { + uthread_resume(next); + return true; + } else { + /* Found a 'done' thread, free its resources */ + list_del(&next->list); + uthread_free(next); + } + } + return false; +} + +/** +* uthread_grp_new_id() - return a new ID for a thread group +* +* Return: the new thread group ID +*/ +unsigned int uthread_grp_new_id (void ) +{ + static unsigned int id = 0; + + return ++id; +} + +/** +* uthread_grp_done() - test if all threads in a group are done +* +* @grp: the ID of the thread group that should be considered +* Return: false if the group contains at least one runnable thread (i.e., one +* thread which entry point has not returned yet), true otherwise +*/ +bool uthread_grp_done (unsigned int grp_id) +{ + struct uthread *next; + + list_for_each_entry(next, &main_thread.list, list) { + if (next->grp_id == grp_id && !next->done) + return false; + } + + return true; +}
PATCH v2 7/14 cyclic: invoke uthread_schedule() from schedule()
In reply to Jerome ForissierMake the schedule() call from the CYCLIC framework a uthread scheduling point too. This makes sense since schedule() is called from a lot of places where uthread_schedule() needs to be called.
--- common/cyclic.c | 3 +++ include/u-boot/schedule.h | 3 +++ 2 files changed, 6 insertions(+)
common/cyclic.c +3 -0
@@ -16,6 +16,7 @@#include <linux/list.h> #include <asm/global_data.h> #include <u-boot/schedule.h> +#include <uthread.h> DECLARE_GLOBAL_DATA_PTR ;
@@ -100,6 +101,8 @@ void schedule(void)*/ if (gd)cyclic_run (); + +uthread_schedule (); }int cyclic_unregister_all (void )
include/u-boot/schedule.h +3 -0
@@ -3,6 +3,8 @@#ifndef _U_BOOT_SCHEDULE_H#define _U_BOOT_SCHEDULE_H +#include <uthread.h> +#if CONFIG_IS_ENABLED (CYCLIC )/** * schedule() - Schedule all potentially waiting tasks
@@ -17,6 +19,7 @@ void schedule(void);static inline void schedule (void ) { +uthread_schedule (); }#endif
Signature · 1 line
2.43.0
Re: [PATCH v2 07/14] cyclic: invoke uthread_schedule() from schedule()
Hi Jerome,
Quoted 5 lines · Jerome Forissier
Make the
schedule()call from the CYCLIC framework a uthread scheduling point too. This makes sense sinceschedule()is called from a lot of places whereuthread_schedule()needs to be called.Signed-off-by Jerome Forissier <[email protected]>
Frankly, at first I was wondering a bit, if and why another framework for "multitasking" is needed in U-Boot, additionally to the cyclic framework that I introduced a few years ago. Which was greatly enhanced by Rasmus over the time. But looking at your "uthread" implementation it makes sense to add such a probably more intuitive interface as well.
In general I'm really happy seeing activity in this "multitaking" area in U-Boot. As it brings a lot of new possibilities and, as you've also shown in your patchset, may greatly help reducing boot time in the USB example. :)
One question though:
Do you have some means in your uthread framework, measuring and perhaps limiting the time spent in these uthreads? If and how is a preemption of a uthread possible? So that it does not consume too much time resulting in e.g. things like dropping input chars on the prompt? Sorry, I did not thoroughly go through all your code to get the internals from there. It would be great if you could elaborate a bit on this.
For this patch:
Thanks,
Stefan
Quoted 40 lines
--- common/cyclic.c | 3 +++ include/u-boot/schedule.h | 3 +++ 2 files changed, 6 insertions(+)common/cyclic.c +3
-0@@ -16,6 +16,7 @@#include <linux/list.h> #include <asm/global_data.h> #include <u-boot/schedule.h> +#include <uthread.h> DECLARE_GLOBAL_DATA_PTR ;@@ -100,6 +101,8 @@ void schedule(void)*/ if (gd)cyclic_run (); + +uthread_schedule (); }int cyclic_unregister_all (void )include/u-boot/schedule.h +2
-0@@ -3,6 +3,8 @@#ifndef _U_BOOT_SCHEDULE_H#define _U_BOOT_SCHEDULE_H +#include <uthread.h> +#if CONFIG_IS_ENABLED (CYCLIC )/** * schedule() - Schedule all potentially waiting tasks
include/u-boot/schedule.h void schedule(void); · line 25
Quoted 7 lines
include/u-boot/schedule.h +1
-0@@ -17,6 +19,7 @@ void schedule(void);static inline void schedule (void ) { +uthread_schedule (); }#endif
Viele Grüße,
Stefan Roese
Signature · 3 lines
DENX Software Engineering GmbH, Managing Director: Erika Unter HRB 165235 Munich, Office: Kirchenstr.5, D-82194 Groebenzell, Germany Phone: (+49)-8142-66989-51 Fax: (+49)-8142-66989-80 Email: [email protected]
Re: [PATCH v2 07/14] cyclic: invoke uthread_schedule() from schedule()
Hi Stefan,
Quoted 7 lines · Stefan Roese
Hi Jerome,
Quoted 4 lines · Jerome Forissier
Make the
schedule()call from the CYCLIC framework a uthread scheduling point too. This makes sense sinceschedule()is called from a lot of places whereuthread_schedule()needs to be called.
Quoted 7 lines
Quoted 1 line
Signed-off-by Jerome Forissier <[email protected]>Frankly, at first I was wondering a bit, if and why another framework for "multitasking" is needed in U-Boot, additionally to the cyclic framework that I introduced a few years ago. Which was greatly enhanced by Rasmus over the time. But looking at your "uthread" implementation it makes sense to add such a probably more intuitive interface as well.
cyclic is clean and simple and certainly well suited when introducing new code. But when reworking older code I find it somewhat difficult to use due to the need to keep a context and pass it everywhere. This can lead to lots of changes when call stacks are deep.
Quoted 4 lines
In general I'm really happy seeing activity in this "multitaking" area in U-Boot. As it brings a lot of new possibilities and, as you've also shown in your patchset, may greatly help reducing boot time in the USB example. :)
Thank you.
Quoted 8 lines
One question though:
Do you have some means in your uthread framework, measuring and perhaps limiting the time spent in these uthreads? If and how is a preemption of a uthread possible? So that it does not consume too much time resulting in e.g. things like dropping input chars on the prompt? Sorry, I did not thoroughly go through all your code to get the internals from there. It would be great if you could elaborate a bit on this.
That's a very valid point. The short answer is no, there is no control over how long a thread keeps the CPU busy. uthread is similar to cyclic in that respect. That said, I occasionally noted the issue you mentioned about the console dropping characters, and yes it is annoying. I believe there is a simple solution though. If we can somehow make sure we're always scheduling the main thread every other time, we're much less likely to starve it from the CPU, especially when many threads are active. That is, assume we have 2 threads in addition to the main thread. The thread list is main -> thread1 -> thread2 and uthread_schedule() will iterate in that order. So back to main only after thread1 *and* thread2 have run and called uthread_schedule(). The idea is to schedule in a different order: main -> thread1 -> main -> thread2 -> main etc., effectively giving a higher priority to the main thread (which would be the console parsing thread).
I feel that introducing preemption would be opening a can of worms... Because in this case we would likely need locking everywhere. Without preemption, we still do need locking in theory, it's just that I have not yet identified critical sections where locks would be mandatory in the code that I have "parallelized". BTW I believe a uthread lock would be trivial to implement like so:
struct uthread_lock {
bool locked;
};void uthread_lock(struct uthread_lock *l)
{
while (l->locked)
uthread_schedule();
l->locked = true;
}
void uthread_unlock(struct uthread_lock *l)
{
l->locked = false;
}Quoted 7 lines
For this patch:
Reviewed-by Stefan Roese <[email protected]>Thanks,
Stefan
Thanks,
Signature · 1 line
Jerome
Quoted 46 lines
Quoted 37 lines
---
common/cyclic.c | 3 +++
include/u-boot/schedule.h| 3 +++2 files changed, 6 insertions(+)common/cyclic.c +1
-0@@ -16,6 +16,7 @@#include <linux/list.h> #include <asm/global_data.h> #include <u-boot/schedule.h> +#include <uthread.h> DECLARE_GLOBAL_DATA_PTR; @@ -100,6 +101,8 @@ void schedule(void) */ if (gd)
cyclic_run();
+
+uthread_schedule();
}
intcyclic_unregister_all(void)include/u-boot/schedule.h +0
-0@@ -3,6 +3,8 @@ #ifndef _U_BOOT_SCHEDULE_H #define _U_BOOT_SCHEDULE_H+#include <
uthread.h>
+
#ifCONFIG_IS_ENABLED(CYCLIC)
/**
*schedule()- Schedule all potentially waiting tasksinclude/u-boot/schedule.h void schedule(void); · line 23
Quoted 5 lines
include/u-boot/schedule.h +1
-0@@ -17,6 +19,7 @@ void schedule(void); static inline void schedule(void) { + uthread_schedule(); } #endifViele Grüße,
Stefan Roese
Re: [PATCH v2 07/14] cyclic: invoke uthread_schedule() from schedule()
Hi Jerome,
Quoted 39 lines · Jerome Forissier
Hi Stefan,
Quoted 7 lines · Stefan Roese
Hi Jerome,
Quoted 4 lines · Jerome Forissier
Make the
schedule()call from the CYCLIC framework a uthread scheduling point too. This makes sense sinceschedule()is called from a lot of places whereuthread_schedule()needs to be called.Quoted 7 lines
Quoted 1 line
Signed-off-by Jerome Forissier <[email protected]>Frankly, at first I was wondering a bit, if and why another framework for "multitasking" is needed in U-Boot, additionally to the cyclic framework that I introduced a few years ago. Which was greatly enhanced by Rasmus over the time. But looking at your "uthread" implementation it makes sense to add such a probably more intuitive interface as well.
cyclic is clean and simple and certainly well suited when introducing new code. But when reworking older code I find it somewhat difficult to use due to the need to keep a context and pass it everywhere. This can lead to lots of changes when call stacks are deep.
Quoted 4 lines
In general I'm really happy seeing activity in this "multitaking" area in U-Boot. As it brings a lot of new possibilities and, as you've also shown in your patchset, may greatly help reducing boot time in the USB example. :)
Thank you.
Quoted 8 lines
One question though:
Do you have some means in your uthread framework, measuring and perhaps limiting the time spent in these uthreads? If and how is a preemption of a uthread possible? So that it does not consume too much time resulting in e.g. things like dropping input chars on the prompt? Sorry, I did not thoroughly go through all your code to get the internals from there. It would be great if you could elaborate a bit on this.
Quoted 14 lines
That's a very valid point. The short answer is no, there is no control over how long a thread keeps the CPU busy. uthread is similar to cyclic in that respect. That said, I occasionally noted the issue you mentioned about the console dropping characters, and yes it is annoying. I believe there is a simple solution though. If we can somehow make sure we're always scheduling the main thread every other time, we're much less likely to starve it from the CPU, especially when many threads are active. That is, assume we have 2 threads in addition to the main thread. The thread list is main -> thread1 -> thread2 and
uthread_schedule()will iterate in that order. So back to main only after thread1 *and* thread2 have run and calleduthread_schedule(). The idea is to schedule in a different order: main -> thread1 -> main -> thread2 -> main etc., effectively giving a higher priority to the main thread (which would be the console parsing thread).
Sounds like a good idea / improvement to me.
Thanks,
Stefan
Quoted 31 lines
I feel that introducing preemption would be opening a can of worms... Because in this case we would likely need locking everywhere. Without preemption, we still do need locking in theory, it's just that I have not yet identified critical sections where locks would be mandatory in the code that I have "parallelized". BTW I believe a uthread lock would be trivial to implement like so:
struct uthread_lock { bool locked; };void
uthread_lock(struct uthread_lock *l){ while (l->locked) uthread_schedule(); l->locked = true; } void uthread_unlock(struct uthread_lock *l) { l->locked = false; }Quoted 7 lines
For this patch:
Reviewed-by Stefan Roese <[email protected]>Thanks,
StefanThanks,
Re: [PATCH v2 07/14] cyclic: invoke uthread_schedule() from schedule()
In reply to Jerome ForissierQuoted 6 lines · Jerome Forissier
Make the
schedule()call from the CYCLIC framework a uthread scheduling point too. This makes sense sinceschedule()is called from a lot of places whereuthread_schedule()needs to be called.Signed-off-by Jerome Forissier <[email protected]>
[...]
PATCH v2 8/14 lib: time: hook uthread_schedule() into udelay()
In reply to Jerome ForissierIntroduce a uthread scheduling loop into udelay() when CONFIG_UTHREAD is enabled. This means that any uthread calling into udelay() may yield to uthread and be scheduled again later.
While not strictly necessary since uthread_schedule() is already called by schedule(), tests show that it is desirable to call it in a tight loop instead of calling __usleep(). It gives more opportunities for other threads to make progress and results in better performances.
--- lib/time.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
lib/time.c +9 -1
@@ -17,6 +17,7 @@#include <asm/global_data.h> #include <asm/io.h> #include <linux/delay.h> +#include <uthread.h> #ifndef CFG_WD_PERIOD # define CFG_WD_PERIOD (10 * 1000 * 1000)/* 10 seconds default */
@@ -197,7 +198,14 @@ void udelay(unsigned long usec)do {schedule (); kv = usec >CFG_WD_PERIOD ?CFG_WD_PERIOD : usec; -__udelay (kv); +if (CONFIG_IS_ENABLED (UTHREAD )) { +ulong t0 =timer_get_us (); +while (timer_get_us () < t0 + kv) +uthread_schedule (); + }else { +__udelay (kv); + } usec -= kv; }while (usec); + }
Signature · 1 line
2.43.0
Re: [PATCH v2 08/14] lib: time: hook uthread_schedule() into udelay()
Hi Jerome,
Quoted 10 lines · Jerome Forissier
Introduce a uthread scheduling loop into
udelay()whenCONFIG_UTHREADis enabled. This means that any uthread calling intoudelay()may yield to uthread and be scheduled again later.While not strictly necessary since
uthread_schedule()is already called byschedule(),
tests show that it is desirable to call it in a tight
loop instead of calling__usleep(). It gives more opportunities for other threads to make progress and results in better performances.
Some examples of timing gains would be nice.
Quoted 19 lines
Signed-off-by Jerome Forissier <[email protected]>--- lib/time.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)lib/time.c +1
-0@@ -17,6 +17,7 @@#include <asm/global_data.h> #include <asm/io.h> #include <linux/delay.h> +#include <uthread.h> #ifndef CFG_WD_PERIOD # define CFG_WD_PERIOD (10 * 1000 * 1000)/* 10 seconds default */
lib/time.c void udelay(unsigned long usec) · line 203
Quoted 7 lines
lib/time.c +3
-1@@ -197,7 +198,14 @@ void udelay(unsigned long usec) do { schedule(); kv = usec > CFG_WD_PERIOD ? CFG_WD_PERIOD : usec; - __udelay(kv); + if (CONFIG_IS_ENABLED(UTHREAD)) { + ulong t0 = timer_get_us(); + while (timer_get_us() < t0 + kv)
Do we make progress by constantly scheduling new tasks? Perhaps we should at least leave the task running for some time?
Thanks
/Ilias
Quoted 11 lines
lib/time.c +5
-1+uthread_schedule (); + }else { +__udelay (kv); + } usec -= kv; }while (usec); + } --2.43.0
Re: [PATCH v2 08/14] lib: time: hook uthread_schedule() into udelay()
Quoted 33 lines · Ilias Apalodimas
Hi Jerome,
Quoted 10 lines · Jerome Forissier
Introduce a uthread scheduling loop into
udelay()whenCONFIG_UTHREADis enabled. This means that any uthread calling intoudelay()may yield to uthread and be scheduled again later.While not strictly necessary since
uthread_schedule()is already called byschedule(),
tests show that it is desirable to call it in a tight
loop instead of calling__usleep(). It gives more opportunities for other threads to make progress and results in better performances.Some examples of timing gains would be nice.
Quoted 16 lines
Signed-off-by Jerome Forissier <[email protected]>--- lib/time.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)lib/time.c +1
-0@@ -17,6 +17,7 @@#include <asm/global_data.h> #include <asm/io.h> #include <linux/delay.h> +#include <uthread.h>
Quoted 13 lines
lib/time.c void udelay(unsigned long usec) · line 203
Quoted 10 lines
lib/time.c +3
-1#ifndef CFG_WD_PERIOD # define CFG_WD_PERIOD (10 * 1000 * 1000)/* 10 seconds default */ @@ -197,7 +198,14 @@ void udelay(unsigned long usec) do { schedule(); kv = usec > CFG_WD_PERIOD ? CFG_WD_PERIOD : usec; - __udelay(kv); + if (CONFIG_IS_ENABLED(UTHREAD)) { + ulong t0 = timer_get_us(); + while (timer_get_us() < t0 + kv)Do we make progress by constantly scheduling new tasks? Perhaps we should at least leave the task running for some time?
If I get the point, the UTHREAD is a cooperative framework, which means a task yields the control flow only when it considers nothing else could be done. And there's no preemption (at least in this revision). Thus I don't think it's a problem.
Quoted 2 lines
Thanks
/Ilias
Best regards,
Yao Zi
Quoted 11 lines
Quoted 11 lines
lib/time.c +5
-1+uthread_schedule (); + }else { +__udelay (kv); + } usec -= kv; }while (usec); + } --2.43.0
Re: [PATCH v2 08/14] lib: time: hook uthread_schedule() into udelay()
Quoted 10 lines · Yao Zi
Quoted 9 lines · Ilias Apalodimas
Hi Jerome,
Quoted 5 lines · Jerome Forissier
Introduce a uthread scheduling loop into
udelay()whenCONFIG_UTHREADis enabled. This means that any uthread calling intoudelay()may yield to uthread and be scheduled again later.
Quoted 7 lines
Quoted 7 lines
Quoted 5 lines
While not strictly necessary since
uthread_schedule()is already called byschedule(),
tests show that it is desirable to call it in a tight
loop instead of calling__usleep(). It gives more opportunities for other threads to make progress and results in better performances.Some examples of timing gains would be nice.
I'll try to provide numbers in v3.
Quoted 31 lines
Quoted 17 lines
Quoted 17 lines
Signed-off-by Jerome Forissier <[email protected]>--- lib/time.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)lib/time.c +1
-0@@ -17,6 +17,7 @@#include <asm/global_data.h> #include <asm/io.h> #include <linux/delay.h> +#include <uthread.h> Quoted 13 lines
lib/time.c void udelay(unsigned long usec) · line 203
Quoted 10 lines
lib/time.c +3
-1#ifndef CFG_WD_PERIOD # define CFG_WD_PERIOD (10 * 1000 * 1000)/* 10 seconds default */ @@ -197,7 +198,14 @@ void udelay(unsigned long usec) do { schedule(); kv = usec > CFG_WD_PERIOD ? CFG_WD_PERIOD : usec; - __udelay(kv); + if (CONFIG_IS_ENABLED(UTHREAD)) { + ulong t0 = timer_get_us(); + while (timer_get_us() < t0 + kv)Do we make progress by constantly scheduling new tasks? Perhaps we should at least leave the task running for some time?
Quoted 4 lines
If I get the point, the UTHREAD is a cooperative framework, which means a task yields the control flow only when it considers nothing else could be done. And there's no preemption (at least in this revision). Thus I don't think it's a problem.
That's correct. Code always executes uninterrupted until it reaches uthread_schedule().
Thanks,
Signature · 1 line
Jerome
Quoted 18 lines
Quoted 3 lines
Thanks
/IliasBest regards,
Yao ZiQuoted 11 lines
Quoted 11 lines
lib/time.c +5
-1+uthread_schedule (); + }else { +__udelay (kv); + } usec -= kv; }while (usec); + } --2.43.0
Re: [PATCH v2 08/14] lib: time: hook uthread_schedule() into udelay()
In reply to Yao ZiHi Yao
Quoted 35 lines · Yao Zi
Quoted 33 lines · Ilias Apalodimas
Hi Jerome,
Quoted 10 lines · Jerome Forissier
Introduce a uthread scheduling loop into
udelay()whenCONFIG_UTHREADis enabled. This means that any uthread calling intoudelay()may yield to uthread and be scheduled again later.While not strictly necessary since
uthread_schedule()is already called byschedule(),
tests show that it is desirable to call it in a tight
loop instead of calling__usleep(). It gives more opportunities for other threads to make progress and results in better performances.Some examples of timing gains would be nice.
Quoted 16 lines
Signed-off-by Jerome Forissier <[email protected]>--- lib/time.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)lib/time.c +1
-0@@ -17,6 +17,7 @@#include <asm/global_data.h> #include <asm/io.h> #include <linux/delay.h> +#include <uthread.h>
Quoted 10 lines
Quoted 10 lines
lib/time.c void udelay(unsigned long usec) · line 203
Quoted 10 lines
lib/time.c +3
-1#ifndef CFG_WD_PERIOD # define CFG_WD_PERIOD (10 * 1000 * 1000)/* 10 seconds default */ @@ -197,7 +198,14 @@ void udelay(unsigned long usec) do { schedule(); kv = usec > CFG_WD_PERIOD ? CFG_WD_PERIOD : usec; - __udelay(kv); + if (CONFIG_IS_ENABLED(UTHREAD)) { + ulong t0 = timer_get_us(); + while (timer_get_us() < t0 + kv)
I think it's better to rewrite this as timer_get_us() - t0 < k.
Quoted 10 lines
Quoted 3 lines
Do we make progress by constantly scheduling new tasks? Perhaps we should at least leave the task running for some time?
If I get the point, the UTHREAD is a cooperative framework, which means a task yields the control flow only when it considers nothing else could be done.
And there's no preemption (at least in this revision). Thus I don't think it's a problem.
I was implying it would cause a problem, I was just wondering if we could optimize it easily somehow. But i think it's fine as is
thanks
/Ilias
Quoted 18 lines
Quoted 3 lines
Thanks
/IliasBest regards,
Yao ZiQuoted 11 lines
Quoted 11 lines
lib/time.c +5
-1+uthread_schedule (); + }else { +__udelay (kv); + } usec -= kv; }while (usec); + } --2.43.0
PATCH v2 9/14 doc: develop: add documentation for uthreads
In reply to Jerome ForissierAdd documentation for the uthread framework.
--- doc/develop/index.rst | 1 + doc/develop/uthread.rst | 136 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 doc/develop/uthread.rst
doc/develop/index.rst +1 -0
@@ -53,6 +53,7 @@ Implementation spl falcon uefi/index + uthread vbe version
doc/develop/uthread.rst new file +136 -0
136 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v2 10/14 test: lib: add uthread test
In reply to Jerome ForissierAdd a uhread framework test to the lib tests.
--- test/lib/Makefile | 1 + test/lib/uthread.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 test/lib/uthread.c
test/lib/Makefile +1 -0
@@ -31,6 +31,7 @@ obj-$(CONFIG_CRC8) += test_crc8.o obj-$(CONFIG_UT_LIB_CRYPT) += test_crypt.o obj-$(CONFIG_UT_TIME) += time.o obj-$(CONFIG_$(XPL_)UT_UNICODE) += unicode.o +obj-$(CONFIG_UTHREAD) += uthread.o obj-$(CONFIG_LIB_UUID) += uuid.o else obj-$(CONFIG_SANDBOX) += kconfig_spl.o
test/lib/uthread.c new file +68 -0
68 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v2 10/14] test: lib: add uthread test
Quoted 97 lines · Jerome Forissier
Add a uhread framework test to the lib tests.
Signed-off-by Jerome Forissier <[email protected]>--- test/lib/Makefile | 1 + test/lib/uthread.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 test/lib/uthread.ctest/lib/Makefile +1
-0@@ -31,6 +31,7 @@ obj-$(CONFIG_CRC8) += test_crc8.o obj-$(CONFIG_UT_LIB_CRYPT) += test_crypt.o obj-$(CONFIG_UT_TIME) += time.o obj-$(CONFIG_$(XPL_)UT_UNICODE) += unicode.o +obj-$(CONFIG_UTHREAD) += uthread.o obj-$(CONFIG_LIB_UUID) += uuid.o else obj-$(CONFIG_SANDBOX) += kconfig_spl.otest/lib/uthread.c new file +68
-1@@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* +* Copyright 2025 Linaro Limited +* +* Unit test for uthread +*/ + +#include <stdbool.h> +#include <test/lib.h> +#include <test/ut.h> +#include <uthread.h> + +static int count; + +static void worker (void *arg) +{ +int loops = (int )(unsigned long )arg; +int i; + +for (i =0 ; i < loops; i++) { + count++; +uthread_schedule (); + } +} + +static int lib_uthread (struct unit_test_state *uts) +{ +int i; +int id1, id2; + + count =0 ; + id1 =uthread_grp_new_id (); +ut_assert (id1 !=0 ); + id2 =uthread_grp_new_id (); +ut_assert (id2 !=0 ); +ut_assert (id1 != id2); +ut_assertok (uthread_create (worker, (void *)5 ,0 , id1)); +ut_assertok (uthread_create (worker, (void *)10 ,0 ,0 )); +/* +* The first call is expected to schedule the first worker, which will +* schedule the second one, which will schedule back to the main thread +* (here). Therefore count should be 2. +*/ +ut_assert (uthread_schedule ()); +ut_asserteq (2 , count); +ut_assert (!uthread_grp_done (id1)); +/* Four more calls should bring the count to 10 */ +for (i =0 ; i <4 ; i++) { +ut_assert (!uthread_grp_done (id1)); +ut_assert (uthread_schedule ()); + } +ut_asserteq (10 , count); +/* This one allows the first worker to exit */ +ut_assert (uthread_schedule ()); +/* At this point there should be no runnable thread in group 'id1' */ +ut_assert (uthread_grp_done (id1)); +/* Five more calls for the second worker to finish incrementing */ +for (i =0 ; i <5 ; i++) +ut_assert (uthread_schedule ()); +ut_asserteq (15 , count); +/* Plus one call to let the second worker return from its entry point */ +ut_assert (uthread_schedule ()); +/* Now both tasks should be done, schedule should return false */ +ut_assert (!uthread_schedule ()); + +return 0 ; +} +LIB_TEST (lib_uthread,0 ); --
Quoted 2 lines
2.43.0
PATCH v2 11/14 dm: usb: move bus initialization into new static function usb_init_bus()
In reply to Jerome ForissierTo prepare for the introduction of coroutines in the USB initialization sequence, move code out of usb_init() into a new helper function:usb_init_bus(). No functional change.
--- drivers/usb/host/usb-uclass.c | 88 +++++++++++++++++++---------------- 1 file changed, 48 insertions(+), 40 deletions(-)
drivers/usb/host/usb-uclass.c +48 -40
@@ -287,9 +287,55 @@ static int usb_probe_companion(struct udevice *bus)return 0 ; } +static int controllers_initialized; + +static void usb_init_bus (struct udevice *bus) +{ +int ret; + +/* init low_level USB */ +printf ("Bus %s: " , bus->name); + +/* +* For Sandbox, we need scan the device tree each time when we +* start the USB stack, in order to re-create the emulated USB +* devices and bind drivers for them before we actually do the +* driver probe. +* +* For USB onboard HUB, we need to do some non-trivial init +* like enabling a power regulator, before enumeration. +*/ +if (IS_ENABLED (CONFIG_SANDBOX ) || +IS_ENABLED (CONFIG_USB_ONBOARD_HUB )) { + ret =dm_scan_fdt_dev (bus); +if (ret) { +printf ("USB device scan from fdt failed (%d)" , ret); +return ; + } + } + + ret =device_probe (bus); +if (ret == -ENODEV ) {/* No such device. */ +puts ("Port not available.\n" ); + controllers_initialized++; +return ; + } + +if (ret) {/* Other error. */ +printf ("probe failed, error %d\n" , ret); +return ; + } + + ret =usb_probe_companion (bus); +if (ret) +return ; + + controllers_initialized++; + usb_started = true; +} +int usb_init (void ) { -int controllers_initialized =0 ;struct usb_uclass_priv *uc_priv;struct usb_bus_priv *priv;struct udevice *bus;
@@ -305,45 +351,7 @@ int usb_init(void) uc_priv =uclass_get_priv (uc); uclass_foreach_dev(bus, uc) { -/* init low_level USB */ -printf ("Bus %s: " , bus->name); - -/* -* For Sandbox, we need scan the device tree each time when we -* start the USB stack, in order to re-create the emulated USB -* devices and bind drivers for them before we actually do the -* driver probe. -* -* For USB onboard HUB, we need to do some non-trivial init -* like enabling a power regulator, before enumeration. -*/ -if (IS_ENABLED (CONFIG_SANDBOX ) || -IS_ENABLED (CONFIG_USB_ONBOARD_HUB )) { - ret =dm_scan_fdt_dev (bus); -if (ret) { -printf ("USB device scan from fdt failed (%d)" , ret); -continue ; - } - } - - ret =device_probe (bus); -if (ret == -ENODEV ) {/* No such device. */ -puts ("Port not available.\n" ); - controllers_initialized++; -continue ; - } - -if (ret) {/* Other error. */ -printf ("probe failed, error %d\n" , ret); -continue ; - } - - ret =usb_probe_companion (bus); -if (ret) -continue ; - - controllers_initialized++; - usb_started = true; +usb_init_bus (bus); }/*
Signature · 1 line
2.43.0
Re: [PATCH v2 11/14] dm: usb: move bus initialization into new static function usb_init_bus()
Quoted 119 lines · Jerome Forissier
To prepare for the introduction of coroutines in the USB initialization sequence, move code out of
usb_init()into a new helper function:usb_init_bus(). No functional change.Signed-off-by Jerome Forissier <[email protected]>--- drivers/usb/host/usb-uclass.c | 88 +++++++++++++++++++---------------- 1 file changed, 48 insertions(+), 40 deletions(-)drivers/usb/host/usb-uclass.c +48
-41@@ -287,9 +287,55 @@ static int usb_probe_companion(struct udevice *bus)return 0 ; } +static int controllers_initialized; + +static void usb_init_bus (struct udevice *bus) +{ +int ret; + +/* init low_level USB */ +printf ("Bus %s: " , bus->name); + +/* +* For Sandbox, we need scan the device tree each time when we +* start the USB stack, in order to re-create the emulated USB +* devices and bind drivers for them before we actually do the +* driver probe. +* +* For USB onboard HUB, we need to do some non-trivial init +* like enabling a power regulator, before enumeration. +*/ +if (IS_ENABLED (CONFIG_SANDBOX ) || +IS_ENABLED (CONFIG_USB_ONBOARD_HUB )) { + ret =dm_scan_fdt_dev (bus); +if (ret) { +printf ("USB device scan from fdt failed (%d)" , ret); +return ; + } + } + + ret =device_probe (bus); +if (ret == -ENODEV ) {/* No such device. */ +puts ("Port not available.\n" ); + controllers_initialized++; +return ; + } + +if (ret) {/* Other error. */ +printf ("probe failed, error %d\n" , ret); +return ; + } + + ret =usb_probe_companion (bus); +if (ret) +return ; + + controllers_initialized++; + usb_started = true; +} +int usb_init (void ) { -int controllers_initialized =0 ;struct usb_uclass_priv *uc_priv;struct usb_bus_priv *priv;struct udevice *bus;@@ -305,45 +351,7 @@ int usb_init(void) uc_priv =uclass_get_priv (uc); uclass_foreach_dev(bus, uc) { -/* init low_level USB */ -printf ("Bus %s: " , bus->name); - -/* -* For Sandbox, we need scan the device tree each time when we -* start the USB stack, in order to re-create the emulated USB -* devices and bind drivers for them before we actually do the -* driver probe. -* -* For USB onboard HUB, we need to do some non-trivial init -* like enabling a power regulator, before enumeration. -*/ -if (IS_ENABLED (CONFIG_SANDBOX ) || -IS_ENABLED (CONFIG_USB_ONBOARD_HUB )) { - ret =dm_scan_fdt_dev (bus); -if (ret) { -printf ("USB device scan from fdt failed (%d)" , ret); -continue ; - } - } - - ret =device_probe (bus); -if (ret == -ENODEV ) {/* No such device. */ -puts ("Port not available.\n" ); - controllers_initialized++; -continue ; - } - -if (ret) {/* Other error. */ -printf ("probe failed, error %d\n" , ret); -continue ; - } - - ret =usb_probe_companion (bus); -if (ret) -continue ; - - controllers_initialized++; - usb_started = true; +usb_init_bus (bus); }/* --
Quoted 2 lines
2.43.0
PATCH v2 12/14 dm: usb: initialize and scan multiple buses simultaneously with uthread
In reply to Jerome ForissierUse the uthread framework to initialize and scan USB buses in parallel for better performance. The console output is slightly modified with a final per-bus report of the number of devices found, common to UTHREAD and !UTHREAD. The USB tests are updated accordingly.
Tested on two platforms:
1. arm64 QEMU on a somewhat contrived example (4 USB buses, each with one audio device, one keyboard, one mouse and one tablet)
$ make qemu_arm64_defconfig
$ make -j$(nproc) CROSS_COMPILE="ccache aarch64-linux-gnu-"
$ qemu-system-aarch64 -M virt -nographic -cpu max -bios u-boot.bin \
$(for i in {1..4}; do echo -device qemu-xhci,id=xhci$i \
-device\ usb-{audio,kbd,mouse,tablet},bus=xhci$i.0; \
done)2. i.MX93 EVK (imx93_11x11_evk_defconfig) with two USB hubs, each with one webcam and one ethernet adapter, resulting in the following device tree:
USB device tree:
1 Hub (480 Mb/s, 0mA)
| u-boot EHCI Host Controller
|
+-2 Hub (480 Mb/s, 100mA)
| GenesysLogic USB2.1 Hub
|
+-3 Vendor specific (480 Mb/s, 350mA)
| Realtek USB 10/100/1000 LAN 001000001
|
+-4 (480 Mb/s, 500mA)
HD Pro Webcam C920 8F7CD51F 1 Hub (480 Mb/s, 0mA)
| u-boot EHCI Host Controller
|
+-2 Hub (480 Mb/s, 100mA)
| USB 2.0 Hub
|
+-3 Vendor specific (480 Mb/s, 200mA)
| Realtek USB 10/100/1000 LAN 000001
|
+-4 (480 Mb/s, 500mA)
Generic OnLan-CS30 201801010008Note that i.MX was tested on top of the downstream repository [1] since USB doesn't work in the upstream master branch.
[1] https://github.com/nxp-imx/uboot-imx/tree/lf-6.6.52-2.2.0
commit 6c4545203d12 ("LF-13928 update key for capsule")The time spent in usb_init() ("usb start" command) is reported on the console. Here are the results:
| CONFIG_UTHREAD=n | CONFIG_UTHREAD=y
--------+------------------+-----------------
QEMU | 5628 ms | 2212 ms i.MX93 | 4591 ms | 2441 ms
--- drivers/usb/host/usb-uclass.c | 92 ++++++++++++++++++++++++++++------- test/boot/bootdev.c | 14 +++--- test/boot/bootflow.c | 2 +- 3 files changed, 83 insertions(+), 25 deletions(-)
drivers/usb/host/usb-uclass.c +75 -17
@@ -9,6 +9,7 @@#define LOG_CATEGORY UCLASS_USB#include <bootdev.h> +#include <uthread.h> #include <dm.h> #include <errno.h> #include <log.h>
@@ -17,6 +18,7 @@#include <dm/device-internal.h> #include <dm/lists.h> #include <dm/uclass-internal.h> +#include <time.h> static bool asynch_allowed;
@@ -221,25 +223,18 @@ int usb_stop(void)return err; } -static void usb_scan_bus (struct udevice *bus,bool recurse) +static void _usb_scan_bus (void *arg) { +struct udevice *bus = (struct udevice *)arg;struct usb_bus_priv *priv;struct udevice *dev;int ret; priv =dev_get_uclass_priv (bus); -assert (recurse);/* TODO: Support non-recusive */ - -printf ("scanning bus %s for devices... " , bus->name); -debug ("\n" ); ret =usb_scan_device (bus,0 ,USB_SPEED_FULL , &dev);if (ret) -printf ("failed, error %d\n" , ret); -else if (priv->next_addr ==0 ) -printf ("No USB Device found\n" ); -else -printf ("%d USB Device(s) found\n" , priv->next_addr); +printf ("Scanning bus %s failed, error %d\n" , bus->name, ret); }static void remove_inactive_children (struct uclass *uc,struct udevice *bus)
@@ -289,12 +284,12 @@ static int usb_probe_companion(struct udevice *bus)static int controllers_initialized; -static void usb_init_bus (struct udevice *bus) +static void _usb_init_bus (void *arg) { +struct udevice *bus = (struct udevice *)arg;int ret;/* init low_level USB */ -printf ("Bus %s: " , bus->name);/* * For Sandbox, we need scan the device tree each time when we
@@ -309,33 +304,84 @@ static void usb_init_bus(struct udevice *bus) IS_ENABLED(CONFIG_USB_ONBOARD_HUB)) { ret =dm_scan_fdt_dev (bus);if (ret) { -printf ("USB device scan from fdt failed (%d)" , ret); +printf ("Bus %s: USB device scan from fdt failed (%d)\n" , + bus->name, ret);return ; } } ret =device_probe (bus);if (ret == -ENODEV ) {/* No such device. */ -puts ("Port not available.\n" ); +printf ("Bus %s: Port not available.\n" , bus->name); controllers_initialized++;return ; }if (ret) {/* Other error. */ -printf ("probe failed, error %d\n" , ret); +printf ("Bus %s: probe failed, error %d\n" , bus->name, ret);return ; } ret =usb_probe_companion (bus); -if (ret) +if (ret) {return ; + } controllers_initialized++; usb_started = true; } +static int nthr; +static int grp_id; + +static void usb_init_bus (struct udevice *bus) +{ +if (!grp_id) + grp_id =uthread_grp_new_id (); +if (!uthread_create (_usb_init_bus, (void *)bus,0 , grp_id)) + nthr++; +} + +static void usb_scan_bus (struct udevice *bus,bool recurse) +{ +if (!grp_id) + grp_id =uthread_grp_new_id (); +if (!uthread_create (_usb_scan_bus, (void *)bus,0 , grp_id)) + nthr++; +} + +static void usb_report_devices (struct uclass *uc) +{ +struct usb_bus_priv *priv; +struct udevice *bus; + + uclass_foreach_dev(bus, uc) { +if (!device_active (bus)) +continue ; + priv =dev_get_uclass_priv (bus); +printf ("Bus %s: " , bus->name); +if (priv->next_addr ==0 ) +printf ("No USB Device found\n" ); +else +printf ("%d USB Device(s) found\n" , priv->next_addr); + } +} + +static void run_threads (void ) +{ +#if CONFIG_IS_ENABLED (UTHREAD ) +if (!nthr) +return ; +while (!uthread_grp_done (grp_id)) +uthread_schedule (); + nthr =0 ; + grp_id =0 ; +#endif +} +int usb_init (void ) { +unsigned long t0 =timer_get_us ();struct usb_uclass_priv *uc_priv;struct usb_bus_priv *priv;struct udevice *bus;
@@ -354,6 +400,9 @@ int usb_init(void)usb_init_bus (bus); } +if (CONFIG_IS_ENABLED (UTHREAD )) +run_threads (); +/* * lowlevel init done, now scan the bus for devices i.e. search HUBs * and configure them, first scan primary controllers.
@@ -367,6 +416,9 @@ int usb_init(void)usb_scan_bus (bus, true); } +if (CONFIG_IS_ENABLED (UTHREAD )) +run_threads (); +/* * Now that the primary controllers have been scanned and have handed * over any devices they do not understand to their companions, scan
@@ -383,7 +435,10 @@ int usb_init(void) } } -debug ("scan end\n" ); +if (CONFIG_IS_ENABLED (UTHREAD )) +run_threads (); + +usb_report_devices (uc);/* Remove any devices that were not found on this scan */ remove_inactive_children (uc, bus);
@@ -397,6 +452,9 @@ int usb_init(void)if (controllers_initialized ==0 )printf ("No USB controllers found\n" ); +debug ("USB initialized in %ld ms\n" , + (timer_get_us () - t0) /1000 ); +return usb_started ?0 : -ENOENT ; }
test/boot/bootdev.c +7 -7
@@ -392,8 +392,8 @@ static int bootdev_test_hunter(struct unit_test_state *uts)ut_assert_console_end ();ut_assertok (bootdev_hunt ("usb1" , false)); -ut_assert_nextline ( -"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" ); +ut_assert_skip_to_line ( +"Bus usb@1: 5 USB Device(s) found" );ut_assert_console_end ();/* USB is 7th in the list, so bit 8 */
@@ -448,8 +448,8 @@ static int bootdev_test_cmd_hunt(struct unit_test_state *uts)ut_assert_nextline ("scanning bus for devices..." );ut_assert_skip_to_line ("Hunting with: spi_flash" );ut_assert_nextline ("Hunting with: usb" ); -ut_assert_nextline ( -"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" ); +ut_assert_skip_to_line ( +"Bus usb@1: 5 USB Device(s) found" );ut_assert_nextline ("Hunting with: virtio" );ut_assert_console_end ();
@@ -550,8 +550,8 @@ static int bootdev_test_hunt_prio(struct unit_test_state *uts)ut_assertok (bootdev_hunt_prio (BOOTDEVP_5_SCAN_SLOW , true));ut_assert_nextline ("Hunting with: ide" );ut_assert_nextline ("Hunting with: usb" ); -ut_assert_nextline ( -"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" ); +ut_assert_skip_to_line ( +"Bus usb@1: 5 USB Device(s) found" );ut_assert_console_end ();return 0 ;
@@ -603,7 +603,7 @@ static int bootdev_test_hunt_label(struct unit_test_state *uts)ut_assertnonnull (dev);ut_asserteq_str ("usb_mass_storage.lun0.bootdev" , dev->name);ut_asserteq (BOOTFLOW_METHF_SINGLE_UCLASS , mflags); -ut_assert_nextlinen ("Bus usb@1: scanning bus usb@1" ); +ut_assert_nextline ("Bus usb@1: 5 USB Device(s) found" );ut_assert_console_end ();return 0 ;
test/boot/bootflow.c +1 -1
@@ -1289,7 +1289,7 @@ static int bootflow_efi(struct unit_test_state *uts)ut_assertok (run_command ("bootflow scan" ,0 ));ut_assert_skip_to_line ( -"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" ); +"Bus usb@1: 5 USB Device(s) found" );ut_assertok (run_command ("bootflow list" ,0 ));
Signature · 1 line
2.43.0
Re: [PATCH v2 12/14] dm: usb: initialize and scan multiple buses simultaneously with uthread
Hi Jerome,
Quoted 61 lines · Jerome Forissier
Use the uthread framework to initialize and scan USB buses in parallel for better performance. The console output is slightly modified with a final per-bus report of the number of devices found, common to UTHREAD and !UTHREAD. The USB tests are updated accordingly.
Tested on two platforms:
1. arm64 QEMU on a somewhat contrived example (4 USB buses, each with one audio device, one keyboard, one mouse and one tablet)
$ make qemu_arm64_defconfig $ make -j$(nproc) CROSS_COMPILE="ccache aarch64-linux-gnu-" $ qemu-system-aarch64 -M virt -nographic -cpu max -bios u-boot.bin \ $(for i in {1..4}; do echo -device qemu-xhci,id=xhci$i \ -device\ usb-{audio,kbd,mouse,tablet},bus=xhci$i.0; \ done)2. i.MX93 EVK (
imx93_11x11_evk_defconfig) with two USB hubs, each with one webcam and one ethernet adapter, resulting in the following device tree:USB device tree:
1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | GenesysLogic USB2.1 Hub | +-3 Vendor specific (480 Mb/s, 350mA) | Realtek USB 10/100/1000 LAN 001000001 | +-4 (480 Mb/s, 500mA) HD Pro Webcam C920 8F7CD51F 1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | USB 2.0 Hub | +-3 Vendor specific (480 Mb/s, 200mA) | Realtek USB 10/100/1000 LAN 000001 | +-4 (480 Mb/s, 500mA) Generic OnLan-CS30 201801010008Note that i.MX was tested on top of the downstream repository [1] since USB doesn't work in the upstream master branch.
[1] https://github.com/nxp-imx/uboot-imx/tree/lf-6.6.52-2.2.0
commit 6c4545203d12 ("LF-13928 update key for capsule")The time spent in
usb_init()("usb start" command) is reported on the console. Here are the results:|
CONFIG_UTHREAD=n|CONFIG_UTHREAD=y
--------+------------------+-----------------QEMU | 5628 ms | 2212 ms i.MX93 | 4591 ms | 2441 ms
Quoted 6 lines
Signed-off-by Jerome Forissier <[email protected]>--- drivers/usb/host/usb-uclass.c | 92 ++++++++++++++++++++++++++++------- test/boot/bootdev.c | 14 +++--- test/boot/bootflow.c | 2 +- 3 files changed, 83 insertions(+), 25 deletions(-)
What happens to output produced by a thread? Does it get stored somewhere and written when the thread completes, or do the threads intermingle their output?
I'm not sure if you saw my email about using a state machine for USB. If so, could you please point me to your reply?
Regards,
Simon
Re: [PATCH v2 12/14] dm: usb: initialize and scan multiple buses simultaneously with uthread
Quoted 72 lines · Simon Glass
Hi Jerome,
Quoted 61 lines · Jerome Forissier
Use the uthread framework to initialize and scan USB buses in parallel for better performance. The console output is slightly modified with a final per-bus report of the number of devices found, common to UTHREAD and !UTHREAD. The USB tests are updated accordingly.
Tested on two platforms:
1. arm64 QEMU on a somewhat contrived example (4 USB buses, each with one audio device, one keyboard, one mouse and one tablet)
$ make qemu_arm64_defconfig $ make -j$(nproc) CROSS_COMPILE="ccache aarch64-linux-gnu-" $ qemu-system-aarch64 -M virt -nographic -cpu max -bios u-boot.bin \ $(for i in {1..4}; do echo -device qemu-xhci,id=xhci$i \ -device\ usb-{audio,kbd,mouse,tablet},bus=xhci$i.0; \ done)2. i.MX93 EVK (
imx93_11x11_evk_defconfig) with two USB hubs, each with one webcam and one ethernet adapter, resulting in the following device tree:USB device tree:
1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | GenesysLogic USB2.1 Hub | +-3 Vendor specific (480 Mb/s, 350mA) | Realtek USB 10/100/1000 LAN 001000001 | +-4 (480 Mb/s, 500mA) HD Pro Webcam C920 8F7CD51F 1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | USB 2.0 Hub | +-3 Vendor specific (480 Mb/s, 200mA) | Realtek USB 10/100/1000 LAN 000001 | +-4 (480 Mb/s, 500mA) Generic OnLan-CS30 201801010008Note that i.MX was tested on top of the downstream repository [1] since USB doesn't work in the upstream master branch.
[1] https://github.com/nxp-imx/uboot-imx/tree/lf-6.6.52-2.2.0
commit 6c4545203d12 ("LF-13928 update key for capsule")The time spent in
usb_init()("usb start" command) is reported on the console. Here are the results:|
CONFIG_UTHREAD=n|CONFIG_UTHREAD=y
--------+------------------+-----------------QEMU | 5628 ms | 2212 ms i.MX93 | 4591 ms | 2441 msQuoted 6 lines
Signed-off-by Jerome Forissier <[email protected]>--- drivers/usb/host/usb-uclass.c | 92 ++++++++++++++++++++++++++++------- test/boot/bootdev.c | 14 +++--- test/boot/bootflow.c | 2 +- 3 files changed, 83 insertions(+), 25 deletions(-)
Quoted 3 lines
What happens to output produced by a thread? Does it get stored somewhere and written when the thread completes, or do the threads intermingle their output?
The latter. That is why I slightly reworked the USB initialization output to print a status once the threads are done, and I also updated the related tests as you can see in the patch. For instance the tests were expecting:
"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" The "scanning bus usb@1 for devices..." part is printed by the threads, therefore in any order. I decided to move the text
"Bus usb@1: 5 USB Device(s) found" to after the threads are complete, iterating over the devices in a deterministic order.
Quoted 3 lines
I'm not sure if you saw my email about using a state machine for USB. If so, could you please point me to your reply?
I did, but I did not reply because I did not try. I have a feeling that the change would be more intrusive than what I did, but above all I am not doing the uthread thing to address only USB but as a general technique to make things parallel without too much trouble (at least that's my hope). So kind of a different goal.
Regards,
Signature · 1 line
Jerome
Re: [PATCH v2 12/14] dm: usb: initialize and scan multiple buses simultaneously with uthread
Hi Jerome,
Quoted 80 lines · Jerome Forissier
Quoted 72 lines · Simon Glass
Hi Jerome,
Quoted 61 lines · Jerome Forissier
Use the uthread framework to initialize and scan USB buses in parallel for better performance. The console output is slightly modified with a final per-bus report of the number of devices found, common to UTHREAD and !UTHREAD. The USB tests are updated accordingly.
Tested on two platforms:
1. arm64 QEMU on a somewhat contrived example (4 USB buses, each with one audio device, one keyboard, one mouse and one tablet)
$ make qemu_arm64_defconfig $ make -j$(nproc) CROSS_COMPILE="ccache aarch64-linux-gnu-" $ qemu-system-aarch64 -M virt -nographic -cpu max -bios u-boot.bin \ $(for i in {1..4}; do echo -device qemu-xhci,id=xhci$i \ -device\ usb-{audio,kbd,mouse,tablet},bus=xhci$i.0; \ done)2. i.MX93 EVK (
imx93_11x11_evk_defconfig) with two USB hubs, each with one webcam and one ethernet adapter, resulting in the following device tree:USB device tree:
1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | GenesysLogic USB2.1 Hub | +-3 Vendor specific (480 Mb/s, 350mA) | Realtek USB 10/100/1000 LAN 001000001 | +-4 (480 Mb/s, 500mA) HD Pro Webcam C920 8F7CD51F 1 Hub (480 Mb/s, 0mA) | u-boot EHCI Host Controller | +-2 Hub (480 Mb/s, 100mA) | USB 2.0 Hub | +-3 Vendor specific (480 Mb/s, 200mA) | Realtek USB 10/100/1000 LAN 000001 | +-4 (480 Mb/s, 500mA) Generic OnLan-CS30 201801010008Note that i.MX was tested on top of the downstream repository [1] since USB doesn't work in the upstream master branch.
[1] https://github.com/nxp-imx/uboot-imx/tree/lf-6.6.52-2.2.0
commit 6c4545203d12 ("LF-13928 update key for capsule")The time spent in
usb_init()("usb start" command) is reported on the console. Here are the results:|
CONFIG_UTHREAD=n|CONFIG_UTHREAD=y
--------+------------------+-----------------QEMU | 5628 ms | 2212 ms i.MX93 | 4591 ms | 2441 msQuoted 6 lines
Signed-off-by Jerome Forissier <[email protected]>--- drivers/usb/host/usb-uclass.c | 92 ++++++++++++++++++++++++++++------- test/boot/bootdev.c | 14 +++--- test/boot/bootflow.c | 2 +- 3 files changed, 83 insertions(+), 25 deletions(-)Quoted 3 lines
What happens to output produced by a thread? Does it get stored somewhere and written when the thread completes, or do the threads intermingle their output?
Quoted 9 lines
The latter. That is why I slightly reworked the USB initialization output to print a status once the threads are done, and I also updated the related tests as you can see in the patch. For instance the tests were expecting:
"Bus usb@1: scanning bus usb@1 for devices... 5 USB Device(s) found" The "scanning bus usb@1 for devices..." part is printed by the threads, therefore in any order. I decided to move the text
"Bus usb@1: 5 USB Device(s) found" to after the threads are complete, iterating over the devices in a deterministic order.
OK. I think at some point we would want to collected the output and only show it when at a prompt or when all processing is done.
Quoted 10 lines
Quoted 4 lines
I'm not sure if you saw my email about using a state machine for USB. If so, could you please point me to your reply?
I did, but I did not reply because I did not try. I have a feeling that the change would be more intrusive than what I did, but above all I am not doing the uthread thing to address only USB but as a general technique to make things parallel without too much trouble (at least that's my hope). So kind of a different goal.
They are separate approaches. I believe that having the usb-scanning state in one place as an iterator would benefit U-Boot. It is currently a bit messy.
Regards,
Simon
PATCH v2 13/14 cmd: add spawn and wait commands
In reply to Jerome ForissierAdd a spawn command which runs another command in the background, as well as a wait command to suspend the shell until one or more background jobs have completed. The job_id environment variable is set by spawn and wait accepts optional job ids, so that one can selectively wait on any job.
Example:
=> date; spawn sleep 5; spawn sleep 3; date; echo "waiting..."; wait; date
Date: 2025-02-21 (Friday) Time: 17:04:52
Date: 2025-02-21 (Friday) Time: 17:04:52
waiting...
Date: 2025-02-21 (Friday) Time: 17:04:57
=>
Another example showing how background jobs can make initlizations faster. The board is i.MX93 EVK, with one spinning HDD connected to USB1 via a hub, and a network cable plugged into ENET1.
# From power up / reset
u-boot=> setenv autoload 0
u-boot=> setenv ud "usb start; dhcp"
u-boot=> time run ud
[...]
time: 8.058 seconds
# From power up / reset
u-boot=> setenv autoload 0
u-boot=> setenv ud "spawn usb start; spawn dhcp; wait" u-boot=> time run ud
[...]
time: 4.475 seconds
--- cmd/Kconfig | 17 +++++ cmd/Makefile | 2 + cmd/spawn.c | 176 +++++++++++++++++++++++++++++++++++++++++++++++ common/console.c | 2 + 4 files changed, 197 insertions(+) create mode 100644 cmd/spawn.c
cmd/Kconfig +17 -0
@@ -3058,4 +3058,21 @@ config CMD_MESON help Enable useful commands for the Meson Soc family developed by Amlogic Inc. +config CMD_SPAWN + bool "spawn and wait commands" + depends on UTHREAD + help + spawn runs a command in the background and sets the job_id environment + variable. wait is used to suspend the shell execution until one or more + jobs are complete. + +config CMD_SPAWN_NUM_JOBS + int "Maximum number of simultaneous jobs for spawn" + default 16 + help + Job identifiers are in the range 1..CMD_SPAWN_NUM_JOBS. In other words + there can be no more that CMD_SPAWN_NUM_JOBS running simultaneously. + When a jobs exits, its identifier is available to be re-used by the next + spawn command. + endif
cmd/Makefile +2 -0
@@ -240,6 +240,8 @@ obj-$(CONFIG_CMD_SCP03) += scp03.o obj-$(CONFIG_HUSH_SELECTABLE) += cli.o +obj-$(CONFIG_CMD_SPAWN) += spawn.o + obj-$(CONFIG_ARM) += arm/ obj-$(CONFIG_RISCV) += riscv/ obj-$(CONFIG_SANDBOX) += sandbox/
cmd/spawn.c new file +176 -0
176 lines not on this page · raw message
common/console.c +2 -0
@@ -24,6 +24,7 @@#include <watchdog.h> #include <asm/global_data.h> #include <linux/delay.h> +#include <uthread.h> DECLARE_GLOBAL_DATA_PTR ;
@@ -508,6 +509,7 @@ int fgetc(int file)*/ for (;;) {schedule (); +uthread_schedule ();if (CONFIG_IS_ENABLED (CONSOLE_MUX )) {/* * Upper layer may have already called tstc() so
Signature · 1 line
2.43.0
PATCH v2 14/14 test: dm: add test for spawn and wait commands
In reply to Jerome ForissierTest the spawn and wait commands.
--- test/cmd/Makefile | 1 + test/cmd/spawn.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 test/cmd/spawn.c
test/cmd/Makefile +1 -0
@@ -39,3 +39,4 @@ obj-$(CONFIG_CMD_WGET) += wget.o endif obj-$(CONFIG_ARM_FFA_TRANSPORT) += armffa.o endif +obj-$(CONFIG_CMD_SPAWN) += spawn.o
test/cmd/spawn.c new file +33 -0
@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Tests for spawn and wait commands +* +* Copyright 2025, Linaro Ltd. +*/ + +#include <command.h> +#include <dm.h> +#include <dm/test.h> +#include <test/test.h> +#include <test/ut.h> + +static int dm_test_cmd_spawn (struct unit_test_state *uts) +{ +ut_assertok (run_command ("wait; spawn sleep 2; setenv j ${job_id}; " +"spawn setenv spawned true; " +"setenv jj ${job_id}; wait; " +"echo ${j} ${jj} ${spawned}" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"1 2 true" )); + +ut_assertok (run_command ("spawn true; wait; setenv t $?; spawn false; " +"wait; setenv f $?; wait; echo $t $f $?" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"0 1 0" )); +ut_assert_console_end (); + +return 0 ; +} +DM_TEST (dm_test_cmd_spawn,UTF_CONSOLE );
Signature · 1 line
2.43.0
Re: [PATCH v2 14/14] test: dm: add test for spawn and wait commands
Hi Jerome,
Quoted 59 lines · Jerome Forissier
Test the spawn and wait commands.
Signed-off-by Jerome Forissier <[email protected]>--- test/cmd/Makefile | 1 + test/cmd/spawn.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 test/cmd/spawn.ctest/cmd/Makefile +1
-0@@ -39,3 +39,4 @@ obj-$(CONFIG_CMD_WGET) += wget.o endif obj-$(CONFIG_ARM_FFA_TRANSPORT) += armffa.o endif +obj-$(CONFIG_CMD_SPAWN) += spawn.otest/cmd/spawn.c new file +33
-1@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Tests for spawn and wait commands +* +* Copyright 2025, Linaro Ltd. +*/ + +#include <command.h> +#include <dm.h> +#include <dm/test.h> +#include <test/test.h> +#include <test/ut.h> + +static int dm_test_cmd_spawn (struct unit_test_state *uts) +{ +ut_assertok (run_command ("wait; spawn sleep 2; setenv j ${job_id}; " +"spawn setenv spawned true; " +"setenv jj ${job_id}; wait; " +"echo ${j} ${jj} ${spawned}" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"1 2 true" )); + +ut_assertok (run_command ("spawn true; wait; setenv t $?; spawn false; " +"wait; setenv f $?; wait; echo $t $f $?" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"0 1 0" )); +ut_assert_console_end (); + +return 0 ; +} +DM_TEST (dm_test_cmd_spawn,UTF_CONSOLE ); --
Quoted 2 lines
2.43.0
This doesn't look like a DM test as it doesn't use devices. Could it be a CMD test?
Regards,
Simon
Re: [PATCH v2 14/14] test: dm: add test for spawn and wait commands
Hi Simon,
Quoted 60 lines · Simon Glass
Hi Jerome,
Quoted 56 lines · Jerome Forissier
Test the spawn and wait commands.
Signed-off-by Jerome Forissier <[email protected]>--- test/cmd/Makefile | 1 + test/cmd/spawn.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 test/cmd/spawn.ctest/cmd/Makefile +1
-0@@ -39,3 +39,4 @@ obj-$(CONFIG_CMD_WGET) += wget.o endif obj-$(CONFIG_ARM_FFA_TRANSPORT) += armffa.o endif +obj-$(CONFIG_CMD_SPAWN) += spawn.otest/cmd/spawn.c new file +31
-0@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Tests for spawn and wait commands +* +* Copyright 2025, Linaro Ltd. +*/ + +#include <command.h> +#include <dm.h> +#include <dm/test.h> +#include <test/test.h> +#include <test/ut.h> + +static int dm_test_cmd_spawn (struct unit_test_state *uts) +{ +ut_assertok (run_command ("wait; spawn sleep 2; setenv j ${job_id}; " +"spawn setenv spawned true; " +"setenv jj ${job_id}; wait; " +"echo ${j} ${jj} ${spawned}" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"1 2 true" )); + +ut_assertok (run_command ("spawn true; wait; setenv t $?; spawn false; " +"wait; setenv f $?; wait; echo $t $f $?" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"0 1 0" )); +ut_assert_console_end (); + +return 0 ;
Quoted 8 lines
Quoted 5 lines
test/cmd/spawn.c new file +2
-1+} +DM_TEST (dm_test_cmd_spawn,UTF_CONSOLE ); --2.43.0
This doesn't look like a DM test as it doesn't use devices. Could it be a CMD test?
Absolutely. In fact I started from a copy of test/cmd/hash.c, which is not a DM test either is it?
Regards,
Signature · 1 line
Jerome
Re: [PATCH v2 14/14] test: dm: add test for spawn and wait commands
Hi Jerome,
Quoted 73 lines · Jerome Forissier
Hi Simon,
Quoted 60 lines · Simon Glass
Hi Jerome,
Quoted 56 lines · Jerome Forissier
Test the spawn and wait commands.
Signed-off-by Jerome Forissier <[email protected]>--- test/cmd/Makefile | 1 + test/cmd/spawn.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 test/cmd/spawn.ctest/cmd/Makefile +1
-0@@ -39,3 +39,4 @@ obj-$(CONFIG_CMD_WGET) += wget.o endif obj-$(CONFIG_ARM_FFA_TRANSPORT) += armffa.o endif +obj-$(CONFIG_CMD_SPAWN) += spawn.otest/cmd/spawn.c new file +31
-0@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Tests for spawn and wait commands +* +* Copyright 2025, Linaro Ltd. +*/ + +#include <command.h> +#include <dm.h> +#include <dm/test.h> +#include <test/test.h> +#include <test/ut.h> + +static int dm_test_cmd_spawn (struct unit_test_state *uts) +{ +ut_assertok (run_command ("wait; spawn sleep 2; setenv j ${job_id}; " +"spawn setenv spawned true; " +"setenv jj ${job_id}; wait; " +"echo ${j} ${jj} ${spawned}" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"1 2 true" )); + +ut_assertok (run_command ("spawn true; wait; setenv t $?; spawn false; " +"wait; setenv f $?; wait; echo $t $f $?" ,0 )); +console_record_readline (uts->actual_str,sizeof (uts->actual_str)); +ut_asserteq_ptr (uts->actual_str, +strstr (uts->actual_str,"0 1 0" )); +ut_assert_console_end (); + +return 0 ;Quoted 8 lines
Quoted 5 lines
test/cmd/spawn.c new file +2
-1+} +DM_TEST (dm_test_cmd_spawn,UTF_CONSOLE ); --2.43.0
This doesn't look like a DM test as it doesn't use devices. Could it be a CMD test?
Quoted 2 lines
Absolutely. In fact I started from a copy of
test/cmd/hash.c, which is not a DM test either is it?
That's right. Since DM had the first tests nearly everything started out as a DM test, so you could clean those up if you have time.
Regards,
SImon