Skip to contentSkip to conversation

Add Atmel I2C TPM AT97SC3204T emulated device

PATCH New Fabio Urquiza 6 participants 14 messages Nov 23, 2016 – Jan 5, 2017 Arm/Microchip (AT91) SoC support

lore
Share & tools
lore
#0 lore raw

cover Add Atmel I2C TPM AT97SC3204T emulated device

### Overview ###

The TPM passthrough feature allow a developer to test TPM functionalities, like Measure Boot, without the need to tamper with critical parts of the host machine, ie. bootloader. It has been implemented to the x86 architecture and have the same interface that is provided to PC machines: TPM TIS.

With the growing of use of the ARM server machines, also comes the need to reuse the same security features that are present in the in the PC server environment. So comes the need to use TPM devices in the ARM architecture.

This patchset provides a new frontend to the QEMU TPM passthrough with an interface suitable to communicate with an ARM based machine.

### Technical details ###

The TPM devices on the PC architecture are integrated in a way that the interface to it is made using an abstraction layer provided by the BIOS/UFI firmware. That interface is not available to ARM machines, therefore a new QEMU front end with a more suitable interface needed to be developed. The options based on the available TPM devices in the market were I2C and SPI. To make the choice, we look into the supported TPM drivers available to ARM architecture in the Linux Kernel. One of the simplest drivers was the ATMEL I2C TPM AT97SC3204T, so that was our target for the emulation.

We created a file called tpm_i2c_atmel.c based on the already available tpm_tis.c, registering as a I2C_SLAVE_CLASS and calling the tpm_backend functions.

One of the problems we had to address is regarding the behavior of the ATMEL I2C TPM AT97SC3204T Linux driver. After the driver sends a request to the TPM, it keeps polling the device with I2C read request. The real AT97SC3204T hardware ignore those requests while the response is not ready simply by not ACKing the I2C read on its address. When the response is ready it will ACK the request and proceed writing the response in the wire.

The QEMU I2C API does not provide a way to not ACK I2C requests when the device is not ready to transmit. In fact, if the device has been configured in the virtual machine, QEMU will automatically ACK every request without asking for the device permission for it. Therefore we created a flag in the I2CSlave struct that tells the I2C subsystem that the device is busy and not ready to ACK a I2C transfer. We understand that it could not be the best solution to the problem, but it appears to be the solution that have the least impact in the code overall. Suggestions on a different approach would be welcome.

### Testing ###

We tested the feature in the versatilepb machine running Linux with TrouSerS and tpm_tools:

qemu-system-arm -M versatilepb -kernel output/images/zImage -dtb output/images/versatile-pb.dtb -drive file=output/images/rootfs.ext2,if=scsi,format=raw -append "root=/dev/sda console=ttyAMA0,115200" -net nic,model=rtl8139 -net user -nographic -device tpm-tis,tpmdev=tpm-tpm0,address=0x20 -tpmdev passthrough,id=tpm-tpm0,path=/dev/tpm0,cancel-path=/sys/devices/pnp0/00:08/tpm/tpm0/cancel

The following device needed to be included on the Device Tree:

        i2c0: i2c@10002000 {
                 #address-cells = <1>;
                 #size-cells = <0>;
                 compatible = "arm,versatile-i2c";
                 reg = <0x10002000 0x1000>;
 
                 rtc@68 {
                         compatible = "dallas,ds1338";
                         reg = <0x68>;
                 };


                 tpm@20 {
                         compatible = "atmel,at97sc3204t";
                         reg = <0x20>;
                 };

The following config needed to be enabled in the Linux Kernel:

I2C_VERSATILE=y
TCG_TPM=y
TCG_TIS_I2C_ATMEL=y

Fabio Urquiza (2):
i2c: Add flag to NACK I2C transfers when busy
tpm: Add TPM I2C Atmel frontend

 default-configs/aarch64-softmmu.mak |   1 +
 default-configs/arm-softmmu.mak     |   1 +
 hw/i2c/core.c                       |   3 +
 hw/tpm/Makefile.objs                |   1 +
 hw/tpm/tpm_i2c_atmel.c              | 361 ++++++++++++++++++++++++++++++++++++
 include/hw/i2c/i2c.h                |   1 +
 6 files changed, 368 insertions(+)
 create mode 100644 hw/tpm/tpm_i2c_atmel.c
Signature · 1 line
2.9.3 (Apple Git-75)
#1 lore raw

PATCH 1/2 i2c: Add flag to NACK I2C transfers when busy

Add a busy flag on the I2CSlave struct which the device could set to NACK I2C transfer requests during the execution of the event handling function. If the busy flag is set, i2c_start_transfer() shall return 1.

---
 hw/i2c/core.c        | 3 +++
 include/hw/i2c/i2c.h | 1 +
 2 files changed, 4 insertions(+)
hw/i2c/core.c +3 -0
index abd4c4c..438233c 100644
@@ -142,6 +142,9 @@ int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)
            start condition.  */
         if (sc->event) {
             sc->event(node->elt, recv ? I2C_START_RECV : I2C_START_SEND);
+            if (node->elt->busy) {
+                return -1;
+            }
         }
     }
     return 0;
include/hw/i2c/i2c.h +1 -0
index c4085aa..9c6b1ce 100644
@@ -48,6 +48,7 @@ struct I2CSlave
 
     /* Remaining fields for internal use by the I2C code.  */
     uint8_t address;
+    uint8_t busy;
 };
 
 I2CBus *i2c_init_bus(DeviceState *parent, const char *name);
Signature · 1 line
2.9.3 (Apple Git-75)
#2 lore raw

PATCH 2/2 tpm: Add TPM I2C Atmel frontend

In reply to Fabio Urquiza

Add a new frontend to the TPM backend that emulate the Atmel I2C TPM AT97SC3204T device and make it available to use on ARM machines that have I2C Bus configured.

---
 default-configs/aarch64-softmmu.mak |   1 +
 default-configs/arm-softmmu.mak     |   1 +
 hw/tpm/Makefile.objs                |   1 +
 hw/tpm/tpm_i2c_atmel.c              | 361 ++++++++++++++++++++++++++++++++++++
 4 files changed, 364 insertions(+)
 create mode 100644 hw/tpm/tpm_i2c_atmel.c
default-configs/aarch64-softmmu.mak +1 -0
index 2449483..232957e 100644
@@ -7,3 +7,4 @@ CONFIG_AUX=y
 CONFIG_DDC=y
 CONFIG_DPCD=y
 CONFIG_XLNX_ZYNQMP=y
+CONFIG_TPM_I2C_ATMEL=$(CONFIG_TPM)
default-configs/arm-softmmu.mak +1 -0
index 6de3e16..ef3c8ac 100644
@@ -115,3 +115,4 @@ CONFIG_ACPI=y
 CONFIG_SMBIOS=y
 CONFIG_ASPEED_SOC=y
 CONFIG_GPIO_KEY=y
+CONFIG_TPM_I2C_ATMEL=$(CONFIG_TPM)
hw/tpm/Makefile.objs +1 -0
index 64cecc3..0d0f0b1 100644
@@ -1,2 +1,3 @@
 common-obj-$(CONFIG_TPM_TIS) += tpm_tis.o
+common-obj-$(CONFIG_TPM_I2C_ATMEL) += tpm_i2c_atmel.o
 common-obj-$(CONFIG_TPM_PASSTHROUGH) += tpm_passthrough.o tpm_util.o
hw/tpm/tpm_i2c_atmel.c new file +361 -0

361 lines not on this page · raw message

Signature · 1 line
2.9.3 (Apple Git-75)
#3 lore raw
In reply to Fabio Urquiza
Your series seems to have some coding style problems. See output below for more information:

Hi,

Your series seems to have some coding style problems. See output below for more information:

Subject: [Qemu-devel] [PATCH 0/2] Add Atmel I2C TPM AT97SC3204T emulated device
Type: series
Message-id: [email protected]

=== TEST SCRIPT BEGIN ===
#!/bin/bash

BASE=base
n=1
total=$(git log --oneline $BASE.. | wc -l)
failed=0

# Useful git options
git config --local diff.renamelimit 0
git config --local diff.renames True

commits="$(git log --format=%H --reverse $BASE..)" for c in $commits; do

    echo "Checking PATCH $n/$total: $(git log -n 1 --format=%s $c)..."
    if ! git show $c --format=email | ./scripts/checkpatch.pl --mailback -; then
        failed=1
        echo
    fi
    n=$((n+1))

done

exit $failed
=== TEST SCRIPT END ===

Updating 3c8cf5a9c21ff8782164d1def7f44bd888713384 Switched to a new branch 'test'
46ef6f2 tpm: Add TPM I2C Atmel frontend 24c07aa i2c: Add flag to NACK I2C transfers when busy

=== OUTPUT BEGIN ===
Checking PATCH 1/2: i2c: Add flag to NACK I2C transfers when busy... Checking PATCH 2/2: tpm: Add TPM I2C Atmel frontend...
WARNING: line over 80 characters
#127: FILE: hw/tpm/tpm_i2c_atmel.c:83:
+static void tpm_i2c_atmel_show_buffer(const TPMSizedBuffer *sb, const char *string)

ERROR: spaces required around that '-' (ctx:VxV)
#235: FILE: hw/tpm/tpm_i2c_atmel.c:191:

+                ret, tis->loc[0].r_offset-1);
                                          ^

WARNING: line over 80 characters
#301: FILE: hw/tpm/tpm_i2c_atmel.c:257:
+ error_setg(errp, "tpm_i2c_atmel: backend driver with id %s could not be "

WARNING: line over 80 characters
#309: FILE: hw/tpm/tpm_i2c_atmel.c:265:
+ error_setg(errp, "tpm_i2c_atmel: backend driver with id %s could not be "

WARNING: line over 80 characters
#315: FILE: hw/tpm/tpm_i2c_atmel.c:271:
+ error_setg(errp, "tpm_i2c_atmel: IRQ %d for TPM TIS is outside valid range "

total: 1 errors, 4 warnings, 372 lines checked

Your patch has style problems, please review. If any of these errors are false positives report them to the maintainer, see CHECKPATCH in MAINTAINERS.

=== OUTPUT END ===

Test command exited with code: 1

---
Email generated automatically by Patchew [http://patchew.org/].
Please send your feedback to [email protected]

#4 lore raw

cover Add Atmel I2C TPM AT97SC3204T emulated device

In reply to Fabio Urquiza

### Overview ###

The TPM passthrough feature allow a developer to test TPM functionalities, like Measure Boot, without the need to tamper with critical parts of the host machine, ie. bootloader. It has been implemented to the x86 architecture and have the same interface that is provided to PC machines: TPM TIS.

With the growing of use of the ARM server machines, also comes the need to reuse the same security features that are present in the in the PC server environment. So comes the need to use TPM devices in the ARM architecture.

This patchset provides a new frontend to the QEMU TPM passthrough with an interface suitable to communicate with an ARM based machine.

### Technical details ###

The TPM devices on the PC architecture are integrated in a way that the interface to it is made using an abstraction layer provided by the BIOS/UFI firmware. That interface is not available to ARM machines, therefore a new QEMU front end with a more suitable interface needed to be developed. The options based on the available TPM devices in the market were I2C and SPI. To make the choice, we look into the supported TPM drivers available to ARM architecture in the Linux Kernel. One of the simplest drivers was the ATMEL I2C TPM AT97SC3204T, so that was our target for the emulation.

We created a file called tpm_i2c_atmel.c based on the already available tpm_tis.c, registering as a I2C_SLAVE_CLASS and calling the tpm_backend functions.

One of the problems we had to address is regarding the behavior of the ATMEL I2C TPM AT97SC3204T Linux driver. After the driver sends a request to the TPM, it keeps polling the device with I2C read request. The real AT97SC3204T hardware ignore those requests while the response is not ready simply by not ACKing the I2C read on its address. When the response is ready it will ACK the request and proceed writing the response in the wire.

The QEMU I2C API does not provide a way to not ACK I2C requests when the device is not ready to transmit. In fact, if the device has been configured in the virtual machine, QEMU will automatically ACK every request without asking for the device permission for it. Therefore we created a flag in the I2CSlave struct that tells the I2C subsystem that the device is busy and not ready to ACK a I2C transfer. We understand that it could not be the best solution to the problem, but it appears to be the solution that have the least impact in the code overall. Suggestions on a different approach would be welcome.

### Testing ###

We tested the feature in the versatilepb machine running Linux with TrouSerS and tpm_tools:

qemu-system-arm -M versatilepb -kernel output/images/zImage \
	-dtb output/images/versatile-pb.dtb \
	-drive file=output/images/rootfs.ext2,if=scsi,format=raw \
	-append "root=/dev/sda console=ttyAMA0,115200" -net nic,model=rtl8139 \
	-net user -nographic -device tpm-tis,tpmdev=tpm-tpm0,address=0x20 \
	-tpmdev passthrough,id=tpm-tpm0,path=/dev/tpm0,cancel-path=/sys/devices/pnp0/00:08/tpm/tpm0/cancel

The following device needed to be included on the Device Tree:

        i2c0: i2c@10002000 {
                 #address-cells = <1>;
                 #size-cells = <0>;
                 compatible = "arm,versatile-i2c";
                 reg = <0x10002000 0x1000>;
 
                 rtc@68 {
                         compatible = "dallas,ds1338";
                         reg = <0x68>;
                 };


                 tpm@20 {
                         compatible = "atmel,at97sc3204t";
                         reg = <0x20>;
                 };

The following config needed to be enabled in the Linux Kernel:

I2C_VERSATILE=y
TCG_TPM=y
TCG_TIS_I2C_ATMEL=y

### Changes from V0 to v1 ###

- Fixed coding style problems found by Patchew.

Fabio Urquiza (2):
i2c: Add flag to NACK I2C transfers when busy
tpm: Add TPM I2C Atmel frontend

 default-configs/aarch64-softmmu.mak |   1 +
 default-configs/arm-softmmu.mak     |   1 +
 hw/i2c/core.c                       |   3 +
 hw/tpm/Makefile.objs                |   1 +
 hw/tpm/tpm_i2c_atmel.c              | 362 ++++++++++++++++++++++++++++++++++++
 include/hw/i2c/i2c.h                |   1 +
 6 files changed, 369 insertions(+)
 create mode 100644 hw/tpm/tpm_i2c_atmel.c
Signature · 1 line
2.8.3
#5 lore raw

PATCH 1/2 i2c: Add flag to NACK I2C transfers when busy

Add a busy flag on the I2CSlave struct which the device could set to NACK I2C transfer requests during the execution of the event handling function. If the busy flag is set, i2c_start_transfer() shall return 1.

---
 hw/i2c/core.c        | 3 +++
 include/hw/i2c/i2c.h | 1 +
 2 files changed, 4 insertions(+)
hw/i2c/core.c +3 -0
index abd4c4c..f36020f 100644
@@ -142,6 +142,9 @@ int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)
            start condition.  */
         if (sc->event) {
             sc->event(node->elt, recv ? I2C_START_RECV : I2C_START_SEND);
+            if (node->elt->busy) {
+                return 1;
+            }
         }
     }
     return 0;
include/hw/i2c/i2c.h +1 -0
index c4085aa..9c6b1ce 100644
@@ -48,6 +48,7 @@ struct I2CSlave
 
     /* Remaining fields for internal use by the I2C code.  */
     uint8_t address;
+    uint8_t busy;
 };
 
 I2CBus *i2c_init_bus(DeviceState *parent, const char *name);
Signature · 1 line
2.8.3
#6 lore raw

PATCH 2/2 tpm: Add TPM I2C Atmel frontend

In reply to Fabio Urquiza

Add a new frontend to the TPM backend that emulate the Atmel I2C TPM AT97SC3204T device and make it available to use on ARM machines that have I2C Bus configured.

---
 default-configs/aarch64-softmmu.mak |   1 +
 default-configs/arm-softmmu.mak     |   1 +
 hw/tpm/Makefile.objs                |   1 +
 hw/tpm/tpm_i2c_atmel.c              | 362 ++++++++++++++++++++++++++++++++++++
 4 files changed, 365 insertions(+)
 create mode 100644 hw/tpm/tpm_i2c_atmel.c
default-configs/aarch64-softmmu.mak +1 -0
index 2449483..232957e 100644
@@ -7,3 +7,4 @@ CONFIG_AUX=y
 CONFIG_DDC=y
 CONFIG_DPCD=y
 CONFIG_XLNX_ZYNQMP=y
+CONFIG_TPM_I2C_ATMEL=$(CONFIG_TPM)
default-configs/arm-softmmu.mak +1 -0
index 6de3e16..ef3c8ac 100644
@@ -115,3 +115,4 @@ CONFIG_ACPI=y
 CONFIG_SMBIOS=y
 CONFIG_ASPEED_SOC=y
 CONFIG_GPIO_KEY=y
+CONFIG_TPM_I2C_ATMEL=$(CONFIG_TPM)
hw/tpm/Makefile.objs +1 -0
index 64cecc3..0d0f0b1 100644
@@ -1,2 +1,3 @@
 common-obj-$(CONFIG_TPM_TIS) += tpm_tis.o
+common-obj-$(CONFIG_TPM_I2C_ATMEL) += tpm_i2c_atmel.o
 common-obj-$(CONFIG_TPM_PASSTHROUGH) += tpm_passthrough.o tpm_util.o
hw/tpm/tpm_i2c_atmel.c new file +362 -0

362 lines not on this page · raw message

Signature · 1 line
2.8.3
#7 lore raw
In reply to Fabio Urquiza

(added a couple of people to cc who might have an opinion on the i2c protocol questions below)

Quoted 7 lines · Fabio Urquiza

### Overview ###

The TPM passthrough feature allow a developer to test TPM functionalities, like Measure Boot, without the need to tamper with critical parts of the host machine, ie. bootloader. It has been implemented to the x86 architecture and have the same interface that is provided to PC machines: TPM TIS.

Quoted 6 lines

With the growing of use of the ARM server machines, also comes the need to reuse the same security features that are present in the in the PC server environment. So comes the need to use TPM devices in the ARM architecture.

This patchset provides a new frontend to the QEMU TPM passthrough with an interface suitable to communicate with an ARM based machine.

Thanks for this patchset (and apologies for not getting to it earlier). Unfortunately I'm completely unfamiliar with TPM, so reviewing this is going to be difficult.

Quoted 11 lines

### Technical details ###

The TPM devices on the PC architecture are integrated in a way that the interface to it is made using an abstraction layer provided by the BIOS/UFI firmware. That interface is not available to ARM machines, therefore a new QEMU front end with a more suitable interface needed to be developed. The options based on the available TPM devices in the market were I2C and SPI. To make the choice, we look into the supported TPM drivers available to ARM architecture in the Linux Kernel. One of the simplest drivers was the ATMEL I2C TPM AT97SC3204T, so that was our target for the emulation.

Quoted 3 lines

We created a file called tpm_i2c_atmel.c based on the already available tpm_tis.c, registering as a I2C_SLAVE_CLASS and calling the tpm_backend functions.

I guess my primary question here is: is an I2C device going to be the way that TPM is exposed on ARM hardware? If actual servers are going to do something else then there's limited benefit to implementing this in QEMU. (On the other hand, having this be just-another-i2c-slave means that adding it to QEMU isn't going to add maintenance complication in cases where it isn't used.)

Quoted 7 lines

One of the problems we had to address is regarding the behavior of the ATMEL I2C TPM AT97SC3204T Linux driver. After the driver sends a request to the TPM, it keeps polling the device with I2C read request. The real AT97SC3204T hardware ignore those requests while the response is not ready simply by not ACKing the I2C read on its address. When the response is ready it will ACK the request and proceed writing the response in the wire.

Quoted 9 lines

The QEMU I2C API does not provide a way to not ACK I2C requests when the device is not ready to transmit. In fact, if the device has been configured in the virtual machine, QEMU will automatically ACK every request without asking for the device permission for it. Therefore we created a flag in the I2CSlave struct that tells the I2C subsystem that the device is busy and not ready to ACK a I2C transfer. We understand that it could not be the best solution to the problem, but it appears to be the solution that have the least impact in the code overall. Suggestions on a different approach would be welcome.

I2C slaves definitely ought to be able to NAK I2C requests. This is possible for sends, ie data sent from the master to the slave (the slave just returns non-zero from its I2CSlaveClass::send function). In i2c protocol terms, this corresponds to the slave generating a NAK (by not taking SDA low) after the master has sent a byte of data. The bitbang_i2c code used by versatile was buggy in handling NAKs for sends until commit 9706e0162d24.

For recv I'm less sure how it ought to work, so if you can explain in terms of the i2c protocol what slave h/w behaviour we're trying to emulate that would help. At what points in the protocol can the slave return a NAK?

Our current API seems to envisage that the slave can return a negative value from I2CSlaveClass::recv instead of a data byte, but I'm not sure what this means in the i2c protocol.

If I understand your patch correctly, this is adding support for the slave refusing to ACK when the master sends out the slave address and r/w bit. I think that makes sense, but rather than having a state flag in the I2CSlave struct, we should change the prototype of the I2CSlaveClass event method so that it can return a value indicating ack or nak.

thanks
-- PMM

#8 lore raw
Quoted 2 lines · Peter Maydell

(added a couple of people to cc who might have an opinion on the i2c protocol questions below)

I'm certainly no expert, but I'll try :)

Quoted 2 lines

On 29 November 2016 at 19:30, Fabio Urquiza <[email protected]> wrote:

<snip>

Quoted 32 lines
Quoted 23 lines

One of the problems we had to address is regarding the behavior of the
ATMEL I2C TPM AT97SC3204T Linux driver. After the driver sends a request
to the TPM, it keeps polling the device with I2C read request. The real
AT97SC3204T hardware ignore those requests while the response is not ready
simply by not ACKing the I2C read on its address. When the response is
ready it will ACK the request and proceed writing the response in the wire.

The QEMU I2C API does not provide a way to not ACK I2C requests when the
device is not ready to transmit. In fact, if the device has been configured
in the virtual machine, QEMU will automatically ACK every request without
asking for the device permission for it. Therefore we created a flag in
the I2CSlave struct that tells the I2C subsystem that the device is

Quoted 8 lines

busy
and not ready to ACK a I2C transfer. We understand that it could not be
the best solution to the problem, but it appears to be the solution that
have the least impact in the code overall. Suggestions on a different
approach would be welcome.

Quoted 9 lines

I2C slaves definitely ought to be able to NAK I2C requests. This is possible for sends, ie data sent from the master to the slave (the slave just returns non-zero from its I2CSlaveClass::send function).
In i2c protocol terms, this corresponds to the slave generating a NAK (by not taking SDA low) after the master has sent a byte of data. The bitbang_i2c code used by versatile was buggy in handling NAKs for sends until commit 9706e0162d24.

I agree that they should be able to NAK, it seems that this may be the first device that actually needs that functionality (or at least, has implemented it).

The change looks about as minimal as one could make it, so I'm mostly happy with it.

I think we may need to add the busy field to hw/i2c/core.c:
VMStateDescription vmstate_i2c_slave, if this state should be persisted.

Also, it looks like the busy element is only ever used in a boolean context, so a boolean type may be more appropriate.

Quoted 8 lines

For recv I'm less sure how it ought to work, so if you can explain in terms of the i2c protocol what slave h/w behaviour we're trying to emulate that would help. At what points in the protocol can the slave return a NAK?

Our current API seems to envisage that the slave can return a negative value from I2CSlaveClass::recv instead of a data byte, but I'm not sure what this means in the i2c protocol.

Negative values are propagated upwards, where they are treated as errors, eg, in hw/i2c/aspeed_i2c.c:aspeed_i2c_bus_handle_cmd():

int ret = i2c_recv(bus->bus);
if (ret < 0) {
    qemu_log_mask(LOG_GUEST_ERROR, "%s: read failed\n", __func__); ret = 0xff;
}

The call to i2c_recv is too late to issue the NAK, I believe they occur during the start_transfer() call.

Quoted 7 lines

If I understand your patch correctly, this is adding support for the slave refusing to ACK when the master sends out the slave address and r/w bit. I think that makes sense, but rather than having a state flag in the I2CSlave struct, we should change the prototype of the I2CSlaveClass event method so that it can return a value indicating ack or nak.

Hmm, this could end up being quite an invasive change, but ultimately more elegant. I'm not sure which way the community prefers.

Quoted 2 lines

thanks
-- PMM

Signature · 4 lines
Alastair D'Silva
Open Source Developer
Linux Technology Centre, IBM Australia
mob: 0423 762 819
#9 lore raw
Quoted 4 lines · Alastair D'Silva
Quoted 2 lines · Peter Maydell

(added a couple of people to cc who might have an opinion on the i2c protocol questions below)

I'm certainly no expert, but I'll try :)

I know a little bit and I've implemented some stuff, so I'll try, too :).

Quoted 3 lines
Quoted 2 lines

On 29 November 2016 at 19:30, Fabio Urquiza <[email protected]> wrote:

<snip>

<snip> some more

Quoted 11 lines
Quoted 8 lines

For recv I'm less sure how it ought to work, so if you can explain in terms of the i2c protocol what slave h/w behaviour we're trying to emulate that would help. At what points in the protocol can the slave return a NAK?

Our current API seems to envisage that the slave can return a negative value from I2CSlaveClass::recv instead of a data byte, but I'm not sure what this means in the i2c protocol.

Negative values are propagated upwards, where they are treated as errors, eg, in hw/i2c/aspeed_i2c.c:aspeed_i2c_bus_handle_cmd():

Quoted 8 lines

int ret = i2c_recv(bus->bus);

if (ret < 0) {
     qemu_log_mask(LOG_GUEST_ERROR, "%s: read failed\n", __func__);
     ret = 0xff;
}

The call to i2c_recv is too late to issue the NAK, I believe they occur during the start_transfer() call.

Indeed, it is. On the wire, a NAK after the address bits have been sent terminates the transaction normally.

Quoted 10 lines
Quoted 8 lines

If I understand your patch correctly, this is adding support for the slave refusing to ACK when the master sends out the slave address and r/w bit. I think that makes sense, but rather than having a state flag in the I2CSlave struct, we should change the prototype of the I2CSlaveClass event method so that it can return a value indicating ack or nak.

Hmm, this could end up being quite an invasive change, but ultimately more elegant. I'm not sure which way the community prefers.

I have a patch that adds a check_event() handler along side the event() handler. If a device wants to send a NAK, it can implement check_event() instead of event() and return non-zero to NAK.

I toyed with just changing all the event() calls, but there are a bunch. This seemed like the better approach. I can send if you like.

-corey

Quoted 2 lines
Quoted 2 lines

thanks
-- PMM

#10 lore raw
Quoted 10 lines · Corey Minyard
Quoted 9 lines · Alastair D'Silva
Quoted 3 lines · Peter Maydell

Our current API seems to envisage that the slave can return a negative value from I2CSlaveClass::recv instead of a data byte, but I'm not sure what this means in the i2c protocol.

Negative values are propagated upwards, where they are treated as errors, eg, in hw/i2c/aspeed_i2c.c:aspeed_i2c_bus_handle_cmd():

Quoted 8 lines
Quoted 8 lines

int ret = i2c_recv(bus->bus);

if (ret < 0) {
     qemu_log_mask(LOG_GUEST_ERROR, "%s: read failed\n", __func__);
     ret = 0xff;
}

The call to i2c_recv is too late to issue the NAK, I believe they occur during the start_transfer() call.

OK, so if returning negative values from i2c_recv() isn't the device saying "I am NAKing this", what *do* they mean?

Quoted 11 lines
Quoted 9 lines
Quoted 7 lines

If I understand your patch correctly, this is adding support for the slave refusing to ACK when the master sends out the slave address and r/w bit. I think that makes sense, but rather than having a state flag in the I2CSlave struct, we should change the prototype of the I2CSlaveClass event method so that it can return a value indicating ack or nak.

Hmm, this could end up being quite an invasive change, but ultimately more elegant. I'm not sure which way the community prefers.

Quoted 8 lines

I have a patch that adds a check_event() handler along side the event() handler.
If a device wants to send a NAK, it can implement check_event() instead of event() and return non-zero to NAK.

I toyed with just changing all the event() calls, but there are a bunch. This seemed
like the better approach. I can send if you like.

It looks like there are only a dozen or so. I think it would be better for the long term just to change the event calls. We should also document in the comments in the I2CSlaveClass struct definition exactly what the semantics of the various functions are.

thanks
-- PMM

#11 lore raw
Quoted 15 lines · Peter Maydell
Quoted 14 lines · Corey Minyard
Quoted 13 lines · Alastair D'Silva
Quoted 3 lines · Peter Maydell

Our current API seems to envisage that the slave can return a negative value from I2CSlaveClass::recv instead of a data byte, but I'm not sure what this means in the i2c protocol.

Negative values are propagated upwards, where they are treated as errors, eg, in hw/i2c/aspeed_i2c.c:aspeed_i2c_bus_handle_cmd():

int ret = i2c_recv(bus->bus);

if (ret < 0) {
      qemu_log_mask(LOG_GUEST_ERROR, "%s: read failed\n", __func__);
      ret = 0xff;
}
Quoted 4 lines
Quoted 2 lines
Quoted 2 lines

The call to i2c_recv is too late to issue the NAK, I believe they occur during the start_transfer() call.

OK, so if returning negative values from i2c_recv() isn't the device saying "I am NAKing this", what *do* they mean?

It actually makes no sense. In real I2C hardware, the receiver of the byte always does the ACK/NAK. The NAK is sent by the receiver of the data to signal that it has finished the transfer.

So when i2c_recv() is called, it's actually the I2c device doing a transmit and the i2c master receiving the data. So the device cannot send a NAK in that scenario.

The start conditions and address are always send by the master to the device, so it makes sense for the start events to be able to return a NAK.

And for i2c_send(), the device should respond with a NAK to terminate the transfer. So it makes sense for i2c_send() to be able to return a NAK. This doesn't appear to be properly implemented in a number of places.

Quoted 15 lines
Quoted 15 lines
Quoted 9 lines
Quoted 7 lines

If I understand your patch correctly, this is adding support for the slave refusing to ACK when the master sends out the slave address and r/w bit. I think that makes sense, but rather than having a state flag in the I2CSlave struct, we should change the prototype of the I2CSlaveClass event method so that it can return a value indicating ack or nak.

Hmm, this could end up being quite an invasive change, but ultimately more elegant. I'm not sure which way the community prefers.

I have a patch that adds a check_event() handler along side the event() handler.
If a device wants to send a NAK, it can implement check_event() instead of event() and return non-zero to NAK.

Quoted 8 lines
Quoted 3 lines

I toyed with just changing all the event() calls, but there are a bunch. This seemed
like the better approach. I can send if you like.

It looks like there are only a dozen or so. I think it would be better for the long term just to change the event calls. We should also document in the comments in the I2CSlaveClass struct definition exactly what the semantics of the various functions are.

Ok, my memory didn't serve me correctly. I'll rework my patch for that.

Thanks,

-corey

Quoted 2 lines

thanks
-- PMM

#12 lore raw

PATCH 1/1 i2c: Allow I2C devices to NAK start events

In reply to Peter Maydell

From: Corey Minyard <[email protected]>

Add a return value to the event handler. Some I2C devices will NAK if they have no data, so allow them to do this. This required the following changes:

Go through all the event handlers and change them to return int and return 0.

Modify i2c_start_transfer to terminate the transaction on a NAK.

Modify smbus handing to not assert if a NAK occurs on a second operation, and terminate the transaction and return -1 instead.

Add some information on semantics to I2CSlaveClass.

---
 hw/arm/pxa2xx.c      |  4 +++-
 hw/arm/tosa.c        |  4 +++-
 hw/arm/z2.c          |  4 +++-
 hw/audio/wm8750.c    |  4 +++-
 hw/display/ssd0303.c |  4 +++-
 hw/gpio/max7310.c    |  4 +++-
 hw/i2c/core.c        | 31 +++++++++++++++++++++++++------
 hw/i2c/i2c-ddc.c     |  4 +++-
 hw/i2c/smbus.c       | 13 +++++++++----
 hw/input/lm832x.c    |  4 +++-
 hw/misc/tmp105.c     |  3 ++-
 hw/timer/ds1338.c    |  4 +++-
 hw/timer/twl92230.c  |  4 +++-
 include/hw/i2c/i2c.h | 16 ++++++++++++----
 14 files changed, 78 insertions(+), 25 deletions(-)
hw/arm/pxa2xx.c +3 -1
index 21ea1d6..4d3179e 100644
@@ -1258,7 +1258,7 @@ static void pxa2xx_i2c_update(PXA2xxI2CState *s)
 }
 
 /* These are only stubs now.  */
-static void pxa2xx_i2c_event(I2CSlave *i2c, enum i2c_event event)
+static int pxa2xx_i2c_event(I2CSlave *i2c, enum i2c_event event)
 {
     PXA2xxI2CSlaveState *slave = PXA2XX_I2C_SLAVE(i2c);
     PXA2xxI2CState *s = slave->host;
@@ -1280,6 +1280,8 @@ static void pxa2xx_i2c_event(I2CSlave *i2c, enum i2c_event event)
         break;
     }
     pxa2xx_i2c_update(s);
+
+    return 0;
 }
 
 static int pxa2xx_i2c_rx(I2CSlave *i2c)
hw/arm/tosa.c +3 -1
index 1ee12f4..1165303 100644
@@ -172,7 +172,7 @@ static int tosa_dac_send(I2CSlave *i2c, uint8_t data)
     return 0;
 }
 
-static void tosa_dac_event(I2CSlave *i2c, enum i2c_event event)
+static int tosa_dac_event(I2CSlave *i2c, enum i2c_event event)
 {
     TosaDACState *s = TOSA_DAC(i2c);
 
@@ -194,6 +194,8 @@ static void tosa_dac_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 static int tosa_dac_recv(I2CSlave *s)
hw/arm/z2.c +3 -1
index 68a92f3..e2d8160 100644
@@ -220,7 +220,7 @@ static int aer915_send(I2CSlave *i2c, uint8_t data)
     return 0;
 }
 
-static void aer915_event(I2CSlave *i2c, enum i2c_event event)
+static int aer915_event(I2CSlave *i2c, enum i2c_event event)
 {
     AER915State *s = AER915(i2c);
 
@@ -238,6 +238,8 @@ static void aer915_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 static int aer915_recv(I2CSlave *slave)
hw/audio/wm8750.c +3 -1
index 0c6500e..f8b5beb 100644
@@ -303,7 +303,7 @@ static void wm8750_reset(I2CSlave *i2c)
     s->i2c_len = 0;
 }
 
-static void wm8750_event(I2CSlave *i2c, enum i2c_event event)
+static int wm8750_event(I2CSlave *i2c, enum i2c_event event)
 {
     WM8750State *s = WM8750(i2c);
 
@@ -321,6 +321,8 @@ static void wm8750_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 #define WM8750_LINVOL	0x00
hw/display/ssd0303.c +3 -1
index d301756..68a80b9 100644
@@ -179,7 +179,7 @@ static int ssd0303_send(I2CSlave *i2c, uint8_t data)
     return 0;
 }
 
-static void ssd0303_event(I2CSlave *i2c, enum i2c_event event)
+static int ssd0303_event(I2CSlave *i2c, enum i2c_event event)
 {
     ssd0303_state *s = SSD0303(i2c);
 
@@ -193,6 +193,8 @@ static void ssd0303_event(I2CSlave *i2c, enum i2c_event event)
         /* Nothing to do.  */
         break;
     }
+
+    return 0;
 }
 
 static void ssd0303_update_display(void *opaque)
hw/gpio/max7310.c +3 -1
index 1bd5eaf..f82e3e6 100644
@@ -129,7 +129,7 @@ static int max7310_tx(I2CSlave *i2c, uint8_t data)
     return 0;
 }
 
-static void max7310_event(I2CSlave *i2c, enum i2c_event event)
+static int max7310_event(I2CSlave *i2c, enum i2c_event event)
 {
     MAX7310State *s = MAX7310(i2c);
     s->len = 0;
@@ -147,6 +147,8 @@ static void max7310_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 static const VMStateDescription vmstate_max7310 = {
hw/i2c/core.c +25 -6
index abd4c4c..584b76d 100644
@@ -88,18 +88,26 @@ int i2c_bus_busy(I2CBus *bus)
     return !QLIST_EMPTY(&bus->current_devs);
 }
 
+/* TODO: Make this handle multiple masters.  */
 /*
- * Returns non-zero if the address is not valid.  If this is called
- * again without an intervening i2c_end_transfer(), like in the SMBus
- * case where the operation is switched from write to read, this
- * function will not rescan the bus and thus cannot fail.
+ * Start or continue an i2c transaction.  When this is called for the
+ * first time or after an i2c_end_transfer(), if it returns an error
+ * the bus transaction is terminated (or really never started).  If
+ * this is called after another i2c_start_transfer() without an
+ * intervening i2c_end_transfer(), and it returns an error, the
+ * transaction will not be terminated.  The caller must do it.
+ *
+ * This corresponds with the way real hardware works.  The SMBus
+ * protocol uses a start transfer to switch from write to read mode
+ * without releasing the bus.  If that fails, the bus is still
+ * in a transaction.
  */
-/* TODO: Make this handle multiple masters.  */
 int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)
 {
     BusChild *kid;
     I2CSlaveClass *sc;
     I2CNode *node;
+    bool bus_scanned = false;
 
     if (address == I2C_BROADCAST) {
         /*
@@ -130,6 +138,7 @@ int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)
                 }
             }
         }
+        bus_scanned = true;
     }
 
     if (QLIST_EMPTY(&bus->current_devs)) {
@@ -137,11 +146,21 @@ int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)
     }
 
     QLIST_FOREACH(node, &bus->current_devs, next) {
+        int rv;
+
         sc = I2C_SLAVE_GET_CLASS(node->elt);
         /* If the bus is already busy, assume this is a repeated
            start condition.  */
+
         if (sc->event) {
-            sc->event(node->elt, recv ? I2C_START_RECV : I2C_START_SEND);
+            rv = sc->event(node->elt, recv ? I2C_START_RECV : I2C_START_SEND);
+            if (rv && !bus->broadcast) {
+                if (bus_scanned) {
+                    /* First call, terminate the transfer. */
+                    i2c_end_transfer(bus);
+                }
+                return rv;
+            }
         }
     }
     return 0;
hw/i2c/i2c-ddc.c +3 -1
index 1227212..66899d7 100644
@@ -230,13 +230,15 @@ static void i2c_ddc_reset(DeviceState *ds)
     s->reg = 0;
 }
 
-static void i2c_ddc_event(I2CSlave *i2c, enum i2c_event event)
+static int i2c_ddc_event(I2CSlave *i2c, enum i2c_event event)
 {
     I2CDDCState *s = I2CDDC(i2c);
 
     if (event == I2C_START_SEND) {
         s->firstbyte = true;
     }
+
+    return 0;
 }
 
 static int i2c_ddc_rx(I2CSlave *i2c)
hw/i2c/smbus.c +9 -4
index 5b4dd3e..2d1b79a 100644
@@ -67,7 +67,7 @@ static void smbus_do_write(SMBusDevice *dev)
     }
 }
 
-static void smbus_i2c_event(I2CSlave *s, enum i2c_event event)
+static int smbus_i2c_event(I2CSlave *s, enum i2c_event event)
 {
     SMBusDevice *dev = SMBUS_DEVICE(s);
 
@@ -148,6 +148,8 @@ static void smbus_i2c_event(I2CSlave *s, enum i2c_event event)
             break;
         }
     }
+
+    return 0;
 }
 
 static int smbus_i2c_recv(I2CSlave *s)
@@ -249,7 +251,8 @@ int smbus_read_byte(I2CBus *bus, uint8_t addr, uint8_t command)
     }
     i2c_send(bus, command);
     if (i2c_start_transfer(bus, addr, 1)) {
-        assert(0);
+        i2c_end_transfer(bus);
+        return -1;
     }
     data = i2c_recv(bus);
     i2c_nack(bus);
@@ -276,7 +279,8 @@ int smbus_read_word(I2CBus *bus, uint8_t addr, uint8_t command)
     }
     i2c_send(bus, command);
     if (i2c_start_transfer(bus, addr, 1)) {
-        assert(0);
+        i2c_end_transfer(bus);
+        return -1;
     }
     data = i2c_recv(bus);
     data |= i2c_recv(bus) << 8;
@@ -307,7 +311,8 @@ int smbus_read_block(I2CBus *bus, uint8_t addr, uint8_t command, uint8_t *data)
     }
     i2c_send(bus, command);
     if (i2c_start_transfer(bus, addr, 1)) {
-        assert(0);
+        i2c_end_transfer(bus);
+        return -1;
     }
     len = i2c_recv(bus);
     if (len > 32) {
hw/input/lm832x.c +3 -1
index 539682c..2340523 100644
@@ -383,7 +383,7 @@ static void lm_kbd_write(LM823KbdState *s, int reg, int byte, uint8_t value)
     }
 }
 
-static void lm_i2c_event(I2CSlave *i2c, enum i2c_event event)
+static int lm_i2c_event(I2CSlave *i2c, enum i2c_event event)
 {
     LM823KbdState *s = LM8323(i2c);
 
@@ -397,6 +397,8 @@ static void lm_i2c_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 static int lm_i2c_rx(I2CSlave *i2c)
hw/misc/tmp105.c +2 -1
index f5c2472..04e8378 100644
@@ -176,7 +176,7 @@ static int tmp105_tx(I2CSlave *i2c, uint8_t data)
     return 0;
 }
 
-static void tmp105_event(I2CSlave *i2c, enum i2c_event event)
+static int tmp105_event(I2CSlave *i2c, enum i2c_event event)
 {
     TMP105State *s = TMP105(i2c);
 
@@ -185,6 +185,7 @@ static void tmp105_event(I2CSlave *i2c, enum i2c_event event)
     }
 
     s->len = 0;
+    return 0;
 }
 
 static int tmp105_post_load(void *opaque, int version_id)
hw/timer/ds1338.c +3 -1
index 0112949..18c8e38 100644
@@ -94,7 +94,7 @@ static void inc_regptr(DS1338State *s)
     }
 }
 
-static void ds1338_event(I2CSlave *i2c, enum i2c_event event)
+static int ds1338_event(I2CSlave *i2c, enum i2c_event event)
 {
     DS1338State *s = DS1338(i2c);
 
@@ -113,6 +113,8 @@ static void ds1338_event(I2CSlave *i2c, enum i2c_event event)
     default:
         break;
     }
+
+    return 0;
 }
 
 static int ds1338_recv(I2CSlave *i2c)
hw/timer/twl92230.c +3 -1
index 7ba4e9a..b8d914e 100644
@@ -713,12 +713,14 @@ static void menelaus_write(void *opaque, uint8_t addr, uint8_t value)
     }
 }
 
-static void menelaus_event(I2CSlave *i2c, enum i2c_event event)
+static int menelaus_event(I2CSlave *i2c, enum i2c_event event)
 {
     MenelausState *s = TWL92230(i2c);
 
     if (event == I2C_START_SEND)
         s->firstbyte = 1;
+
+    return 0;
 }
 
 static int menelaus_tx(I2CSlave *i2c, uint8_t data)
include/hw/i2c/i2c.h +12 -4
index c4085aa..2ce611d 100644
@@ -32,14 +32,22 @@ typedef struct I2CSlaveClass
     /* Callbacks provided by the device.  */
     int (*init)(I2CSlave *dev);
 
-    /* Master to slave.  */
+    /* Master to slave. Returns non-zero for a NAK, 0 for success. */
     int (*send)(I2CSlave *s, uint8_t data);
 
-    /* Slave to master.  */
+    /*
+     * Slave to master.  This cannot fail, the device should always
+     * return something here.  Negative values probably result in 0xff
+     * and a possible log from the driver, and shouldn't be used.
+     */
     int (*recv)(I2CSlave *s);
 
-    /* Notify the slave of a bus state change.  */
-    void (*event)(I2CSlave *s, enum i2c_event event);
+    /*
+     * Notify the slave of a bus state change.  For start event,
+     * returns non-zero to NAK an operation.  For other events the
+     * return code is not used and should be zero.
+     */
+    int (*event)(I2CSlave *s, enum i2c_event event);
 } I2CSlaveClass;
 
 struct I2CSlave
Signature · 1 line
2.7.4
#13 lore raw

Re: [Qemu-devel] [PATCH] i2c: Allow I2C devices to NAK start events

Quoted 9 lines · On 20 December 2016 at 21:26, <[email protected]> wrote:

From: Corey Minyard <[email protected]>

Add a return value to the event handler. Some I2C devices will NAK if they have no data, so allow them to do this. This required the following changes:

Go through all the event handlers and change them to return int and return 0.

Quoted 8 lines

Modify i2c_start_transfer to terminate the transaction on a NAK.

Modify smbus handing to not assert if a NAK occurs on a second operation, and terminate the transaction and return -1 instead.

Add some information on semantics to I2CSlaveClass.

Thanks; added to target-arm.next.

-- PMM