kestrel.c 153 KB
Newer Older
1 2 3 4 5 6
// © 2020 - 2021 Raptor Engineering, LLC
//
// Released under the terms of the GPL v3
// See the LICENSE file for full details

#define WITH_SPI 1
7 8 9 10 11 12
#define WITH_ZEPHYR 1

#if (WITH_ZEPHYR)
#include <logging/log.h>
LOG_MODULE_REGISTER(kestrel_core, LOG_LEVEL_DBG);
#endif
13 14 15 16

#include "fsi.h"
#include "utility.h"

17
#include <sys/crc.h>
18 19 20 21 22 23
#include <generated/csr.h>
#include <generated/mem.h>
#include <irq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
24 25 26
#if (WITH_ZEPHYR)
#include <sys/types.h>
#endif
27 28 29 30 31 32 33 34
#if (WITH_SPI)
#include "micron_n25q_flash.h"
#include "tercel_spi.h"
#endif

#include "aquila.h"
#include "ipmi_bt.h"
#include "opencores_i2c.h"
35
#include "simple_pwm.h"
36

37 38
#include "kestrel.h"

39
// Performance controls
40 41 42 43 44
#define ENABLE_LPC_FW_CYCLE_IRQ_HANDLER  1 // Set to 1 to enable LPC master transfer interrupts to the BMC soft core
#define ENABLE_LPC_IO_CYCLE_IRQ_HANDLER  1 // Set to 1 to enable LPC I/O transfer interrupts to the BMC soft core
#define ENABLE_LPC_TPM_CYCLE_IRQ_HANDLER 1 // Set to 1 to enable LPC TPM transfer interrupts to the BMC soft core
#define ENABLE_LPC_FW_CYCLE_DMA          1 // Set to 1 to allow the LPC master to DMA data to/from the Wishbone bus
#define ALLOW_SPI_QUAD_MODE              1 // Set to 1 to allow quad-mode SPI transfers if the hardware supports them
45 46

// Debug knobs
47 48 49 50
#define DEBUG_HOST_SPI_FLASH_READ           0 // Set to 1 to enable verbose logging of SPI flash read process
#define SPI_FLASH_TRIPLE_READ               0 // Set to 1 to enable triple-read data checks (slow)
#define ENABLE_IPMI_DEBUG                   0 // Set to 1 to enable verbose logging of IPMI requests and responses
#define CLEAR_FLASH_CACHE_BUFFER_ON_STARTUP 0 // Set to 1 to clear the Flash cache buffer on startup
51 52 53 54 55 56 57 58

// General RCS platform registers
#define HOST_PLATFORM_FPGA_I2C_REG_STATUS  0x7
#define HOST_PLATFORM_FPGA_I2C_REG_MFR_OVR 0x33

// Host platform configuration
#define HOST_PLATFORM_FPGA_I2C_ADDRESS 0x31

59 60 61
// Limits
#define FLASH_WRITE_LOCATION_RETRY_LIMIT 5

62 63 64 65 66
extern uint32_t irq_unhandled_vector;
extern uint32_t irq_unhandled_source;
extern uint8_t irq_unhandled_vector_valid;
extern uint8_t irq_unhandled_source_valid;

67
#define POST_CODE_INTERRUPT_TRANSIENT_BUFFER_SIZE 32
68
#define VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE 32
69
#define VUART_RING_BUFFER_SIZE 512
70

71
// Interrupt transient POST code buffer
72
static uint16_t post_code_incoming_interrupt_transient_buffer[POST_CODE_INTERRUPT_TRANSIENT_BUFFER_SIZE];
73 74 75
static int post_code_incoming_interrupt_transient_buffer_pos = 0;
static uint8_t post_code_incoming_interrupt_transient_buffer_overflow = 0;

76 77 78 79 80 81
// Interrupt transient VUART1 buffer
static uint8_t vuart1_incoming_interrupt_transient_buffer[VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE];
static int vuart1_incoming_interrupt_transient_buffer_pos = 0;
static uint8_t vuart1_incoming_interrupt_transient_buffer_overflow = 0;

// BMC to host VUART1 buffer
82
static uint8_t vuart1_outgoing_buffer[VUART_RING_BUFFER_SIZE];
83 84 85 86
static int vuart1_outgoing_buffer_read_pos = 0;
static int vuart1_outgoing_buffer_write_pos = 0;

// Host to BMC VUART1 buffer
87
static uint8_t vuart1_incoming_buffer[VUART_RING_BUFFER_SIZE];
88 89 90 91 92 93 94 95 96
static int vuart1_incoming_buffer_read_pos = 0;
static int vuart1_incoming_buffer_write_pos = 0;

// Interrupt transient VUART2 buffer
static uint8_t vuart2_incoming_interrupt_transient_buffer[VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE];
static int vuart2_incoming_interrupt_transient_buffer_pos = 0;
static uint8_t vuart2_incoming_interrupt_transient_buffer_overflow = 0;

// // BMC to host VUART2 buffer
97
// static uint8_t vuart2_outgoing_buffer[VUART_RING_BUFFER_SIZE];
98 99 100 101
// static int vuart2_outgoing_buffer_read_pos = 0;
// static int vuart2_outgoing_buffer_write_pos = 0;

// Host to BMC VUART2 buffer
102
static uint8_t vuart2_incoming_buffer[VUART_RING_BUFFER_SIZE];
103 104 105 106 107 108 109 110 111
// static int vuart2_incoming_buffer_read_pos = 0;
static int vuart2_incoming_buffer_write_pos = 0;

// IPMI BT buffer
static ipmi_request_message_t ipmi_bt_interrupt_transient_request;
static uint8_t ipmi_bt_interrupt_transient_request_valid = 0;
static ipmi_request_message_t ipmi_bt_current_request;

// HIOMAP
112
static uint8_t *hiomap_write_buffer;
113 114
static uint8_t *host_flash_buffer;
static hiomap_configuration_data_t hiomap_config;
115
uint8_t hiomap_use_direct_access = 0;
116 117

// Background service tasks
118 119 120
uint8_t host_background_service_task_active = 0;
uint8_t host_console_service_task_active = 0;
uint8_t host_console_service_task_requested = 0;
121
uint8_t host_power_status = HOST_POWER_STATUS_OFFLINE;
122 123 124 125 126 127 128 129
static int configured_cpu_count = 1;

// POST codes
uint8_t post_code_high = 0;
uint8_t post_code_low = 0;

// Global configuration
static uint8_t allow_flash_write = 0;
130
static uint8_t enable_post_code_console_output = 1;
131

132 133 134
// External service interface
struct firmware_buffer_region main_firmware_buffer;

135 136 137 138 139 140 141
// System status
uint8_t kestrel_basic_init_complete = 0;

#if (WITH_ZEPHYR)
// Thread identifiers
k_tid_t kestrel_service_thread_id = NULL;
k_tid_t kestrel_console_thread_id = NULL;
142
k_tid_t thermal_service_thread_id = NULL;
143 144 145

// Mutexes
struct k_mutex vuart1_access_mutex;
146
struct k_mutex occ_access_mutex;
147 148 149 150 151 152 153

// Console structures
const struct shell *host_console_service_task_shell = NULL;
#endif

#define KESTREL_LOG(...) LOG_INF(__VA_ARGS__)

154 155 156 157 158 159 160 161 162
#if (WITH_ZEPHYR)
#if (DEBUG_HOST_SPI_FLASH_READ)
static uint32_t crc32(const uint8_t *data, size_t len)
{
    return crc32_ieee(data, len);
}
#endif
#endif

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
typedef struct
{
    int8_t index;
    uint8_t *i2c_master;
    uint32_t i2c_frequency;
    uint8_t vdd_regulator_addr;
    uint8_t vdn_regulator_addr;
    uint8_t vdd_smbus_addr;
    uint8_t vdn_smbus_addr;
} cpu_info_t;
static const cpu_info_t g_cpu_info[] = {
    {
        .index = 0,
        .i2c_master = (uint8_t *)I2CMASTER1_BASE,
        .i2c_frequency = 100000,
        .vdd_regulator_addr = 0x70,
        .vdn_regulator_addr = 0x73,
        .vdd_smbus_addr = 0x28,
        .vdn_smbus_addr = 0x2b,

    },
#ifdef I2CMASTER2_BASE
    {
        .index = 1,
        .i2c_master = (uint8_t *)I2CMASTER2_BASE,
        .i2c_frequency = 100000,
        .vdd_regulator_addr = 0x70,
        .vdn_regulator_addr = 0x73,
        .vdd_smbus_addr = 0x28,
        .vdn_smbus_addr = 0x2b,
    },
#endif
};
#define MAX_CPUS_SUPPORTED (sizeof(g_cpu_info) / sizeof(g_cpu_info[0]))

static const struct power_limit_data_desc board_power_limits[] = {
    [PowerLimitDataGeneric] =
    {
        .packet =
        {
            .fail_response = POWERLIMIT_EXECTPION_ACT_HARD_SHUTDOWN,
            .max_watts = 0,
        },
        .completion_code = DCMI_CC_NO_POWER_LIMIT,
    },
};

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
static void memcpy32(uint32_t *destination, uint32_t *source, int words)
{
    int word;
    for (word = 0; word < words; word++)
    {
        *destination = *source;
        destination++;
        source++;
    }
}

static void memset32(uint32_t *destination, uint32_t value, int words)
{
    int word;
    for (word = 0; word < words; word++)
    {
        *destination = value;
        destination++;
    }
}

231
#if (!(WITH_ZEPHYR))
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
static char *readstr(void)
{
    char c[2];
    static char s[64];
    static int ptr = 0;

    if (readchar_nonblock())
    {
        c[0] = readchar();
        c[1] = 0;
        switch (c[0])
        {
            case 0x7f:
            case 0x08:
                if (ptr > 0)
                {
                    ptr--;
                    putsnonl("\x08 \x08");
                }
                break;
            case 0x07:
                break;
            case '\r':
            case '\n':
                s[ptr] = 0x00;
                putsnonl("\n");
                ptr = 0;
                return s;
            default:
                if (ptr >= (sizeof(s) - 1))
                {
                    break;
                }
                putsnonl(c);
                s[ptr] = c[0];
                ptr++;
                break;
        }
    }

    primary_service_event_loop();

    return NULL;
}

static char *get_token(char **str)
{
    char *c, *d;

    c = (char *)strchr(*str, ' ');
    if (c == NULL)
    {
        d = *str;
        *str = *str + strlen(*str);
        return d;
    }
    *c = 0;
    d = *str;
    *str = c + 1;
    return d;
}

static void prompt(void)
{
296
    KESTREL_LOG("FSP0>");
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
}

static void help(void)
{
    puts("Available commands:");
    puts("help                            - this command");
    puts("reboot                          - reboot BMC CPU");
    puts("poweron                         - Turn chassis power on, start IPL, "
         "and attach to host console");
    puts("console                         - Attach to host console");
    puts("status                          - Print system status");
    puts("ipl                             - Start IPL sequence");
    puts("chassison                       - Turn chassis power on and prepare "
         "for IPL");
    puts("chassisoff                      - Turn chassis power off");
    puts("sbe_status                      - Get SBE status register");
    puts("post_codes                      - Enable or disable output of POST "
         "codes on console");
    puts("mr <address> <length>           - Read data from BMC internal address "
         "in 32-bit words");
    puts("mw <address> <length> <data>    - Write data from BMC internal address "
         "in 32-bit words");
}

static void reboot(void)
{
    ctrl_reset_write(1);
}
325
#endif
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

static void display_character(char character, int dp)
{
    uint16_t value;

    // FIXME Only supports numbers for now
    switch (character)
    {
        case '0':
            value = 0x003f;
            break;
        case '1':
            value = 0x0006;
            break;
        case '2':
            value = 0x221b;
            break;
        case '3':
            value = 0x220f;
            break;
        case '4':
            value = 0x2226;
            break;
        case '5':
            value = 0x222d;
            break;
        case '6':
            value = 0x223d;
            break;
        case '7':
            value = 0x0007;
            break;
        case '8':
            value = 0x223f;
            break;
        case '9':
            value = 0x222f;
            break;
        default:
            value = 0x0000;
            break; // OFF
    }

    gpio3_out_write(~(value | ((dp == 0) ? 0x0000 : 0x4000)));
}

static void set_led_bank_display(uint8_t bitfield)
{
    gpio1_out_write(~bitfield);
}

static void gpio_init(void)
{
    // Set up discrete LED bank
    set_led_bank_display(0x00);
    gpio1_oe_write(0xff);

    // Set up alphanumeric display
    gpio3_out_write(0xefff);
    gpio3_oe_write(0xefff);
}

static void set_lpc_slave_irq_enable(uint8_t enabled)
{
    if (!enabled)
    {
        hostlpcslave_ev_enable_write(0);
393
        irq_disable(HOSTLPCSLAVE_INTERRUPT);
394 395 396 397 398 399 400 401
    }

    // Clear pending interrupts
    hostlpcslave_ev_pending_write(hostlpcslave_ev_pending_read());

    if (enabled)
    {
        hostlpcslave_ev_enable_write(AQUILA_EV_MASTER_IRQ);
402
        irq_enable(HOSTLPCSLAVE_INTERRUPT);
403 404 405 406 407
    }
}

void lpc_slave_isr(void)
{
408
#if ((ENABLE_LPC_FW_CYCLE_IRQ_HANDLER) || (ENABLE_LPC_IO_CYCLE_IRQ_HANDLER) || (ENABLE_LPC_TPM_CYCLE_IRQ_HANDLER))
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    int byte;
    int word;
#endif
    uint32_t dword;
    uint32_t ev_status;
    uint32_t address;
    uint32_t physical_flash_address;
    uint8_t write_not_read;
    uint32_t status1_reg;
    uint32_t status2_reg;
    uint32_t status4_reg;
    uint32_t vuart_status;
    volatile ipmi_request_message_t *ipmi_bt_request_ptr;

    ev_status = hostlpcslave_ev_pending_read();
    if (ev_status & AQUILA_EV_MASTER_IRQ)
    {
        // Master IRQ asserted
        // Determine source within the LPC slave core
        status4_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS4);
#if (ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
        if (status4_reg & AQUILA_LPC_FW_CYCLE_IRQ_ASSERTED)
        {
            // Firmware cycle request has caused IRQ assert
            // This should remain at the beginning of the ISR for maximum transfer
            // performance
            status1_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS1);
            status2_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS2);
            address = (status2_reg >> AQUILA_LPC_STATUS_ACT_ADDR_SHIFT) & AQUILA_LPC_STATUS_ACT_ADDR_MASK;
            write_not_read = (status1_reg >> AQUILA_LPC_STATUS_CYC_WNR_SHIFT) & AQUILA_LPC_STATUS_CYC_WNR_MASK;

            if (((status1_reg >> AQUILA_LPC_STATUS_CYCLE_TYPE_SHIFT) & AQUILA_LPC_STATUS_CYCLE_TYPE_MASK) == AQUILA_LPC_STATUS_CYCLE_TYPE_FW)
            {
                uint8_t fw_cycle_idsel = (status1_reg >> AQUILA_LPC_STATUS_FW_CYCLE_IDSEL_SHIFT) & AQUILA_LPC_STATUS_FW_CYCLE_IDSEL_MASK;
                uint8_t fw_cycle_msize = (status1_reg >> AQUILA_LPC_STATUS_FW_CYCLE_MSIZE_SHIFT) & AQUILA_LPC_STATUS_FW_CYCLE_MSIZE_MASK;

                if (fw_cycle_idsel == 0)
                {
447 448
                    // Limit firmware address to Flash device size (wrap around)
                    address &= (FLASH_SIZE_BYTES - 1);
449

450
                    // Compute active window address
451
                    physical_flash_address = address;
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                    uint8_t *active_host_flash_buffer;
                    if (hiomap_use_direct_access)
                    {
                        if (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE)
                        {
                            active_host_flash_buffer = hiomap_write_buffer;
                        }
                        else
                        {
                            active_host_flash_buffer = (void*)(HOSTSPIFLASH_BASE + physical_flash_address);
                        }
                    }
                    else
                    {
                        active_host_flash_buffer = host_flash_buffer + physical_flash_address;
                    }

469 470 471 472 473 474 475 476 477 478
                    if ((address >= hiomap_config.window_start_address) && ((address - hiomap_config.window_start_address) < hiomap_config.window_length_bytes))
                    {
                        if (!write_not_read &&
                            ((hiomap_config.window_type == HIOMAP_WINDOW_TYPE_READ) || (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE)))
                        {
                            if (lpc_fw_msize_to_bytes(fw_cycle_msize) >= 4)
                            {
                                for (word = 0; word < (lpc_fw_msize_to_bytes(fw_cycle_msize) / 4); word++)
                                {
                                    *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_FW_DATA_BLOCK_OFFSET + (word * 4))) =
479
                                        *((uint32_t *)(active_host_flash_buffer + (word * 4)));
480 481 482 483 484 485 486
                                }
                            }
                            else
                            {
                                for (byte = 0; byte < lpc_fw_msize_to_bytes(fw_cycle_msize); byte++)
                                {
                                    *((volatile uint8_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_FW_DATA_BLOCK_OFFSET + byte)) =
487
                                        *((uint8_t *)(active_host_flash_buffer + byte));
488 489 490 491 492 493 494 495 496 497 498 499 500 501
                                }
                            }

                            // Transfer success -- do not send error
                            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                            dword &= ~((AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                        }
                        else if (write_not_read && (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE))
                        {
                            if (lpc_fw_msize_to_bytes(fw_cycle_msize) >= 4)
                            {
                                for (word = 0; word < (lpc_fw_msize_to_bytes(fw_cycle_msize) / 4); word++)
                                {
502
                                    *((uint32_t *)(active_host_flash_buffer + (word * 4))) =
503 504 505 506 507 508 509
                                        *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_FW_DATA_BLOCK_OFFSET + (word * 4)));
                                }
                            }
                            else
                            {
                                for (byte = 0; byte < lpc_fw_msize_to_bytes(fw_cycle_msize); byte++)
                                {
510
                                    *((uint8_t *)(active_host_flash_buffer + byte)) =
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
                                        *((volatile uint8_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_FW_DATA_BLOCK_OFFSET + byte));
                                }
                            }

                            // Transfer success -- do not send error
                            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                            dword &= ~((AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                        }
                        else
                        {
                            // Invalid access -- send error
                            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                            dword |= ((1 & AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                        }
                    }
                    else
                    {
                        // Invalid access -- send error
                        dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                        dword |= ((1 & AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                    }
                }
                else
                {
                    // Received firmware cycle request for unknown IDSEL!  Dazed and
                    // confused, but trying to continue... Do not send error
                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                    dword &= ~((AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                }

                // Acknowledge data transfer
                dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                dword |= ((1 & AQUILA_LPC_CTL_XFER_CONT_MASK) << AQUILA_LPC_CTL_XFER_CONT_SHIFT);
                write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
            }
        }
#endif
552 553
#if (ENABLE_LPC_IO_CYCLE_IRQ_HANDLER)
        if (status4_reg & AQUILA_LPC_IO_CYCLE_IRQ_ASSERTED)
554
        {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
            status1_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS1);
            status2_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS2);
            address = (status2_reg >> AQUILA_LPC_STATUS_ACT_ADDR_SHIFT) & AQUILA_LPC_STATUS_ACT_ADDR_MASK;
            write_not_read = (status1_reg >> AQUILA_LPC_STATUS_CYC_WNR_SHIFT) & AQUILA_LPC_STATUS_CYC_WNR_MASK;

            if (((status1_reg >> AQUILA_LPC_STATUS_CYCLE_TYPE_SHIFT) & AQUILA_LPC_STATUS_CYCLE_TYPE_MASK) == AQUILA_LPC_STATUS_CYCLE_TYPE_IO)
            {
                if ((address >= 0x80) && (address <= 0x82))
                {
                    if (write_not_read)
                    {
                        uint8_t post_code = (read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS3) >> AQUILA_LPC_STATUS_ACT_WDATA_SHIFT) &
                                            AQUILA_LPC_STATUS_ACT_WDATA_MASK;
                        if (address == 0x81)
                        {
                            post_code_high = post_code;
                        }
                        else if (address == 0x82)
                        {
                            post_code_low = post_code;
                            if (post_code_incoming_interrupt_transient_buffer_pos < POST_CODE_INTERRUPT_TRANSIENT_BUFFER_SIZE)
                            {
577
                                post_code_incoming_interrupt_transient_buffer[post_code_incoming_interrupt_transient_buffer_pos] = ((post_code_high & 0xff) << 8) | (post_code_low & 0xff);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
                                post_code_incoming_interrupt_transient_buffer_pos++;
                            }
                            else
                            {
                                // Transient buffer is full
                                // Discard incoming data and signal overflow
                                post_code_incoming_interrupt_transient_buffer_overflow = 1;
                            }
                        }
                    }

                    // Transfer success -- do not send error
                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                    dword &= ~((AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);

                    // Acknowledge data transfer
                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                    dword |= ((1 & AQUILA_LPC_CTL_XFER_CONT_MASK) << AQUILA_LPC_CTL_XFER_CONT_SHIFT);
                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                }
                else
                {
                    // Transfer failed -- send error
                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                    dword |= ((1 & AQUILA_LPC_CTL_XFER_ERR_MASK) << AQUILA_LPC_CTL_XFER_ERR_SHIFT);
                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);

                    // Acknowledge data transfer
                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2);
                    dword |= ((1 & AQUILA_LPC_CTL_XFER_CONT_MASK) << AQUILA_LPC_CTL_XFER_CONT_SHIFT);
                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL2, dword);
                }
            }
            else
            {
                // Mask LPC I/O cycle IRQ
                dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
                dword &= ~((1 & AQUILA_LPC_CTL_EN_IO_CYCLE_IRQ_MASK) << AQUILA_LPC_CTL_EN_IO_CYCLE_IRQ_SHIFT);
                write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);
618 619

#if (WITH_ZEPHYR)
620 621
                // Temporarily raise background thread priority
                k_thread_priority_set(kestrel_service_thread_id, KESTREL_SERVICE_THREAD_PRIORITY);
622
#endif
623
            }
624
        }
625 626 627
#endif
#if (ENABLE_LPC_TPM_CYCLE_IRQ_HANDLER)
        if (status4_reg & AQUILA_LPC_TPM_CYCLE_IRQ_ASSERTED)
628
        {
629 630 631 632 633 634 635 636 637 638 639 640 641 642
            // Mask LPC TPM cycle IRQ
            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
            dword &= ~((1 & AQUILA_LPC_CTL_EN_TPM_CYCLE_IRQ_MASK) << AQUILA_LPC_CTL_EN_TPM_CYCLE_IRQ_SHIFT);
            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);

#if (WITH_ZEPHYR)
            // Temporarily raise background thread priority
            k_thread_priority_set(kestrel_service_thread_id, KESTREL_SERVICE_THREAD_PRIORITY);
#endif
        }
#endif
        if ((status4_reg & AQUILA_LPC_VUART1_IRQ_ASSERTED) || (status4_reg & AQUILA_LPC_VUART2_IRQ_ASSERTED))
        {
            // VUART1 or VUART2 has asserted its IRQ
643 644 645 646
            // Copy received characters to IRQ receive buffer
            do
            {
                vuart_status = *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + 0x0));
647 648 649 650 651 652 653 654 655 656 657 658 659 660
                if (!(vuart_status & AQUILA_LPC_VUART1_FIFO_EMPTY)) {
                    vuart1_incoming_interrupt_transient_buffer[vuart1_incoming_interrupt_transient_buffer_pos] =
                        (vuart_status >> AQUILA_LPC_VUART1_FIFO_READ_SHIFT) & AQUILA_LPC_VUART1_FIFO_READ_MASK;
                    vuart1_incoming_interrupt_transient_buffer_pos++;
                    if (vuart1_incoming_interrupt_transient_buffer_pos >= VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE)
                    {
                        // Transient buffer is full
                        // Disable VUART1 interrupts, since we are no longer able to service
                        // them, then exit the copy routine
                        dword = (*((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART1_CONTROL_REG)));
                        dword &= ~((1 & AQUILA_LPC_VUART_IRQ_EN_MASK) << AQUILA_LPC_VUART_IRQ_EN_SHIFT);
                        (*((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART1_CONTROL_REG))) = dword;
                        vuart1_incoming_interrupt_transient_buffer_overflow = 1;
                    }
661
                }
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
                if (!(vuart_status & AQUILA_LPC_VUART2_FIFO_EMPTY)) {
                    vuart2_incoming_interrupt_transient_buffer[vuart2_incoming_interrupt_transient_buffer_pos] =
                        (vuart_status >> AQUILA_LPC_VUART2_FIFO_READ_SHIFT) & AQUILA_LPC_VUART2_FIFO_READ_MASK;
                    vuart2_incoming_interrupt_transient_buffer_pos++;
                    if (vuart2_incoming_interrupt_transient_buffer_pos >= VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE)
                    {
                        // Transient buffer is full
                        // Disable VUART2 interrupts, since we are no longer able to service
                        // them, then exit the copy routine
                        dword = (*((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART2_CONTROL_REG)));
                        dword &= ~((1 & AQUILA_LPC_VUART_IRQ_EN_MASK) << AQUILA_LPC_VUART_IRQ_EN_SHIFT);
                        (*((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART2_CONTROL_REG))) = dword;
                        vuart2_incoming_interrupt_transient_buffer_overflow = 1;
                    }
                }
            } while (((!(vuart_status & AQUILA_LPC_VUART1_FIFO_EMPTY)) && (!vuart1_incoming_interrupt_transient_buffer_overflow))
                        || ((!(vuart_status & AQUILA_LPC_VUART2_FIFO_EMPTY)) && (!vuart2_incoming_interrupt_transient_buffer_overflow)));
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        }
        if (status4_reg & AQUILA_LPC_IPMI_BT_IRQ_ASSERTED)
        {
            // The IPMI BT module has asserted its IRQ
            // Copy IPMI BT request to IRQ receive buffer

            // Signal BMC read starting
            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS) & (1 << IPMI_BT_CTL_B_BUSY_SHIFT);
            if (!(dword & (1 << IPMI_BT_CTL_B_BUSY_SHIFT)))
            {
                // Set B_BUSY
                dword |= (1 << IPMI_BT_CTL_B_BUSY_SHIFT);
            }
            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS, dword);

            // Clear H2B_ATN
            dword = 0;
            dword |= (1 << IPMI_BT_CTL_H2B_ATN_SHIFT);
            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS, dword);

            ipmi_bt_request_ptr = (ipmi_request_message_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_IPMI_BT_DATA_BLOCK_OFFSET);
            ipmi_bt_interrupt_transient_request = *ipmi_bt_request_ptr;

            // Signal BMC read complete
            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS) & (1 << IPMI_BT_CTL_B_BUSY_SHIFT);
            if (dword & (1 << IPMI_BT_CTL_B_BUSY_SHIFT))
            {
                // Clear B_BUSY
                dword |= (1 << IPMI_BT_CTL_B_BUSY_SHIFT);
            }
            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS, dword);

            ipmi_bt_interrupt_transient_request_valid = 1;
        }
    }

    hostlpcslave_ev_pending_write(AQUILA_EV_MASTER_IRQ);
716 717

#if (WITH_ZEPHYR)
718 719
    if ((post_code_incoming_interrupt_transient_buffer_pos > 0)
        || (vuart1_incoming_interrupt_transient_buffer_pos > 0)
720 721 722
        || (vuart2_incoming_interrupt_transient_buffer_pos > 0)
        || (ipmi_bt_interrupt_transient_request_valid)) {
        // Temporarily raise service thread priority
723
        k_thread_priority_set(kestrel_service_thread_id, KESTREL_SERVICE_THREAD_PRIORITY);;
724 725
    }
#endif
726 727 728 729
}

uint8_t uart_register_bank[8];

730
uint8_t ipmi_bt_transaction_state;
731

732
static void configure_flash_write_enable(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr, uint8_t enable_writes)
733 734
{
    // Set user mode
735 736
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
737 738 739 740 741
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    if (enable_writes)
    {
        // Send write enable command
742
        *((volatile uint8_t *)spi_ctl_baseaddr) = 0x06;
743 744 745 746
    }
    else
    {
        // Send write disable command
747
        *((volatile uint8_t *)spi_ctl_baseaddr) = 0x04;
748 749 750
    }

    // Clear user mode
751 752
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
753 754 755
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
}

756
static uint8_t read_flash_flag_status_register(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr)
757 758 759 760
{
    uint8_t flag_status = 0;

    // Set user mode
761 762
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
763 764 765
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Send Read Flag Status Register command
766
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x70;
767 768

    // Read response
769
    flag_status = *((volatile uint8_t *)spi_ctl_baseaddr);
770 771

    // Clear user mode
772 773
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
774 775 776 777 778
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    return flag_status;
}

779
static void reset_flash_device(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr)
780 781
{
    // Set user mode
782 783
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
784 785 786
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Issue RESET ENABLE command
787
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x66;
788 789

    // Clear user mode
790 791
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
792 793 794
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Set user mode
795 796
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
797 798 799
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Issue RESET MEMORY command
800
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x99;
801 802

    // Clear user mode
803 804
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
805 806 807
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
}

808
static void configure_flash_device(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr)
809 810 811 812
{
    uint8_t config_byte;

    // Set user mode
813 814
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
815 816 817
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Enable 4 byte addressing mode
818
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0xb7;
819 820

    // Clear user mode
821 822
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
823 824
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

825
    configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 1);
826 827

    // Set user mode
828 829
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
830 831 832
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Initialize volatile configuration register
833
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x81;
834 835 836 837 838 839 840

    config_byte = 0;
    config_byte |= (MICRON_N25Q_SPI_FAST_READ_DUMMY_CLOCK_CYCLES & 0xf) << 4;
    config_byte |= (1 & 0x1) << 3;
    config_byte |= (0 & 0x1) << 2;
    config_byte |= (3 & 0x3) << 0;

841
    *((volatile uint8_t *)spi_ctl_baseaddr) = config_byte;
842 843

    // Clear user mode
844 845
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
846 847
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

848
    configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 0);
849 850
}

851
static void erase_flash_subsector(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr, uint32_t address)
852 853 854 855
{
    // Limit Flash address to active memory
    address = address & 0x0fffffff;

856
    while (!(read_flash_flag_status_register(spi_ctl_cfgaddr, spi_ctl_baseaddr) & 0x80))
857 858 859 860 861
    {
        // Wait for pending operation to complete
    }

    // Set user mode
862 863
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
864 865 866
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Send subsector erase command
867
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x21;
868 869

    // Send address
870 871 872 873
    *((volatile uint8_t *)spi_ctl_baseaddr) = (address >> 24) & 0xff;
    *((volatile uint8_t *)spi_ctl_baseaddr) = (address >> 16) & 0xff;
    *((volatile uint8_t *)spi_ctl_baseaddr) = (address >> 8) & 0xff;
    *((volatile uint8_t *)spi_ctl_baseaddr) = address & 0xff;
874 875

    // Clear user mode
876 877
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
878 879
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

880
    while (!(read_flash_flag_status_register(spi_ctl_cfgaddr, spi_ctl_baseaddr) & 0x80))
881 882 883 884 885
    {
        // Wait for pending operation to complete
    }
}

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
static void hiomap_remove_write_window(uint32_t start_address)
{
    int i;
    int j;

    // Remove mapping
    for (i = 0; i < hiomap_config.write_window_count; i++)
    {
        if (hiomap_config.write_windows[i].start_address == start_address)
        {
            if (hiomap_config.write_windows[i].active)
            {
                free(hiomap_config.write_windows[i].buffer);
                hiomap_config.write_windows[i].active = 0;
                break;
            }
        }
    }

    // Garbage collect
    for (i = 0; i < hiomap_config.write_window_count; i++)
    {
        if (!hiomap_config.write_windows[i].active)
        {
            for (j = i + 1; j < hiomap_config.write_window_count; j++)
            {
                hiomap_config.write_windows[j-1] = hiomap_config.write_windows[j];
            }
            hiomap_config.write_window_count--;
        }
    }
}

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
#if (WITH_SPI)
static uint32_t read_host_spi_flash_id(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr)
{
    uint32_t flash_id = 0;

    // Set user mode
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Send Flash ID command
    *((volatile uint8_t *)spi_ctl_baseaddr) = 0x9e;

    // Read response
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)spi_ctl_baseaddr) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)spi_ctl_baseaddr) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)spi_ctl_baseaddr) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)spi_ctl_baseaddr) & 0xff);

    // Clear user mode
    write_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(spi_ctl_cfgaddr, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    return flash_id;
}

946
static int write_data_to_flash(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr, uint8_t *data, uint32_t bytes, uint32_t flash_offset, uint8_t erase_before_write)
947
{
948
    uint32_t flash_device_id;
949 950
    uint32_t flash_address;
    uint32_t bytes_remaining;
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    uint8_t flag_status_register;
    uint8_t retry_operation;
    uint8_t retry_count;
    size_t max_bytes_per_write;
    int micron_n25q_device_found;
    int write_is_32bits;
    int i;
    int retcode;

    // Check alignment
    const uintptr_t alignment_mask = sizeof(mem_word_t) - 1;
    if ((uintptr_t)data & alignment_mask)
    {
        KESTREL_LOG("\n[ERROR] Unaligned data passed to write_data_to_flash()\n");
        return -2;
    }
    write_is_32bits = 1;
    if (bytes & 0x3)
    {
        write_is_32bits = 0;
    }
972

973
    // Limit Flash address to active memory region of SPI Flash controller
974 975
    flash_offset = flash_offset & 0x0fffffff;

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    // Read device ID in case special handling is required
    flash_device_id = read_host_spi_flash_id(spi_ctl_cfgaddr, spi_ctl_baseaddr);
    micron_n25q_device_found = 0;
    for (i = 0; i < (sizeof(micron_n25q_spi_device_ids) / sizeof(micron_n25q_spi_device_ids[0])); i++)
    {
        if (flash_device_id == micron_n25q_spi_device_ids[i])
        {
            micron_n25q_device_found = 1;
        }
    }
    if (micron_n25q_device_found)
    {
        // The N25Q512A and related devices are "special"
        // For some reason, it requires a flag status register read after every PAGE PROGRAM command
        // This means we can only write up to four bytes at a time in 32-bit copy mode
        if (write_is_32bits)
        {
            max_bytes_per_write = 4;
        }
        else
        {
            max_bytes_per_write = 1;
        }
    }
    else
    {
        max_bytes_per_write = FLASH_PAGE_SIZE_BYTES;
    }

    retcode = 0;
1006 1007 1008 1009 1010 1011 1012
    if (allow_flash_write)
    {
        // Flash erase if needed, then write data
        if (erase_before_write)
        {
            for (flash_address = flash_offset; (flash_address - flash_offset) < bytes; flash_address = flash_address + FLASH_ERASE_GRAN_BYTES)
            {
1013 1014
                configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 1);
                erase_flash_subsector(spi_ctl_cfgaddr, spi_ctl_baseaddr, flash_address);
1015 1016
            }

1017
            configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 0);
1018 1019
        }

1020 1021 1022
        retry_operation = 0;
        retry_count = 0;
        for (flash_address = flash_offset; (flash_address - flash_offset) < bytes; flash_address = flash_address + max_bytes_per_write)
1023
        {
1024 1025 1026 1027 1028 1029
            if (retry_operation)
            {
                flash_address = flash_address - max_bytes_per_write;
                retry_operation = 0;
                retry_count++;
            }
1030
            bytes_remaining = bytes - (flash_address - flash_offset);
1031 1032
            configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 1);
            while (!(read_flash_flag_status_register(spi_ctl_cfgaddr, spi_ctl_baseaddr) & 0x80))
1033 1034 1035
            {
                // Wait for pending operation to complete
            }
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
            if (write_is_32bits)
            {
                memcpy32((uint32_t *)(spi_ctl_baseaddr + flash_address), (uint32_t *)(data + (flash_address - flash_offset)),
                       (bytes_remaining > max_bytes_per_write) ? (max_bytes_per_write / 4) : (bytes_remaining / 4));
            }
            else
            {
                memcpy((uint8_t *)(spi_ctl_baseaddr + flash_address), data + (flash_address - flash_offset),
                       (bytes_remaining > max_bytes_per_write) ? max_bytes_per_write : bytes_remaining);
            }
            while (!((flag_status_register = read_flash_flag_status_register(spi_ctl_cfgaddr, spi_ctl_baseaddr)) & 0x80))
1047 1048 1049
            {
                // Wait for pending operation to complete
            }
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
            if (flag_status_register & 0x10)
            {
                retry_operation = 1;
            }
            else {
                if (memcmp((uint8_t *)(spi_ctl_baseaddr + flash_address), data + (flash_address - flash_offset),
                   (bytes_remaining > max_bytes_per_write) ? max_bytes_per_write : bytes_remaining) != 0)
                   {
                       retry_operation = 1;
                   }
            }
            if (retry_operation && (retry_count > FLASH_WRITE_LOCATION_RETRY_LIMIT))
            {
                KESTREL_LOG("\n[WARNING] Program failed at address 0x%08x (flag status 0x%02x)!  Retry limit reached, aborting write to location.\n", flash_address, flag_status_register);
                retry_operation = 0;
                retry_count = 0;
                retcode = -1;
            }
#if (WITH_ZEPHYR)
            if (retry_operation)
            {
                // Give the Flash device some time to recover / flush data
                k_usleep(100000);
            }
#endif
1075 1076
        }

1077
        configure_flash_write_enable(spi_ctl_cfgaddr, spi_ctl_baseaddr, 0);
1078
    }
1079

1080
    return retcode;
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
}

static int write_hiomap_data_to_flash(uintptr_t spi_ctl_cfgaddr, uintptr_t spi_ctl_baseaddr, uint32_t bytes, uint32_t flash_offset, uint8_t erase_before_write)
{
    uint32_t start_address;
    uint8_t *write_buffer;
    int i;
    int retcode;

    // Determine origin buffer address
    start_address = flash_offset;
    if (hiomap_use_direct_access)
    {
        write_buffer = NULL;
        for (i = 0; i < hiomap_config.write_window_count; i++)
        {
            if (hiomap_config.write_windows[i].start_address == start_address)
            {
                if (hiomap_config.write_windows[i].active)
                {
                    write_buffer = hiomap_config.write_windows[i].buffer;
                    break;
                }
            }
        }
        if (!write_buffer)
        {
            KESTREL_LOG("[WARNING] Flash data write called with no active data buffer!\n");
            return -1;
        }
1111 1112 1113
    }
    else
    {
1114
        write_buffer = (uint8_t *)(host_flash_buffer + (start_address & (FLASH_SIZE_BYTES - 1)));
1115
    }
1116 1117 1118 1119

    retcode = write_data_to_flash(spi_ctl_cfgaddr, spi_ctl_baseaddr, write_buffer, bytes, flash_offset, erase_before_write);

    return retcode;
1120
}
1121
#endif
1122 1123 1124 1125 1126 1127 1128 1129

// NOTE
// The POWER9 host uses true multitasking (kernel preemptive), so it is entirely
// possible to receive various LPC commands during processing of others.  As a
// result, we need at least a primitive multitasking system for the BMC. For
// now, use cooperative multitasking in this basic bare metal firmware... All
// functions called from the main TX/RX loop should return within some
// timeframe, e.g. 10ms
1130
static int process_host_to_bmc_ipmi_bt_transactions(void)
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
{
    uint32_t dword;

    static uint8_t unhandled_ipmi_command;
    volatile ipmi_response_message_t *response_ptr;
    static ipmi_response_message_t response;
    static uint8_t request_netfn;
    static uint8_t request_lun;

    uint32_t offset_bytes = 0;
    uint32_t length_bytes = 0;
    uint8_t flags = 0;

    int i;

1146 1147 1148 1149 1150 1151 1152
#if (WITH_ZEPHYR)
    if (ipmi_bt_transaction_state != 0) {
        // Temporarily raise service thread priority
        k_thread_priority_set(kestrel_service_thread_id, KESTREL_SERVICE_THREAD_PRIORITY);
    }
#endif

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    switch (ipmi_bt_transaction_state)
    {
        case 0:
            // Idle
            break;
        case 1:
            // Extract NETFN/LUN from request
            request_netfn = ipmi_bt_current_request.netfn_lun >> 2;
            request_lun = ipmi_bt_current_request.netfn_lun & 0x3;

            // Set up basic response parameters
            response.netfn_lun = (((request_netfn + 1) & 0x3f) << 2) | (request_lun & 0x3);
            response.sequence = ipmi_bt_current_request.sequence;
            response.command = ipmi_bt_current_request.command;
            response.length = BASE_IPMI_RESPONSE_LENGTH;
            response.completion_code = IPMI_CC_INVALID_COMMAND;
            memset(response.data, 0, sizeof(response.data));

1171 1172 1173 1174
            if (ENABLE_IPMI_DEBUG) {
                printk("[IPMI] Received request netfn 0x%02x lun 0x%02x\n", request_netfn, request_lun);
            }

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
            unhandled_ipmi_command = 0;
            switch (request_netfn)
            {
                case IPMI_NETFN_SENS_ET_REQ:
                    unhandled_ipmi_command = 1;
                    break;
                case IPMI_NETFN_APP_REQUEST:
                    switch (ipmi_bt_current_request.command)
                    {
                        case IPMI_CMD_GET_DEVICE_ID:
                            response.data[0] = 0x00;
                            response.data[1] = 0x00;
                            response.data[2] = 0x00;
                            response.data[3] = 0x00;
                            response.data[4] = 0x02;
                            response.data[5] = 0x00;
                            response.data[6] = 0x05;
                            response.data[7] = 0xcb;
                            response.data[8] = 0x00;
                            response.data[9] = 0x01;
                            response.data[10] = 0x00;
                            response.data[11] = 0x00;
                            response.data[12] = 0x00;
                            response.data[13] = 0x00;
                            response.data[14] = 0x00;
                            response.length = BASE_IPMI_RESPONSE_LENGTH + 15;
                            response.completion_code = IPMI_CC_NO_ERROR;
                            break;
                        case IPMI_CMD_GET_BT_INT_CAP:
                            response.data[0] = 0x01;
                            response.data[1] = 0x3f;
                            response.data[2] = 0x3f;
                            response.data[3] = 0x01;
                            response.data[4] = 0x01;
                            response.length = BASE_IPMI_RESPONSE_LENGTH + 5;
                            response.completion_code = IPMI_CC_NO_ERROR;
                            break;
                        default:
                            unhandled_ipmi_command = 1;
                            break;
                    }
                    break;
                case IPMI_NETFN_STORAGE_REQ:
                    unhandled_ipmi_command = 1;
                    break;
                case IPMI_NETFN_DCMI_GP_REQ:
                    switch (ipmi_bt_current_request.command)
                    {
                        case DCMI_CMD_GET_POWER_CAP:
                        {
                            /* Only a generic P9 profile with no power
                             * limits is included at the moment.*/
                            uint32_t limit_index = PowerLimitDataGeneric;
                            memcpy(response.data, &board_power_limits[limit_index].packet, sizeof(board_power_limits[0].packet));

                            response.completion_code = board_power_limits[limit_index].completion_code;
                            response.length = BASE_DCMI_RESPONSE_LENGTH + sizeof(board_power_limits[0].packet);
                        }
                        break;
                        default:
                            unhandled_ipmi_command = 1;
                            break;
                    }
                    break;
                case IPMI_NETFN_OEM_IBM_REQ:
                    switch (ipmi_bt_current_request.command)
                    {
                        case IPMI_CMD_IBM_HIOMAP_REQ:
                            switch (ipmi_bt_current_request.data[0])
                            {
                                case HIOMAP_CMD_GET_INFO:
                                    if (ipmi_bt_current_request.data[2] > 3)
                                    {
                                        // We only support up to the HIOMAP v3 protocol
                                        hiomap_config.protocol_version = 3;
                                    }
                                    else
                                    {
                                        hiomap_config.protocol_version = ipmi_bt_current_request.data[2];
                                    }
                                    switch (hiomap_config.protocol_version)
                                    {
                                        case 1:
                                            response.data[2] = hiomap_config.protocol_version;
                                            response.data[3] = FLASH_SIZE_BLOCKS & 0xff;
                                            response.data[4] = (FLASH_SIZE_BLOCKS >> 8) & 0xff;
                                            response.data[5] = FLASH_SIZE_BLOCKS & 0xff;
                                            response.data[6] = (FLASH_SIZE_BLOCKS >> 8) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 5;
                                            break;
                                        case 2:
                                            response.data[2] = hiomap_config.protocol_version;
                                            response.data[3] = FLASH_BLOCK_SIZE_SHIFT;
                                            response.data[4] = HIOMAP_SUGGESTED_TIMEOUT_S & 0xff;
                                            response.data[5] = (HIOMAP_SUGGESTED_TIMEOUT_S >> 8) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 4;
                                            break;
                                        case 3:
                                            response.data[2] = hiomap_config.protocol_version;
                                            response.data[3] = FLASH_BLOCK_SIZE_SHIFT;
                                            response.data[4] = HIOMAP_SUGGESTED_TIMEOUT_S & 0xff;
                                            response.data[5] = (HIOMAP_SUGGESTED_TIMEOUT_S >> 8) & 0xff;
                                            response.data[6] = HIOMAP_PNOR_DEVICE_COUNT;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 5;
                                            break;
                                    }
                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
                                case HIOMAP_CMD_GET_FLASH_INFO:
                                    switch (hiomap_config.protocol_version)
                                    {
                                        case 1:
                                            response.data[2] = FLASH_SIZE_BYTES & 0xff;
                                            response.data[3] = (FLASH_SIZE_BYTES >> 8) & 0xff;
                                            response.data[4] = (FLASH_SIZE_BYTES >> 16) & 0xff;
                                            response.data[5] = (FLASH_SIZE_BYTES >> 24) & 0xff;
                                            response.data[6] = FLASH_ERASE_GRAN_BYTES & 0xff;
                                            response.data[7] = (FLASH_ERASE_GRAN_BYTES >> 8) & 0xff;
                                            response.data[8] = (FLASH_ERASE_GRAN_BYTES >> 16) & 0xff;
                                            response.data[9] = (FLASH_ERASE_GRAN_BYTES >> 24) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 8;
                                            break;
                                        case 2:
                                            // Fall through, same format as protocol version 3
                                        case 3:
                                            response.data[2] = FLASH_SIZE_BLOCKS & 0xff;
                                            response.data[3] = (FLASH_SIZE_BLOCKS >> 8) & 0xff;
                                            response.data[4] = FLASH_ERASE_GRAN_BLOCKS & 0xff;
                                            response.data[5] = (FLASH_ERASE_GRAN_BLOCKS >> 8) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 4;
                                            break;
                                    }
                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
                                case HIOMAP_CMD_CLOSE_WINDOW:
                                    // Mark window inactive
                                    hiomap_config.window_type = HIOMAP_WINDOW_INACTIVE;

                                    // Implicitly flush any dirty ranges
                                    for (i = 0; i < hiomap_config.dirty_range_count; i++)
                                    {
                                        write_hiomap_data_to_flash(HOSTSPIFLASHCFG_BASE, HOSTSPIFLASH_BASE,
                                                            hiomap_config.dirty_ranges[i].bytes, hiomap_config.dirty_ranges[i].start_address,
                                                            !hiomap_config.dirty_ranges[i].erased);
                                    }
                                    hiomap_config.dirty_range_count = 0;

1326 1327 1328
                                    // Close active window
                                    hiomap_remove_write_window(hiomap_config.window_start_address);

1329 1330 1331 1332 1333
                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.length = BASE_HIOMAP_RESPONSE_LENGTH;
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
1334 1335
                                case HIOMAP_CMD_CREATE_RD_WIN:
                                case HIOMAP_CMD_CREATE_WR_WIN:
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
                                    // Implicitly shut down any active window
                                    if (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE)
                                    {
                                        // Implicitly flush any dirty ranges
                                        for (i = 0; i < hiomap_config.dirty_range_count; i++)
                                        {
                                            write_hiomap_data_to_flash(HOSTSPIFLASHCFG_BASE, HOSTSPIFLASH_BASE,
                                                                hiomap_config.dirty_ranges[i].bytes, hiomap_config.dirty_ranges[i].start_address,
                                                                !hiomap_config.dirty_ranges[i].erased);
                                        }
                                        hiomap_config.dirty_range_count = 0;

                                        // Close active window
                                        hiomap_remove_write_window(hiomap_config.window_start_address);
                                    }
                                    hiomap_config.window_type = HIOMAP_WINDOW_INACTIVE;

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
                                    // Parse request data
                                    hiomap_config.window_start_address =
                                        (((((uint32_t)ipmi_bt_current_request.data[3]) << 8) | ipmi_bt_current_request.data[2]) << FLASH_BLOCK_SIZE_SHIFT) &
                                        ((1 << LPC_ADDRESS_BITS) - 1);
                                    hiomap_config.window_length_bytes =
                                        (((((uint32_t)ipmi_bt_current_request.data[5]) << 8) | ipmi_bt_current_request.data[4]) << FLASH_BLOCK_SIZE_SHIFT) &
                                        ((1 << LPC_ADDRESS_BITS) - 1);
                                    hiomap_config.active_device_id = ipmi_bt_current_request.data[6];
                                    if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_RD_WIN)
                                    {
                                        hiomap_config.window_type = HIOMAP_WINDOW_TYPE_READ;
                                    }
                                    else if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_WR_WIN)
                                    {
                                        hiomap_config.window_type = HIOMAP_WINDOW_TYPE_WRITE;
                                    }
                                    else
                                    {
                                        hiomap_config.window_type = HIOMAP_WINDOW_INACTIVE;
                                    }

                                    // Sanitize input
                                    switch (hiomap_config.protocol_version)
                                    {
                                        case 1:
                                            if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_RD_WIN)
                                            {
                                                // Size unspecified, use one block as the size
                                                hiomap_config.window_length_bytes = 1 << FLASH_BLOCK_SIZE_SHIFT;
                                            }
                                            if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_WR_WIN)
                                            {
                                                // Size unspecified, use one block or the maximum write
                                                // cache size as the returned size, whichever is smaller...
                                                if (FLASH_MAX_WR_WINDOW_BYTES < (1 << FLASH_BLOCK_SIZE_SHIFT))
                                                {
                                                    hiomap_config.window_length_bytes = FLASH_MAX_WR_WINDOW_BYTES;
                                                }
                                                else
                                                {
                                                    hiomap_config.window_length_bytes = 1 << FLASH_BLOCK_SIZE_SHIFT;
                                                }
                                            }
                                            break;
                                        case 2:
                                        case 3:
                                            if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_RD_WIN)
                                            {
                                                // Zero sized window indicates undefined size, but must be at
                                                // least one block Just use one block as the size in this corner
                                                // case...
                                                if (hiomap_config.window_length_bytes == 0)
                                                {
                                                    hiomap_config.window_length_bytes = 1 << FLASH_BLOCK_SIZE_SHIFT;
                                                }
                                            }
                                            if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_WR_WIN)
                                            {
                                                // Zero sized window indicates undefined size, but must be at
                                                // least one block Just use one block as the size in this corner
                                                // case...
                                                if (hiomap_config.window_length_bytes == 0)
                                                {
                                                    hiomap_config.window_length_bytes = 1 << FLASH_BLOCK_SIZE_SHIFT;
                                                }
                                                else
                                                {
                                                    // The host can only request a window size, not demand one
                                                    // If the request is larger than our write cache size, limit
                                                    // the returned window to the write cache size...
                                                    if (hiomap_config.window_length_bytes > FLASH_MAX_WR_WINDOW_BYTES)
                                                    {
                                                        hiomap_config.window_length_bytes = FLASH_MAX_WR_WINDOW_BYTES;
                                                    }
                                                }
                                            }
                                            break;
                                    }

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
                                    if (hiomap_use_direct_access)
                                    {
                                        // Locate or allocate Flash sector buffer as required
                                        hiomap_write_buffer = NULL;
                                        for (i = 0; i < hiomap_config.write_window_count; i++)
                                        {
                                            if (hiomap_config.write_windows[i].start_address == hiomap_config.window_start_address)
                                            {
                                                if (hiomap_config.write_windows[i].active)
                                                {
                                                    hiomap_write_buffer = hiomap_config.write_windows[i].buffer;
                                                    break;
                                                }
                                            }
                                        }
                                        if ((!hiomap_write_buffer) && (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE))
                                        {
                                            hiomap_config.write_windows[hiomap_config.write_window_count].start_address = hiomap_config.window_start_address;
                                            hiomap_config.write_windows[hiomap_config.write_window_count].bytes = hiomap_config.window_length_bytes;
                                            hiomap_config.write_windows[hiomap_config.write_window_count].buffer = malloc(FLASH_MAX_WR_WINDOW_BYTES);
                                            hiomap_config.write_windows[hiomap_config.write_window_count].active = 1;
                                            hiomap_write_buffer = hiomap_config.write_windows[hiomap_config.write_window_count].buffer;
                                            hiomap_config.write_window_count++;
                                        }
                                    }

1458
#if (ENABLE_LPC_FW_CYCLE_DMA)
1459 1460 1461
                                    // Deactivate interrupts on entering critical section
                                    int key = irq_lock();

1462 1463 1464 1465 1466 1467
                                    // Disable DMA engine
                                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG1);
                                    dword &= ~((1 & AQUILA_LPC_CTL_EN_FW_DMA_R_MASK) << AQUILA_LPC_CTL_EN_FW_DMA_R_SHIFT);
                                    dword &= ~((1 & AQUILA_LPC_CTL_EN_FW_DMA_W_MASK) << AQUILA_LPC_CTL_EN_FW_DMA_W_SHIFT);
                                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG1, dword);

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                                    // Set up any required buffers while DMA engine is disabled
                                    if ((hiomap_use_direct_access) && (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE))
                                    {
                                        // Buffer data in write window from external Flash
                                        if (hiomap_config.window_length_bytes > FLASH_MAX_WR_WINDOW_BYTES)
                                        {
                                            KESTREL_LOG("[WARNING] HIOMAP write window set larger than maximum allowed write window size!  Clamping window to %d bytes\n", FLASH_MAX_WR_WINDOW_BYTES);
                                            hiomap_config.window_length_bytes = FLASH_MAX_WR_WINDOW_BYTES;
                                        }
                                        memcpy32((uint32_t *)hiomap_write_buffer, (uint32_t *)(uintptr_t)(HOSTSPIFLASH_BASE + hiomap_config.window_start_address), (hiomap_config.window_length_bytes / 4));
                                    }

1480
                                    // Reconfigure LPC firmware cycle DMA ranges
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
                                    if ((hiomap_use_direct_access) && (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE))
                                    {
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG2, (uintptr_t)hiomap_write_buffer);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG3, hiomap_config.window_length_bytes);
                                        // This is a little trick used to hide the moving buffer location in LPC firmware space from the host
                                        // By masking off all but the lowest address lines coming from the host, the host continues
                                        // to send addresses for higher regions of the mapped LPC firmware memory, but they end up diverted
                                        // into the small write buffer allocated earlier.
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG4, 0);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG5, hiomap_config.window_length_bytes);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG6, FLASH_MAX_WR_WINDOW_BYTES - 1);
                                    }
                                    else
                                    {
                                        if (hiomap_use_direct_access)
                                        {
                                            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG2, (uintptr_t)HOSTSPIFLASH_BASE);
                                        }
                                        else
                                        {
                                            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG2, (uintptr_t)host_flash_buffer);
                                        }
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG3, FLASH_SIZE_BYTES);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG4, hiomap_config.window_start_address);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG5,
                                                              hiomap_config.window_start_address + hiomap_config.window_length_bytes);
                                        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG6, FLASH_SIZE_BYTES - 1);
                                    }
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

                                    // Enable DMA engine
                                    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG1);
                                    dword |= ((1 & AQUILA_LPC_CTL_EN_FW_DMA_R_MASK) << AQUILA_LPC_CTL_EN_FW_DMA_R_SHIFT);
                                    if (hiomap_config.window_type == HIOMAP_WINDOW_TYPE_WRITE)
                                    {
                                        dword |= ((1 & AQUILA_LPC_CTL_EN_FW_DMA_W_MASK) << AQUILA_LPC_CTL_EN_FW_DMA_W_SHIFT);
                                    }
                                    else
                                    {
                                        dword &= ~((1 & AQUILA_LPC_CTL_EN_FW_DMA_W_MASK) << AQUILA_LPC_CTL_EN_FW_DMA_W_SHIFT);
                                    }
                                    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG1, dword);
1522 1523 1524

                                    // Re-activate interupts on exiting critical section
                                    irq_unlock(key);
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
#endif

                                    // Generate response
                                    switch (hiomap_config.protocol_version)
                                    {
                                        case 1:
                                            // Use 1:1 mapping between LPC firmware address and SPI Flash
                                            // address
                                            response.data[2] = (hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) & 0xff;
                                            response.data[3] = ((hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) >> 8) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 2;
                                            break;
                                        case 2:
                                        case 3:
                                            // Use 1:1 mapping between LPC firmware address and SPI Flash
                                            // address
                                            response.data[2] = (hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) & 0xff;
                                            response.data[3] = ((hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) >> 8) & 0xff;
                                            // Echo configured Flash window start / length
                                            response.data[4] = (hiomap_config.window_length_bytes >> FLASH_BLOCK_SIZE_SHIFT) & 0xff;
                                            response.data[5] = ((hiomap_config.window_length_bytes >> FLASH_BLOCK_SIZE_SHIFT) >> 8) & 0xff;
                                            response.data[6] = (hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) & 0xff;
                                            response.data[7] = ((hiomap_config.window_start_address >> FLASH_BLOCK_SIZE_SHIFT) >> 8) & 0xff;
                                            response.length = BASE_HIOMAP_RESPONSE_LENGTH + 6;
                                            break;
                                    }

                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
                                case HIOMAP_CMD_MARK_DIRTY:
                                    flags = 0;
                                    switch (hiomap_config.protocol_version)
                                    {
                                        case 1:
                                            offset_bytes = (((((uint32_t)ipmi_bt_current_request.data[3]) << 8) | ipmi_bt_current_request.data[2])
                                                            << FLASH_BLOCK_SIZE_SHIFT) &
                                                           ((1 << LPC_ADDRESS_BITS) - 1);
                                            length_bytes =
                                                ((((uint32_t)ipmi_bt_current_request.data[7]) << 24) | (((uint32_t)ipmi_bt_current_request.data[6]) << 16) |
                                                 (((uint32_t)ipmi_bt_current_request.data[5]) << 8) | ipmi_bt_current_request.data[4]);
                                            break;
                                        case 2:
                                        case 3:
                                            offset_bytes = hiomap_config.window_start_address +
                                                           ((((((uint32_t)ipmi_bt_current_request.data[3]) << 8) | ipmi_bt_current_request.data[2])
                                                             << FLASH_BLOCK_SIZE_SHIFT) &
                                                            ((1 << LPC_ADDRESS_BITS) - 1));
                                            length_bytes = (((((uint32_t)ipmi_bt_current_request.data[5]) << 8) | ipmi_bt_current_request.data[4])
                                                            << FLASH_BLOCK_SIZE_SHIFT) &
                                                           ((1 << LPC_ADDRESS_BITS) - 1);
                                            if (hiomap_config.protocol_version == 3)
                                            {
                                                flags = ipmi_bt_current_request.data[6];
                                            }
                                            break;
                                    }

                                    // Record dirty page
                                    hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].start_address = offset_bytes;
                                    hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].bytes = length_bytes;
                                    hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].erased = flags & 0x1;
                                    hiomap_config.dirty_range_count++;

                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.length = BASE_HIOMAP_RESPONSE_LENGTH;
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
                                case HIOMAP_CMD_FLUSH:
                                    if (hiomap_config.protocol_version == 1)
                                    {
                                        // Only HIOMAP protocol v1 has the ability to mark a page dirty in
                                        // the FLUSH command
                                        offset_bytes =
                                            (((((uint32_t)ipmi_bt_current_request.data[3]) << 8) | ipmi_bt_current_request.data[2]) << FLASH_BLOCK_SIZE_SHIFT) &
                                            ((1 << LPC_ADDRESS_BITS) - 1);
                                        length_bytes =
                                            ((((uint32_t)ipmi_bt_current_request.data[7]) << 24) | (((uint32_t)ipmi_bt_current_request.data[6]) << 16) |
                                             (((uint32_t)ipmi_bt_current_request.data[5]) << 8) | ipmi_bt_current_request.data[4]);

                                        // Record dirty page
                                        hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].start_address = offset_bytes;
                                        hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].bytes = length_bytes;
                                        hiomap_config.dirty_ranges[hiomap_config.dirty_range_count].erased = 0;
                                        hiomap_config.dirty_range_count++;
                                    }

                                    for (i = 0; i < hiomap_config.dirty_range_count; i++)
                                    {
1616
                                        write_hiomap_data_to_flash(HOSTSPIFLASHCFG_BASE, HOSTSPIFLASH_BASE,
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
                                                            hiomap_config.dirty_ranges[i].bytes, hiomap_config.dirty_ranges[i].start_address,
                                                            !hiomap_config.dirty_ranges[i].erased);
                                    }
                                    hiomap_config.dirty_range_count = 0;

                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.length = BASE_HIOMAP_RESPONSE_LENGTH;
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                case HIOMAP_CMD_ACK:
                                    // Mask is in ipmi_bt_current_request.data[2]
                                    // For now just ignore and claim sucess
                                    response.data[0] = ipmi_bt_current_request.data[0];
                                    response.data[1] = ipmi_bt_current_request.data[1];
                                    response.length = BASE_HIOMAP_RESPONSE_LENGTH;
                                    response.completion_code = IPMI_CC_NO_ERROR;
                                    break;
                                default:
                                    unhandled_ipmi_command = 1;
                                    break;
                            }
                            break;
                        default:
                            unhandled_ipmi_command = 1;
                            break;
                    }
                    break;
                default:
                    unhandled_ipmi_command = 1;
                    break;
            }

            if (unhandled_ipmi_command)
            {
                response.length = BASE_IPMI_RESPONSE_LENGTH;
                response.completion_code = IPMI_CC_INVALID_COMMAND;
            }

1655 1656 1657 1658
            if (ENABLE_IPMI_DEBUG) {
                printk("[IPMI] Responding with completion code 0x%02x\n", response.completion_code);
            }

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
            ipmi_bt_transaction_state = 2;
            break;
        case 2:
            // Wait for H_BUSY clear
            if (!(read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS) & (1 << IPMI_BT_CTL_H_BUSY_SHIFT)))
            {
                ipmi_bt_transaction_state = 3;
            }
            break;
        case 3:
            // Initialize pointer
            response_ptr = (ipmi_response_message_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_IPMI_BT_DATA_BLOCK_OFFSET);

            // Send response
            // A full copy is done so as to ensure any potentially sensitive data stored
            // in the IPMI BT buffer from a previous request is overwritten
            *response_ptr = response;

            // Signal BMC data ready
            dword = 0;
            dword |= (1 << IPMI_BT_CTL_B2H_ATN_SHIFT);
            write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS, dword);

            ipmi_bt_transaction_state = 4;
            break;
        case 4:
            // Wait for processing to complete
            // If B2H_ATN, and H_BUSY are both clear, processing has been completed
            dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS);
            if ((!(dword & (1 << IPMI_BT_CTL_B2H_ATN_SHIFT))) && (!(dword & (1 << IPMI_BT_CTL_H_BUSY_SHIFT))))
            {
1690 1691 1692
                if (ENABLE_IPMI_DEBUG) {
                    printk("[IPMI] Response complete, returning to idle\n");
                }
1693 1694 1695 1696 1697 1698 1699
                ipmi_bt_transaction_state = 0;
            }
            break;
        default:
            ipmi_bt_transaction_state = 0;
            break;
    }
1700 1701

    return 0;
1702 1703 1704 1705 1706 1707
}

#if !(ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
static uint32_t previous_fw_read_address;
#endif

1708
static int process_interrupts_stage2(void)
1709 1710 1711
{
    uint32_t dword;
    int read_position;
1712 1713
    int work_executed;

1714
#if (WITH_ZEPHYR)
1715 1716 1717 1718
    if (k_mutex_lock(&vuart1_access_mutex, K_MSEC(100)) != 0) {
        printk("Unable to acquire VUART1 mutex in a timely manner! %s:%d\n", __FILE__, __LINE__);
        return -EAGAIN;
    }
1719
#endif
1720 1721

    work_executed = 0;
1722 1723

    // Deactivate interrupts on entering critical section
1724
    int key = irq_lock();
1725 1726

    // CRITICAL SECTION
1727
    // No LPC interrupts can fire here!
1728 1729 1730 1731
    // All code in this section must be able to run in bounded time -- do NOT wait
    // on external events etc. here, just move and enqueue data as needed for
    // further processing at a later time

1732 1733 1734 1735 1736 1737 1738
    // Process incoming POST code data
    if (post_code_incoming_interrupt_transient_buffer_pos > 0)
    {
        read_position = 0;
        while (read_position < post_code_incoming_interrupt_transient_buffer_pos)
        {
            uint16_t post_code = post_code_incoming_interrupt_transient_buffer[read_position];
1739 1740
            uint8_t led_post_code = (((post_code >> 8) & 0xf) << 4) | (post_code & 0xf);
            set_led_bank_display(led_post_code);
1741

1742 1743 1744 1745 1746 1747 1748
            if (post_code == 0xfefe)
            {
                host_power_status = HOST_POWER_STATUS_RUNNING;
                set_led_bank_display(0);
                display_character('0' + 2 + host_power_status, 0); // STATUS CODE
            }

1749 1750
            if (enable_post_code_console_output)
            {
1751
                KESTREL_LOG("[POST CODE] %d.%d", (post_code >> 8) & 0xff, post_code & 0xff);
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
            }
            read_position++;
        }
        post_code_incoming_interrupt_transient_buffer_pos = 0;
        if (post_code_incoming_interrupt_transient_buffer_overflow)
        {
            // Clear overflow flag
            post_code_incoming_interrupt_transient_buffer_overflow = 0;
        }
        work_executed = 1;
    }

1764 1765 1766 1767 1768 1769 1770 1771
    // Process incoming VUART data
    if (vuart1_incoming_interrupt_transient_buffer_pos > 0)
    {
        read_position = 0;
        while (read_position < vuart1_incoming_interrupt_transient_buffer_pos)
        {
            vuart1_incoming_buffer[vuart1_incoming_buffer_write_pos] = vuart1_incoming_interrupt_transient_buffer[read_position];
            vuart1_incoming_buffer_write_pos++;
1772
            if (vuart1_incoming_buffer_write_pos >= VUART_RING_BUFFER_SIZE)
1773 1774 1775 1776
            {
                vuart1_incoming_buffer_write_pos = 0;
            }
            read_position++;