i2c: Add i2c-pseudo driver for userspace I2C adapters.
Subsystems (2)
PATCH v4 1/1 i2c: Add i2c-pseudo driver for userspace I2C adapters.
The i2c-pseudo module provides I2C adapters backed by userspace programs. This allows for userspace implementations of functionality such as tunneling I2C through another communication channel, or mocking of real I2C devices whose behavior cannot be modeled with i2c-stub.
---
Module naming: A pseudo I2C adapter is analogous to a pseudo terminal.
In the Chromium OS ecosystem we are using this for a userspace I2C adapter built on top of an existing userspace I2C-over-USB implementation used with embedded debug devices that act as I2C master to a device under test (DUT). This arrangement is used for interacting with I2C slaves on the DUT, particularly for transferring firmware to an embedded controller IC which receives programming via I2C.
That I2C pseudo controller implementation is here:
https://chromium.googlesource.com/chromiumos/third_party/hdctools/+/refs/heads/master/servo/interface/i2c_pseudo.py
---
Changelog v4:
- Documentation: I2C addresses on the controller streams are right-aligned without any read/write bit.
- Documentation: fix "transacton" -> "transaction" typo
- add Reviewed-by: Harry Cutts <[email protected]>
Changelog v3:
- i2c: replace nonseekable_open() with stream_open()
Changelog v2:
- i2c: fix ARCH=um compilation error from non-const strlen("literal")
--- .../i2c/pseudo-controller-interface.rst | 306 ++ drivers/i2c/Kconfig | 17 +- drivers/i2c/Makefile | 1 + drivers/i2c/i2c-pseudo.c | 3202 +++++++++++++++++ 4 files changed, 3525 insertions(+), 1 deletion(-) create mode 100644 Documentation/i2c/pseudo-controller-interface.rst create mode 100644 drivers/i2c/i2c-pseudo.c
Documentation/i2c/pseudo-controller-interface.rst new file +306 -0
@@ -0,0 +1,306 @@ +================= +i2c-pseudo driver +================= + +Usually I2C adapters are implemented in a kernel driver. It is also possible to +implement an adapter in userspace, through the /dev/i2c-pseudo-controller +interface. Load module i2c-pseudo for this. + +Use cases for this module include: + +- Using local I2C device drivers, particularly i2c-dev, with I2C busses on + remote systems. For example, interacting with a Device Under Test (DUT) + connected to a Linux host through a debug interface, or interacting with a + remote host over a network. + +- Implementing I2C device driver tests that are impractical with the i2c-stub + module. For example, when simulating an I2C device where its driver might + issue a sequence of reads and writes without interruption, and the value at a + certain address must change during the sequence. + +This is not intended to replace kernel drivers for actual I2C busses on the +local host machine. + + +Details +======= + +Each time /dev/i2c-pseudo-controller is opened, and the correct initialization +command is written to it (ADAPTER_START), a new I2C adapter is created. The +adapter will live until its file descriptor is closed. Multiple pseudo adapters +can co-exist simultaneously, controlled by the same or different userspace +processes. When an I2C device driver sends an I2C message to a pseudo adapter, +the message becomes readable from its file descriptor. If a reply is written +before the adapter timeout expires, that reply will be sent back to the I2C +device driver. + +Reads and writes are buffered inside i2c-pseudo such that userspace controllers +may split them up into arbitrarily small chunks. Multiple commands, or portions +of multiple commands, may be read or written together. + +Blocking I/O is the default. Non-blocking I/O is supported as well, enabled by +O_NONBLOCK. Polling is supported, with or without non-blocking I/O. A special +command (ADAPTER_SHUTDOWN) is available to unblock any pollers or blocked +reads or writes, as a convenience for a multi-threaded or multi-process program +that wants to exit. + +It is safe to access a single controller fd from multiple threads or processes +concurrently, though it is up to the controller to ensure proper ordering, and +to ensure that writes for different commands do not get interleaved. However, +it is recommended (not required) that controller implementations have only one +reader thread and one writer thread, which may or may not be the same thread. +Avoiding multiple readers and multiple writers greatly simplifies controller +implementation, and there is likely no performance benefit to be gained from +concurrent reads or concurrent writes due to how i2c-pseudo serializes them +internally. After all, on a real I2C bus only one I2C message can be active at +a time. + +Commands are newline-terminated, both those read from the controller device, and +those written to it. + + +Read Commands +============= + +The commands that may be read from a pseudo controller device are: + +---- + +:Read Command: ``I2C_ADAPTER_NUM <num>`` +:Example: ``"I2C_ADAPTER_NUM 5\n"`` +:Details: + | This is read in response to the GET_ADAPTER_NUM command being written. + The number is the I2C adapter number in decimal. This can only occur after + ADAPTER_START, because before that the number is not known and cannot be + predicted reliably. + +---- + +:Read Command: ``I2C_PSEUDO_ID <num>`` +:Example: ``"I2C_PSEUDO_ID 98\n"`` +:Details: + | This is read in response to the GET_PSEUDO_ID command being written. + The number is the pseudo ID in decimal. + +---- + +:Read Command: ``I2C_BEGIN_XFER`` +:Example: ``"I2C_BEGIN_XFER\n"`` +:Details: + | This indicates the start of an I2C transaction request, in other words + the start of the I2C messages from a single invocation of the I2C adapter's + master_xfer() callback. This can only occur after ADAPTER_START. + +---- + +:Read Command: ``I2C_XFER_REQ <xfer_id> <msg_id> <addr> <flags> <data_len> [<write_byte>[:...]]`` +:Example: ``"I2C_XFER_REQ 3 0 0x0070 0x0000 2 AB:9F\n"`` +:Example: ``"I2C_XFER_REQ 3 1 0x0070 0x0001 4\n"`` +:Details: + | This is a single I2C message that a device driver requested be sent on + the bus, in other words a single struct i2c_msg from master_xfer() msgs arg. + | + | The xfer_id is a number representing the whole I2C transaction, thus all + I2C_XFER_REQ between a I2C_BEGIN_XFER + I2C_COMMIT_XFER pair share an + xfer_id. The purpose is to ensure replies from the userspace controller are + always properly matched to the intended master_xfer() request. The first + transaction has xfer_id 0, and it increases by 1 with each transaction, + however it will eventually wrap back to 0 if enough transactions happen + during the lifetime of a pseudo adapter. It is guaranteed to have a large + enough maximum value such that there can never be multiple outstanding + transactions with the same ID, due to an internal limit in i2c-pseudo that + will block master_xfer() calls when the controller is falling behind in its + replies. + | + | The msg_id is a decimal number representing the index of the I2C message + within its transaction, in other words the index in master_xfer() \*msgs + array arg. This starts at 0 after each I2C_BEGIN_XFER. This is guaranteed + to not wrap. + | + | The addr is the hexadecimal I2C address for this I2C message. The address + is right-aligned without any read/write bit. + | + | The flags are the same bitmask flags used in struct i2c_msg, in hexadecimal + form. Of particular importance to any pseudo controller is the read bit, + which is guaranteed to be 0x1 per Linux I2C documentation. + | + | The data_len is the decimal number of either how many bytes to write that + will follow, or how many bytes to read and reply with if this is a read + request. + | + | If this is a read, data_len will be the final field in this command. If + this is a write, data_len will be followed by the given number of + colon-separated hexadecimal byte values, in the format shown in the example + above. + +---- + +:Read Command: ``I2C_COMMIT_XFER`` +:Example: ``"I2C_COMMIT_XFER\n"`` +:Details: + | This indicates the end of an I2C transaction request, in other words the + end of the I2C messages from a single invocation of the I2C adapter's + master_xfer() callback. This should be read exactly once after each + I2C_BEGIN_XFER, with a varying number of I2C_XFER_REQ between them. + + +Write Commands +============== + +The commands that may be written to a pseudo controller device are: + + +:Write Command: ``SET_ADAPTER_NAME_SUFFIX <suffix>`` +:Example: ``"SET_ADAPTER_NAME_SUFFIX My Adapter\n"`` +:Details: + | Sets a suffix to append to the auto-generated I2C adapter name. Only + valid before ADAPTER_START. A space or other separator character will be + placed between the auto-generated name and the suffix, so there is no need + to include a leading separator in the suffix. If the resulting name is too + long for the I2C adapter name field, it will be quietly truncated. + +---- + +:Write Command: ``SET_ADAPTER_TIMEOUT_MS <ms>`` +:Example: ``"SET_ADAPTER_TIMEOUT_MS 2000\n"`` +:Details: + | Sets the timeout in milliseconds for each I2C transaction, in other words + for each master_xfer() reply. Only valid before ADAPTER_START. The I2C + subsystem will automatically time out transactions based on this setting. + Set to 0 to use the I2C subsystem default timeout. The default timeout for + new pseudo adapters where this command has not been used is configurable at + i2c-pseudo module load time, and itself has a default independent from the + I2C subsystem default. (If the i2c-pseudo module level default is set to 0, + that has the same meaning as here.) + +---- + +:Write Command: ``ADAPTER_START`` +:Example: ``"ADAPTER_START\n"`` +:Details: + | Tells i2c-pseudo to actually create the I2C adapter. Only valid once per + open controller fd. + +---- + +:Write Command: ``GET_ADAPTER_NUM`` +:Example: ``"GET_ADAPTER_NUM\n"`` +:Details: + | Asks i2c-pseudo for the number assigned to this I2C adapter by the I2C + subsystem. Only valid after ADAPTER_START, because before that the number + is not known and cannot be predicted reliably. + +---- + +:Write Command: ``GET_PSEUDO_ID`` +:Example: ``"GET_PSEUDO_ID\n"`` +:Details: + | Asks i2c-pseudo for the pseudo ID of this I2C adapter. The pseudo ID will + not be reused for the lifetime of the i2c-pseudo module, unless an internal + counter wraps. I2C clients can use this to track specific instances of + pseudo adapters, even when adapter numbers have been reused. + +---- + +:Write Command: ``I2C_XFER_REPLY <xfer_id> <msg_id> <addr> <flags> <errno> [<read_byte>[:...]]`` +:Example: ``"I2C_XFER_REPLY 3 0 0x0070 0x0000 0\n"`` +:Example: ``"I2C_XFER_REPLY 3 1 0x0070 0x0001 0 0B:29:02:D9\n"`` +:Details: + | This is how a pseudo controller can reply to I2C_XFER_REQ. Only valid + after I2C_XFER_REQ. A pseudo controller should write one of these for each + I2C_XFER_REQ it reads, including for failures, so that I2C device drivers + need not wait for the adapter timeout upon failure (if failure is known + sooner). + | + | The fields in common with I2C_XFER_REQ have their same meanings, and their + values are expected to exactly match what was read in the I2C_XFER_REQ + command that this is in reply to. + | + | The errno field is how the pseudo controller indicates success or failure + for this I2C message. A 0 value indicates success. A non-zero value + indicates a failure. Pseudo controllers are encouraged to use errno values + to encode some meaning in a failure response, but that is not a requirement, + and the I2C adapter interface does not provide a way to pass per-message + errno values to a device driver anyways. + | + | Pseudo controllers are encouraged to reply in the same order as messages + were received, however i2c-pseudo will properly match up out-of-order + replies with their original requests. + +---- + +:Write Command: ``ADAPTER_SHUTDOWN`` +:Example: ``"ADAPTER_SHUTDOWN\n"`` +:Details: + | This tells i2c-pseudo that the pseudo controller wants to shutdown and + intends to close the controller device fd soon. Use of this is OPTIONAL, it + is perfectly valid to close the controller device fd without ever using this + command. + | + | This commands unblocks any blocked controller I/O (reads, writes, or polls), + and that is its main purpose. + | + | Any I2C transactions attempted by a device driver after this command will + fail, and will not be passed on to the userspace controller. + | + | This DOES NOT delete the I2C adapter. Only closing the fd will do that. + That MAY CHANGE in the future, such that this does delete the I2C adapter. + (However this will never be required, it will always be okay to simply close + the fd.) + + +Example userspace controller code +================================= + +In C, a simple exchange between i2c-pseudo and userspace might look like the +example below. Note that for brevity this lacks any error checking and +handling, which a real pseudo controller implementation should have. + +:: + + int fd; + char buf[1<<12]; + + fd = open("/dev/i2c-pseudo-controller", O_RDWR); + /* Create the I2C adapter. */ + dprintf(fd, "ADAPTER_START\n"); + + /* + * Pretend this I2C adapter number is 5, and the first I2C xfer sent to it was + * from this command (using its i2c-dev interface): + * $ i2cset -y 5 0x70 0xC2 + * + * Then this read would place the following into *buf: + * "I2C_BEGIN_XFER\n" + * "I2C_XFER_REQ 0 0 0x0070 0x0000 1 C2\n" + * "I2C_COMMIT_XFER\n" + */ + read(fd, buf, sizeof(buf)); + + /* This reply would allow the i2cset command above to exit successfully. */ + dprintf(fd, "I2C_XFER_REPLY 0 0 0x0070 0x0000 0\n"); + + /* + * Now pretend the next I2C xfer sent to this adapter was from: + * $ i2cget -y 5 0x70 0xAB + * + * Then this read would place the following into *buf: + * "I2C_BEGIN_XFER\n" + * "I2C_XFER_REQ 1 0 0x0070 0x0000 1 AB\n" + * "I2C_XFER_REQ 1 1 0x0070 0x0001 1\n'" + * "I2C_COMMIT_XFER\n" + */ + read(fd, buf, sizeof(buf)); + + /* + * These replies would allow the i2cget command above to print the following to + * stdout and exit successfully: + * 0x0b + * + * Note that it is also valid to write these together in one write(). + */ + dprintf(fd, "I2C_XFER_REPLY 1 0 0x0070 0x0000 0\n"); + dprintf(fd, "I2C_XFER_REPLY 1 1 0x0070 0x0001 0 0B\n"); + + /* Destroy the I2C adapter. */ + close(fd);
drivers/i2c/Kconfig +16 -1
@@ -56,7 +56,7 @@ config I2C_CHARDEV programs use the I2C bus. Information on how to do this is contained in the file <file:Documentation/i2c/dev-interface.rst>. - This support is also available as a module. If so, the module + This support is also available as a module. If so, the module will be called i2c-dev. config I2C_MUX
@@ -98,6 +98,21 @@ config I2C_SMBUS source "drivers/i2c/algos/Kconfig" source "drivers/i2c/busses/Kconfig" +config I2C_PSEUDO + tristate "I2C userspace adapter interface" + depends on m + default 'n' + help + Say Y here to have an i2c-pseudo-controller device file, usually + found in the /dev directory on your system. This makes it + possible to have user-space programs implement an I2C bus + (I2C adapter in kernel lingo). Information on how to do this is + contained in the file <file:Documentation/i2c/i2c-pseudo>. + + This support is only available as a module, called i2c-pseudo. + + If you don't know what to do here, definitely say N. + config I2C_STUB tristate "I2C/SMBus Test Stub" depends on m
drivers/i2c/Makefile +1 -0
@@ -14,6 +14,7 @@ obj-$(CONFIG_I2C_SMBUS) += i2c-smbus.o obj-$(CONFIG_I2C_CHARDEV) += i2c-dev.o obj-$(CONFIG_I2C_MUX) += i2c-mux.o obj-y += algos/ busses/ muxes/ +obj-$(CONFIG_I2C_PSEUDO) += i2c-pseudo.o obj-$(CONFIG_I2C_STUB) += i2c-stub.o obj-$(CONFIG_I2C_SLAVE_EEPROM) += i2c-slave-eeprom.o
drivers/i2c/i2c-pseudo.c new file +3202 -0
2,658 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.27.0.rc0.183.gde8f92d652-goog
Part of the diff is not shown here. View the raw message.
kbuild test robot
build botThank you for the patch! Perhaps something to improve:
Hi Matthew,
Thank you for the patch! Perhaps something to improve:
[auto build test WARNING on wsa/i2c/for-next]
[also build test WARNING on v5.7-rc6 next-20200519]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]
url: https://github.com/0day-ci/linux/commits/Matthew-Blecker/i2c-Add-i2c-pseudo-driver-for-userspace-I2C-adapters/20200521-083201 base: https://git.kernel.org/pub/scm/linux/kernel/git/wsa/linux.git i2c/for-next config: m68k-allmodconfig (attached as .config) compiler: m68k-linux-gcc (GCC) 9.3.0
reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-9.3.0 make.cross ARCH=m68k
If you fix the issue, kindly add following tag as appropriate
All warnings (new ones prefixed by >>, old ones prefixed by <<):
drivers/i2c/i2c-pseudo.c:104: warning: "STR" redefined
104 | #define STR(num) STR_HELPER(num)
|
In file included from arch/m68k/include/asm/irqflags.h:8,
from include/linux/irqflags.h:16,
from arch/m68k/include/asm/atomic.h:6,
from include/linux/atomic.h:7,
from include/linux/mutex.h:18,
from include/linux/kernfs.h:12,
from include/linux/sysfs.h:16,
from include/linux/kobject.h:20,
from include/linux/cdev.h:5,
from drivers/i2c/i2c-pseudo.c:10:arch/m68k/include/asm/entry.h:244: note: this is the location of the previous definition 244 | #define STR(X) STR1(X)
|drivers/i2c/i2c-pseudo.c: In function 'vanprintf':
>> drivers/i2c/i2c-pseudo.c:767:2: warning: function 'vanprintf' might be a candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format]
767 | ret = vsnprintf(NULL, 0, fmt, ap);
| ^~~drivers/i2c/i2c-pseudo.c:782:2: warning: function 'vanprintf' might be a candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format] 782 | ret = vsnprintf(buf, buf_size, fmt, args1);
| ^~~drivers/i2c/i2c-pseudo.c: In function 'i2cp_cmd_set_timeout_cmd_completer':
>> drivers/i2c/i2c-pseudo.c:1838:27: warning: comparison of unsigned expression < 0 is always false [-Wtype-limits]
1838 | if (cmd_data->timeout_ms < I2CP_TIMEOUT_MS_MIN ||
| ^drivers/i2c/i2c-pseudo.c: In function 'i2cp_init':drivers/i2c/i2c-pseudo.c:3130:17: warning: comparison of unsigned expression < 0 is always false [-Wtype-limits] 3130 | if (i2cp_limit < I2CP_ADAPTERS_MIN || i2cp_limit > I2CP_ADAPTERS_MAX) {
| ^
vim +767 drivers/i2c/i2c-pseudo.c
756
757 /* vanprintf - See anprintf() documentation. */
758 static ssize_t vanprintf(char **out, ssize_t max_size, gfp_t gfp,
759 const char *fmt, va_list ap)
760 {
761 int ret;
762 ssize_t buf_size;
763 char *buf = NULL;
764 va_list args1;
765
766 va_copy(args1, ap);
> 767 ret = vsnprintf(NULL, 0, fmt, ap);
768 if (ret < 0)
769 goto fail_before_args1;
770 if (max_size >= 0 && ret > max_size) {
771 ret = -ERANGE;
772 goto fail_before_args1;
773 }
774
775 buf_size = ret + 1;
776 buf = kmalloc_track_caller(buf_size, gfp);
777 if (buf == NULL) {
778 ret = -ENOMEM;
779 goto fail_before_args1;
780 }
781
782 ret = vsnprintf(buf, buf_size, fmt, args1);
783 va_end(args1);
784 if (ret < 0)
785 goto fail_after_args1;
786 if (ret + 1 != buf_size) {
787 ret = -ENOTRECOVERABLE;
788 goto fail_after_args1;
789 }
790
791 *out = buf;
792 return ret;
793
794 fail_before_args1:
795 va_end(args1);
796 fail_after_args1:
797 kfree(buf);
798 if (ret >= 0)
799 ret = -ENOTRECOVERABLE;
800 return ret;
801 }
802
---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org
kbuild test robot
build botThank you for the patch! Perhaps something to improve:
Hi Matthew,
Thank you for the patch! Perhaps something to improve:
[auto build test WARNING on wsa/i2c/for-next]
[also build test WARNING on v5.7-rc6 next-20200522]
[if your patch is applied to the wrong git tree, please drop us a note to help improve the system. BTW, we also suggest to use '--base' option to specify the base tree in git format-patch, please see https://stackoverflow.com/a/37406982]
url: https://github.com/0day-ci/linux/commits/Matthew-Blecker/i2c-Add-i2c-pseudo-driver-for-userspace-I2C-adapters/20200521-083201 base: https://git.kernel.org/pub/scm/linux/kernel/git/wsa/linux.git i2c/for-next config: x86_64-randconfig-r012-20200524 (attached as .config) compiler: gcc-5 (Ubuntu 5.5.0-12ubuntu1) 5.5.0 20171010 reproduce (this is a W=1 build): # save the attached .config to linux build tree make ARCH=x86_64
If you fix the issue, kindly add following tag as appropriate
All warnings (new ones prefixed by >>, old ones prefixed by <<):
drivers/i2c/i2c-pseudo.c: In function 'vanprintf':
>> drivers/i2c/i2c-pseudo.c:767:2: warning: function might be possible candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format]
ret = vsnprintf(NULL, 0, fmt, ap);
^drivers/i2c/i2c-pseudo.c:782:2: warning: function might be possible candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format] ret = vsnprintf(buf, buf_size, fmt, args1);
^drivers/i2c/i2c-pseudo.c: In function 'i2cp_cmd_set_timeout_cmd_completer':drivers/i2c/i2c-pseudo.c:1838:27: warning: comparison of unsigned expression < 0 is always false [-Wtype-limits]
if (cmd_data->timeout_ms < I2CP_TIMEOUT_MS_MIN ||
^drivers/i2c/i2c-pseudo.c: In function 'i2cp_init':drivers/i2c/i2c-pseudo.c:3130:17: warning: comparison of unsigned expression < 0 is always false [-Wtype-limits]
if (i2cp_limit < I2CP_ADAPTERS_MIN || i2cp_limit > I2CP_ADAPTERS_MAX) {
^
vim +/gnu_printf +767 drivers/i2c/i2c-pseudo.c
756
757 /* vanprintf - See anprintf() documentation. */
758 static ssize_t vanprintf(char **out, ssize_t max_size, gfp_t gfp,
759 const char *fmt, va_list ap)
760 {
761 int ret;
762 ssize_t buf_size;
763 char *buf = NULL;
764 va_list args1;
765
766 va_copy(args1, ap);
> 767 ret = vsnprintf(NULL, 0, fmt, ap);
768 if (ret < 0)
769 goto fail_before_args1;
770 if (max_size >= 0 && ret > max_size) {
771 ret = -ERANGE;
772 goto fail_before_args1;
773 }
774
775 buf_size = ret + 1;
776 buf = kmalloc_track_caller(buf_size, gfp);
777 if (buf == NULL) {
778 ret = -ENOMEM;
779 goto fail_before_args1;
780 }
781
782 ret = vsnprintf(buf, buf_size, fmt, args1);
783 va_end(args1);
784 if (ret < 0)
785 goto fail_after_args1;
786 if (ret + 1 != buf_size) {
787 ret = -ENOTRECOVERABLE;
788 goto fail_after_args1;
789 }
790
791 *out = buf;
792 return ret;
793
794 fail_before_args1:
795 va_end(args1);
796 fail_after_args1:
797 kfree(buf);
798 if (ret >= 0)
799 ret = -ENOTRECOVERABLE;
800 return ret;
801 }
802
---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org
Hi Matthew,
Overall, this is a huge driver (3K+ lines!), is there anything you can do to try to shrink it down to the bare minimum, so we could review that first?
Very, very, partial review below.
Quoted 15 lines · Matthew Blecker
The i2c-pseudo module provides I2C adapters backed by userspace programs. This allows for userspace implementations of functionality such as tunneling I2C through another communication channel, or mocking of real I2C devices whose behavior cannot be modeled with i2c-stub.
Signed-off-by Matthew Blecker <[email protected]>Reviewed-by Harry Cutts <[email protected]>---
[snip]drivers/i2c/Kconfig +0
-0
drivers/i2c/Kconfig config I2C_CHARDEV · line 59
Quoted 5 lines
drivers/i2c/Kconfig +1
-1@@ -56,7 +56,7 @@ config I2C_CHARDEV programs use the I2C bus. Information on how to do this is contained in the file <file:Documentation/i2c/dev-interface.rst>. - This support is also available as a module. If so, the module + This support is also available as a module. If so, the module
Drop this change.
Quoted 43 lines
drivers/i2c/Kconfig +15
-0will be called i2c-dev. config I2C_MUX@@ -98,6 +98,21 @@ config I2C_SMBUS source "drivers/i2c/algos/Kconfig" source "drivers/i2c/busses/Kconfig" +config I2C_PSEUDO + tristate "I2C userspace adapter interface" + depends on m + default 'n' + help + Say Y here to have an i2c-pseudo-controller device file, usually + found in the /dev directory on your system. This makes it + possible to have user-space programs implement an I2C bus + (I2C adapter in kernel lingo). Information on how to do this is + contained in the file <file:Documentation/i2c/i2c-pseudo>. + + This support is only available as a module, called i2c-pseudo. + + If you don't know what to do here, definitely say N. + config I2C_STUB tristate "I2C/SMBus Test Stub" depends on mdrivers/i2c/Makefile +1
-0@@ -14,6 +14,7 @@ obj-$(CONFIG_I2C_SMBUS) += i2c-smbus.o obj-$(CONFIG_I2C_CHARDEV) += i2c-dev.o obj-$(CONFIG_I2C_MUX) += i2c-mux.o obj-y += algos/ busses/ muxes/ +obj-$(CONFIG_I2C_PSEUDO) += i2c-pseudo.o obj-$(CONFIG_I2C_STUB) += i2c-stub.o obj-$(CONFIG_I2C_SLAVE_EEPROM) += i2c-slave-eeprom.odrivers/i2c/i2c-pseudo.c new file +0
-0
drivers/i2c/i2c-pseudo.c line 1
Quoted 1 line
drivers/i2c/i2c-pseudo.c new file +1
-0@@ -0,0 +1,3202 @@ +// SPDX-License-Identifier: GPL-2.0
You still need to add a copyright line here. Google LLC.
Quoted 52 lines
drivers/i2c/i2c-pseudo.c new file +52
-0+/* +* This Linux kernel module implements pseudo I2C adapters that can be backed +* by userspace programs. This allows for implementing an I2C bus from +* userspace, which can tunnel the I2C commands through another communication +* channel to a remote I2C bus. +*/ + +#include <linux/build_bug.h> +#include <linux/cdev.h> +#include <linux/completion.h> +#include <linux/device.h> +#include <linux/errno.h> +#include <linux/fs.h> +#include <linux/i2c.h> +#include <linux/init.h> +#include <linux/jiffies.h> +#include <linux/kernel.h> +#include <linux/kobject.h> +#include <linux/list.h> +#include <linux/module.h> +#include <linux/mutex.h> +#include <linux/poll.h> +#include <linux/slab.h> +#include <linux/string.h> +#include <linux/time64.h> +#include <linux/types.h> +#include <linux/uaccess.h> +#include <linux/wait.h> + +/* Minimum i2cp_limit module parameter value. */ +#define I2CP_ADAPTERS_MIN 0 +/* Maximum i2cp_limit module parameter value. */ +#define I2CP_ADAPTERS_MAX 256 +/* Default i2cp_limit module parameter value. */ +#define I2CP_DEFAULT_LIMIT 8 +/* Value for alloc_chrdev_region() baseminor arg. */ +#define I2CP_CDEV_BASEMINOR 0 +#define I2CP_TIMEOUT_MS_MIN 0 +#define I2CP_TIMEOUT_MS_MAX (60 * MSEC_PER_SEC) +#define I2CP_DEFAULT_TIMEOUT_MS (3 * MSEC_PER_SEC) + +/* Used in struct device.kobj.name field. */ +#define I2CP_DEVICE_NAME "i2c-pseudo-controller" +/* Value for alloc_chrdev_region() name arg. */ +#define I2CP_CHRDEV_NAME "i2c_pseudo" +/* Value for class_create() name arg. */ +#define I2CP_CLASS_NAME "i2c-pseudo" +/* Value for alloc_chrdev_region() count arg. Should always be 1. */ +#define I2CP_CDEV_COUNT 1 + +#define I2CP_ADAP_START_CMD "ADAPTER_START" +#define I2CP_ADAP_SHUTDOWN_CMD "ADAPTER_SHUTDOWN"
drivers/i2c/i2c-pseudo.c line 63
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+#define I2CP_GET_NUMBER_CMD "GET_ADAPTER_NUM" +#define I2CP_NUMBER_REPLY_CMD "I2C_ADAPTER_NUM" +#define I2CP_GET_PSEUDO_ID_CMD "GET_PSEUDO_ID" +#define I2CP_PSEUDO_ID_REPLY_CMD "I2C_PSEUDO_ID" +#define I2CP_SET_NAME_SUFFIX_CMD "SET_ADAPTER_NAME_SUFFIX" +#define I2CP_SET_TIMEOUT_CMD "SET_ADAPTER_TIMEOUT_MS" +#define I2CP_BEGIN_MXFER_REQ_CMD "I2C_BEGIN_XFER" +#define I2CP_COMMIT_MXFER_REQ_CMD "I2C_COMMIT_XFER" +#define I2CP_MXFER_REQ_CMD "I2C_XFER_REQ" +#define I2CP_MXFER_REPLY_CMD "I2C_XFER_REPLY"
I wonder if all of those should be ioctls, instead of doing string/command parsing in the kernel.
Any reason you're not using ioctls?
Quoted 28 lines
drivers/i2c/i2c-pseudo.c new file +28
-0+ +/* Maximum size of a controller command. */ +#define I2CP_CTRLR_CMD_LIMIT 255 +/* Maximum number of controller read responses to allow enqueued at once. */ +#define I2CP_CTRLR_RSP_QUEUE_LIMIT 256 +/* The maximum size of a single controller read response. */ +#define I2CP_MAX_MSG_BUF_SIZE 16384 +/* Maximum length (not size!) of i2cp_cmds static array. */ +#define I2CP_CMDS_SANITY_LIMIT 64 +/* Maximum size of a controller read or write. */ +#define I2CP_RW_SIZE_LIMIT 1048576 + +/* +* Marks the end of a controller command or read response. +* +* Fundamentally, controller commands and read responses could use different end +* marker characters, but for sanity they should be the same. +* +* This must be a variable, not a macro, because it is passed to copy_to_user() +* by address. Taking the address of a character literal causes a compiler +* error. Making these C strings instead of characters would allow for that +* (with other implications), but then copy_to_user() itself refuses to compile, +* because of an assertion that the copy size (1) must match the size of the +* string literal (2 with its trailing null). +*/ +static const char i2cp_ctrlr_end_char ='\n' ; +/* Separator between I2C message header fields in the controller bytestream. */ +static const char i2cp_ctrlr_header_sep_char =' ' ;
drivers/i2c/i2c-pseudo.c line 101
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+/* Separator between I2C message data bytes in the controller bytestream. */ +static const char i2cp_ctrlr_data_sep_char =':' ; + +/* +* This used instead of strcmp(in_str, other_str) because in_str may have null +* characters within its in_size boundaries, which could cause an unintended +* match. +*/ +#define STRING_NEQ (in_str, in_size, other_str) \ + (in_size != strlen(other_str) || memcmp(other_str, in_str, in_size))
I'd define STRING_EQ instead. Also, this is not used?
Quoted 15 lines
drivers/i2c/i2c-pseudo.c new file +15
-0+ +#define STR_HELPER (num) #num +#define STR (num) STR_HELPER(num) + +#define CONST_STRLEN (str) (sizeof(str) - 1) + +/* +* The number of pseudo I2C adapters permitted. This default value can be +* overridden at module load time. Must be in the range +* [I2CP_ADAPTERS_MIN, I2CP_ADAPTERS_MAX]. +* +* As currently used, this MUST NOT be changed during or after module +* initialization. If the ability to change this at runtime is desired, an +* audit of the uses of this variable will be necessary. +*/
drivers/i2c/i2c-pseudo.c line 126
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+static unsigned int i2cp_limit =I2CP_DEFAULT_LIMIT ; +module_param (i2cp_limit, uint,0444 ); + +/* +* The default I2C pseudo adapter timeout, in milliseconds. +* 0 means use Linux I2C adapter default. +* Can be changed per adapter by the controller. +*/ +static unsigned int i2cp_default_timeout_ms =I2CP_DEFAULT_TIMEOUT_MS ; +module_param (i2cp_default_timeout_ms, uint,0444 );
Why do you need this? Maybe drop it to simplify?
Quoted 18 lines
drivers/i2c/i2c-pseudo.c new file +18
-0+ +struct i2cp_controller ; + +/* This tracks all I2C pseudo adapters. */ +struct i2cp_counters { +/* This must be held while accessing any fields. */ +struct mutex lock; +unsigned int count; +/* +* This is used to make a strong attempt at avoiding ID reuse, +* especially during the lifetime of a userspace i2c-dev client. This +* can wrap by design, and thus makes no perfect guarantees. +*/ +/* Same type as struct i2cp_controller.id field. */ +unsigned int next_ctrlr_id; +struct i2cp_controller **all_controllers; +}; +
[snip]
Quoted 80 lines
drivers/i2c/i2c-pseudo.c new file +80
-0+/* vanprintf - See anprintf() documentation. */ +static ssize_t vanprintf (char **out,ssize_t max_size,gfp_t gfp, +const char *fmt,va_list ap) +{ +int ret; +ssize_t buf_size; +char *buf =NULL ; +va_list args1; + +va_copy (args1, ap); + ret =vsnprintf (NULL ,0 , fmt, ap); +if (ret <0 ) + goto fail_before_args1; +if (max_size >=0 && ret > max_size) { + ret = -ERANGE ; + goto fail_before_args1; + } + + buf_size = ret +1 ; + buf =kmalloc_track_caller (buf_size, gfp); +if (buf ==NULL ) { + ret = -ENOMEM ; + goto fail_before_args1; + } + + ret =vsnprintf (buf, buf_size, fmt, args1); +va_end (args1); +if (ret <0 ) + goto fail_after_args1; +if (ret +1 != buf_size) { + ret = -ENOTRECOVERABLE ; + goto fail_after_args1; + } + + *out = buf; +return ret; + + fail_before_args1: +va_end (args1); + fail_after_args1: +kfree (buf); +if (ret >=0 ) + ret = -ENOTRECOVERABLE ; +return ret; +} + +/* +* anprintf - Format a string and place it into a newly allocated buffer. +* @out: Address of the pointer to place the buffer address into. Will only be +* written to with a successful positive return value. +* @max_size: If non-negative, the maximum buffer size that this function will +* attempt to allocate. If the formatted string including trailing null +* character would not fit, no buffer will be allocated, and an error will +* be returned. (Thus max_size of 0 will always result in an error.) +* @gfp: GFP flags for kmalloc(). +* @fmt: The format string to use. +* @...: Arguments for the format string. +* +* Return value meanings: +* +* >=0: A buffer of this size was allocated and its address written to *out. +* The caller now owns the buffer and is responsible for freeing it with +* kfree(). The final character in the buffer, not counted in this +* return value, is the trailing null. This is the same return value +* meaning as snprintf(3). +* +* <0: An error occurred. Negate the return value for the error number. +* @out will not have been written to. Errors that might come from +* snprintf(3) may come from this function as well. Additionally, the +* following errors may occur from this function: +* +* ERANGE: A buffer larger than @max_size would be needed to fit the +* formatted string including its trailing null character. +* +* ENOMEM: Allocation of the output buffer failed. +* +* ENOTRECOVERABLE: An unexpected condition occurred. This may indicate +* a bug. +*/ +static ssize_t anprintf(char **out, ssize_t max_size, gfp_t gfp,
drivers/i2c/i2c-pseudo.c line 846
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+ const char *fmt, ...) +{ + ssize_t ret; +va_list args; + +va_start (args, fmt); + ret =vanprintf (out, max_size, gfp, fmt, args); +va_end (args); +return ret; +}
I'm a bit worried you need to define your own custom string manipulation functions. If they are really necessary, please add them to the core.
Quoted 5 lines
drivers/i2c/i2c-pseudo.c new file +5
-0+ +static ssize_t i2cp_rsp_buffer_formatter (void *data,char **out) +{ +struct i2cp_rsp_buffer *rsp_buf; +
drivers/i2c/i2c-pseudo.c line 861
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+ rsp_buf = data; +if (rsp_buf->buf) { +if (rsp_buf->size >0 ) { + *out = rsp_buf->buf; + rsp_buf->buf =NULL ; +return rsp_buf->size; + } +kfree (rsp_buf->buf); + } +kfree (rsp_buf);
This is really hard to follow, reverse the tests:
if (!rsp_buf->buf) {
kfree(rsp_buf);
return;
}
if (rsp_buf->size <= 0) {
...
}
etc.
Quoted 6 lines
drivers/i2c/i2c-pseudo.c new file +6
-0+return 0 ; +} + +static ssize_t i2cp_rsp_master_xfer_formatter (void *data,char **out) +{ +ssize_t ret;
[snip]
Quoted 7 lines
drivers/i2c/i2c-pseudo.c new file +7
-0+ +static ssize_t i2cp_cdev_read (struct file *filep,char __user *buf, +size_t count,loff_t *f_ps) +{ +ssize_t ret =0 ; +bool non_blocking; +struct i2cp_controller *pdata;
drivers/i2c/i2c-pseudo.c line 2607
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+ +/* +* Just in case this could change out from under us, best to keep a +* consistent view for the duration of this syscall. +*/ + non_blocking = !!(filep->f_flags &O_NONBLOCK ); + pdata = filep->private_data; + +if (count > (size_t )I2CP_RW_SIZE_LIMIT ) + count =I2CP_RW_SIZE_LIMIT ;
I think you should just error out instead.
Quoted 5 lines
drivers/i2c/i2c-pseudo.c new file +5
-0+ +/* +* Since read() calls are effectively serialized by way of +* pdata->rsp_lock, we MUST NOT block on obtaining that lock if in +* non-blocking mode, because it might be held by a blocking read().
[snip]
Quoted 24 lines
drivers/i2c/i2c-pseudo.c new file +24
-0+static ssize_t i2cp_cdev_write (struct file *filep,const char __user *buf, +size_t count,loff_t *f_ps) +{ +ssize_t ret =0 ; +bool non_blocking; +size_t remaining; +char *kbuf, *start; +struct i2cp_controller *pdata; + +/* +* Just in case this could change out from under us, best to keep a +* consistent view for the duration of this syscall. +* +* Write command implementations, i.e. struct i2cp_cmd implementations, +* do NOT have to support blocking writes. For example, if a write of +* an I2C message reply is received for a message that the pseudo +* adapter never requested or expected, it makes more sense to indicate +* an error than to block until possibly receiving a master_xfer request +* for that I2C message, even if blocking is permitted. +* +* Furthermore, controller writes MUST NEVER block indefinitely, even +* when non_blocking is false. E.g. while non_blocking may be used to +* select between mutex_trylock and mutex_lock*, even in the +* latter case the lock should never be blocked on I/O, on userspace, or
drivers/i2c/i2c-pseudo.c line 2897
Quoted 10 lines
drivers/i2c/i2c-pseudo.c new file +10
-0+* on anything else outside the control of this driver. It IS +* permissable for the lock to be blocked on processing of previous or +* concurrent write input, so long as that processing does not violate +* these rules. +*/ + non_blocking = !!(filep->f_flags &O_NONBLOCK ); + pdata = filep->private_data; + +if (count > (size_t )I2CP_RW_SIZE_LIMIT ) + count =I2CP_RW_SIZE_LIMIT ;
I'd error out instead.
Quoted 5 lines
drivers/i2c/i2c-pseudo.c new file +5
-0+ + kbuf =kzalloc (count,GFP_KERNEL ); +if (!kbuf) { + ret = -ENOMEM ; + goto free_kbuf;
[snip]