emulation: implement partial ec i2c

This implements some i2c functionality on the EC. Additionally, it
implements the Betrusted watchdog.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2021-08-30 12:36:04 +08:00
parent 0ae6d1460a
commit 5aaf166541
11 changed files with 1537 additions and 592 deletions

View file

@ -3,15 +3,21 @@ cpu: CPU.VexRiscv @ sysbus
PerformanceInMips: 6
uart: UART.LiteX_UART @ {
sysbus 0xE0001800
sysbus 0xE0003800
}
-> cpu@1000
-> cpu@1001
timer0: Timers.LiteX_Timer_32 @ {
sysbus 0xe0002000
sysbus 0xe0001000
}
frequency: 100000000
-> cpu@1001
-> cpu@1000
i2c: I2C.BetrustedEcI2C @ sysbus 0xE0004800
-> cpu @ 1002
ticktimer: Timers.TickTimer @ sysbus 0xe0005000
-> cpu @ 1003
sram: Memory.MappedMemory @ {
sysbus 0x10000000;
@ -19,16 +25,14 @@ sram: Memory.MappedMemory @ {
}
size: 0x00020000
ticktimer: Timers.TickTimer @ sysbus 0xe0005000
periodInMs: 1
-> cpu @ 1003
flash_mem: Memory.MappedMemory @ {
sysbus 0x20000000;
sysbus 0xA0000000 // shadow
}
size: 0x8000000
bq27421: Sensors.BQ27421 @ i2c 0x55
sysbus:
init:
ApplySVD @ec/soc.svd

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,346 @@
//
// Copyright (c) 2010-2020 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Antmicro.Renode.Core;
using Antmicro.Renode.Core.Structure.Registers;
using Antmicro.Renode.Logging;
using Antmicro.Renode.Peripherals.I2C;
using Antmicro.Renode.Peripherals.Sensor;
using Antmicro.Renode.Utilities;
using Antmicro.Renode.Exceptions;
namespace Antmicro.Renode.Peripherals.Sensors
{
public class BQ27421 : II2CPeripheral, IProvidesRegisterCollection<ByteRegisterCollection>, ISensor, ITemperatureSensor
{
public BQ27421()
{
RegistersCollection = new ByteRegisterCollection(this);
IRQ = new GPIO();
DefineRegisters();
}
public void FinishTransmission(){}
public void Reset()
{
RegistersCollection.Reset();
IRQ.Set(false);
regAddress = 0;
}
public void Write(byte[] data)
{
if(data.Length == 0 || data.Length == 1)
{
this.Log(LogLevel.Warning, "Unexpected write with no data");
return;
}
// The first byte contains our address.
this.Log(LogLevel.Noisy, "Write with {0} bytes of data: {1}", data.Length, Misc.PrettyPrintCollectionHex(data));
// The second byte contains the register address
regAddress = (Registers)data[1];
if(data.Length == 2)
{
this.Log(LogLevel.Noisy, "Preparing to read register {0} (0x{0:X})", regAddress);
readyPending.Value = true;
UpdateInterrupts();
return;
}
// // skip the two bytes as they contain our address and the register address
// foreach(var b in data.Skip(2))
// {
// this.Log(LogLevel.Noisy, "Writing 0x{0:X} to register {1} (0x{1:X})", b, regAddress);
// RegistersCollection.Write((byte)regAddress, b);
// }
if (data[1] == 0x00) {
var cmd = (data[2] << 0) | (data[3] << 8);
this.Log(LogLevel.Noisy, "Issuing control command (0x{0:X})", cmd);
switch (cmd) {
case 0x0000: response = controlStatus; break;
case 0x0012: controlStatus &= 0xffbf; break;
default: this.Log(LogLevel.Error, "Unhandled Control code: 0x{0:X}", cmd); break;
}
}
}
public byte[] Read(int count)
{
this.Log(LogLevel.Error, "Reading {0} bytes from register {1} (0x{1:X})", count, regAddress);
var result = new byte[count];
readyPending.Value = false;
UpdateInterrupts();
if (count >= 1) {
result[0] = (byte)(response & 0xff);
}
if (count >= 2) {
result[1] = (byte)((response >> 8) & 0xff);
}
// for(var i = 0; i < result.Length; i++)
// {
// result[i] = RegistersCollection.Read((byte)regAddress);
// this.Log(LogLevel.Error, "Read value {0}", result[i]);
// RegistersAutoIncrement();
// }
return result;
}
// public decimal AccelerationX
// {
// get => accelarationX;
// set
// {
// if (!IsAccelerationOutOfRange(value))
// {
// accelarationX = value;
// this.Log(LogLevel.Noisy, "AccelerationX set to {0}", accelarationX);
// }
// }
// }
// public decimal AccelerationY
// {
// get => accelarationY;
// set
// {
// if (!IsAccelerationOutOfRange(value))
// {
// accelarationY = value;
// this.Log(LogLevel.Noisy, "AccelerationY set to {0}", accelarationY);
// }
// }
// }
// public decimal AccelerationZ
// {
// get => accelarationZ;
// set
// {
// if (!IsAccelerationOutOfRange(value))
// {
// accelarationZ = value;
// this.Log(LogLevel.Noisy, "AccelerationZ set to {0}", accelarationZ);
// }
// }
// }
public decimal Temperature { get; set; }
public GPIO IRQ { get; }
public ByteRegisterCollection RegistersCollection { get; }
private void DefineRegisters()
{
// Registers.WhoAmI.Define(this, 0x43);
// Registers.Control1.Define(this) //RW
// .WithTaggedFlag("BLOCK_DATA_UPDATE", 0)
// .WithFlag(1, out highFreqDataRateMode, name: "HIGH_FREQ_MODE_ENABLE")
// .WithValueField(2, 2, out fullScale, name: "FULL_SCALE_SELECT")
// .WithValueField(4, 4, out outDataRate, name: "OUTPUT_DATA_RATE");
// Registers.Control4.Define(this, 0x01) //RW
// .WithFlag(0, out readyEnabled, name: "DATA_READY_IRQ1_ENABLE")
// .WithTaggedFlag("FIFO_THRESHOLD_IRQ1_ENABLE", 1)
// .WithTaggedFlag("6D_RECON_IRQ1_ENABLE", 2)
// .WithTaggedFlag("DOUBLE_TAP_RECON_IRQ1_ENABLE", 3)
// .WithTaggedFlag("FREE_FALL_RECON_IRQ1_ENABLE", 4)
// .WithTaggedFlag("WAKEUP_RECON_IRQ1_ENABLE", 5)
// .WithTaggedFlag("SINGLE_TAP_RECON_IRQ1_ENABLE", 6)
// .WithTaggedFlag("MASTER_DATA_READY_IRQ1_ENABLE", 7)
// .WithWriteCallback((_, __) => UpdateInterrupts());
Registers.Temp.Define(this)
.WithValueField(0, 8, FieldMode.Read, name: "TEMPERATURE_SENSOR", valueProviderCallback: _ => TwoComplementSignConvert(Temperature));
// Registers.Status.Define(this) //RO
// .WithFlag(0, out readyPending, FieldMode.Read, name: "XYZ_DATA_AVAILABLE")
// .WithTaggedFlag("FREE_FALL_EVENT_DETECT", 1)
// .WithTaggedFlag("CHANGE_IN_POSITION_DETECT", 2)
// .WithTaggedFlag("SINGLE_TAP_EVENT_DETECT", 3)
// .WithTaggedFlag("DOUBLE_TAP_EVENT_DETECT", 4)
// .WithTaggedFlag("SLEEP_EVENT_DETECT", 5)
// .WithTaggedFlag("WAKEUP_EVENT_DETECT", 6)
// .WithTaggedFlag("FIFO_REACH_THRESHOLD", 7);
// Registers.DataOutXLow.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "X_ACCEL_DATA[7:2]", valueProviderCallback: _ => Convert(AccelerationX, upperByte: false));
// Registers.DataOutXHigh.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "X_ACCEL_DATA[15:8]", valueProviderCallback: _ => Convert(AccelerationX, upperByte: true));
// Registers.DataOutYLow.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "Y_ACCEL_DATA[7:2]", valueProviderCallback: _ => Convert(AccelerationY, upperByte: false));
// Registers.DataOutYHigh.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "Y_ACCEL_DATA[15:8]", valueProviderCallback: _ => Convert(AccelerationY, upperByte: true));
// Registers.DataOutZLow.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "Z_ACCEL_DATA[7:2]", valueProviderCallback: _ => Convert(AccelerationZ, upperByte: false));
// Registers.DataOutZHigh.Define(this)
// .WithValueField(0, 8, FieldMode.Read, name: "Z_ACCEL_DATA[15:8]", valueProviderCallback: _ => Convert(AccelerationZ, upperByte: true));
// Registers.StatusEventDetection.Define(this) //RO
// .WithFlag(0, out readyPending, FieldMode.Read, name: "XYZ_DATA_AVAILABLE")
// .WithTaggedFlag("FREE_FALL_EVENT_DETECT", 1)
// .WithTaggedFlag("CHANGE_IN_POSITION_DETECT", 2)
// .WithTaggedFlag("SINGLE_TAP_EVENT_DETECT", 3)
// .WithTaggedFlag("DOUBLE_TAP_EVENT_DETECT", 4)
// .WithTaggedFlag("SLEEP_EVENT_DETECT", 5)
// .WithTaggedFlag("WAKEUP_EVENT_DETECT", 6)
// .WithTaggedFlag("FIFO_REACH_THRESHOLD", 7);
}
private void RegistersAutoIncrement()
{
// if(regAddress >= Registers.DataOutXLow && regAddress < Registers.DataOutZHigh)
// {
// regAddress = (Registers)((int)regAddress + 1);
// this.Log(LogLevel.Noisy, "Auto-incrementing to the next register 0x{0:X} - {0}", regAddress);
// }
}
private void UpdateInterrupts()
{
var status = readyEnabled.Value && readyPending.Value;
this.Log(LogLevel.Noisy, "Setting IRQ to {0}", status);
IRQ.Set(status);
}
// private decimal GetSenesorSensitivity()
// {
// decimal gain = SensorSensitivity;
// switch(fullScale.Value)
// {
// case (uint)FullScaleSelect.fullScale2g:
// gain = SensorSensitivity;
// break;
// case (uint)FullScaleSelect.fullScale16g:
// gain = 8 * SensorSensitivity;
// break;
// case (uint)FullScaleSelect.fullScale4g:
// gain = 2 * SensorSensitivity;
// break;
// case (uint)FullScaleSelect.fullScale8g:
// gain = 4 * SensorSensitivity;
// break;
// default:
// gain = SensorSensitivity;
// break;
// }
// return gain;
// }
// private bool IsAccelerationOutOfRange(decimal acceleration)
// {
// // This range protects from the overflow of the short variables in the 'Convert' function.
// if (acceleration < MinAcceleration || acceleration > MaxAcceleration)
// {
// this.Log(LogLevel.Warning, "Acceleration is out of range, use value from the range <-19.5;19.5>");
// return true;
// }
// return false;
// }
// private byte Convert(decimal value, bool upperByte)
// {
// byte result = 0;
// decimal gain = GetSenesorSensitivity();
// value = (value * 1000 / gain) / GravitationalConst;
// var valueAsShort = (short)value;
// if(upperByte)
// {
// result = (byte)(valueAsShort >> 8);
// }
// else
// {
// if(highFreqDataRateMode.Value &&
// outDataRate.Value >= (byte)DataRateModeStartRange.HighFreqDataRateStartRange &&
// outDataRate.Value < (byte)DataRateModeStartRange.LowPowerDataRateStartRange)
// {
// result = (byte)(valueAsShort & (byte)CoverBytes.HighFreqMode);
// this.Log(LogLevel.Noisy, "High frequencies mode is selected.");
// }
// else if(outDataRate.Value >= (byte)DataRateModeStartRange.LowPowerDataRateStartRange)
// {
// result = (byte)(valueAsShort & (byte)CoverBytes.LowPowerMode);
// this.Log(LogLevel.Noisy, "Low power mode is selected.");
// }
// else
// {
// result = (byte)(valueAsShort & (byte)CoverBytes.NoneExtraModes);
// this.Log(LogLevel.Noisy, "High frequencies and low power modes aren't selected.");
// }
// }
// return result;
// }
private byte TwoComplementSignConvert(decimal temp)
{
byte tempAsByte = Decimal.ToByte(temp);
if(temp < 0)
{
byte twoComplementTemp = (byte)(~tempAsByte + 1);
return twoComplementTemp;
}
return tempAsByte;
}
private IFlagRegisterField readyPending;
private IFlagRegisterField readyEnabled;
private IFlagRegisterField highFreqDataRateMode;
private IValueRegisterField outDataRate;
private IValueRegisterField fullScale;
private Registers regAddress;
private ushort controlStatus;
private ushort response;
private enum Registers : byte
{
Cntl = 0x00,
// Reserved: 0x01
Temp = 0x02,
// Reserved: 0x03
Volt = 0x04,
// Reserved: 0x05
Flag = 0x06,
// Reserved: 0x07
NomCap = 0x08,
// Reserved: 0x09
FullCap = 0x0A,
// Reserved: 0x0B
Rm = 0x0C,
// Reserved: 0x0d
Fcc = 0x0e,
// Reserved: 0x0f
AvgCur = 0x10,
// Reserved: 0x11
SbyCur = 0x12,
// Reserved: 0x13
MaxCur = 0x14,
// Reserved: 0x15 - 0x17
AvgPwr = 0x18,
// Reserved: 0x19 = 0x1b
Soc = 0x1c,
// Reserved: 0x1d
IntTemp = 0x1e,
// Reserved: 0x1f
Soh = 0x20,
}
}
}

View file

@ -0,0 +1,344 @@
//
// Copyright (c) 2010-2018 Antmicro
// Copyright (c) 2021 Precursor Project
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using System.Collections.Generic;
using System;
using Antmicro.Renode.Peripherals.Bus;
using Antmicro.Renode.Core.Structure.Registers;
using Antmicro.Renode.Core.Structure;
using Antmicro.Renode.Core;
using Antmicro.Renode.Logging;
using Antmicro.Renode.Time;
using System.Threading;
// This project is a reimplementation of the OpenCoresI2C module.
namespace Antmicro.Renode.Peripherals.I2C
{
[AllowedTranslations(AllowedTranslation.ByteToDoubleWord)]
public class BetrustedEcI2C : SimpleContainer<II2CPeripheral>, IDoubleWordPeripheral, IKnownSize
{
public BetrustedEcI2C(Machine machine) : base(machine)
{
dataToSlave = new Queue<byte>();
dataFromSlave = new Queue<byte>();
IRQ = new GPIO();
irqTimeoutCallback = new ClockEntry((ulong)5, ClockEntry.FrequencyToRatio(machine, 1000), this.FinishTransaction, machine, "Irq Scheduler");
var registersMap = new Dictionary<long, DoubleWordRegister>()
{
{(long)Registers.Prescale, new DoubleWordRegister(this)
.WithValueField(0, 16, FieldMode.Read | FieldMode.Write)
},
{(long)Registers.Control, new DoubleWordRegister(this)
.WithFlag(7, out enabled)
.WithTag("Interrupt enable", 6, 1)
.WithReservedBits(0, 6)
},
{(long)Registers.Txr, new DoubleWordRegister(this)
.WithValueField(0, 8, out transmitBuffer, FieldMode.Write)
},
{(long)Registers.Rxr, new DoubleWordRegister(this)
.WithValueField(0, 8, out receiveBuffer, FieldMode.Read)
},
{(long)Registers.Status, new DoubleWordRegister(this)
.WithFlag(7, out receivedAckFromSlaveNegated, FieldMode.Read)
.WithFlag(6, FieldMode.Read, valueProviderCallback: _ => false, name: "Busy")
.WithFlag(5, FieldMode.Read, valueProviderCallback: _ => false, name: "Arbitration lost")
.WithReservedBits(2, 3)
.WithFlag(1, FieldMode.Read, valueProviderCallback: _ => false, name: "Transfer in progress")
.WithFlag(0, out i2cIrqStatus, FieldMode.Read)
},
{(long)Registers.Command, new DoubleWordRegister(this)
.WithFlag(7, out generateStartCondition, FieldMode.Write)
.WithFlag(6, out generateStopCondition, FieldMode.Write)
.WithFlag(5, out readFromSlave, FieldMode.Write)
.WithFlag(4, out writeToSlave, FieldMode.Write)
.WithFlag(3, FieldMode.Read, name: "ACK", valueProviderCallback: _ => true)
// .WithTag("ACK", 3, 1)
.WithReservedBits(1, 2)
.WithFlag(0, FieldMode.Write, writeCallback: (_, __) => i2cIrqStatus.Value = false)
.WithWriteCallback((_, __) =>
{
if(!enabled.Value)
{
return;
}
if(generateStartCondition.Value)
{
generateStartCondition.Value = false;
if(transactionInProgress)
{
// repeated start - finish previous transaction first
SendDataToSlave();
}
else
{
transactionInProgress = true;
}
dataFromSlave.Clear();
if (selectedSlave != null) {
selectedSlave.FinishTransmission();
}
if(!TryResolveSelectedSlave(out selectedSlave))
{
return;
}
}
if(writeToSlave.Value)
{
writeToSlave.Value = false;
HandleWriteToSlaveCommand();
}
if(readFromSlave.Value)
{
readFromSlave.Value = false;
HandleReadFromSlaveCommand();
}
if (transactionInProgress && 0 == Interlocked.CompareExchange(ref irqTimeoutCallbackQueued, 1, 0)) {
// this.Log(LogLevel.Error, "I2C: Adding clock entry for {0}",this.irqTimeoutCallback);
try {
machine.ClockSource.AddClockEntry(irqTimeoutCallback);
} catch (ArgumentException ex) {
this.Log(LogLevel.Error, "Unable to add clock entry for timeout (queued: {0}): {1}", ex, irqTimeoutCallbackQueued);
// this.Log(LogLevel.Error, "I2C: Done adding clock entry for {0}",this.irqTimeoutCallback);
}
}
if(generateStopCondition.Value)
{
if (selectedSlave != null) {
selectedSlave.FinishTransmission();
}
generateStopCondition.Value = false;
if(!transactionInProgress)
{
return;
}
SendDataToSlave();
transactionInProgress = false;
}
shouldSendTxRxIrq = true;
})
},
{(long)Registers.EventStatus, new DoubleWordRegister(this)
.WithFlag(3, FieldMode.Read, name: "USBCC_INT_STATUS", valueProviderCallback: _ => usbccIrqStatus)
.WithFlag(2, FieldMode.Read, name: "GYRO_INT_STATUS", valueProviderCallback: _ => gyroIrqStatus)
.WithFlag(1, FieldMode.Read, name: "GG_INT_STATUS", valueProviderCallback: _ => ggIrqStatus)
.WithFlag(0, FieldMode.Read, name: "I2C_INT_STATUS", valueProviderCallback: _ => i2cIrqStatus.Value)
},
{(long)Registers.EventPending, new DoubleWordRegister(this)
.WithFlag(3, out usbccIrqPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "USBCC_INT_PENDING", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(2, out gyroIrqPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "GYRO_INT_PENDING", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(1, out ggIrqPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "GG_INT_PENDING", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(0, out i2cIrqPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "I2C_INT_PENDING", changeCallback: (_, __) => UpdateInterrupts())
},
{(long)Registers.EventEnable, new DoubleWordRegister(this)
.WithFlag(3, out usbccIrqEnabled, name: "USBCC_INT_ENABLE", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(2, out gyroIrqEnabled, name: "GYRO_INT_ENABLE", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(1, out ggIrqEnabled, name: "GG_INT_ENABLE", changeCallback: (_, __) => UpdateInterrupts())
.WithFlag(0, out i2cIrqEnabled, name: "I2C_INT_ENABLE", changeCallback: (_, __) => UpdateInterrupts())
}
};
registers = new DoubleWordRegisterCollection(this, registersMap);
UpdateInterrupts();
}
private void FinishTransaction()
{
// this.Log(LogLevel.Error, "I2C: Removing clock entry for {0}",this.irqTimeoutCallback);
machine.ClockSource.RemoveClockEntry(FinishTransaction);
irqTimeoutCallbackQueued = 0;
if (shouldSendTxRxIrq)
{
shouldSendTxRxIrq = false;
txRxDoneIrqStatus = true;
UpdateInterrupts();
txRxDoneIrqStatus = false;
}
}
public override void Reset()
{
registers.Reset();
dataToSlave.Clear();
dataFromSlave.Clear();
UpdateInterrupts();
}
public uint ReadDoubleWord(long offset)
{
return registers.Read(offset);
}
public void WriteDoubleWord(long offset, uint value)
{
registers.Write(offset, value);
}
private void UpdateInterrupts()
{
if (i2cIrqStatus.Value)
{
i2cIrqPending.Value = true;
}
if (ggIrqStatus)
{
ggIrqPending.Value = true;
}
if (gyroIrqStatus)
{
gyroIrqPending.Value = true;
}
if (usbccIrqStatus)
{
usbccIrqPending.Value = true;
}
// this.Log(LogLevel.Noisy, " Setting status: {0}, enabled: {1}, pending: {2}", txRxDoneIrqStatus, txRxDoneIrqEnabled.Value, txRxDoneIrqPending.Value);
IRQ.Set((i2cIrqPending.Value && i2cIrqEnabled.Value)
|| (ggIrqPending.Value && ggIrqEnabled.Value)
|| (gyroIrqPending.Value && gyroIrqEnabled.Value)
|| (usbccIrqPending.Value && usbccIrqEnabled.Value)
);
}
public GPIO IRQ
{
get;
private set;
}
public long Size { get { return 0x800; } }
private bool TryResolveSelectedSlave(out II2CPeripheral selectedSlave)
{
var slaveAddress = (byte)(transmitBuffer.Value >> 1);
if (!ChildCollection.TryGetValue(slaveAddress, out selectedSlave))
{
this.Log(LogLevel.Warning, "Addressing unregistered slave: 0x{0:X}", slaveAddress);
receivedAckFromSlaveNegated.Value = true;
return false;
}
receivedAckFromSlaveNegated.Value = false;
return true;
}
private void HandleReadFromSlaveCommand()
{
if (dataFromSlave.Count == 0)
{
foreach (var b in selectedSlave.Read())
{
dataFromSlave.Enqueue(b);
}
if (dataFromSlave.Count == 0)
{
this.Log(LogLevel.Warning, "Trying to read from slave, but no data is available");
receiveBuffer.Value = 0;
return;
}
}
receiveBuffer.Value = dataFromSlave.Dequeue();
UpdateInterrupts();
}
private void SendDataToSlave()
{
if (dataToSlave.Count == 0 || selectedSlave == null)
{
this.Log(LogLevel.Warning, "Trying to send data to slave, but either no data is available or the slave is not selected");
return;
}
selectedSlave.Write(dataToSlave.ToArray());
dataToSlave.Clear();
}
private void HandleWriteToSlaveCommand()
{
if (!transactionInProgress)
{
this.Log(LogLevel.Warning, "Writing to slave without generating START signal");
return;
}
dataToSlave.Enqueue((byte)transmitBuffer.Value);
i2cIrqStatus.Value = true;
UpdateInterrupts();
}
private bool transactionInProgress;
private II2CPeripheral selectedSlave;
private readonly Queue<byte> dataToSlave;
private readonly Queue<byte> dataFromSlave;
private readonly IValueRegisterField receiveBuffer;
private readonly IValueRegisterField transmitBuffer;
private readonly IFlagRegisterField readFromSlave;
private readonly IFlagRegisterField writeToSlave;
private IFlagRegisterField i2cIrqEnabled;
private IFlagRegisterField ggIrqEnabled;
private IFlagRegisterField gyroIrqEnabled;
private IFlagRegisterField usbccIrqEnabled;
private IFlagRegisterField i2cIrqStatus;
private bool ggIrqStatus;
private bool gyroIrqStatus;
private bool usbccIrqStatus;
private IFlagRegisterField i2cIrqPending;
private IFlagRegisterField ggIrqPending;
private IFlagRegisterField gyroIrqPending;
private IFlagRegisterField usbccIrqPending;
private bool shouldSendTxRxIrq;
private bool txRxDoneIrqStatus;
private long irqTimeoutCallbackQueued;
private readonly IFlagRegisterField enabled;
private readonly IFlagRegisterField receivedAckFromSlaveNegated;
private readonly IFlagRegisterField generateStartCondition;
private readonly IFlagRegisterField generateStopCondition;
private readonly DoubleWordRegisterCollection registers;
private ClockEntry irqTimeoutCallback;
private enum Registers
{
Prescale = 0x0,
Control = 0x4,
Txr = 0x8,
Rxr = 0xC,
Command = 0x10,
Status = 0x14,
BitbangMode = 0x18,
Bb = 0x1c,
BbR = 0x20,
EventStatus = 0x24,
EventPending = 0x28,
EventEnable = 0x2c
}
}
}

View file

@ -58,6 +58,14 @@ namespace Antmicro.Renode.Peripherals.I2C
.WithFlag(0, out i2cIntIrqStatus, FieldMode.Read)
},
{(long)Registers.CoreReset, new DoubleWordRegister(this)
.WithFlag(0, FieldMode.Write, writeCallback: (_, do_it) => {
if (do_it) {
Reset();
}
})
},
{(long)Registers.EventStatus, new DoubleWordRegister(this)
.WithFlag(1, FieldMode.Read, name: "TX_RX_DONE_STATUS", valueProviderCallback: _ => txRxDoneIrqStatus)
.WithFlag(0, FieldMode.Read, name: "I2C_INT_STATUS", valueProviderCallback: _ => i2cIntIrqStatus.Value)
@ -184,16 +192,17 @@ namespace Antmicro.Renode.Peripherals.I2C
private void UpdateInterrupts()
{
if (i2cIntIrqStatus.Value && i2cIntIrqEnabled.Value)
if (i2cIntIrqStatus.Value)
{
i2cIntIrqPending.Value = true;
}
if (txRxDoneIrqStatus && txRxDoneIrqEnabled.Value)
if (txRxDoneIrqStatus)
{
txRxDoneIrqPending.Value = true;
}
// this.Log(LogLevel.Noisy, " Setting status: {0}, enabled: {1}, pending: {2}", txRxDoneIrqStatus, txRxDoneIrqEnabled.Value, txRxDoneIrqPending.Value);
IRQ.Set(i2cIntIrqPending.Value || txRxDoneIrqPending.Value);
IRQ.Set((i2cIntIrqPending.Value && txRxDoneIrqEnabled.Value)
|| (txRxDoneIrqPending.Value && i2cIntIrqEnabled.Value));
}
public GPIO IRQ
@ -295,7 +304,7 @@ namespace Antmicro.Renode.Peripherals.I2C
Receive = 0xC,
Command = 0x10,
Status = 0x14,
Reset = 0x18,
CoreReset = 0x18,
EventStatus = 0x1c,
EventPending = 0x20,
EventEnable = 0x24

View file

@ -0,0 +1,101 @@
//
// Copyright (c) 2010-2018 Antmicro
// Copyright (c) 2011-2015 Realtime Embedded
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using Antmicro.Renode.Core;
using Antmicro.Renode.Core.Structure.Registers;
using Antmicro.Renode.Peripherals.Bus;
using Antmicro.Renode.Time;
using System.Threading;
using System.Collections.Generic;
using System;
namespace Antmicro.Renode.Peripherals.Timers
{
public sealed class BetrustedWatchdog : BasicDoubleWordPeripheral, IKnownSize
{
public BetrustedWatchdog(Machine machine) : base(machine)
{
machine.ClockSource.AddClockEntry(new ClockEntry(10, ClockEntry.FrequencyToRatio(this, 1000), OnTick, this, String.Empty));
var registersMap = new Dictionary<long, DoubleWordRegister>()
{
{(long)Registers.Watchdog, new DoubleWordRegister(this)
.WithFlag(1, FieldMode.Read | FieldMode.Write, (_, enable) => {
if (enable) {
enabled = true;
}
})
.WithFlag(0, FieldMode.Read | FieldMode.Write, (_, should_reset) => {
Interlocked.Exchange(ref counter, 0);
})
},
{(long)Registers.Period, new DoubleWordRegister(this)
.WithValueField(0, 32, FieldMode.Read | FieldMode.Write, (_, period) => {
this.reset_target = XilinxClockToMs(period);
})
},
{(long)Registers.State, new DoubleWordRegister(this)
.WithFlag(0, FieldMode.Read, valueProviderCallback: (_) => enabled, name: "ENABLED")
.WithFlag(1, FieldMode.Read, valueProviderCallback: (_) => false, name: "ARMED1")
.WithFlag(2, FieldMode.Read, valueProviderCallback: (_) => false, name: "ARMED2")
.WithFlag(3, FieldMode.Read, valueProviderCallback: (_) => false, name: "DISARMED")
},
};
registers = new DoubleWordRegisterCollection(this, registersMap);
Reset();
}
private void OnTick()
{
Interlocked.Increment(ref counter);
if (((uint)counter) >= this.reset_target) {
this.machine.RequestReset();
}
}
public override uint ReadDoubleWord(long offset)
{
return registers.Read(offset);
}
public override void WriteDoubleWord(long offset, uint value)
{
registers.Write(offset, value);
}
public override void Reset()
{
registers.Reset();
enabled = false;
counter = 0;
reset_target = XilinxClockToMs(325000000);
}
// Convert "approximately 65MHz" ticks to milliseconds
private uint XilinxClockToMs(uint xilinx_clocks)
{
return (uint) ((((ulong)xilinx_clocks) * 1000) / 65000000);
}
public long Size
{
get
{
return 0xC;
}
}
private int counter;
private uint reset_target;
private bool enabled;
private readonly DoubleWordRegisterCollection registers;
private enum Registers
{
Watchdog = 0x0,
Period = 0x4,
State = 0x8,
}
}
}

View file

@ -0,0 +1,113 @@
//
// Copyright (c) 2010-2018 Antmicro
// Copyright (c) 2011-2015 Realtime Embedded
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using System;
using Antmicro.Renode.Core;
using System.Linq;
using Antmicro.Renode.Time;
using Antmicro.Renode.Exceptions;
using Antmicro.Migrant.Hooks;
using Antmicro.Renode.Peripherals.SPI;
using System.Collections.Generic;
namespace Antmicro.Renode.Peripherals.UART
{
public static class SPIHubExtensions
{
public static void CreateSPIHub(this Emulation emulation, string name)
{
emulation.ExternalsManager.AddExternal(new SPIBus(), name);
}
}
public sealed class SPIBus : IExternal, IHasOwnLife, IConnectable<ISPIPeripheral>
{
public SPIBus()
{
peripherals = new Dictionary<ISPIPeripheral, Func<byte, byte>>();
locker = new object();
}
public void AttachTo(ISPIPeripheral peripheral)
{
lock (locker)
{
if (peripherals.ContainsKey(peripheral))
{
throw new RecoverableException("Cannot attach to the provided UART as it is already registered in this hub.");
}
var d = (Func<byte, byte>)(x => HandleByteTransmitted(x, peripheral));
peripherals.Add(peripheral, d);
// peripheral.CharReceived += d;
}
}
public void Start()
{
Resume();
}
public void Pause()
{
started = false;
}
public void Resume()
{
started = true;
}
public void DetachFrom(ISPIPeripheral peripheral)
{
lock (locker)
{
if (!peripherals.ContainsKey(peripheral))
{
throw new RecoverableException("Cannot detach the provided SPI peripheral as it is not registered in this bus.");
}
// uart.CharReceived -= uarts[uart];
peripherals.Remove(peripheral);
}
}
private byte HandleByteTransmitted(byte obj, ISPIPeripheral peripheral)
{
if (!started)
{
return 0;
}
lock (locker)
{
foreach (var item in uarts.Where(x => x.Key != sender).Select(x => x.Key))
{
item.GetMachine().HandleTimeDomainEvent(item.WriteChar, obj, TimeDomainsManager.Instance.VirtualTimeStamp);
}
}
return 0;
}
[PostDeserialization]
private void ReattachUARTsAfterDeserialization()
{
lock (locker)
{
foreach (var uart in uarts)
{
uart.Key.CharReceived += uart.Value;
}
}
}
private bool started;
private readonly Dictionary<ISPIPeripheral, Func<byte, byte>> peripherals;
private readonly object locker;
}
}

View file

@ -5,15 +5,15 @@ cpu: CPU.VexRiscv @ sysbus
privilegeArchitecture: PrivilegeArchitecture.Priv1_10
PerformanceInMips: 120
// Platform Peripherals
// Unrecognized peripheral: reboot
// Unrecognized peripheral: reboot @ 0xf0000000
timer0: Timers.LiteX_Timer_32 @ sysbus 0xf0001000
frequency: 100000000
-> cpu @ 1000
// Unrecognized peripheral: crg
// Unrecognized peripheral: crg @ 0xf0002000
// Unrecognized peripheral: gpio
// Unrecognized peripheral: gpio @ 0xf0003000
uart: UART.LiteX_UART @ sysbus 0xf0005000
-> cpu @ 1002
@ -24,47 +24,47 @@ console: UART.LiteX_UART @ sysbus 0xf0007000
app_uart: UART.LiteX_UART @ sysbus 0xf0009000
-> cpu @ 1004
// Unrecognized peripheral: info
// Unrecognized peripheral: info @ 0xf000a000
// Unrecognized peripheral: sram_ext
// Unrecognized peripheral: sram_ext @ 0xf000b000
memlcd: Video.BetrustedLCD @ sysbus 0xf000c000
memAddr: 0xb0000000
memSize: 0x5c20
// Unrecognized peripheral: com
// Unrecognized peripheral: com @ 0xf000d000
i2c: I2C.BetrustedI2C @ sysbus 0xf000e000
-> cpu @ 1006
// Unrecognized peripheral: btevents
// Unrecognized peripheral: btevents @ 0xf000f000
// Unrecognized peripheral: messible
// Unrecognized peripheral: messible @ 0xf0010000
// Unrecognized peripheral: messible2
// Unrecognized peripheral: messible2 @ 0xf0011000
ticktimer: Timers.TickTimer @ sysbus 0xf0012000
-> cpu @ 1008
// Unrecognized peripheral: susres
// Unrecognized peripheral: susres @ 0xf0013000
// Unrecognized peripheral: power
// Unrecognized peripheral: power @ 0xf0014000
spinor_soft_int: Miscellaneous.SpinorSoftInt @ sysbus 0xf0015000
-> cpu @ 1011
// Unrecognized peripheral: spinor
// Unrecognized peripheral: spinor @ 0xf0016000
keyboard: Input.BetrustedKbd @ sysbus 0xf0017000
-> cpu @ 1013
// Unrecognized peripheral: keyinject
// Unrecognized peripheral: keyinject @ 0xf0018000
// Unrecognized peripheral: seed
// Unrecognized peripheral: seed @ 0xf0019000
keyrom: Miscellaneous.Keyrom @ sysbus 0xf001a000
// Unrecognized peripheral: audio
// Unrecognized peripheral: audio @ 0xf001b000
trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xf001c000
-> cpu @ 1015
@ -72,7 +72,7 @@ trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xf001c000
trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xf001d000
-> cpu @ 1016
// Unrecognized peripheral: trng
// Unrecognized peripheral: trng @ 0xf001e000
sha512: Miscellaneous.Sha512 @ sysbus 0xf001f000
memAddr: 0xe0002000
@ -84,15 +84,15 @@ engine: Miscellaneous.Engine @ sysbus 0xf0020000
memSize: 0x20000
-> cpu @ 1018
// Unrecognized peripheral: jtag
// Unrecognized peripheral: jtag @ 0xf0021000
// Unrecognized peripheral: wdt
wdt: Timers.BetrustedWatchdog @ sysbus 0xf0022000
// Unrecognized peripheral: d11ctime
// Unrecognized peripheral: d11ctime @ 0xf0023000
wfi: Miscellaneous.BetrustedWfi @ sysbus 0xf0024000
// Unrecognized peripheral: identifier_mem
// Unrecognized peripheral: identifier_mem @ 0xf0025000
// Physical base addresses of memory regions

View file

@ -9,7 +9,10 @@ using sysbus
# Add peripherals that are defined in C#. You must restart Renode
# if you modify these files.
i @peripherals/ABRTCMC.cs
i @peripherals/BetrustedEcI2C.cs
i @peripherals/BetrustedI2C.cs
i @peripherals/BetrustedWatchdog.cs
i @peripherals/BQ27421.cs
i @peripherals/engine.cs
i @peripherals/keyboard.cs
i @peripherals/keyrom.cs
@ -46,9 +49,9 @@ sysbus Tag <0xB0000000, 0xB0006000> "Framebuffer"
# logLevel -1 sha512
# Silence COM and WDT and WFI
sysbus SilenceRange <0xF000D000, 0xF000DFFF>
sysbus SilenceRange <0xF0021000, 0xF0021FFF>
sysbus SilenceRange <0xF0023000, 0xF0023FFF>
# sysbus SilenceRange <0xF000D000, 0xF000DFFF>
# sysbus SilenceRange <0xF0021000, 0xF0021FFF>
# sysbus SilenceRange <0xF0023000, 0xF0023FFF>
# The macro `reset` gets called implicitly when running `machine Reset`
macro reset
@ -80,8 +83,7 @@ macro reset
"""
runMacro $reset
# Silence I2C for now while we work on the driver
sysbus SilenceRange <0xB0000000, 0xB000FFFF>
logLevel -1 bq27421
mach clear

View file

@ -592,7 +592,7 @@ fn print_peripherals<U: Write>(
writeln!(out, " -> cpu @ {}", 1000 + irq.value)?;
}
} else {
writeln!(out, "// Unrecognized peripheral: {}", lc_name)?;
writeln!(out, "// Unrecognized peripheral: {} @ 0x{:08x}", lc_name, peripheral.base)?;
}
writeln!(out)?;
}
@ -645,6 +645,7 @@ pub fn generate<T: Read, U: Write>(src: T, dest: &mut U) -> Result<(), ParseErro
cs_peripherals.insert("ticktimer", "Timers.TickTimer");
cs_peripherals.insert("uart", "UART.LiteX_UART");
cs_peripherals.insert("wfi", "Miscellaneous.BetrustedWfi");
cs_peripherals.insert("wdt", "Timers.BetrustedWatchdog");
print_header(dest).or(Err(ParseError::WriteError))?;
print_peripherals(