# MVGAL Contributor Guide

**Version:** 1.0  
**Date:** 2026-06-02

---

## Table of Contents

1. [Getting Started](#1-getting-started)
2. [Development Environment](#2-development-environment)
3. [Building from Source](#3-building-from-source)
4. [Code Structure](#4-code-structure)
5. [Coding Standards](#5-coding-standards)
6. [Submitting Changes](#6-submitting-changes)
7. [Testing](#7-testing)
8. [API Design Guidelines](#8-api-design-guidelines)
9. [Security Considerations](#9-security-considerations)
10. [Release Process](#10-release-process)

---

## 1. Getting Started

### 1.1 Prerequisites

**Build Requirements:**
- Linux kernel 5.10+ development headers
- GCC 9+ or Clang 10+
- CMake 3.20+
- Ninja or Make
- Vulkan SDK headers
- Optional: Rust 1.75+, Go 1.20+

**Runtime Requirements:**
- Linux distribution with Vulkan support
- Compatible GPU drivers (see README.md)

### 1.2 Fork and Clone

```bash
# Fork the repository on GitHub
# Then clone your fork
git clone https://github.com/YOUR_USERNAME/mvgal.git
cd mvgal

# Add upstream remote
git remote add upstream https://github.com/TheCreateGM/mvgal.git
```

---

## 2. Development Environment

### 2.1 Recommended Setup

```bash
# Ubuntu/Debian
sudo apt install build-essential cmake ninja-build \
    libdrm-dev libvulkan-dev vulkan-tools \
    gcc-12 clang-15 rustup cargo \
    python3-dev golang-go git

# Fedora/RHEL
sudo dnf install cmake ninja-build \
    libdrm-devel vulkan-devel \
    gcc-c++ rust cargo golang \
    git

# Arch Linux
sudo pacman -S cmake ninja libdrm vulkan-devel \
    clang rust go git
```

### 2.2 IDE/Editor Setup

**VS Code (recommended extensions):**
- C/C++ (Microsoft)
- CMake Tools
- Vulkan
- Rust Analyzer
- CodeLLDB

**Vim/Neovim:**
```vim
" Add to ~/.vimrc
set makeprg=cmake\ -\B.\build&&cmake\ --build\ build
set errorformat=%f:%l:%c:\ %t%*[^:]:\ %m
```

---

## 3. Building from Source

### 3.1 Quick Build

```bash
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Debug -DMVGAL_BUILD_TOOLS=ON
ninja
```

### 3.2 Build Options

| Option | Default | Description |
|--------|---------|-------------|
| `MVGAL_BUILD_KERNEL` | ON | Build kernel module |
| `MVGAL_BUILD_API` | ON | Build user-space library |
| `MVGAL_BUILD_RUNTIME` | ON | Build mvgald daemon |
| `MVGAL_BUILD_TOOLS` | ON | Build CLI tools |
| `MVGAL_BUILD_TESTS` | OFF | Build test suite |
| `MVGAL_ENABLE_RUST` | ON | Enable Rust safety crates |
| `MVGAL_BUILD_GAMING` | ON | Enable Steam/Proton integration |

### 3.3 Debug Build

```bash
cmake .. -DCMAKE_BUILD_TYPE=Debug \
         -DMVGAL_BUILD_TESTS=ON \
         -DMVGAL_VULKAN_DEBUG=ON
ninja
```

### 3.4 Running Tests

```bash
# Run unit tests
ninja test

# Or run manually
./build/src/tests/test_mvgal_api
./build/src/tests/test_cross_vendor_compute

# Run with verbose output
./build/src/tests/test_mvgal_api --verbose
```

---

## 4. Code Structure

```
mvgal/
├── kernel/              # Linux kernel module
│   ├── mvgal_main.c     # Device discovery, UAPI
│   ├── mvgal_device.c   # Logical device management
│   ├── mvgal_memory.c   # DMA-BUF coordination
│   ├── mvgal_sync.c     # Cross-GPU synchronization
│   └── vendors/         # Per-vendor integrations
├── runtime/             # C++ daemon (mvgald)
│   └── daemon/
│       ├── scheduler.cpp
│       ├── memory_manager.cpp
│       ├── power_manager.cpp
│       └── ipc_server.cpp
├── safe/                # Rust safety crates
│   ├── fence_manager.rs
│   ├── memory_safety.rs
│   └── capability_model.rs
├── src/userspace/       # C library
│   ├── api/             # Public API
│   ├── memory/          # Memory management
│   └── intercept/       # API interception layers
├── include/mvgal/       # Public headers
├── tools/               # CLI tools
├── steam/               # Steam/Proton integration
└── docs/                # Documentation
```

---

## 5. Coding Standards

### 5.1 C/C++ Code Style

**Kernel Module (C):**
- Follow Linux kernel coding style
- 80-character line limit
- Use `pr_info`, `pr_debug` for logging
- No floating point in kernel

```c
/* Example: well-documented function */
/**
 * mvgal_gpu_init - Initialize a GPU device
 * @gpu: GPU device structure to initialize
 *
 * Performs vendor-specific initialization and
 * queries hardware capabilities.
 *
 * Return: 0 on success, negative error code on failure
 */
int mvgal_gpu_init(struct mvgal_gpu_device *gpu)
{
    int ret;

    if (!gpu)
        return -EINVAL;

    ret = gpu->ops->init(gpu);
    if (ret < 0)
        pr_err("Failed to init GPU: %d\n", ret);

    return ret;
}
```

**Userspace (C/C++):**
- 100-character line limit
- Google-style comments
- RAII in C++
- `std::string` over `char*`

### 5.2 Rust Code Style

```rust
/// Calculate power budget for a workload
///
/// # Arguments
/// * `workload_flux` - Estimated data throughput (bytes/sec)
/// * `gpu_count` - Number of GPUs involved
///
/// # Returns
/// Required power in watts, or None if calculation failed
pub fn calculate_power_budget(workload_flux: usize, gpu_count: u32) -> Option<u64> {
    // ... implementation ...
}
```

### 5.3 CMake Style

```cmake
# Good: Descriptive option names
option(MVGAL_BUILD_GAMING
    "Enable Steam/Proton and gaming integration" ON)

# Bad: Abbreviated names
option(MVGAL_GMNG ON)  # No!

# Good: Clear comments
# Build the Vulkan layer for API interception
if(WITH_VULKAN)
    add_subdirectory(src/userspace/intercept/vulkan)
endif()
```

---

## 6. Submitting Changes

### 6.1 Branch Naming

```
feature/add-new-scheduler
bugfix/fix-dmabuf-leak
docs/update-api-reference
refactor/simplify-memory-manager
```

### 6.2 Commit Messages

```
feat(scheduler): add hybrid scheduling algorithm

Implement adaptive scheduling that selects between AFR and
compute_offload based on workload type and GPU capabilities.

- Add HybridScheduler class with ML-based strategy selection
- Add benchmark results to docs/hybrid-scheduler.md
- Include unit tests for strategy transitions

Fixes #123
```

### 6.3 Pull Request Process

1. **Update main branch**
   ```bash
   git checkout main
   git pull upstream main
   ```

2. **Create feature branch**
   ```bash
   git checkout -b feature/my-new-feature
   ```

3. **Make changes with tests**
   - Add/update unit tests
   - Update documentation
   - Follow coding standards

4. **Push and create PR**
   ```bash
   git push origin feature/my-new-feature
   ```

5. **PR Checklist**
   - [ ] Tests pass locally
   - [ ] New code is documented
   - [ ] Commits are squashed and cleaned up
   - [ ] PR description explains "why" not just "what"

---

## 7. Testing

### 7.1 Unit Tests

```bash
# Run C tests
ctest --test-dir build --output-on-failure

# Run Rust tests
cargo test --manifest-path runtime/Cargo.toml

# Run specific test
./build/src/tests/test_mvgal_api --verbose
```

### 7.2 Integration Tests

```bash
# Device enumeration test
./build/tools/mvgal-info --check

# Vulkan layer test
MVGAL_VULKAN_DEBUG=1 vkcube --c 1 | grep MVGAL

# Memory transfer test
./build/tools/mvgal-bench memory
```

### 7.3 Hardware Testing

Test on the following configurations:
- [ ] Single NVIDIA GPU
- [ ] Single AMD GPU
- [ ] Single Intel GPU
- [ ] NVIDIA + AMD
- [ ] NVIDIA + Intel
- [ ] AMD + Intel
- [ ] All three vendors

---

## 8. API Design Guidelines

### 8.1 ABI Stability

- Never break ABI compatibility
- Use version numbers for new APIs
- Deprecation: mark old functions, keep for 2 releases

```c
/* New function - add to API */
mvgal_error_t mvgal_new_feature(uint32_t param);

/* Deprecated function - mark clearly */
MVGAL_DEPRECATED("Use mvgal_new_feature instead")
mvgal_error_t mvgal_old_feature(uint32_t param);
```

### 8.2 Error Handling

All public APIs return `mvgal_error_t`:

```c
typedef enum {
    MVGAL_SUCCESS = 0,
    MVGAL_ERROR_INVALID_ARGUMENT = -1,
    MVGAL_ERROR_NOT_INITIALIZED = -2,
    MVGAL_ERROR_OUT_OF_MEMORY = -3,
    MVGAL_ERROR_UNSUPPORTED = -4,
    MVGAL_ERROR_NOT_FOUND = -5,
    MVGAL_ERROR_FENCE_TIMEOUT = -6,
} mvgal_error_t;
```

---

## 9. Security Considerations

### 9.1 Privilege Escalation

- Always use `pkexec` for privileged operations
- Never use `sudo` in scripts
- Validate all inputs before passing to kernel

```bash
#!/bin/bash
# Good
pkexec insmod /lib/modules/$(uname -r)/kernel/drivers/gpu/drm/mvgal.ko

# Bad
sudo insmod mvgal.ko  # Don't do this!
```

### 9.2 Input Validation

```c
mvgal_error_t mvgal_set_power_state(uint32_t gpu_index, 
                                     enum mvgal_power_state state)
{
    if (gpu_index >= MAX_GPUS)
        return MVGAL_ERROR_INVALID_ARGUMENT;
    
    if (state >= MVGAL_POWER_STATE_COUNT)
        return MVGAL_ERROR_INVALID_ARGUMENT;
    
    /* ... implementation ... */
}
```

---

## 10. Release Process

### 10.1 Version Numbers

Follow Semantic Versioning: `MAJOR.MINOR.PATCH`

- MAJOR: Breaking API changes
- MINOR: New features, backwards compatible
- PATCH: Bug fixes, backwards compatible

### 10.2 Pre-release Checklist

- [ ] All tests pass
- [ ] Update version in `kernel/mvgal_version.h`
- [ ] Update `CHANGELOG.md`
- [ ] Tag release: `git tag vx.y.z`
- [ ] Build packages for all distros
- [ ] Update COPR/NVIDIA devzone

### 10.3 Post-release

- [ ] Create GitHub release
- [ ] Update documentation
- [ ] Announce on mailing list/Reddit
- [ ] Update package repositories

---

## 11. Getting Help

### 11.1 Communication Channels

- **GitHub Issues**: Bug reports and feature requests
- **Discussions**: Questions and usage help
- **Matrix**: #mvgal:matrix.org (development chat)
- **Mailing List**: mvgal-dev@googlegroups.com

### 11.2 Reporting Bugs

When reporting bugs, please include:

1. **System information**
   ```
   uname -a
   lspci | grep -i vga
   lsmod | grep mvgal
   ```

2. **MVGAL version**
   ```
   mvgal-info --version
   ```

3. **Steps to reproduce**
   - Clear description of what you did
   - What happened
   - What you expected

4. **Logs**
   ```bash
   journalctl -u mvgald --no-pager
   dmesg | grep mvgal
   ```

---

## 12. Code of Conduct

We are committed to providing a welcoming and inclusive environment for all contributors.

- Be respectful and constructive
- Welcome newcomers and help them learn
- Focus on technical merit
- Accept disagreement gracefully
- Report harassment to maintainers

See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for details.