Unified the 400x state machine for address latching

Fixed timing issues
This commit is contained in:
Jan-Peter von Hunnius 2025-11-14 18:51:10 +01:00
parent e17d6ad177
commit 633463e370
26 changed files with 11904 additions and 2471 deletions

View file

@ -1,269 +1,296 @@
# Hardware Components
# Rusty Emu - Cross-Platform System Emulator
This directory contains implementations of various hardware components used in the Intel 4004 microprocessor system and
other architectures.
![Rust](https://img.shields.io/badge/language-Rust-orange.svg)
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Platform](https://img.shields.io/badge/platform-cross--platform-lightgrey.svg)
## Component Architecture
## 🎯 Project Overview
All components implement the base `Component` trait defined in `src/component.rs`, which provides:
**Rusty Emu** is a modular, cross-platform system emulator written in Rust, designed to emulate various historical computing systems and embedded devices with a focus on accuracy and performance.
- **Pin Management**: Components expose named pins for interconnection
- **Lifecycle Management**: Components can be started, stopped, and updated
- **Thread Safety**: All components are `Send + Sync` for concurrent access
- **State Management**: Components maintain internal state and respond to clock cycles
### Currently Supported Systems
## Component Categories
| System | Status | Description |
|--------|---------|-------------|
| **Intel MCS-4** | ✅ Implemented | Historical 4-bit microprocessor family |
| **Commodore VIC-20** | 🔄 Planned | Classic 8-bit home computer |
| **Yamaha TG100** | 🔄 Planned | AWM tone generator module |
### CPU Components (`cpu/`)
---
#### Intel 4004 CPU
## 🏗️ Architecture
- **File**: `intel_4004.rs`
- **Features**:
- Complete Intel 4004 instruction set implementation
- 4-bit data processing
- 12-bit address space
- Two-phase clock operation (Φ1, Φ2)
- 16 general-purpose registers (8 index, 8 main)
- Stack-based subroutine calls
- **Status**: Fully implemented with comprehensive testing
### Core Components
```text
rusty_emu/
├── src/
│ ├── core/ # Emulator core infrastructure
│ │ ├── cpu/ # CPU emulation base
│ │ ├── memory/ # Memory management
│ │ └── peripherals/ # I/O device handling
│ ├── systems/ # System-specific implementations
│ │ ├── intel_mcs4/ # Intel MCS-4 emulation
│ │ ├── vic20/ # VIC-20 emulation (planned)
│ │ └── yamaha_tg100/ # Yamaha TG100 emulation (planned)
│ └── ui/ # User interface components
```
---
#### MOS 6502 CPU (Placeholder)
### Key Features
- **File**: `mos_6502.rs`
- **Features**: Placeholder for MOS Technology 6502 implementation
- **Status**: Not yet implemented
- **Modular Design**: Easily extensible for new systems
- **Cross-Platform**: Runs on Windows, macOS, and Linux
- **Cycle-Accurate**: Precise timing emulation
- **Debugging Support**: Built-in debugging capabilities
- **Hardware Rendering**: Efficient graphics emulation
#### WDC 65C02 CPU (Placeholder)
---
- **File**: `wdc_65c02.rs`
- **Features**: Placeholder for Western Design Center 65C02 implementation
- **Status**: Not yet implemented
## 🚀 Getting Started
### Memory Components (`memory/`)
### Prerequisites
#### Intel 4001 ROM
- Rust **1.70+** toolchain
- Cargo package manager
- System dependencies for graphics/audio
- **File**: `intel_4001.rs`
- **Features**:
- 256 bytes of mask-programmable ROM
- 4-bit I/O ports for peripheral interface (datasheet-compliant)
- Two-phase addressing (8-bit address in two 4-bit cycles)
- 500ns typical access time
- SYNC signal detection for instruction fetch
- I/O port addressing via SRC instruction (ports 0-3)
- WRM/RDM instruction support for I/O operations
- I/O direction control (input/output per port)
- I/O latch persistence as per datasheet specifications
- **Status**: Fully implemented with comprehensive testing
### Installation
##### I/O Port Features
```bash
# Clone the repository
git clone https://github.com/jhunnius/rusty_emu.git
cd rusty_emu
- **Port Addressing**: I/O ports 0-3 addressed using lower 2 bits of address
- **Direction Control**: Each port can be configured as input or output
- **Latch Persistence**: Output values persist until changed or reset
- **CPU Control**: I/O operations controlled by WRM/RDM instructions
- **Pin Interface**: IO0-IO3 pins for external peripheral connection
# Build in release mode
cargo build --release
#### Intel 4002 RAM
- **File**: `intel_4002.rs`
- **Features**:
- 320 bits of read/write memory (80 × 4-bit characters)
- 4-bit output port for status/display
- Banked memory organization (4 banks × 20 characters)
- Refresh circuitry for dynamic memory cells
- Status character instructions for control
- **Status**: Implemented with known limitations
#### Intel 4003 Shift Register
- **File**: `intel_4003.rs`
- **Features**:
- 10-bit static shift register
- Serial input/output capability
- Parallel input from data bus
- 200ns typical access time
- Bidirectional shifting
- **Status**: Basic implementation
#### Generic Memory Components
- **GenericRAM**: `generic_ram.rs` - Configurable RAM implementation
- **GenericROM**: `generic_rom.rs` - Configurable ROM implementation
### Common Functionality (`common/`)
#### Intel 400x Series Common Code
- **File**: `intel_400x.rs`
- **Purpose**: Shared functionality for all Intel 400x series chips
- **Features**:
- Common timing constants and state machines
- Clock edge detection and handling
- Data bus operations and bit manipulation
- Address latching and assembly logic
- Control pin reading and management
- Reset handling and initialization
- Memory operation state machines
### Clock Components (`clock/`)
#### Generic Clock Generator
- **File**: `generic_clock.rs`
- **Features**:
- Configurable frequency and duty cycle
- Multiple output waveforms
- Synchronization capabilities
- Test pattern generation
- **Status**: Basic implementation
## Component Interface
### Required Methods
All components must implement:
```rust
fn name(&self) -> String; // Component identifier
fn pins(&self) -> HashMap<String, Arc<Mutex<Pin>>>; // Pin configuration
fn get_pin(&self, name: &str) -> Result<Arc<Mutex<Pin>>, String>; // Pin access
fn update(&mut self); // Process one clock cycle
fn run(&mut self); // Continuous execution
fn stop(&mut self); // Graceful shutdown
fn is_running(&self) -> bool; // Execution status
# Run with specific system
cargo run --release -- --system intel_mcs4 --rom path/to/rom.bin
```
### Optional Traits
### Quick Examples
Components can implement additional traits for specialized functionality:
```bash
# Emulate Intel MCS-4 system
./rusty_emu --system intel_mcs4 --rom examples/mcs4/demo.rom
- **RunnableComponent**: Automatic thread spawning
# Enable debug mode
./rusty_emu --system intel_mcs4 --rom demo.rom --debug
## Pin Configuration
# Load with specific configuration
./rusty_emu --system intel_mcs4 --rom demo.rom --config mcs4_config.toml
```
### Standard Pin Types
---
- **Data Pins**: `D0-D3` for 4-bit data/address bus
- **Clock Pins**: `PHI1`, `PHI2` for two-phase clock
- **Control Pins**: `SYNC`, `RESET`, `CM`, `CI` for system control
- **I/O Pins**: `IO0-IO3` for peripheral interface
## 📋 System Specifications
### Pin Signal States
### Intel MCS-4 Implementation
- **High**: Logic level 1
- **Low**: Logic level 0
- **HighZ**: High impedance (tri-state, not driving)
**Supported Components:**
✅ Intel 4004 CPU (4-bit processor)
✅ 4001 ROM (2560-bit ROM with I/O)
✅ 4002 RAM (320-bit RAM with output port)
✅ 4003 Shift Register (10-bit I/O expander)
## Usage Examples
**Memory Architecture:**
- Instruction ROM: 4KB
- Data RAM: 1280 bits
- I/O Ports: Multiple 4-bit ports
### Creating and Using a Component
---
### VIC-20 Emulation (Planned)
**Target Specifications:**
- CPU: MOS 6502 @ 1.108 MHz
- Memory: 5KB RAM (expandable to 32KB)
- Graphics: VIC-I chip, 176×184 resolution
- Sound: 3 voices + noise
- I/O: Tape, Serial, User Port
---
### Yamaha TG100 Emulation (Planned)
**Target Features:**
- Tone Generation: AWM (Advanced Wave Memory)
- Polyphony: 16–32 voices
- Effects: Reverb, Chorus
- MIDI Implementation
---
## 🛠️ Development
### Adding New Systems
**Create System Module**
```rust
use rusty_emu::components::memory::intel_4001::Intel4001;
// systems/my_system/mod.rs
pub struct MySystem {
cpu: MyCpu,
memory: MemoryMap,
peripherals: Vec<Box<dyn Peripheral>>,
}
// Create a ROM component
let mut rom = Intel4001::new("ROM1".to_string());
// Load program data
let program = vec![0x12, 0x34, 0x56, 0x78];
rom.load_rom_data(program, 0) ?;
// Use in simulation loop
while simulation_running() {
rom.update(); // Process one clock cycle
impl System for MySystem {
fn step(&mut self) -> EmulatorResult<()> {
// System emulation logic
}
}
```
### Component Interconnection
**Implement CPU Core**
```rust
// Components connect through shared pin references
let cpu_pin = cpu.get_pin("D0") ?;
let rom_pin = rom.get_pin("D0") ?;
let ram_pin = ram.get_pin("D0") ?;
// Connect pins together
connect_pins(vec![cpu_pin, rom_pin, ram_pin]) ?;
// systems/my_system/cpu.rs
impl Cpu for MyCpu {
fn execute_instruction(&mut self) -> EmulatorResult<()> {
// Instruction execution
}
}
```
## Testing Strategy
**Register System**
```rust
// src/lib.rs
pub mod systems {
pub mod my_system;
}
```
### Unit Tests
---
- Located in each component's implementation file
- Test individual component behavior in isolation
- Focus on state management and pin operations
### Building from Source
```bash
# Debug build with logging
RUST_LOG=debug cargo build
### Integration Tests
# Run tests
cargo test
- Located in `tests/` directory
- Test component interactions and system behavior
- Verify proper timing and signal propagation
# Benchmark performance
cargo bench
### Mock-Based Tests
# Check code quality
cargo clippy
cargo fmt
```
- Use mock components for controlled testing
- Test error conditions and edge cases
- Verify behavior with various input patterns
---
## Development Guidelines
## 🧪 Testing
```bash
# Run all tests
cargo test
### Adding New Components
# System-specific tests
cargo test --test intel_mcs4
1. **Implement Core Traits**: Start with `Component` trait implementation
2. **Define Pin Configuration**: Specify required pins and their purposes
3. **Implement Timing**: Add clock cycle processing in `update()` method
4. **Add Specialized Functionality**: Implement component-specific methods and behaviors as needed
5. **Write Tests**: Add comprehensive unit tests for the new component
6. **Update Exports**: Add the component to the appropriate module exports
# Integration tests
cargo test --test integration
### Component Design Principles
# Performance benchmarks
cargo bench
```
- **Single Responsibility**: Each component should have one primary function
- **Clear Interfaces**: Well-defined pin configurations and behaviors
- **Timing Awareness**: Proper handling of clock cycles and timing constraints
- **Error Handling**: Graceful handling of invalid inputs and states
- **Testability**: Design for easy testing and verification
---
### Performance Considerations
## 📊 Performance
- **Pin Access**: Minimize lock contention on shared pins
- **State Updates**: Efficient state machine transitions
- **Memory Layout**: Optimize memory access patterns
- **Clock Processing**: Minimize overhead in update cycles
**Current performance targets:**
- Intel MCS-4: 740 kHz emulation speed (real-time)
- VIC-20: 1.108 MHz emulation speed (real-time)
- Yamaha TG100: Audio processing at 44.1 kHz
## Hardware Accuracy
---
### Intel 4004 Series Specifics
## 🔧 Configuration
- **Two-Phase Clock**: All operations synchronized to Φ1 and Φ2
- **4-Bit Architecture**: Data processed in 4-bit nibbles
- **12-Bit Addressing**: 8-bit addresses transferred in two 4-bit cycles
- **Timing Constraints**: Specific setup and hold times for signals
- **Bus Sharing**: Multiple components share the same data bus
**Example Configuration (TOML)**
```toml
[system.intel_mcs4]
clock_speed = 740000 # 740 kHz
memory_size = 4096 # 4KB ROM
### Implementation Notes
[display]
width = 800
height = 600
scale = 2
fullscreen = false
- Some timing specifications are approximated due to Rust's timing limitations
- Pin signal propagation is simplified for simulation performance
- Bus contention handling prioritizes correctness over perfect hardware accuracy
- Memory refresh cycles may be abstracted for simplicity
[audio]
sample_rate = 44100
buffer_size = 1024
## Future Enhancements
[debug]
breakpoints = [0x1234, 0x5678]
log_level = "info"
```
### Planned Components
---
- Enhanced Intel 4002 RAM with proper refresh cycles
- Intel 4008/4009 I/O expanders
- Intel 4269 programmable ROM
- More accurate timing simulation
- Cycle-accurate instruction execution
## 🤝 Contributing
### Architecture Improvements
We welcome contributions! Please see our **Contributing Guide** for details.
- Better pin signal propagation modeling
- More sophisticated bus arbitration
- Enhanced timing constraint checking
- Improved debugging and introspection capabilities
### Development Workflow
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### Code Style
- Follow Rust conventions and `cargo fmt`
- Use meaningful variable names
- Include documentation comments
- Write tests for new functionality
---
## 📝 License
This project is licensed under the **MIT License** — see the `LICENSE` file for details.
---
## 🙏 Acknowledgments
- **Intel MCS-4:** Reference documentation from Intel archives
- **VIC-20:** VICE emulator team for reference implementation
- **Yamaha TG100:** Yamaha technical documentation
- **Rust Community:** Excellent emulation resources and crates
---
## 📚 Resources
### Documentation
- [Intel MCS-4 Manuals](https://archive.org/details/intel-4004)
- [VIC-20 Programmer's Reference](https://archive.org/details/VIC-20_Programmers_Reference_Guide)
- Yamaha TG100 Service Manual
### Related Projects
- **VICE:** [Versatile Commodore Emulator](https://github.com/VICE-Team/svn-mirror)
- **MAME:** [Multiple Arcade Machine Emulator](https://github.com/mamedev/mame)
- **Yuzu:** [Nintendo Switch Emulator](https://github.com/yuzu-emu/yuzu)
---
## 🐛 Issue Reporting
If you find a bug, please open an issue with:
- System and ROM information
- Steps to reproduce
- Expected vs. actual behavior
- Log output (if available)
---
## 📞 Support
- **Discussions:** [GitHub Discussions](https://github.com/jhunnius/rusty_emu/discussions)
- **Issues:** [GitHub Issues](https://github.com/jhunnius/rusty_emu/issues)
> *Rusty Emu — Preserving computing history through accurate emulation.* 🕹️