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

6 7
#define WITH_SPI 1

8 9
#include "fsi.h"
#include "utility.h"
10

11
#include <console.h>
12
#include <crc.h>
13
#include <endian.h>
14
#include <generated/csr.h>
15
#include <generated/mem.h>
16 17 18 19 20
#include <irq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uart.h>
21
#if (WITH_SPI)
22
#include "micron_n25q_flash.h"
23
#include "tercel_spi.h"
24 25 26 27 28 29 30
#endif

#include "aquila.h"
#include "ipmi_bt.h"
#include "opencores_i2c.h"

// Performance controls
31 32 33
#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_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
34 35

// Debug knobs
36 37
#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)
38 39

// General RCS platform registers
40 41
#define HOST_PLATFORM_FPGA_I2C_REG_STATUS  0x7
#define HOST_PLATFORM_FPGA_I2C_REG_MFR_OVR 0x33
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

// Host platform configuration
#define HOST_PLATFORM_FPGA_I2C_ADDRESS 0x31

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;

#define VUART_INTERRUPT_TRANSIENT_BUFFER_SIZE 32

// 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
static uint8_t vuart1_outgoing_buffer[512];
static int vuart1_outgoing_buffer_read_pos = 0;
static int vuart1_outgoing_buffer_write_pos = 0;

// Host to BMC VUART1 buffer
static uint8_t vuart1_incoming_buffer[512];
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
// static uint8_t vuart2_outgoing_buffer[512];
// static int vuart2_outgoing_buffer_read_pos = 0;
// static int vuart2_outgoing_buffer_write_pos = 0;
77

78 79 80 81 82 83 84 85 86 87 88
// Host to BMC VUART2 buffer
static uint8_t vuart2_incoming_buffer[512];
// 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
89
static uint8_t *host_flash_buffer;
90 91 92 93 94
static hiomap_configuration_data_t hiomap_config;

// Background service tasks
static uint8_t host_background_service_task_active = 0;
static uint8_t host_console_service_task_active = 0;
95
static int configured_cpu_count = 1;
96 97 98 99 100 101 102 103 104

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

// Global configuration
static uint8_t allow_flash_write = 0;
static uint8_t enable_post_code_console_output = 0;

105 106 107 108
typedef struct
{
    int8_t index;
    uint8_t *i2c_master;
109
    uint32_t i2c_frequency;
110
    uint8_t vdd_regulator_addr;
111 112 113
    uint8_t vdd_regulator_page;
    uint8_t vcs_regulator_addr;
    uint8_t vcs_regulator_page;
114
    uint8_t vdn_regulator_addr;
115
    uint8_t vdn_regulator_page;
116 117
    uint8_t vdd_smbus_addr;
    uint8_t vdn_smbus_addr;
118 119
} cpu_info_t;
static const cpu_info_t g_cpu_info[] = {
120 121 122
    {
        .index = 0,
        .i2c_master = (uint8_t *)I2CMASTER1_BASE,
123
        .i2c_frequency = 100000,
124
        .vdd_regulator_addr = 0x70,
125 126 127
        .vdd_regulator_page = 0x00,
        .vcs_regulator_addr = 0x70,
        .vcs_regulator_page = 0x01,
128
        .vdn_regulator_addr = 0x73,
129
        .vdn_regulator_page = 0x00,
130 131 132 133
        .vdd_smbus_addr = 0x28,
        .vdn_smbus_addr = 0x2b,

    },
134
#ifdef I2CMASTER2_BASE
135 136 137
    {
        .index = 1,
        .i2c_master = (uint8_t *)I2CMASTER2_BASE,
138
        .i2c_frequency = 100000,
139
        .vdd_regulator_addr = 0x70,
140 141 142
        .vdd_regulator_page = 0x00,
        .vcs_regulator_addr = 0x70,
        .vcs_regulator_page = 0x01,
143
        .vdn_regulator_addr = 0x73,
144
        .vdn_regulator_page = 0x00,
145 146 147
        .vdd_smbus_addr = 0x28,
        .vdn_smbus_addr = 0x2b,
    },
148 149
#endif
};
150
#define MAX_CPUS_SUPPORTED (sizeof(g_cpu_info) / sizeof(g_cpu_info[0]))
151

152 153 154 155 156 157 158 159 160 161 162 163
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,
    },
};

164
void primary_service_event_loop(void);
165

166 167
static char *readstr(void)
{
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
    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))
196
                {
197
                    break;
198
                }
199 200 201 202 203 204 205 206 207 208
                putsnonl(c);
                s[ptr] = c[0];
                ptr++;
                break;
        }
    }

    primary_service_event_loop();

    return NULL;
209 210 211 212
}

static char *get_token(char **str)
{
213 214 215 216 217 218 219 220 221 222 223 224 225
    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;
226 227 228 229
}

static void prompt(void)
{
230
    printf("FSP0>");
231 232 233 234
}

static void help(void)
{
235 236 237 238 239
    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");
240
    puts("console                         - Attach to host console");
241 242 243 244 245 246 247 248 249 250 251 252
    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");
253 254 255 256
}

static void reboot(void)
{
257
    ctrl_reset_write(1);
258 259
}

260 261
static void display_character(char character, int dp)
{
262 263 264 265 266
    uint16_t value;

    // FIXME Only supports numbers for now
    switch (character)
    {
267
        case '0':
268
            value = 0x003f;
269 270
            break;
        case '1':
271
            value = 0x0006;
272 273
            break;
        case '2':
274
            value = 0x221b;
275 276
            break;
        case '3':
277
            value = 0x220f;
278 279
            break;
        case '4':
280
            value = 0x2226;
281 282
            break;
        case '5':
283
            value = 0x222d;
284 285
            break;
        case '6':
286
            value = 0x223d;
287 288
            break;
        case '7':
289
            value = 0x0007;
290 291
            break;
        case '8':
292
            value = 0x223f;
293 294
            break;
        case '9':
295
            value = 0x222f;
296
            break;
297 298 299 300 301 302
        default:
            value = 0x0000;
            break; // OFF
    }

    gpio3_out_write(~(value | ((dp == 0) ? 0x0000 : 0x4000)));
303 304 305 306
}

static void set_led_bank_display(uint8_t bitfield)
{
307
    gpio1_out_write(~bitfield);
308 309 310 311
}

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

316 317 318
    // Set up alphanumeric display
    gpio3_out_write(0xefff);
    gpio3_oe_write(0xefff);
319 320 321 322
}

static void set_lpc_slave_irq_enable(uint8_t enabled)
{
323 324 325 326 327 328 329 330 331 332 333 334 335 336
    if (!enabled)
    {
        hostlpcslave_ev_enable_write(0);
        irq_setmask(irq_getmask() & ~(1 << HOSTLPCSLAVE_INTERRUPT));
    }

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

    if (enabled)
    {
        hostlpcslave_ev_enable_write(AQUILA_EV_MASTER_IRQ);
        irq_setmask(irq_getmask() | (1 << HOSTLPCSLAVE_INTERRUPT));
    }
337 338 339 340
}

void lpc_slave_isr(void)
{
341
#if (ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
342 343
    int byte;
    int word;
344
#endif
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    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);
362
#if (ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 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 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        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)
                {
                    // Limit firmware address to 64MB (wrap around)
                    address &= 0x3ffffff;

                    physical_flash_address = address;
                    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))) =
                                        *((uint32_t *)(host_flash_buffer + physical_flash_address + (word * 4)));
                                }
                            }
                            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)) =
                                        *((uint8_t *)(host_flash_buffer + physical_flash_address + 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 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++)
                                {
                                    *((uint32_t *)(host_flash_buffer + physical_flash_address + (word * 4))) =
                                        *((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++)
                                {
                                    *((uint8_t *)(host_flash_buffer + physical_flash_address + byte)) =
                                        *((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);
            }
        }
466
#endif
467
        if ((status4_reg & AQUILA_LPC_VUART1_IRQ_ASSERTED) || (status4_reg & AQUILA_LPC_VUART2_IRQ_ASSERTED))
468
        {
469
            // VUART1 or VUART2 has asserted its IRQ
470 471 472 473
            // Copy received characters to IRQ receive buffer
            do
            {
                vuart_status = *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + 0x0));
474
                if (!(vuart_status & AQUILA_LPC_VUART1_FIFO_EMPTY))
475
                {
476 477 478 479 480 481 482 483 484 485 486 487 488
                    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;
                    }
489
                }
490
                if (!(vuart_status & AQUILA_LPC_VUART2_FIFO_EMPTY))
491
                {
492 493 494 495 496 497 498 499 500 501 502 503 504
                    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;
                    }
505
                }
506 507
            } 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)));
508 509 510 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
        }
        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);
545 546 547 548 549 550
}

uint8_t uart_register_bank[8];

static uint8_t ipmi_bt_transaction_state;

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
static void configure_flash_write_enable(uint8_t enable_writes)
{
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    if (enable_writes)
    {
        // Send write enable command
        *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x06;
    }
    else
    {
        // Send write disable command
        *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x04;
    }

    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
573 574
}

575 576 577
static uint8_t read_flash_flag_status_register(void)
{
    uint8_t flag_status = 0;
578

579 580 581 582
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
583

584 585
    // Send Read Flag Status Register command
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x70;
586

587 588
    // Read response
    flag_status = *((volatile uint8_t *)HOSTSPIFLASH_BASE);
589

590 591 592 593
    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
594

595
    return flag_status;
596 597
}

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
static void reset_flash_device(void)
{
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Issue RESET ENABLE command
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x66;

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

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

    // Issue RESET MEMORY command
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x99;

    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
625 626
}

627 628 629
static void configure_flash_device(void)
{
    uint8_t config_byte;
630

631 632 633 634
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
635

636 637
    // Enable 4 byte addressing mode
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0xb7;
638

639 640 641 642
    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
643

644
    configure_flash_write_enable(1);
645

646 647 648 649
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
650

651 652
    // Initialize volatile configuration register
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x81;
653

654 655 656 657 658
    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;
659

660
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = config_byte;
661

662 663 664 665
    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
666

667
    configure_flash_write_enable(0);
668 669
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
static void erase_flash_subsector(uint32_t address)
{
    // Limit Flash address to active memory
    address = address & 0x0fffffff;

    while (!(read_flash_flag_status_register() & 0x80))
    {
        // Wait for pending operation to complete
    }

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

    // Send subsector erase command
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x21;

    // Send address
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = (address >> 24) & 0xff;
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = (address >> 16) & 0xff;
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = (address >> 8) & 0xff;
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = address & 0xff;

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

    while (!(read_flash_flag_status_register() & 0x80))
    {
        // Wait for pending operation to complete
    }
703 704
}

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
static int write_data_to_flash(uint8_t *write_buffer, uint32_t bytes, uint32_t flash_offset, uint8_t erase_before_write)
{
    uint32_t flash_address;
    uint32_t bytes_remaining;

    // Limit Flash address to active memory
    flash_offset = flash_offset & 0x0fffffff;

    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)
            {
                configure_flash_write_enable(1);
                erase_flash_subsector(flash_address);
            }

            configure_flash_write_enable(0);
        }

        for (flash_address = flash_offset; (flash_address - flash_offset) < bytes; flash_address = flash_address + FLASH_PAGE_SIZE_BYTES)
        {
            bytes_remaining = bytes - (flash_address - flash_offset);
            configure_flash_write_enable(1);
            while (!(read_flash_flag_status_register() & 0x80))
            {
                // Wait for pending operation to complete
            }
            memcpy((uint8_t *)(HOSTSPIFLASH_BASE + flash_address), write_buffer + (flash_address - flash_offset),
                   (bytes_remaining > 256) ? 256 : bytes_remaining);
            while (!(read_flash_flag_status_register() & 0x80))
            {
                // Wait for pending operation to complete
            }
        }

        configure_flash_write_enable(0);

        return -1;
    }
    else
    {
        return 0;
    }
751 752 753
}

// NOTE
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
// 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
static void process_host_to_bmc_ipmi_bt_transactions(void)
{
    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;

    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));

            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:
840 841 842 843 844
                    switch (ipmi_bt_current_request.command)
                    {
                        case DCMI_CMD_GET_POWER_CAP:
                        {
                            /* Only a generic P9 profile with no power
845
                             * limits is included at the moment.*/
846 847 848 849 850 851 852 853 854 855 856
                            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;
                    }
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 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 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
                    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;
                                case HIOMAP_CMD_CREATE_RD_WIN:
                                case HIOMAP_CMD_CREATE_WR_WIN:
                                    // 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)
943
                                    {
944
                                        hiomap_config.window_type = HIOMAP_WINDOW_TYPE_READ;
945
                                    }
946
                                    else if (ipmi_bt_current_request.data[0] == HIOMAP_CMD_CREATE_WR_WIN)
947
                                    {
948
                                        hiomap_config.window_type = HIOMAP_WINDOW_TYPE_WRITE;
949
                                    }
950
                                    else
951
                                    {
952
                                        hiomap_config.window_type = HIOMAP_WINDOW_INACTIVE;
953
                                    }
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 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 1006 1007 1008 1009 1010 1011

                                    // 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;
                                    }
1012

1013
#if (ENABLE_LPC_FW_CYCLE_DMA)
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
                                    // 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);

                                    // Reconfigure LPC firmware cycle DMA ranges
                                    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);

                                    // 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);
1040 1041
#endif

1042 1043 1044 1045 1046 1047 1048 1049 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 1075 1076 1077 1078 1079 1080 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 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 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
                                    // 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++)
                                    {
                                        write_data_to_flash(((uint8_t *)(host_flash_buffer + hiomap_config.dirty_ranges[i].start_address)),
                                                            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;
            }

            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))))
            {
                ipmi_bt_transaction_state = 0;
            }
            break;
        default:
            ipmi_bt_transaction_state = 0;
            break;
    }
1208 1209
}

1210
#if !(ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
1211 1212 1213
static uint32_t previous_fw_read_address;
#endif

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
static void process_interrupts_stage2(void)
{
    uint32_t dword;
    int read_position;

    // Deactivate interrupts on entering critical section
    irq_setie(0);

    // CRITICAL SECTION
    // No interrupts can fire here!
    // 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

    // 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++;
            if (vuart1_incoming_buffer_write_pos >= 512)
            {
                vuart1_incoming_buffer_write_pos = 0;
            }
            read_position++;
            if (read_position >= 512)
            {
                break;
            }
        }
        vuart1_incoming_interrupt_transient_buffer_pos = 0;
        if (vuart1_incoming_interrupt_transient_buffer_overflow)
        {
            // Reenable VUART1 interrupts
            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 = 0;
        }
    }
    if (vuart2_incoming_interrupt_transient_buffer_pos > 0)
    {
        read_position = 0;
        while (read_position < vuart2_incoming_interrupt_transient_buffer_pos)
        {
            vuart2_incoming_buffer[vuart2_incoming_buffer_write_pos] = vuart2_incoming_interrupt_transient_buffer[read_position];
            vuart2_incoming_buffer_write_pos++;
            if (vuart2_incoming_buffer_write_pos >= 512)
            {
                vuart2_incoming_buffer_write_pos = 0;
            }
            read_position++;
            if (read_position >= 512)
            {
                break;
            }
        }
        vuart2_incoming_interrupt_transient_buffer_pos = 0;
        if (vuart2_incoming_interrupt_transient_buffer_overflow)
        {
            // Reenable VUART1 interrupts
            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;
            vuart2_incoming_interrupt_transient_buffer_overflow = 0;
        }
    }

    // Process incoming IPMI BT request data
    if (ipmi_bt_interrupt_transient_request_valid)
    {
        if (ipmi_bt_transaction_state == 0)
        {
            ipmi_bt_current_request = ipmi_bt_interrupt_transient_request;
            ipmi_bt_interrupt_transient_request_valid = 0;
            ipmi_bt_transaction_state = 1;
        }
    }

    // Re-activate interupts on exiting critical section
    irq_setie(1);
1297 1298 1299 1300
}

static void run_pre_ipl_bmc_peripheral_setup(void)
{
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    uint32_t dword;

    // Reset POST codes and display
    post_code_high = 0;
    post_code_low = 0;
    set_led_bank_display(0x00);

    // Deactivate interrupts on entering critical section
    irq_setie(0);

    // Reset VUART1 FIFO pointers
    vuart1_incoming_interrupt_transient_buffer_pos = 0;
    vuart1_incoming_interrupt_transient_buffer_overflow = 0;
    vuart1_outgoing_buffer_read_pos = 0;
    vuart1_outgoing_buffer_write_pos = 0;
    vuart1_incoming_buffer_read_pos = 0;
    vuart1_incoming_buffer_write_pos = 0;

    // Re-activate interupts on exiting critical section
    irq_setie(1);

    // Configure VUART1
    dword = 0;
    dword |= (1 & AQUILA_LPC_VUART_FIFO_TRIG_LVL_MASK) << AQUILA_LPC_VUART_FIFO_TRIG_LVL_SHIFT;
    dword |= (1 & AQUILA_LPC_VUART_IRQ_EN_MASK) << AQUILA_LPC_VUART_IRQ_EN_SHIFT;
    dword |= (1 & AQUILA_LPC_VUART_FIFO_IRQ_EN_MASK) << AQUILA_LPC_VUART_FIFO_IRQ_EN_SHIFT;
    (*((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART1_CONTROL_REG))) = dword;

    // Enable LPC slave IRQs
    set_lpc_slave_irq_enable(1);

    // Clear IPMI BT B_BUSY flag
    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))
    {
        dword |= (1 << IPMI_BT_CTL_B_BUSY_SHIFT);
    }
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_IPMI_BT_STATUS, dword);

    // Enable IPMI BT IRQ
    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
    dword |= ((1 & AQUILA_LPC_CTL_EN_IPMI_BT_IRQ_MASK) << AQUILA_LPC_CTL_EN_IPMI_BT_IRQ_SHIFT);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);
1344

1345
#if (ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
1346 1347 1348 1349
    // Enable LPC firmware cycle IRQ
    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
    dword |= ((1 & AQUILA_LPC_CTL_EN_FW_CYCLE_IRQ_MASK) << AQUILA_LPC_CTL_EN_FW_CYCLE_IRQ_SHIFT);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);
1350 1351
#endif

1352 1353 1354 1355 1356 1357 1358
    // Reset HIOMAP windows
    hiomap_config.protocol_version = 0;
    hiomap_config.window_start_address = 0;
    hiomap_config.window_length_bytes = FLASH_SIZE_BYTES;
    hiomap_config.active_device_id = 0;
    hiomap_config.window_type = HIOMAP_WINDOW_TYPE_READ;
    hiomap_config.dirty_range_count = 0;
1359

1360
#if (ENABLE_LPC_FW_CYCLE_DMA)
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    // Configure and enable LPC firmware cycle DMA
    // Set up default window with address masking based on physical ROM size
    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, 0x0);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG5, FLASH_SIZE_BYTES);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DMA_CONFIG6, FLASH_SIZE_BYTES - 1);

    // 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);
    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);
1374 1375
#endif

1376 1377
    // Enable host background service task
    host_background_service_task_active = 1;
1378

1379 1380
    // Assume console service task is inactive at startup
    host_console_service_task_active = 0;
1381 1382 1383 1384
}

static void run_post_shutdown_bmc_peripheral_teardown(void)
{
1385
    uint32_t dword;
1386

1387 1388 1389
    // Disable host and console background service tasks
    host_background_service_task_active = 0;
    host_console_service_task_active = 0;
1390

1391 1392
    // Reset internal state variables
    ipmi_bt_transaction_state = 0;
1393

1394 1395 1396 1397 1398 1399 1400 1401
    // Set IPMI BT B_BUSY flag
    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);
1402

1403
#if (ENABLE_LPC_FW_CYCLE_DMA)
1404 1405 1406 1407 1408
    // 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);
1409 1410
#endif

1411
#if (ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
1412 1413 1414 1415
    // Disable LPC firmware cycle IRQ
    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
    dword &= ~((1 & AQUILA_LPC_CTL_EN_FW_CYCLE_IRQ_MASK) << AQUILA_LPC_CTL_EN_FW_CYCLE_IRQ_SHIFT);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);
1416 1417
#endif

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    // Disable IPMI BT IRQ
    dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
    dword &= ~((1 & AQUILA_LPC_CTL_EN_IPMI_BT_IRQ_MASK) << AQUILA_LPC_CTL_EN_IPMI_BT_IRQ_SHIFT);
    write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);

    // Disable LPC slave IRQs
    set_lpc_slave_irq_enable(0);

    // Reset HIOMAP windows
    hiomap_config.protocol_version = 0;
    hiomap_config.window_start_address = 0;
    hiomap_config.window_length_bytes = FLASH_SIZE_BYTES;
    hiomap_config.active_device_id = 0;
    hiomap_config.window_type = HIOMAP_WINDOW_TYPE_READ;
    hiomap_config.dirty_range_count = 0;

    // Reset POST codes and display
    post_code_high = 0;
    post_code_low = 0;
    set_led_bank_display(0x00);
1438 1439
}

1440
static int apply_avsbus_workarounds_cpu(const cpu_info_t *cpu)
1441
{
1442 1443
    printf("\tVDD/VCS %d: Enabling AVSBus CLK/MDAT pullups and selecting "
           "VIH/VIL 0x2 (0.65V/0.55V)\n",
1444
           cpu->index);
1445
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdd_smbus_addr, 0x2e, 0x23))
1446 1447 1448
    {
        return -1;
    }
1449

1450 1451
    printf("\tVDN %d: Enabling AVSBus CLK/MDAT pullups and selecting VIH/VIL "
           "0x2 (0.65V/0.55V)\n",
1452
           cpu->index);
1453
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdn_smbus_addr, 0x2e, 0x23))
1454 1455 1456 1457
    {
        return -1;
    }

1458 1459 1460
    return 0;
}

1461
static int apply_avsbus_workarounds(const cpu_info_t *cpu_info, int cpu_count)
1462 1463 1464
{
    printf("Applying AVSBus workarounds...\n");

1465
    for (int i = 0; i < cpu_count; i++)
1466
    {
1467
        if (apply_avsbus_workarounds_cpu(&cpu_info[i]))
1468 1469 1470 1471 1472 1473 1474
        {
            return -1;
        }
    }

    printf("\tAVSBus workaround application complete!\n");
    return 0;
1475 1476
}

1477
static int enable_avsbus_pmbus_cpu(const cpu_info_t *cpu)
1478
{
1479
    printf("\tVDD %d: Placing device in AVSBus voltage command mode\n", cpu->index);
1480
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdd_regulator_addr, 0x00, cpu->vdd_regulator_page))
1481 1482 1483
    {
        return -1;
    }
1484
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdd_regulator_addr, 0x01, 0xb0))
1485 1486 1487 1488
    {
        return -1;
    }

1489
    printf("\tVCS %d: Placing device in AVSBus voltage command mode\n", cpu->index);
1490
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vcs_regulator_addr, 0x00, cpu->vcs_regulator_page))
1491 1492 1493
    {
        return -1;
    }
1494
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vcs_regulator_addr, 0x01, 0xb0))
1495 1496 1497 1498
    {
        return -1;
    }

1499
    printf("\tVDN %d: Placing device in AVSBus voltage command mode\n", cpu->index);
1500
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdn_regulator_addr, 0x00, cpu->vdn_regulator_page))
1501 1502 1503
    {
        return -1;
    }
1504
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdn_regulator_addr, 0x01, 0xb0))
1505 1506 1507 1508
    {
        return -1;
    }

1509 1510
    return 0;
}
1511

1512
static int enable_avsbus_pmbus(const cpu_info_t *cpu_info, int cpu_count)
1513 1514
{
    printf("Enabling AVSbus PMBUS functionality...\n");
1515

1516
    for (int i = 0; i < cpu_count; i++)
1517
    {
1518
        if (enable_avsbus_pmbus_cpu(&cpu_info[i]))
1519 1520 1521 1522 1523 1524 1525
        {
            return -1;
        }
    }

    printf("\tAVSBus PMBUS functionality enabled!\n");
    return 0;
1526 1527
}

1528
static int disable_avsbus_pmbus_cpu(const cpu_info_t *cpu)
1529
{
1530
    printf("\tVDD %d: Placing device in immediate off mode\n", cpu->index);
1531
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdd_regulator_addr, 0x00, cpu->vdd_regulator_page))
1532 1533 1534
    {
        return -1;
    }
1535
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdd_regulator_addr, 0x01, 0x80))
1536 1537 1538 1539
    {
        return -1;
    }

1540
    printf("\tVCS %d: Placing device in immediate off mode\n", cpu->index);
1541
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vcs_regulator_addr, 0x00, cpu->vcs_regulator_page))
1542 1543 1544
    {
        return -1;
    }
1545
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vcs_regulator_addr, 0x01, 0x80))
1546 1547 1548 1549
    {
        return -1;
    }

1550
    printf("\tVDN %d: Placing device in immediate off mode\n", cpu->index);
1551
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdn_regulator_addr, 0x00, cpu->vdn_regulator_page))
1552 1553 1554
    {
        return -1;
    }
1555
    if (i2c_write_register_byte(cpu->i2c_master, cpu->vdn_regulator_addr, 0x01, 0x80))
1556 1557 1558 1559
    {
        return -1;
    }

1560 1561
    return 0;
}
1562
static int disable_avsbus_pmbus(const cpu_info_t *cpu_info, int cpu_count)
1563
{
1564
    int status = 0;
1565
    printf("Disabling AVSbus PMBUS functionality...\n");
1566

1567
    for (int i = 0; i < cpu_count; i++)
1568
    {
1569
        // Attempt to turn of power on all CPUs, even if one isn't responding.
1570
        if (disable_avsbus_pmbus_cpu(&cpu_info[i]))
1571
        {
1572
            status = -1;
1573 1574 1575 1576
        }
    }

    printf("\tAVSBus PMBUS functionality disabled!\n");
1577
    return status;
1578 1579
}

1580 1581 1582
static void power_off_chassis(void)
{
    // Disable PMBUS
1583
    if (disable_avsbus_pmbus(g_cpu_info, configured_cpu_count))
1584 1585 1586
    {
        printf("PMBUS disable failed!\n");
    }
1587

1588 1589
    // Power off host via platform FPGA commands
    i2c_write_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, HOST_PLATFORM_FPGA_I2C_REG_MFR_OVR, 0x00);
1590

1591
    run_post_shutdown_bmc_peripheral_teardown();
1592 1593
}

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 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
static int power_on_chassis(void)
{
    uint8_t platform_fpga_identifier[4];
    int platform_power_on_timeout_counter;
    int cpu_count = 1;
    int i2c_read_retcode;
    uint8_t byte;

    // Verify communication with platform control FPGA
    platform_fpga_identifier[0] = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, 0x0c, NULL);
    if (platform_fpga_identifier[0] == 0xff)
    {
        return -1;
    }
    platform_fpga_identifier[1] = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, 0x0d, NULL);
    platform_fpga_identifier[2] = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, 0x0e, NULL);
    platform_fpga_identifier[3] = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, 0x0f, NULL);
    if ((platform_fpga_identifier[0] != 0x52) || (platform_fpga_identifier[1] != 0x43) || (platform_fpga_identifier[2] != 0x53) ||
        (platform_fpga_identifier[3] != 0x20))
    {
        return -1;
    }
    printf("Platform FPGA communication verified\n");

    // Enable BMC runtime support tasks
    run_pre_ipl_bmc_peripheral_setup();

    // Power on host via platform FPGA commands
    printf("Commanding chassis power ON...\n");
    i2c_write_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, HOST_PLATFORM_FPGA_I2C_REG_MFR_OVR, 0x01);
    platform_power_on_timeout_counter = 0;
    byte = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, HOST_PLATFORM_FPGA_I2C_REG_STATUS, &i2c_read_retcode);
    while (i2c_read_retcode || (((byte)&0x03) != 0x03))
    {
        if (platform_power_on_timeout_counter > 20000)
        {
            printf("Chassis poweron timeout!\n");
            power_off_chassis();
            return -2;
        }
        usleep(100);
        platform_power_on_timeout_counter++;
        byte = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, HOST_PLATFORM_FPGA_I2C_REG_STATUS, &i2c_read_retcode);
    }
    if (i2c_read_retcode)
    {
        printf("FPGA communication failure during poweron!\n");
        return -3;
    }
    if (byte & 0x20)
    {
        cpu_count = 2;
    }
    printf("Chassis power verified active\n");
    configured_cpu_count = cpu_count;
1649 1650 1651 1652 1653
    if (cpu_count > MAX_CPUS_SUPPORTED)
    {
        configured_cpu_count = cpu_count = MAX_CPUS_SUPPORTED;
        printf("Limiting number of CPUs to %d\n", MAX_CPUS_SUPPORTED);
    }
1654 1655 1656
    printf("%d CPU(s) installed\n", cpu_count);

    // Apply AVSBus workarounds
1657
    if (apply_avsbus_workarounds(g_cpu_info, cpu_count))
1658 1659 1660 1661 1662 1663 1664
    {
        printf("AVSBus setup failed!\n");
        power_off_chassis();
        return -4;
    }

    // Enable PMBUS
1665
    if (enable_avsbus_pmbus(g_cpu_info, cpu_count))
1666 1667 1668 1669 1670 1671 1672
    {
        printf("PMBUS enable failed!\n");
        power_off_chassis();
        return -5;
    }

    return 0;
1673 1674
}

1675 1676 1677 1678 1679 1680
static int power_on_host(void)
{
    if (power_on_chassis())
    {
        return -1;
    }
1681

1682 1683 1684 1685
    if (start_ipl(0))
    {
        return -1;
    }
1686

1687
    return 0;
1688 1689
}

1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
static void print_chassis_status(void)
{
    int i2c_read_retcode;
    uint8_t byte;

    byte = i2c_read_register_byte((uint8_t *)I2CMASTER4_BASE, HOST_PLATFORM_FPGA_I2C_ADDRESS, HOST_PLATFORM_FPGA_I2C_REG_STATUS, &i2c_read_retcode);
    if (i2c_read_retcode)
    {
        printf("Unable to communicate with platform control FPGA!\n");
    }

    printf("Platform FPGA status:\n");
    if (byte & 0x1)
    {
        printf("\tPSU commanded ON\n");
    }
    else
    {
        printf("\tPSU commanded OFF\n");
    }
    if (byte & 0x2)
    {
        printf("\tPSU PGOOD asserted\n");
    }
    else
    {
        printf("\tPSU PGOOD deasserted\n");
    }
    printf("Platform overall status:\n");
    if (byte & 0x20)
    {
        printf("\t2 CPUs installed\n");
    }
    else
    {
        printf("\t1 CPU installed\n");
    }
    printf("BMC status:\n");
    if (host_background_service_task_active)
    {
        printf("\tBackground host services active\n");
    }
    else
    {
        printf("\tBackground host services inactive\n");
    }
1736 1737
}

1738 1739 1740 1741 1742
static void host_background_service_task_event_loop(void)
{
    uint32_t address;
    uint8_t write_not_read;
    uint32_t dword;
1743
#if !(ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
1744 1745 1746
    int byte;
    int word;
    uint32_t physical_flash_address;
1747 1748
#endif

1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    // IRQ debugging routines
    if (irq_unhandled_source_valid)
    {
        printf("[WARNING] Interrupt triggered without external IRQ set!  source: %d\n", irq_unhandled_source);
        irq_unhandled_source_valid = 0;
    }
    if (irq_unhandled_vector_valid)
    {
        printf("[ERROR] Unhandled exception 0x%03d\n", irq_unhandled_vector);
        irq_unhandled_vector_valid = 0;
    }

    if (read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS1) & (AQUILA_LPC_STATUS_ATTN_REQ_MASK << AQUILA_LPC_STATUS_ATTN_REQ_SHIFT))
    {
        // Store / retrieve data
        uint32_t status1_reg = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_STATUS1);
        uint32_t 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;
1768
#if !(ENABLE_LPC_FW_CYCLE_IRQ_HANDLER)
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
        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)
            {
                // Limit firmware address to 64MB (wrap around)
                address &= 0x3ffffff;

                previous_fw_read_address = address;
                physical_flash_address = address;
                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))) =
                                    *((uint32_t *)(host_flash_buffer + physical_flash_address + (word * 4)));
                            }
                        }
                        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)) =
                                    *((uint8_t *)(host_flash_buffer + physical_flash_address + 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 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++)
                            {
                                *((uint32_t *)(host_flash_buffer + physical_flash_address + (word * 4))) =
                                    *((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++)
                            {
                                *((uint8_t *)(host_flash_buffer + physical_flash_address + byte)) =
                                    *((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
                    {
                        printf("[WARNING] Data transfer attempted without active HIOMAP "
                               "window!  Returning error to host...\n");

                        // 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
                {
                    printf("[WARNING] Data transfer attempted outside configured HIOMAP "
                           "window!  Returning error to host...\n");

                    // 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
            {
                printf("[WARNING] Received firmware cycle request for IDSEL 0x%02x "
                       "(address 0x%08x)!  Dazed and confused, but trying to "
                       "continue...\n",
                       fw_cycle_idsel, address);

                // 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
1872
#endif
1873 1874 1875 1876 1877 1878 1879 1880
            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;
1881
                    if (address == 0x81)
1882 1883 1884
                    {
                        post_code_high = post_code;
                    }
1885
                    else if (address == 0x82)
1886 1887 1888
                    {
                        post_code_low = post_code;
                        set_led_bank_display(((post_code_high & 0xf) << 4) | (post_code_low & 0xf));
1889 1890 1891 1892 1893

                        if (enable_post_code_console_output)
                        {
                            printf("[POST CODE] %d.%d\n", post_code_high, post_code_low);
                        }
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
                    }
                }

                // 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
            {
                printf("[WARNING] LPC I/O transfer attempted to invalid address 0x%04x\n", address);

                // 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);
            }
        }
        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);
        }
    }
1930 1931
}

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
void primary_service_event_loop(void)
{
    // ===================================================================================
    // Main service loop
    // ===================================================================================
    // This loop is called as frequently as practical to keep response times low
    // All background tasks, from LPC I/O transfers to IPMI requests, are handled
    // here
    // ===================================================================================

    if (host_background_service_task_active)
    {
        // Run background service task event loop
        host_background_service_task_event_loop();

        // Process queued interrupt tasks
        process_interrupts_stage2();

        // Process cooperative multitasking threads
        process_host_to_bmc_ipmi_bt_transactions();
    }
1953 1954
}

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
static void attach_to_host_console(void)
{
    uint8_t escape_sequence_state;
    uint8_t character;
    uint8_t character_read;

    // Deactivate interrupts on entering critical section
    irq_setie(0);

    // Reset VUART1 FIFO pointers
    vuart1_incoming_interrupt_transient_buffer_pos = 0;
    vuart1_incoming_interrupt_transient_buffer_overflow = 0;
    vuart1_outgoing_buffer_read_pos = 0;
    vuart1_outgoing_buffer_write_pos = 0;
    vuart1_incoming_buffer_read_pos = 0;
    vuart1_incoming_buffer_write_pos = 0;

    // Re-activate interupts on exiting critical section
    irq_setie(1);

    // Signal host console service is now active
    host_console_service_task_active = 1;

    // Enter polling loop
    escape_sequence_state = 0;

    while (1)
    {
        // Escape sequence handler
        character_read = 0;
        if (readchar_nonblock())
        {
            character = readchar();
            character_read = 1;
            switch (escape_sequence_state)
            {
                case 0:
                    if (character == '\n')
                    {
                        escape_sequence_state = 1;
                    }
                    break;
                case 1:
                    if (character == '~')
                    {
                        escape_sequence_state = 2;
                    }
                    else
                    {
                        escape_sequence_state = 0;
                    }
                    break;
                case 2:
                    if (character == '.')
                    {
                        escape_sequence_state = 3;
                    }
                    else
                    {
                        escape_sequence_state = 0;
                    }
                    break;
                default:
                    escape_sequence_state = 0;
            }
        }
        if (escape_sequence_state == 3)
        {
            break;
        }

        while (vuart1_outgoing_buffer_write_pos != vuart1_outgoing_buffer_read_pos)
        {
            uint32_t vuart1_status_register = *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART1_STATUS_REG));
            if (!((vuart1_status_register >> AQUILA_LPC_VUART_WFIFO_FULL_SHIFT) & AQUILA_LPC_VUART_WFIFO_FULL_MASK))
            {
                // VUART FIFO now has room, send queued character to VUART hardware
                *((volatile uint8_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + 0x0)) = vuart1_outgoing_buffer[vuart1_outgoing_buffer_read_pos];
                vuart1_outgoing_buffer_read_pos++;
                if (vuart1_outgoing_buffer_read_pos >= 512)
                {
                    vuart1_outgoing_buffer_read_pos = 0;
                }
            }
            else
            {
                break;
            }
        }

        if (character_read)
        {
            // Attempt to send character to host
            uint32_t vuart1_status_register = *((volatile uint32_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + AQUILA_LPC_VUART1_STATUS_REG));
            if ((vuart1_status_register >> AQUILA_LPC_VUART_WFIFO_FULL_SHIFT) & AQUILA_LPC_VUART_WFIFO_FULL_MASK)
            {
                // VUART FIFO full, add to soft buffer
                vuart1_outgoing_buffer[vuart1_outgoing_buffer_write_pos] = character;
                vuart1_outgoing_buffer_write_pos++;
                if (vuart1_outgoing_buffer_write_pos >= 512)
                {
                    vuart1_outgoing_buffer_write_pos = 0;
                }
            }
            else
            {
                // VUART FIFO still has room, send character to VUART hardware
                *((volatile uint8_t *)(HOSTLPCSLAVE_BASE + AQUILA_LPC_VUART_BLOCK_OFFSET + 0x0)) = character;
            }
        }

        // Send any queued VUART output from host to BMC console
        while (vuart1_incoming_buffer_write_pos != vuart1_incoming_buffer_read_pos)
        {
            printf("%c", vuart1_incoming_buffer[vuart1_incoming_buffer_read_pos]);
            vuart1_incoming_buffer_read_pos++;
            if (vuart1_incoming_buffer_read_pos >= 512)
            {
                vuart1_incoming_buffer_read_pos = 0;
            }
        }

        primary_service_event_loop();
    }

    // Signal host console service is now inactive
    host_console_service_task_active = 0;
2082 2083
}

2084 2085 2086 2087 2088 2089 2090
static uint64_t parse_user_provided_number(const char *string)
{
    if (((*(string + 0)) == '0') && (((*(string + 1)) == 'x') || ((*(string + 1)) == 'X')))
    {
        return strtoul(string, NULL, 16);
    }
    return strtoul(string, NULL, 10);
2091 2092
}

2093 2094 2095 2096 2097 2098 2099
static uint8_t sanitize_ascii(uint8_t char_in)
{
    if ((char_in >= 32) && (char_in <= 126))
    {
        return char_in;
    }
    return '.';
2100 2101
}

2102 2103
static void console_service(void)
{
2104 2105 2106 2107 2108 2109 2110 2111 2112
    char *str;
    char *token;
    uint64_t address;
    uint32_t data;
    unsigned int i;
    unsigned int length;

    str = readstr();
    if (str == NULL)
2113
    {
2114
        return;
2115
    }
2116 2117
    token = get_token(&str);
    if (strcmp(token, "help") == 0)
2118
    {
2119
        help();
2120
    }
2121
    else if (strcmp(token, "reboot") == 0)
2122
    {
2123
        reboot();
2124
    }
2125
    else if (strcmp(token, "ipl") == 0)
2126
    {
2127
        start_ipl(0);
2128
    }
2129
    else if (strcmp(token, "sbe_status") == 0)
2130
    {
2131
        get_sbe_status();
2132
    }
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    else if (strcmp(token, "mr") == 0)
    {
        if (*str)
        {
            token = get_token(&str);
            address = parse_user_provided_number(token);
            if (*str)
            {
                token = get_token(&str);
                length = parse_user_provided_number(token);
            }
            else
            {
                length = 1;
            }
            for (i = 0; i < length; i++)
            {
                printf("0x%08x: 0x%08x\t%02x%02x%02x%02x\t%c%c%c%c\n", address + (i * 4), *((volatile uint32_t *)(address + (i * 4))),
                       *((volatile uint8_t *)(address + (i * 4) + 0)), *((volatile uint8_t *)(address + (i * 4) + 1)),
                       *((volatile uint8_t *)(address + (i * 4) + 2)), *((volatile uint8_t *)(address + (i * 4) + 3)),
                       sanitize_ascii(*((volatile uint8_t *)(address + (i * 4) + 0))), sanitize_ascii(*((volatile uint8_t *)(address + (i * 4) + 1))),
                       sanitize_ascii(*((volatile uint8_t *)(address + (i * 4) + 2))), sanitize_ascii(*((volatile uint8_t *)(address + (i * 4) + 3))));
            }
        }
        else
        {
            printf("USAGE: mr <memory address>\n");
        }
    }
    else if (strcmp(token, "mw") == 0)
    {
        if (*str)
        {
            token = get_token(&str);
            address = parse_user_provided_number(token);
            if (*str)
            {
                token = get_token(&str);
                length = parse_user_provided_number(token);
            }
            else
            {
                length = 1;
            }
            i = 0;
            while (*str)
            {
                token = get_token(&str);
                data = parse_user_provided_number(token);
                *((volatile uint32_t *)(address)) = data;
                i++;
                if (i >= length)
                {
                    break;
                }
            }
        }
        else
        {
            printf("USAGE: mr <memory address>\n");
        }
    }
    else if (strcmp(token, "flash_write") == 0)
    {
        if (*str)
        {
            token = get_token(&str);
            if (strcmp(token, "enable") == 0)
            {
                allow_flash_write = 1;
                printf("Flash write ENABLED\n");
            }
            else if (strcmp(token, "disable") == 0)
            {
                allow_flash_write = 0;
                printf("Flash write DISABLED\n");
            }
            else
            {
                printf("USAGE: flash_write <enable|disable>\n");
            }
        }
        else
        {
            printf("USAGE: flash_write <enable|disable>\n");
        }
    }
    else if (strcmp(token, "chassison") == 0)
    {
        power_on_chassis();
    }
    else if (strcmp(token, "chassisoff") == 0)
    {
        power_off_chassis();
        printf("Chassis power commanded OFF\n");
    }
    else if (strcmp(token, "status") == 0)
    {
        print_chassis_status();
    }
    else if (strcmp(token, "poweron") == 0)
    {
        if (power_on_host() == 0)
        {
            attach_to_host_console();
        }
        else
        {
            printf("Host poweron procedure FAILED\n");
        }
    }
    else if (strcmp(token, "post_codes") == 0)
    {
        if (*str)
        {
            token = get_token(&str);
            if (strcmp(token, "enable") == 0)
            {
                enable_post_code_console_output = 1;
                printf("POST code console output ENABLED\n");
            }
            else if (strcmp(token, "disable") == 0)
            {
                enable_post_code_console_output = 0;
                printf("POST code console output DISABLED\n");
            }
            else
            {
                printf("USAGE: post_codes <enable|disable>\n");
            }
        }
        else
        {
            printf("USAGE: post_codes <enable|disable>\n");
        }
    }
    else if (strcmp(token, "console") == 0)
2270
    {
2271
        attach_to_host_console();
2272
    }
2273
    else if (strcmp(token, "") != 0)
2274
    {
2275
        printf("%s: command not found\n", token);
2276
    }
2277
    prompt();
2278 2279
}

2280 2281 2282 2283 2284 2285 2286 2287 2288
static void memcpy32(uint32_t *destination, uint32_t *source, int words)
{
    int word;
    for (word = 0; word < words; word++)
    {
        *destination = *source;
        destination++;
        source++;
    }
2289 2290
}

2291 2292 2293 2294 2295 2296 2297 2298
static void memset32(uint32_t *destination, uint32_t value, int words)
{
    int word;
    for (word = 0; word < words; word++)
    {
        *destination = value;
        destination++;
    }
2299 2300
}

2301
#if (WITH_SPI)
2302 2303 2304
static uint32_t read_host_spi_flash_id(void)
{
    uint32_t flash_id = 0;
2305

2306 2307 2308 2309
    // Set user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) |
                              (TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
2310

2311 2312
    // Send Flash ID command
    *((volatile uint8_t *)HOSTSPIFLASH_BASE) = 0x9e;
2313

2314 2315 2316 2317 2318
    // Read response
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)HOSTSPIFLASH_BASE) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)HOSTSPIFLASH_BASE) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)HOSTSPIFLASH_BASE) & 0xff);
    flash_id = (flash_id << 8) | (*((volatile uint8_t *)HOSTSPIFLASH_BASE) & 0xff);
2319

2320 2321 2322 2323
    // Clear user mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));
2324

2325
    return flash_id;
2326 2327
}

2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
static int host_spi_flash_init(void)
{
    int i;
    uint32_t dword;
    uint32_t flash_device_id;

    if ((read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_DEVICE_ID_HIGH) != TERCEL_SPI_DEVICE_ID_HIGH) ||
        (read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_DEVICE_ID_LOW) != TERCEL_SPI_DEVICE_ID_LOW))
    {
        return -1;
    }

    uint32_t tercel_version = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_DEVICE_VERSION);
    printf("Raptor Tercel SPI master found, device version %0d.%0d.%d\n", (tercel_version >> TERCEL_SPI_VERSION_MAJOR_SHIFT) & TERCEL_SPI_VERSION_MAJOR_MASK,
           (tercel_version >> TERCEL_SPI_VERSION_MINOR_SHIFT) & TERCEL_SPI_VERSION_MINOR_MASK,
           (tercel_version >> TERCEL_SPI_VERSION_PATCH_SHIFT) & TERCEL_SPI_VERSION_PATCH_MASK);

    flash_device_id = read_host_spi_flash_id();
    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])
        {
            printf("%s Flash device detected, configuring\n", micron_n25q_spi_device_names[i]);

            // Set up Flash-specific commands
            dword = 0;
            dword |= (MICRON_N25Q_SPI_4BA_QSPI_READ_CMD & TERCEL_SPI_4BA_QSPI_CMD_MASK) << TERCEL_SPI_4BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_QSPI_READ_CMD & TERCEL_SPI_3BA_QSPI_CMD_MASK) << TERCEL_SPI_3BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_4BA_SPI_READ_CMD & TERCEL_SPI_4BA_SPI_CMD_MASK) << TERCEL_SPI_4BA_SPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_SPI_READ_CMD & TERCEL_SPI_3BA_SPI_CMD_MASK) << TERCEL_SPI_3BA_SPI_CMD_SHIFT;
            write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG1, dword);

            dword = 0;
            dword |= (MICRON_N25Q_SPI_4BA_QSPI_FAST_READ_CMD & TERCEL_SPI_4BA_QSPI_CMD_MASK) << TERCEL_SPI_4BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_QSPI_FAST_READ_CMD & TERCEL_SPI_3BA_QSPI_CMD_MASK) << TERCEL_SPI_3BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_4BA_SPI_FAST_READ_CMD & TERCEL_SPI_4BA_SPI_CMD_MASK) << TERCEL_SPI_4BA_SPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_SPI_FAST_READ_CMD & TERCEL_SPI_3BA_SPI_CMD_MASK) << TERCEL_SPI_3BA_SPI_CMD_SHIFT;
            write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG2, dword);

            dword = 0;
            dword |= (MICRON_N25Q_SPI_4BA_QSPI_PAGE_PROGRAM_CMD & TERCEL_SPI_4BA_QSPI_CMD_MASK) << TERCEL_SPI_4BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_QSPI_PAGE_PROGRAM_CMD & TERCEL_SPI_3BA_QSPI_CMD_MASK) << TERCEL_SPI_3BA_QSPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_4BA_SPI_PAGE_PROGRAM_CMD & TERCEL_SPI_4BA_SPI_CMD_MASK) << TERCEL_SPI_4BA_SPI_CMD_SHIFT;
            dword |= (MICRON_N25Q_SPI_3BA_SPI_PAGE_PROGRAM_CMD & TERCEL_SPI_3BA_SPI_CMD_MASK) << TERCEL_SPI_3BA_SPI_CMD_SHIFT;
            write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG3, dword);

            // Enable extended QSPI read/write operations
            dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
            dword |= TERCEL_SPI_PHY_QSPI_EXT_READ_EN_MASK << TERCEL_SPI_PHY_QSPI_EXT_READ_EN_SHIFT;
            dword |= TERCEL_SPI_PHY_QSPI_EXT_WRITE_EN_MASK << TERCEL_SPI_PHY_QSPI_EXT_WRITE_EN_SHIFT;
            write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

            break;
        }
    }

    // Set SPI core to automatic mode
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CORE_CTL1) &
                              ~(TERCEL_SPI_ENABLE_USER_MODE_MASK << TERCEL_SPI_ENABLE_USER_MODE_SHIFT));

    // Set extra CS delay cycle count to 0
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_CS_EXTRA_IDLE_CYC_MASK << TERCEL_SPI_PHY_CS_EXTRA_IDLE_CYC_SHIFT);
    dword |= ((0 & TERCEL_SPI_PHY_CS_EXTRA_IDLE_CYC_MASK) << TERCEL_SPI_PHY_CS_EXTRA_IDLE_CYC_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

    // Set maximum CS assert cycle count to 10000
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG4);
    dword &= ~(TERCEL_SPI_FLASH_CS_EN_LIMIT_CYC_MASK << TERCEL_SPI_FLASH_CS_EN_LIMIT_CYC_SHIFT);
    dword |= ((10000 & TERCEL_SPI_FLASH_CS_EN_LIMIT_CYC_MASK) << TERCEL_SPI_FLASH_CS_EN_LIMIT_CYC_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG4, dword);

    // Set SPI fast read dummy cycles to
    // MICRON_N25Q_SPI_FAST_READ_DUMMY_CLOCK_CYCLES
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_DUMMY_CYCLES_MASK << TERCEL_SPI_PHY_DUMMY_CYCLES_SHIFT);
    dword |= ((MICRON_N25Q_SPI_FAST_READ_DUMMY_CLOCK_CYCLES & TERCEL_SPI_PHY_DUMMY_CYCLES_MASK) << TERCEL_SPI_PHY_DUMMY_CYCLES_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

    // Enable SPI fast read functionality
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_FAST_READ_ENABLE_MASK << TERCEL_SPI_PHY_FAST_READ_ENABLE_SHIFT);
    dword |= ((1 & TERCEL_SPI_PHY_FAST_READ_ENABLE_MASK) << TERCEL_SPI_PHY_FAST_READ_ENABLE_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

    // Set SPI controller to 4BA mode
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_4BA_ENABLE_MASK << TERCEL_SPI_PHY_4BA_ENABLE_SHIFT);
    dword |= ((TERCEL_SPI_PHY_4BA_MODE & TERCEL_SPI_PHY_4BA_ENABLE_MASK) << TERCEL_SPI_PHY_4BA_ENABLE_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

2420
#if (ALLOW_SPI_QUAD_MODE)
2421 2422 2423 2424 2425
    // Set SPI controller to QSPI mode
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_IO_TYPE_MASK << TERCEL_SPI_PHY_IO_TYPE_SHIFT);
    dword |= ((TERCEL_SPI_PHY_IO_TYPE_QUAD & TERCEL_SPI_PHY_IO_TYPE_MASK) << TERCEL_SPI_PHY_IO_TYPE_SHIFT);
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);
2426
#endif
2427

2428
    // Set SPI clock cycle divider to 5
2429 2430
    dword = read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1);
    dword &= ~(TERCEL_SPI_PHY_CLOCK_DIVISOR_MASK << TERCEL_SPI_PHY_CLOCK_DIVISOR_SHIFT);
2431
    dword |= ((5 & TERCEL_SPI_PHY_CLOCK_DIVISOR_MASK) << TERCEL_SPI_PHY_CLOCK_DIVISOR_SHIFT);
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1, dword);

    // Calculate and dump configured SPI clock speed
    uint8_t spi_divisor =
        (read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1) >> TERCEL_SPI_PHY_CLOCK_DIVISOR_SHIFT) & TERCEL_SPI_PHY_CLOCK_DIVISOR_MASK;
    spi_divisor = (spi_divisor + 1) * 2;
    uint8_t spi_dummy_cycles =
        (read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_PHY_CFG1) >> TERCEL_SPI_PHY_DUMMY_CYCLES_SHIFT) & TERCEL_SPI_PHY_DUMMY_CYCLES_MASK;
    printf("Flash controller frequency configured to %d MHz (bus frequency %d MHz, "
           "dummy cycles %d)\n",
           (read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CLK_FREQ) / spi_divisor) / 1000000,
           read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_CLK_FREQ) / 1000000, spi_dummy_cycles);

    // Enable read merging
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG5,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG5) |
                              (TERCEL_SPI_FLASH_EN_MULTCYC_READ_MASK << TERCEL_SPI_FLASH_EN_MULTCYC_READ_SHIFT));

    // Enable write merging
    write_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG5,
                          read_tercel_register(HOSTSPIFLASHCFG_BASE, TERCEL_SPI_REG_SYS_FLASH_CFG5) |
                              (TERCEL_SPI_FLASH_EN_MULTCYC_WRITE_MASK << TERCEL_SPI_FLASH_EN_MULTCYC_WRITE_SHIFT));

    return 0;
2456
}
2457
#endif
2458

2459
#if (WITH_SPI)
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
#define SPI_READ_TRANSFER_SIZE (1 * 1024 * 1024LL)
int copy_spi_flash_to_internal_buffer(uintptr_t flash_data, uintptr_t flash_ctl, uint8_t *buffer)
{
    int retcode;
    int chunk;
    int redundancy_chunk;
    uintptr_t redundancy_buffer_offset;
#if (SPI_FLASH_TRIPLE_READ)
    uintptr_t buffer_check_offset;
    uint32_t value1;
    uint32_t value2;
    uint32_t value3;
    uint32_t final_value;
#endif

    printf("Copying host Flash ROM (%p) to internal buffer (%p)...\n", flash_data, buffer);
    retcode = 0;

    for (chunk = 0; chunk < FLASH_SIZE_BYTES / SPI_READ_TRANSFER_SIZE; chunk++)
    {
#if (SPI_FLASH_TRIPLE_READ)
        for (redundancy_chunk = 0; redundancy_chunk < 3; redundancy_chunk++)
        {
#else
        for (redundancy_chunk = 0; redundancy_chunk < 1; redundancy_chunk++)
        {
#endif
            redundancy_buffer_offset = redundancy_chunk * SPI_READ_TRANSFER_SIZE;
            memcpy32((uint32_t *)(buffer + redundancy_buffer_offset + (chunk * SPI_READ_TRANSFER_SIZE)),
                     (uint32_t *)(flash_data + (chunk * SPI_READ_TRANSFER_SIZE)), SPI_READ_TRANSFER_SIZE / 4);
            printf("\r[%d/%d]", chunk + 1, FLASH_SIZE_BYTES / SPI_READ_TRANSFER_SIZE);

            // Reset ongoing multibyte access due to die switch requirements on the N25Q
            // Flash devices
            write_tercel_register(flash_ctl, TERCEL_SPI_REG_SYS_FLASH_CFG5,
                                  read_tercel_register(flash_ctl, TERCEL_SPI_REG_SYS_FLASH_CFG5) &
                                      ~(TERCEL_SPI_FLASH_EN_MULTCYC_READ_MASK << TERCEL_SPI_FLASH_EN_MULTCYC_READ_SHIFT));
            write_tercel_register(flash_ctl, TERCEL_SPI_REG_SYS_FLASH_CFG5,
                                  read_tercel_register(flash_ctl, TERCEL_SPI_REG_SYS_FLASH_CFG5) |
                                      (TERCEL_SPI_FLASH_EN_MULTCYC_READ_MASK << TERCEL_SPI_FLASH_EN_MULTCYC_READ_SHIFT));
        }
#if (SPI_FLASH_TRIPLE_READ)
        for (buffer_check_offset = 0; buffer_check_offset < SPI_READ_TRANSFER_SIZE; buffer_check_offset = buffer_check_offset + 4)
        {
            value1 = *((uint32_t *)(buffer + buffer_check_offset + (chunk * SPI_READ_TRANSFER_SIZE)));
            value2 = *((uint32_t *)(buffer + buffer_check_offset + SPI_READ_TRANSFER_SIZE + (chunk * SPI_READ_TRANSFER_SIZE)));
            value3 = *((uint32_t *)(buffer + buffer_check_offset + (2 * SPI_READ_TRANSFER_SIZE) + (chunk * SPI_READ_TRANSFER_SIZE)));
            if (!((value1 == value2) && (value1 == value3)))
            {
                printf("[WARNING] Triple read FAILED integrity check at address 0x%08x!  Values 0x%08x/0x%08x/0x%08x\n",
                       buffer + buffer_check_offset + (chunk * SPI_READ_TRANSFER_SIZE), value1, value2, value3);
                if (value1 == value2)
                {
                    final_value = value1;
                }
                else if (value2 == value3)
                {
                    final_value = value2;
                }
                else if (value1 == value3)
                {
                    final_value = value1;
                }
                else
                {
                    printf("[ERROR] UNCORRECTABLE data read at address 0x%08x!\n", buffer + buffer_check_offset + (chunk * SPI_READ_TRANSFER_SIZE));
                    final_value = 0xdeadbeef;
                    retcode = -1;
                }
                *((uint32_t *)(buffer + buffer_check_offset + (chunk * SPI_READ_TRANSFER_SIZE))) = final_value;
                if (retcode)
                {
                    // Fast abort on fatal error
                    break;
                }
            }
        }
#endif
    }
    printf("\r%dMB copied\n", chunk);

    return retcode;
}
#endif

2545 2546
int main(void)
{
2547
    uint32_t dword;
2548

2549
#ifdef CONFIG_CPU_HAS_INTERRUPT
2550 2551 2552
    // Mask external interrupts / enable global interrupts
    irq_setmask(0);
    irq_setie(1);
2553
#endif
2554 2555 2556
    uart_init();
    gpio_init();

2557
    display_character('0', 0); // STATUS CODE: 0
2558

2559 2560 2561 2562
    for (int i = 0; i < MAX_CPUS_SUPPORTED; i++)
    {
        initialize_i2c_master(g_cpu_info[i].i2c_master, g_cpu_info[i].i2c_frequency);
    }
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
    // initialize_i2c_master((uint8_t*)I2CMASTER3_BASE, 100000);
    initialize_i2c_master((uint8_t *)I2CMASTER4_BASE, 100000);

    // Check for Aquila core presence
    if ((read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DEVICE_ID_HIGH) == AQUILA_LPC_DEVICE_ID_HIGH) &&
        (read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DEVICE_ID_LOW) == AQUILA_LPC_DEVICE_ID_LOW))
    {
        uint32_t aquila_version = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_DEVICE_VERSION);
        printf("Raptor Aquila LPC slave found, device version %0d.%0d.%d\n", (aquila_version >> AQUILA_LPC_VERSION_MAJOR_SHIFT) & AQUILA_LPC_VERSION_MAJOR_MASK,
               (aquila_version >> AQUILA_LPC_VERSION_MINOR_SHIFT) & AQUILA_LPC_VERSION_MINOR_MASK,
               (aquila_version >> AQUILA_LPC_VERSION_PATCH_SHIFT) & AQUILA_LPC_VERSION_PATCH_MASK);

        // Configure Aquila core to intercept I/O port ranges 0x80-0x82 and
        // 0x3f8-0x3ff 0x80
        dword = 0;
        dword |= ((0x82 & AQUILA_LPC_RANGE_END_ADDR_MASK) << AQUILA_LPC_RANGE_END_ADDR_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_RANGE1_END, dword);
        dword = 0;
        dword |= ((0x80 & AQUILA_LPC_RANGE_START_ADDR_MASK) << AQUILA_LPC_RANGE_START_ADDR_SHIFT);
        dword |= ((1 & AQUILA_LPC_RANGE_ALLOW_IO_MASK) << AQUILA_LPC_RANGE_ALLOW_IO_SHIFT);
        dword |= ((1 & AQUILA_LPC_RANGE_ENABLE_MASK) << AQUILA_LPC_RANGE_ENABLE_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_RANGE1_CONFIG, dword);

        // Enable I/O cycle intercept
        dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
        dword |= ((1 & AQUILA_LPC_CTL_EN_IO_CYCLES_MASK) << AQUILA_LPC_CTL_EN_IO_CYCLES_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);

        // Enable VUART1
        dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
        dword |= ((1 & AQUILA_LPC_CTL_EN_VUART1_MASK) << AQUILA_LPC_CTL_EN_VUART1_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);

        // Enable IPMI BT functionality
        dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
        dword |= ((1 & AQUILA_LPC_CTL_EN_IPMI_BT_MASK) << AQUILA_LPC_CTL_EN_IPMI_BT_SHIFT);
        dword &= ~((AQUILA_LPC_CTL_IPMI_BT_ADDR_MASK) << AQUILA_LPC_CTL_IPMI_BT_ADDR_SHIFT);
        dword |= ((0xe4 & AQUILA_LPC_CTL_IPMI_BT_ADDR_MASK) << AQUILA_LPC_CTL_IPMI_BT_ADDR_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);

        // Enable firmware cycle intercept
        dword = read_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1);
        dword |= ((1 & AQUILA_LPC_CTL_EN_FW_CYCLES_MASK) << AQUILA_LPC_CTL_EN_FW_CYCLES_SHIFT);
        write_aquila_register(HOSTLPCSLAVE_BASE, AQUILA_LPC_REG_CONTROL1, dword);
    }

    // Allocate internal host SPI Flash ROM buffer
2610
    host_flash_buffer = (uint8_t *)(MAIN_RAM_BASE + 0x3e00000);
2611 2612 2613 2614 2615 2616

    // Clear SPI Flash buffer
    printf("Clearing host ROM internal buffer...");
    memset32((uint32_t *)host_flash_buffer, 0xdeadbeef, 0x4000000 / 4);
    printf("\rInternal host ROM buffer cleared    \n");

2617
    display_character('1', 0); // STATUS CODE: 1
2618

2619
#if (WITH_SPI)
2620 2621 2622 2623 2624 2625 2626 2627
    host_spi_flash_init();

    // Detect and print attached host SPI Flash ID
    printf("Host SPI flash ID: 0x%08x\n", read_host_spi_flash_id());

    reset_flash_device();
    configure_flash_device();

2628 2629
    // Copy external SPI Flash ROM contents to internal host SPI Flash ROM buffer
    copy_spi_flash_to_internal_buffer(HOSTSPIFLASH_BASE, HOSTSPIFLASHCFG_BASE, host_flash_buffer);
2630

2631
#if (DEBUG_HOST_SPI_FLASH_READ)
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
    printf("host_flash_buffer: %p First 1KB:\n", host_flash_buffer);
    int byte = 0;
    int row = 0;
    for (row = 0; row < 32; row++)
    {
        for (byte = 0; byte < 32; byte++)
        {
            printf("%02x ", host_flash_buffer[byte + (row * 32)]);
        }
        printf("\n");
    }

    printf("[1/5] CRC of first 64B: %08x\n", crc32(host_flash_buffer, 1 * 64LL));
    printf("[2/5] CRC of first 1KB: %08x (next %08x, next %08x)\n", crc32(host_flash_buffer, 1024LL), crc32(host_flash_buffer + 1024LL, 1024LL),
           crc32(host_flash_buffer + (2 * 1024LL), 1024LL));
    printf("[3/5] CRC of first 1KB: %08x (next %08x, next %08x)\n", crc32(host_flash_buffer, 1024LL), crc32(host_flash_buffer + 1024LL, 1024LL),
           crc32(host_flash_buffer + (2 * 1024LL), 1024LL));
    printf("[4/5] CRC of first 1MB: %08x\n", crc32(host_flash_buffer, 1 * 1024 * 1024LL));
    printf("[5/5] CRC of full 64MB: %08x\n", crc32(host_flash_buffer, 64 * 1024 * 1024LL));

    // HBBL on test sytem is from 0x206200 to 0x207388 inclusive
    printf("\nHBBL region:\n");
    for (row = 0; row < 141; row++)
    {
        for (byte = 0; byte < 32; byte++)
        {
            printf("%02x ", *(host_flash_buffer + 0x206200ULL + (byte + (row * 32))));
            // printf("%02x ", *(host_flash_buffer + 0x1000ULL + (byte + (row *
            // 32))));
        }
        printf("\n");
    }
    printf("CRC of HBBL region: %08x\n", crc32(host_flash_buffer + 0x206200ULL, 4488));
2665
#endif
2666 2667
#endif

2668
    display_character('2', 0); // STATUS CODE: 2
2669

2670 2671 2672 2673 2674
    puts("\nRaptor Open FSP\nBuilt "__DATE__
         " "__TIME__
         "\n");
    help();
    prompt();
2675

2676 2677 2678 2679
    while (1)
    {
        console_service();
    }
2680

2681
    return 0;
2682
}