diff --git a/hw/dv/dpi/common/tcp_server/tcp_server.c b/hw/dv/dpi/common/tcp_server/tcp_server.c index 46025bb73c4966..cabfdb4398922f 100644 --- a/hw/dv/dpi/common/tcp_server/tcp_server.c +++ b/hw/dv/dpi/common/tcp_server/tcp_server.c @@ -419,7 +419,7 @@ struct tcp_server_ctx *tcp_server_create(const char *display_name, if (pthread_mutex_init(&ctx->sock_mutex, NULL) != 0 || pthread_create(&ctx->sock_thread, NULL, server_create, (void *)ctx) != - 0) { + 0) { fprintf(stderr, "%s: Unable to create TCP socket thread\n", ctx->display_name); ctx_free(ctx); diff --git a/hw/dv/dpi/gpiodpi/gpiodpi.c b/hw/dv/dpi/gpiodpi/gpiodpi.c index 7fa103249f3af9..720753efabdd4c 100644 --- a/hw/dv/dpi/gpiodpi/gpiodpi.c +++ b/hw/dv/dpi/gpiodpi/gpiodpi.c @@ -144,7 +144,8 @@ void *gpiodpi_create(const char *name, int listen_port, int n_bits) { assert(cwd != NULL); int path_len; - path_len = snprintf(ctx->dev_to_host_path, PATH_MAX, "%s/%s-read", cwd, name); + path_len = + snprintf(ctx->dev_to_host_path, PATH_MAX, "%s/%s-read", cwd, name); assert(path_len > 0 && path_len <= PATH_MAX); path_len = snprintf(ctx->host_to_dev_path, PATH_MAX, "%s/%s-write", cwd, name); @@ -256,7 +257,7 @@ uint32_t gpiodpi_host_to_device_tick(void *ctx_void, svBitVecVal *gpio_oe, read_len++; } } while (read_len > 0 && read_len < 256 && - (gpio_str[read_len - 1] != '\0' && + (gpio_str[read_len - 1] != '\0' && gpio_str[read_len - 1] != '\r' && gpio_str[read_len - 1] != '\n')); } else { @@ -288,7 +289,7 @@ uint32_t gpiodpi_host_to_device_tick(void *ctx_void, svBitVecVal *gpio_oe, } CLR_BIT(ctx->driven_pin_values, idx); set_bit_val(&ctx->weak_pins, idx, weak); - } else if (idx == 255){ + } else if (idx == 255) { ctx->rst_n = 0; } else { fprintf(stderr, @@ -310,7 +311,7 @@ uint32_t gpiodpi_host_to_device_tick(void *ctx_void, svBitVecVal *gpio_oe, } SET_BIT(ctx->driven_pin_values, idx); set_bit_val(&ctx->weak_pins, idx, weak); - } else if (idx == 255){ + } else if (idx == 255) { ctx->rst_n = 1; } else { fprintf(stderr, @@ -355,12 +356,12 @@ void gpiodpi_close(void *ctx_void) { tcp_server_close(ctx->sock); } else { if (close(ctx->dev_to_host_fifo) != 0) { - printf("GPIO: Failed to close FIFO file at %s: %s\n", ctx->dev_to_host_path, - strerror(errno)); + printf("GPIO: Failed to close FIFO file at %s: %s\n", + ctx->dev_to_host_path, strerror(errno)); } if (close(ctx->host_to_dev_fifo) != 0) { - printf("GPIO: Failed to close FIFO file at %s: %s\n", ctx->host_to_dev_path, - strerror(errno)); + printf("GPIO: Failed to close FIFO file at %s: %s\n", + ctx->host_to_dev_path, strerror(errno)); } if (unlink(ctx->dev_to_host_path) != 0) { diff --git a/hw/dv/dpi/spidpi/spidpi.c b/hw/dv/dpi/spidpi/spidpi.c index 81b439b512be15..49e2ee01a0092a 100644 --- a/hw/dv/dpi/spidpi/spidpi.c +++ b/hw/dv/dpi/spidpi/spidpi.c @@ -21,9 +21,8 @@ #include #include -#include "verilator_sim_ctrl.h" - #include "tcp_server.h" +#include "verilator_sim_ctrl.h" // Enable this define to stop tracing at cycle 4 // and resume at the first SPI packet @@ -69,30 +68,35 @@ struct spidpi_ctx { static const char *json_find_next_char(char value, const char *ptr) { const char *tmp_ptr = ptr; - while (tmp_ptr != NULL && - *tmp_ptr!= value && *tmp_ptr != ']' && *tmp_ptr != '\0') tmp_ptr++; + while (tmp_ptr != NULL && *tmp_ptr != value && *tmp_ptr != ']' && + *tmp_ptr != '\0') + tmp_ptr++; // Exit conditions - if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') tmp_ptr = NULL; + if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') + tmp_ptr = NULL; return tmp_ptr; } -static const char *json_parse_next_tag(char *tag, int tag_size, const char *ptr) { +static const char *json_parse_next_tag(char *tag, int tag_size, + const char *ptr) { const char *tmp_ptr = ptr; tmp_ptr = json_find_next_char('"', tmp_ptr); - if (tmp_ptr != NULL) tmp_ptr++; + if (tmp_ptr != NULL) + tmp_ptr++; int index = 0; - while (index < (tag_size - 1) && tmp_ptr != NULL && - *tmp_ptr != '"' && *tmp_ptr != ']' && *tmp_ptr != '\0') { + while (index < (tag_size - 1) && tmp_ptr != NULL && *tmp_ptr != '"' && + *tmp_ptr != ']' && *tmp_ptr != '\0') { tag[index++] = *tmp_ptr++; } tag[index] = '\0'; // Exit conditions - if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') tmp_ptr = NULL; + if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') + tmp_ptr = NULL; return tmp_ptr; } @@ -101,7 +105,8 @@ static const char *json_parse_next_integer(int *val, const char *ptr) { const char *tmp_ptr = ptr; char digits[32]; - while (tmp_ptr != NULL && isspace(*tmp_ptr)) tmp_ptr++; + while (tmp_ptr != NULL && isspace(*tmp_ptr)) + tmp_ptr++; int index = 0; while (index < (sizeof(digits) - 1) && tmp_ptr != NULL && @@ -114,7 +119,8 @@ static const char *json_parse_next_integer(int *val, const char *ptr) { } // Exit conditions - if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') tmp_ptr = NULL; + if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') + tmp_ptr = NULL; return tmp_ptr; } @@ -131,10 +137,12 @@ static const char *json_parse_next_integer_array(char *vals, int *num_vals, } tmp_ptr = json_find_next_char('[', tmp_ptr); - if (tmp_ptr != NULL) tmp_ptr++; + if (tmp_ptr != NULL) + tmp_ptr++; while (tmp_ptr != NULL && *tmp_ptr != ']') { - while (isspace(*tmp_ptr)) tmp_ptr++; + while (isspace(*tmp_ptr)) + tmp_ptr++; int index = 0; while (index < (sizeof(digits) - 1) && @@ -146,13 +154,18 @@ static const char *json_parse_next_integer_array(char *vals, int *num_vals, vals[(*num_vals)++] = atoi(digits); } - while (isspace(*tmp_ptr)) tmp_ptr++; - if (*tmp_ptr == ',') tmp_ptr++; - if (*tmp_ptr == '\0') tmp_ptr = NULL; + while (isspace(*tmp_ptr)) + tmp_ptr++; + if (*tmp_ptr == ',') + tmp_ptr++; + if (*tmp_ptr == '\0') + tmp_ptr = NULL; } // Exit conditions - if (tmp_ptr != NULL && *tmp_ptr == ']') tmp_ptr++; - if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') tmp_ptr = NULL; + if (tmp_ptr != NULL && *tmp_ptr == ']') + tmp_ptr++; + if (tmp_ptr == NULL || *tmp_ptr == ']' || *tmp_ptr == '\0') + tmp_ptr = NULL; return tmp_ptr; } @@ -186,15 +199,14 @@ static const char *xfer_parse_next_trans(void *ctx_void, const char *xfer_ptr) { if (trans_ptr != NULL) { int data_size = sizeof(ctx->buf); trans_ptr++; - trans_ptr = json_parse_next_integer_array(ctx->buf, &data_size, trans_ptr); + trans_ptr = + json_parse_next_integer_array(ctx->buf, &data_size, trans_ptr); ctx->xfer_write = true; ctx->nmax = data_size; } } trans_ptr = json_find_next_char('}', trans_ptr); - } - else - if (strstr(tag, "Read") != NULL) { + } else if (strstr(tag, "Read") != NULL) { trans_ptr = json_find_next_char('{', trans_ptr); trans_ptr = json_parse_next_tag(tag, sizeof(tag), trans_ptr); if (strstr(tag, "len") != NULL) { @@ -208,13 +220,12 @@ static const char *xfer_parse_next_trans(void *ctx_void, const char *xfer_ptr) { } } trans_ptr = json_find_next_char('}', trans_ptr); - } - else - if (strstr(tag, "Both") != NULL) { + } else if (strstr(tag, "Both") != NULL) { assert(false && "Both transaction not supported."); } - if (trans_ptr != NULL) trans_ptr++; + if (trans_ptr != NULL) + trans_ptr++; trans_ptr = json_find_next_char('}', trans_ptr); return trans_ptr; @@ -231,8 +242,7 @@ static bool xfer_parse(void *ctx_void) { // Simple parser of SPI JSON transaction header char *ptr = ctx->xfer_buf_in; if ((ptr = strstr(ptr, "Req")) != NULL && - (ptr = strstr(ptr, "Spi")) != NULL && - (ptr = strstr(ptr, "id")) != NULL && + (ptr = strstr(ptr, "Spi")) != NULL && (ptr = strstr(ptr, "id")) != NULL && (ptr = strstr(ptr, "command")) != NULL && (ptr = strstr(ptr, "RunTransaction")) != NULL && (ptr = strstr(ptr, "transaction")) != NULL && @@ -250,7 +260,8 @@ static void xfer_respond_next_trans(void *ctx_void) { // assemble SPI JSON response if (!ctx->xfer_start) { - sprintf(ctx->xfer_buf_out, "{\"Res\":{\"Ok\":{" + sprintf(ctx->xfer_buf_out, + "{\"Res\":{\"Ok\":{" "\"Spi\":{\"RunTransaction\":{\"transaction\":["); ctx->xfer_start = true; } else { @@ -259,11 +270,9 @@ static void xfer_respond_next_trans(void *ctx_void) { if (ctx->xfer_write && ctx->xfer_read) { assert(false && "Response to Both transaction not supported."); - } else - if (ctx->xfer_write) { + } else if (ctx->xfer_write) { strcat(ctx->xfer_buf_out, "\"Write\""); - } else - if (ctx->xfer_read) { + } else if (ctx->xfer_read) { char value[16]; strcat(ctx->xfer_buf_out, "{\"Read\":{\"data\":["); @@ -283,7 +292,8 @@ static void xfer_respond(void *ctx_void, bool error) { struct spidpi_ctx *ctx = (struct spidpi_ctx *)ctx_void; if (error) { - sprintf(ctx->xfer_buf_out, "{\"Res\":{\"Err\":{" + sprintf(ctx->xfer_buf_out, + "{\"Res\":{\"Err\":{" "\"description\":\"Error processing SPI device transaction\"," "\"backtrace\":\"%s:%d\"" "}}}\n", @@ -377,7 +387,8 @@ void *spidpi_create(const char *name, int listen_port, int mode, int loglevel) { printf( "\n" - "SPI: Created %s for %s. Connect to it with any terminal program, e.g.\n" + "SPI: Created %s for %s. Connect to it with any terminal program, " + "e.g.\n" "$ screen %s\n" "NOTE: a SPI transaction is run for every 4 characters entered.\n", ctx->ptyname, name, ctx->ptyname); @@ -432,8 +443,7 @@ char spidpi_tick(void *ctx_void, const svLogicVecVal *d2p_data) { int result; if ((result = read(ctx->host, &buf, 1)) == 1) { valid = true; - } else - if (result == -1) { + } else if (result == -1) { if (errno != EAGAIN) { xfer_reset(ctx); fprintf(stderr, "Read on SPI FIFO gave %s\n", strerror(errno)); @@ -442,9 +452,8 @@ char spidpi_tick(void *ctx_void, const svLogicVecVal *d2p_data) { } if (valid) { if (buf == '\n') { - // Eat newlines - } else - if (ctx->xfer_start) { + // Eat newlines + } else if (ctx->xfer_start) { ctx->xfer_buf_in[ctx->xfer_count++] = buf; switch (buf) { case '{': @@ -459,8 +468,7 @@ char spidpi_tick(void *ctx_void, const svLogicVecVal *d2p_data) { if (ctx->xfer_indent == 0) { ctx->xfer_finish = true; } - } else - if (buf == '{') { + } else if (buf == '{') { ctx->xfer_buf_in[ctx->xfer_count++] = buf; ctx->xfer_indent = 1; ctx->xfer_start = true; @@ -474,8 +482,7 @@ char spidpi_tick(void *ctx_void, const svLogicVecVal *d2p_data) { fprintf(stderr, "Transaction size bigger than buffer\n"); xfer_respond(ctx, true); xfer_reset(ctx); - } else - if (ctx->xfer_finish) { + } else if (ctx->xfer_finish) { if (xfer_parse(ctx)) { ctx->nout = 0; ctx->nin = 0; @@ -557,8 +564,8 @@ char spidpi_tick(void *ctx_void, const svLogicVecVal *d2p_data) { break; case SP_CSRISE: xfer_respond_next_trans(ctx); - if ((ctx->xfer_next = - xfer_parse_next_trans(ctx, ctx->xfer_next)) != NULL) { + if ((ctx->xfer_next = xfer_parse_next_trans(ctx, ctx->xfer_next)) != + NULL) { ctx->nout = 0; ctx->nin = 0; ctx->bout = ctx->msbfirst ? 0x80 : 0x01; diff --git a/hw/dv/dpi/spidpi/spidpi.h b/hw/dv/dpi/spidpi/spidpi.h index 41efd1a900dc38..def5ac07d7cf8c 100644 --- a/hw/dv/dpi/spidpi/spidpi.h +++ b/hw/dv/dpi/spidpi/spidpi.h @@ -12,7 +12,7 @@ extern "C" { #define MAX_TRANSACTION (8 * 1024) -#define MAX_TRANSFER (4 * 1024) +#define MAX_TRANSFER (4 * 1024) struct spidpi_ctx; // SPI Host States diff --git a/hw/dv/dpi/uartdpi/uartdpi.c b/hw/dv/dpi/uartdpi/uartdpi.c index 2de39090592555..fd99d65aefffeb 100644 --- a/hw/dv/dpi/uartdpi/uartdpi.c +++ b/hw/dv/dpi/uartdpi/uartdpi.c @@ -67,7 +67,8 @@ void *uartdpi_create(const char *name, int listen_port, printf( "\n" - "UART: Created %s for %s. Connect to it with any terminal program, e.g.\n" + "UART: Created %s for %s. Connect to it with any terminal program, " + "e.g.\n" "$ screen %s\n", ctx->ptyname, name, ctx->ptyname); } diff --git a/hw/dv/dpi/uartdpi/uartdpi.h b/hw/dv/dpi/uartdpi/uartdpi.h index a8896c0c7a5e9e..fc1847b56a61e4 100644 --- a/hw/dv/dpi/uartdpi/uartdpi.h +++ b/hw/dv/dpi/uartdpi/uartdpi.h @@ -11,8 +11,7 @@ extern "C" { struct uartdpi_ctx; -void *uartdpi_create(const char *name, - int listen_port, +void *uartdpi_create(const char *name, int listen_port, const char *log_file_path); void uartdpi_close(void *ctx_void); int uartdpi_can_read(void *ctx_void); diff --git a/sw/device/silicon_creator/lib/drivers/spi_device.c b/sw/device/silicon_creator/lib/drivers/spi_device.c index 81117bb3294c28..5b9c0f14376485 100644 --- a/sw/device/silicon_creator/lib/drivers/spi_device.c +++ b/sw/device/silicon_creator/lib/drivers/spi_device.c @@ -656,8 +656,8 @@ rom_error_t spi_device_cmd_get(spi_device_cmd_t *cmd) { bitfield_field32_read(reg, SPI_DEVICE_UPLOAD_STATUS2_PAYLOAD_DEPTH_FIELD); // `payload_byte_count` can be at most `kSpiDevicePayloadAreaNumBytes`. HARDENED_CHECK_LE(cmd->payload_byte_count, kSpiDevicePayloadAreaNumBytes); - uint32_t src = - kBase + SPI_DEVICE_INGRESS_BUFFER_REG_OFFSET + kSpiDevicePayloadAreaOffset; + uint32_t src = kBase + SPI_DEVICE_INGRESS_BUFFER_REG_OFFSET + + kSpiDevicePayloadAreaOffset; char *dest = (char *)&cmd->payload; for (size_t i = 0; i < cmd->payload_byte_count; i += sizeof(uint32_t)) { write_32(abs_mmio_read32(src + i), dest + i); diff --git a/sw/device/silicon_creator/rom/bootstrap.c b/sw/device/silicon_creator/rom/bootstrap.c index e26700ee7d8aff..d6c5ab8bb095be 100644 --- a/sw/device/silicon_creator/rom/bootstrap.c +++ b/sw/device/silicon_creator/rom/bootstrap.c @@ -21,9 +21,13 @@ enum { /* - * Maximum ctn sram address, exclusive. + * Base ctn sram address, exclusive. */ - kMaxAddress = TOP_DARJEELING_RAM_CTN_SIZE_BYTES, + kBaseAddress = TOP_DARJEELING_RAM_CTN_BASE_ADDR, + /* + * Maximum ctn sram size, exclusive. + */ + kMaxSize = TOP_DARJEELING_RAM_CTN_SIZE_BYTES, }; /** @@ -66,8 +70,7 @@ typedef enum bootstrap_state { */ OT_WARN_UNUSED_RESULT static rom_error_t bootstrap_chip_erase(void) { - memset((void *)TOP_DARJEELING_RAM_CTN_BASE_ADDR, - 0x0, TOP_DARJEELING_RAM_CTN_SIZE_BYTES); + memset((void *)kBaseAddress, 0x0, kMaxSize); return kErrorOk; } @@ -88,12 +91,12 @@ static rom_error_t bootstrap_sector_erase(uint32_t addr) { kPageAddrMask = ~UINT32_C(4096) + 1, }; - if (addr >= kMaxAddress) { + if (addr >= kMaxSize) { return kErrorBootstrapEraseAddress; } addr &= kPageAddrMask; - memset((void *)(TOP_DARJEELING_RAM_CTN_BASE_ADDR + addr), 0x0, 4096); + memset((void *)(kBaseAddress + addr), 0x0, 4096); return kErrorOk; } @@ -110,10 +113,10 @@ static rom_error_t bootstrap_sector_erase(uint32_t addr) { OT_WARN_UNUSED_RESULT static rom_error_t bootstrap_page_program(uint32_t addr, size_t byte_count, uint8_t *data) { - if (addr + byte_count >= kMaxAddress) { + if (addr + byte_count >= kMaxSize) { return kErrorBootstrapProgramAddress; } - memcpy((void *)addr, data, byte_count); + memcpy((void *)(kBaseAddress + addr), data, byte_count); return kErrorOk; } @@ -167,16 +170,25 @@ OT_WARN_UNUSED_RESULT static rom_error_t bootstrap_handle_erase_verify(bootstrap_state_t *state) { HARDENED_CHECK_EQ(*state, kBootstrapStateEraseVerify); - memset((void *)TOP_DARJEELING_RAM_CTN_BASE_ADDR, - 0x0, TOP_DARJEELING_RAM_CTN_SIZE_BYTES); + memset((void *)kBaseAddress, 0x0, kMaxSize); rom_error_t err_0 = kErrorOk; - for (uint32_t i = 0; i < TOP_DARJEELING_RAM_CTN_SIZE_BYTES / 4; i++) { + // Check first page for zero + for (uint32_t i = 0; i < 4096 / 4; i++) { uint32_t zero = 0x0; - if (!memcmp((void *)(TOP_DARJEELING_RAM_CTN_BASE_ADDR + 4 * i), - (void *)zero, 4)) { + if (memcmp((void *)(kBaseAddress + 4 * i), (void *)&zero, 4)) { + err_0 = kErrorFlashCtrlDataEraseVerify; + break; + } + } + if (err_0 == kErrorOk) { + // Check subsequent pages for zero + for (uint32_t i = 1; i < kMaxSize / 4096; i++) { + if (memcmp((void *)(kBaseAddress), (void *)(kBaseAddress + 4096 * i), + 4096)) { err_0 = kErrorFlashCtrlDataEraseVerify; break; + } } } HARDENED_RETURN_IF_ERROR(err_0); diff --git a/sw/device/tests/BUILD b/sw/device/tests/BUILD index a881a0a22149ad..b9e09f5bc75765 100644 --- a/sw/device/tests/BUILD +++ b/sw/device/tests/BUILD @@ -2699,19 +2699,19 @@ opentitan_functest( "--bootstrap=\"$(rootpath {flash})\"", ] + DARJEELING_OPENTITANTOOL_OPENOCD_TEST_CMDS, ), + data = DARJEELING_OPENTITANTOOL_OPENOCD_DATA_DEPS, + targets = [ + #"verilator", + "cw310_rom_with_fake_keys", + ], + test_harness = "//sw/host/tests/chip/jtag:openocd_test", verilator = verilator_params( timeout = "long", test_cmds = [ - "--reset-delay=\"180sec\"", + "--reset-delay=\"120sec\"", "--bootstrap=\"$(rootpath {flash})\"", ] + DARJEELING_OPENTITANTOOL_OPENOCD_TEST_CMDS, ), - data = DARJEELING_OPENTITANTOOL_OPENOCD_DATA_DEPS, - targets = [ - #"verilator", - "cw310_rom_with_fake_keys" - ], - test_harness = "//sw/host/tests/chip/jtag:openocd_test", deps = [ "//sw/device/lib/testing/test_framework:ottf_main", "//sw/lib/sw/device/runtime:log", @@ -2730,19 +2730,19 @@ opentitan_functest( "--bootstrap=\"$(location {flash})\"", ], ), + targets = [ + #"verilator", + "cw310_test_rom", + ], + test_harness = "//sw/host/tests/chip/spi_device_ottf_console", verilator = verilator_params( timeout = "long", tags = ["manual"], test_cmds = [ - "--reset-delay=\"180sec\"", + "--reset-delay=\"120sec\"", "--bootstrap=\"$(location {flash})\"", ], ), - targets = [ - #"verilator", - "cw310_test_rom", - ], - test_harness = "//sw/host/tests/chip/spi_device_ottf_console", deps = [ "//hw/top_darjeeling/sw/autogen:top_darjeeling", "//sw/device/lib/testing/test_framework:ottf_main", diff --git a/sw/host/opentitanlib/src/transport/verilator/gpio.rs b/sw/host/opentitanlib/src/transport/verilator/gpio.rs index c6c6ef086b3c65..6da20cedf6a5ca 100644 --- a/sw/host/opentitanlib/src/transport/verilator/gpio.rs +++ b/sw/host/opentitanlib/src/transport/verilator/gpio.rs @@ -106,23 +106,28 @@ impl GpioInner { let write; let stream; let use_stream; - + // check if read_name is in TCP socket or pipe device format - if read_name.contains(":") && !read_name.contains("/") { + if read_name.contains(':') && !read_name.contains('/') { read = None; write = None; - stream = Some(TcpStream::connect(read_name) - .map_err(|e| TransportError::ProxyConnectError(read_name.to_string(), e.to_string()))?); + stream = Some(TcpStream::connect(read_name).map_err(|e| { + TransportError::ProxyConnectError(read_name.to_string(), e.to_string()) + })?); use_stream = true; } else { - read = Some(OpenOptions::new() - .read(true) - .open(read_name) - .map_err(|e| TransportError::OpenError(read_name.to_string(), e.to_string()))?); - write = Some(OpenOptions::new() - .write(true) - .open(write_name) - .map_err(|e| TransportError::OpenError(write_name.to_string(), e.to_string()))?); + read = + Some(OpenOptions::new().read(true).open(read_name).map_err(|e| { + TransportError::OpenError(read_name.to_string(), e.to_string()) + })?); + write = Some( + OpenOptions::new() + .write(true) + .open(write_name) + .map_err(|e| { + TransportError::OpenError(write_name.to_string(), e.to_string()) + })?, + ); stream = None; use_stream = false; } @@ -209,10 +214,8 @@ impl GpioInner { } } } else { - return Err(anyhow!("TCP socket not connected")) - .context("GPIO read error"); + return Err(anyhow!("TCP socket not connected")).context("GPIO read error"); } - Ok(()) } fn read_pipe(&mut self) -> Result<()> { @@ -255,8 +258,7 @@ impl GpioInner { } } } else { - return Err(anyhow!("Read pipe not opened")) - .context("GPIO read error"); + return Err(anyhow!("Read pipe not opened")).context("GPIO read error"); } Ok(()) } @@ -287,18 +289,14 @@ impl GpioInner { .write(command.as_bytes()) .context("GPIO write error")?; } else { - return Err(anyhow!("TCP socket not connected")) - .context("GPIO write error"); + return Err(anyhow!("TCP socket not connected")).context("GPIO write error"); } + } else if let Some(ref mut write) = self.write { + write + .write(command.as_bytes()) + .context("GPIO write error")?; } else { - if let Some(ref mut write) = self.write { - write - .write(command.as_bytes()) - .context("GPIO write error")?; - } else { - return Err(anyhow!("Write pipe not opened")) - .context("GPIO write error"); - } + return Err(anyhow!("Write pipe not opened")).context("GPIO write error"); } Ok(()) } diff --git a/sw/host/opentitanlib/src/transport/verilator/spi.rs b/sw/host/opentitanlib/src/transport/verilator/spi.rs index a72f8d9146361f..a6e56db6d96de9 100644 --- a/sw/host/opentitanlib/src/transport/verilator/spi.rs +++ b/sw/host/opentitanlib/src/transport/verilator/spi.rs @@ -4,19 +4,17 @@ use anyhow::{anyhow, bail, ensure, Context, Result}; use serde::{Deserialize, Serialize}; -use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use std::fs::OpenOptions; use std::io; use std::io::{BufWriter, ErrorKind, Read, Write}; use std::net::TcpStream; +use std::rc::Rc; use thiserror::Error; use crate::impl_serializable_error; -use crate::io::spi::{ - AssertChipSelect, MaxSizes, SpiError, Target, Transfer, TransferMode, -}; +use crate::io::spi::{AssertChipSelect, MaxSizes, SpiError, Target, Transfer, TransferMode}; use crate::proxy::protocol::{ Message, Request, Response, SpiRequest, SpiResponse, SpiTransferRequest, SpiTransferResponse, }; @@ -49,12 +47,12 @@ impl VerilatorSpi { let use_stream; // check if read_name is in TCP socket or pipe device format - if name.contains(":") && !name.contains("/") { - let stream = TcpStream::connect(name) - .map_err(|e| return TransportError::ProxyConnectError(name.to_string(), e.to_string()))?; + if name.contains(':') && !name.contains('/') { + let stream = TcpStream::connect(name) + .map_err(|e| TransportError::ProxyConnectError(name.to_string(), e.to_string()))?; ref_pipe = None; - ref_stream = Some(RefCell::new(stream)); + ref_stream = Some(RefCell::new(stream)); use_stream = true; } else { let pipe = OpenOptions::new() @@ -62,22 +60,22 @@ impl VerilatorSpi { .write(true) .open(name) .map_err(|e| TransportError::OpenError(name.to_string(), e.to_string()))?; - + ref_pipe = Some(RefCell::new(pipe)); - ref_stream = None; + ref_stream = None; use_stream = false; } Ok(VerilatorSpi { instance: instance.to_string(), - use_stream: use_stream, + use_stream, stream: ref_stream, pipe: ref_pipe, recv_buf: RefCell::new(Vec::new()), }) } - // Convenience method for issuing SPI commands via proxy protocol. + // Convenience method for issuing SPI commands via proxy protocol. fn execute_command(&self, command: SpiRequest) -> Result { match self.execute_request(Request::Spi { id: self.instance.clone(), @@ -114,8 +112,7 @@ impl VerilatorSpi { writer.write_all(&[b'\n'])?; writer.flush()?; } else { - return Err(anyhow!("TCP socket not connected")) - .context("SPI write error"); + return Err(anyhow!("TCP socket not connected")).context("SPI write error"); } Ok(()) } @@ -130,8 +127,7 @@ impl VerilatorSpi { writer.write_all(&[b'\n'])?; writer.flush()?; } else { - return Err(anyhow!("Pipe not opened")) - .context("SPI write error"); + return Err(anyhow!("Pipe not opened")).context("SPI write error"); } Ok(()) } @@ -139,9 +135,9 @@ impl VerilatorSpi { /// Send a one-line JSON encoded requests, terminated with one newline. fn send_json_request(&self, req: Request) -> Result<()> { if self.use_stream { - return self.send_json_request_stream(req) + self.send_json_request_stream(req) } else { - return self.send_json_request_pipe(req) + self.send_json_request_pipe(req) } } @@ -173,8 +169,7 @@ impl VerilatorSpi { return Ok(result); } } else { - return Err(anyhow!("TCP socket not connected")) - .context("SPI read error"); + Err(anyhow!("TCP socket not connected")).context("SPI read error") } } @@ -206,17 +201,16 @@ impl VerilatorSpi { return Ok(result); } } else { - return Err(anyhow!("Pipe not opened")) - .context("SPI read error"); + return Err(anyhow!("Pipe not opened")).context("SPI read error"); } } /// Decode one JSON response, possibly waiting for more data. fn recv_json_response(&self) -> Result { if self.use_stream { - return self.recv_json_response_stream() + self.recv_json_response_stream() } else { - return self.recv_json_response_pipe() + self.recv_json_response_pipe() } } @@ -279,16 +273,12 @@ impl Target for VerilatorSpi { let mut req: Vec = Vec::new(); for transfer in transaction.iter() { match transfer { - Transfer::Read(rbuf) => { - req.push(SpiTransferRequest::Read { - len: rbuf.len() as u32, - }) - }, - Transfer::Write(wbuf) => { - req.push(SpiTransferRequest::Write { - data: wbuf.to_vec(), - }) - }, + Transfer::Read(rbuf) => req.push(SpiTransferRequest::Read { + len: rbuf.len() as u32, + }), + Transfer::Write(wbuf) => req.push(SpiTransferRequest::Write { + data: wbuf.to_vec(), + }), Transfer::Both(wbuf, rbuf) => { ensure!( rbuf.len() == wbuf.len(), diff --git a/sw/host/opentitanlib/src/transport/verilator/transport.rs b/sw/host/opentitanlib/src/transport/verilator/transport.rs index 966b051ffe6878..fe614a5c969f7e 100644 --- a/sw/host/opentitanlib/src/transport/verilator/transport.rs +++ b/sw/host/opentitanlib/src/transport/verilator/transport.rs @@ -15,8 +15,8 @@ use crate::io::gpio::{GpioError, GpioPin}; use crate::io::spi::Target; use crate::io::uart::Uart; use crate::transport::verilator::gpio::{GpioInner, VerilatorGpioPin}; -use crate::transport::verilator::subprocess::{Options, Subprocess}; use crate::transport::verilator::spi::VerilatorSpi; +use crate::transport::verilator::subprocess::{Options, Subprocess}; use crate::transport::verilator::uart::VerilatorUart; use crate::transport::{ Capabilities, Capability, Transport, TransportError, TransportInterfaceType, @@ -74,7 +74,11 @@ impl Verilator { spi_file: spi, gpio_read_file: gpio_rd, gpio_write_file: gpio_wr, - inner: Rc::new(RefCell::new(Inner { gpio, spi: None, uart: None })), + inner: Rc::new(RefCell::new(Inner { + gpio, + spi: None, + uart: None, + })), }) } @@ -96,7 +100,9 @@ impl Drop for Verilator { impl Transport for Verilator { fn capabilities(&self) -> Result { - Ok(Capabilities::new(Capability::GPIO | Capability::SPI | Capability::UART)) + Ok(Capabilities::new( + Capability::GPIO | Capability::SPI | Capability::UART, + )) } fn uart(&self, instance: &str) -> Result> { diff --git a/sw/host/opentitanlib/src/transport/verilator/uart.rs b/sw/host/opentitanlib/src/transport/verilator/uart.rs index 62a11e5ba1834d..88673d8c257bef 100644 --- a/sw/host/opentitanlib/src/transport/verilator/uart.rs +++ b/sw/host/opentitanlib/src/transport/verilator/uart.rs @@ -34,12 +34,12 @@ impl VerilatorUart { let use_stream; // check if read_name is in TCP socket or pipe device format - if name.contains(":") && !name.contains("/") { - let stream = TcpStream::connect(name) - .map_err(|e| return TransportError::ProxyConnectError(name.to_string(), e.to_string()))?; + if name.contains(':') && !name.contains('/') { + let stream = TcpStream::connect(name) + .map_err(|e| TransportError::ProxyConnectError(name.to_string(), e.to_string()))?; ref_pipe = None; - ref_stream = Some(RefCell::new(stream)); + ref_stream = Some(RefCell::new(stream)); use_stream = true; } else { let pipe = OpenOptions::new() @@ -47,9 +47,9 @@ impl VerilatorUart { .write(true) .open(name) .map_err(|e| TransportError::OpenError(name.to_string(), e.to_string()))?; - + ref_pipe = Some(RefCell::new(pipe)); - ref_stream = None; + ref_stream = None; use_stream = false; } @@ -60,7 +60,7 @@ impl VerilatorUart { // only deal with about 4 chars per second. baudrate: Cell::new(40), flow_control: Cell::new(FlowControl::None), - use_stream: use_stream, + use_stream, stream: ref_stream, pipe: ref_pipe, rxbuf: RefCell::default(), @@ -131,8 +131,7 @@ impl VerilatorUart { } } } else { - return Err(anyhow!("TCP socket not connected")) - .context("UART read error"); + return Err(anyhow!("TCP socket not connected")).context("UART read error"); } Ok(()) } @@ -175,17 +174,16 @@ impl VerilatorUart { self.rxbuf.borrow_mut().push_back(ch); } } else { - return Err(anyhow!("Pipe not opened")) - .context("UART read error"); + return Err(anyhow!("Pipe not opened")).context("UART read error"); } Ok(()) } fn read_worker(&self, timeout: Duration) -> Result<()> { if self.use_stream { - return self.read_stream(timeout) + self.read_stream(timeout) } else { - return self.read_pipe(timeout) + self.read_pipe(timeout) } } @@ -256,19 +254,15 @@ impl Uart for VerilatorUart { .write_all(std::slice::from_ref(b)) .context("UART write error")?; } else { - return Err(anyhow!("TCP socket not connected")) - .context("UART write error"); - } - } else { - if let Some(ref ref_pipe) = self.pipe { - ref_pipe - .borrow_mut() - .write_all(std::slice::from_ref(b)) - .context("UART write error")?; - } else { - return Err(anyhow!("Pipe not opened")) - .context("UART write error"); + return Err(anyhow!("TCP socket not connected")).context("UART write error"); } + } else if let Some(ref ref_pipe) = self.pipe { + ref_pipe + .borrow_mut() + .write_all(std::slice::from_ref(b)) + .context("UART write error")?; + } else { + return Err(anyhow!("Pipe not opened")).context("UART write error"); } } Ok(()) @@ -289,19 +283,17 @@ impl Uart for VerilatorUart { } while let Ok(size) = stream.read(&mut buf) { - if size != buf.len() { break; } + if size != buf.len() { + break; + } } } else { - return Err(anyhow!("TCP socket not connected")) - .context("UART reset error"); + return Err(anyhow!("TCP socket not connected")).context("UART reset error"); } + } else if let Some(ref ref_pipe) = self.pipe { + ref_pipe.borrow_mut().seek(SeekFrom::End(0))?; } else { - if let Some(ref ref_pipe) = self.pipe { - ref_pipe.borrow_mut().seek(SeekFrom::End(0))?; - } else { - return Err(anyhow!("Pipe not opened")) - .context("UART reset error"); - } + return Err(anyhow!("Pipe not opened")).context("UART reset error"); } Ok(()) }