c#
|>
js
_
tf
+
+
+
graphql
+
+
pycharm
+
toml
+=
+
pnpm
+
+
fastapi
cypress
!=
+
+
+
torch
pnpm
+
+
+
gin
+
+
+
terraform
=>
zig
+
+
numpy
cdn
bitbucket
+
deno
django
+
vault
+
azure
json
+
+
+
+
wasm
+
lisp
laravel
+
+
notepad++
+
asm
+
node
+
+
symfony
+
ocaml
π
nomad
docker
+
+
+
react
+
clj
gh
+
+
linux
+
spacy
jenkins
@
fastapi
Back to Blog
Fixing Alpine Linux Graphics Issues 🖥️
alpine-linux graphics drivers

Fixing Alpine Linux Graphics Issues 🖥️

Published Jun 3, 2025

Master Alpine Linux graphics troubleshooting with comprehensive driver management, X11/Wayland configuration, and GPU optimization. Complete guide covering Intel, AMD, NVIDIA, and integrated graphics solutions.

5 min read
0 views
Table of Contents

Graphics issues in Alpine Linux can range from missing drivers to display configuration problems. This comprehensive guide provides systematic approaches to diagnose, configure, and optimize graphics systems for desktop environments, servers with GUI needs, and specialized graphics workloads.

🔍 Understanding Alpine Graphics Architecture

Alpine Linux’s minimal approach requires explicit graphics driver installation and configuration. Understanding the graphics stack helps identify and resolve display-related issues effectively.

Graphics Stack Components

  • Kernel Drivers - Low-level hardware interface 🔧
  • Mesa Libraries - OpenGL/Vulkan implementation 🎨
  • X11/Wayland - Display server protocols 🖼️
  • Window Managers - Desktop environment integration 🪟
  • GPU Firmware - Hardware initialization files 📦

Common Graphics Hardware Types

# Identify graphics hardware
lspci | grep -i vga
lspci | grep -i display
lspci | grep -i 3d

# Check kernel modules
lsmod | grep -E "(i915|radeon|amdgpu|nouveau|nvidia)"

# Display current driver information
cat /proc/fb
ls /dev/dri/

🛠️ Basic Graphics Setup and Configuration

Essential Graphics Packages Installation

# Install base graphics support
apk add xorg-server xf86-video-vesa mesa-dri-gallium

# Install common drivers
apk add xf86-video-intel      # Intel graphics
apk add xf86-video-amdgpu     # AMD graphics  
apk add xf86-video-ati        # Legacy ATI graphics
apk add xf86-video-nouveau    # NVIDIA open source

# Install Mesa drivers
apk add mesa-dri-gallium mesa-gl mesa-gles mesa-vulkan-intel mesa-vulkan-radeon

# Install firmware (often required)
apk add linux-firmware

X11 Server Configuration

# Generate basic X11 configuration
Xorg -configure

# Create minimal xorg.conf
cat > /etc/X11/xorg.conf << 'EOF'
Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "InputDevice"
    Identifier  "Keyboard0"
    Driver      "kbd"
EndSection

Section "InputDevice"
    Identifier  "Mouse0"
    Driver      "mouse"
    Option      "Protocol" "auto"
    Option      "Device" "/dev/input/mice"
    Option      "ZAxisMapping" "4 5 6 7"
EndSection

Section "Monitor"
    Identifier   "Monitor0"
    VendorName   "Monitor Vendor"
    ModelName    "Monitor Model"
EndSection

Section "Device"
    Identifier  "Device0"
    Driver      "modesetting"  # Generic driver
EndSection

Section "Screen"
    Identifier "Screen0"
    Device     "Device0"
    Monitor    "Monitor0"
    DefaultDepth     24
    SubSection "Display"
        Depth       24
    EndSubSection
EndSection
EOF

# Test X11 configuration
X -config /etc/X11/xorg.conf

🔧 Hardware-Specific Driver Configuration

Intel Graphics Configuration

# Install Intel graphics drivers
apk add xf86-video-intel mesa-dri-gallium intel-media-driver

# Intel-specific X11 configuration
cat > /etc/X11/xorg.conf.d/20-intel.conf << 'EOF'
Section "Device"
    Identifier  "Intel Graphics"
    Driver      "intel"
    Option      "AccelMethod" "sna"
    Option      "TearFree" "true"
    Option      "DRI" "3"
EndSection
EOF

# Enable Intel GuC/HuC firmware loading
echo "options i915 enable_guc=2" > /etc/modprobe.d/i915.conf

# Create Intel GPU monitoring script
cat > /usr/local/bin/monitor-intel-gpu << 'EOF'
#!/bin/sh

# Intel GPU monitoring tool
echo "=== Intel GPU Status ==="
echo "Date: $(date)"
echo ""

# GPU information
echo "1. GPU Information:"
echo "=================="
lspci | grep -i intel | grep -i vga
echo ""

# Driver status
echo "2. Driver Status:"
echo "================"
if lsmod | grep -q i915; then
    echo "✅ i915 driver loaded"
    echo "Driver version: $(modinfo i915 | grep version | head -1)"
else
    echo "❌ i915 driver not loaded"
fi
echo ""

# DRM information
echo "3. DRM Information:"
echo "=================="
if [ -d /sys/class/drm ]; then
    ls -la /sys/class/drm/
    echo ""
    
    for card in /sys/class/drm/card*; do
        if [ -d "$card" ]; then
            echo "Card: $(basename "$card")"
            if [ -f "$card/device/vendor" ]; then
                echo "  Vendor: $(cat "$card/device/vendor")"
            fi
            if [ -f "$card/device/device" ]; then
                echo "  Device: $(cat "$card/device/device")"
            fi
        fi
    done
fi
echo ""

# GPU frequency information
echo "4. GPU Frequency:"
echo "================="
if [ -f /sys/class/drm/card0/gt_cur_freq_mhz ]; then
    echo "Current frequency: $(cat /sys/class/drm/card0/gt_cur_freq_mhz) MHz"
fi
if [ -f /sys/class/drm/card0/gt_max_freq_mhz ]; then
    echo "Maximum frequency: $(cat /sys/class/drm/card0/gt_max_freq_mhz) MHz"
fi
echo ""

# Memory information
echo "5. GPU Memory:"
echo "============="
if command -v intel_gpu_top >/dev/null 2>&1; then
    timeout 2 intel_gpu_top -l 1 2>/dev/null || echo "Intel GPU top not available"
fi

echo ""
echo "Monitoring completed"
EOF

chmod +x /usr/local/bin/monitor-intel-gpu

# Run Intel GPU monitoring
monitor-intel-gpu

AMD Graphics Configuration

# Install AMD graphics drivers
apk add xf86-video-amdgpu mesa-dri-gallium mesa-vulkan-radeon

# AMD-specific X11 configuration
cat > /etc/X11/xorg.conf.d/20-amdgpu.conf << 'EOF'
Section "Device"
    Identifier  "AMD Graphics"
    Driver      "amdgpu"
    Option      "AccelMethod" "glamor"
    Option      "DRI" "3"
    Option      "TearFree" "on"
EndSection
EOF

# Enable AMD GPU power management
echo "auto" > /sys/class/drm/card0/device/power_dpm_force_performance_level

# Create AMD GPU status script
cat > /usr/local/bin/monitor-amd-gpu << 'EOF'
#!/bin/sh

# AMD GPU monitoring tool
echo "=== AMD GPU Status ==="
echo "Date: $(date)"
echo ""

# GPU information
echo "1. GPU Information:"
echo "=================="
lspci | grep -i amd | grep -i vga
echo ""

# Driver status
echo "2. Driver Status:"
echo "================"
if lsmod | grep -q amdgpu; then
    echo "✅ amdgpu driver loaded"
    echo "Driver version: $(modinfo amdgpu | grep version | head -1)"
else
    echo "❌ amdgpu driver not loaded"
fi
echo ""

# GPU clock information
echo "3. GPU Clocks:"
echo "============="
if [ -f /sys/class/drm/card0/device/pp_dpm_sclk ]; then
    echo "GPU Clock levels:"
    cat /sys/class/drm/card0/device/pp_dpm_sclk
fi
echo ""

# Memory clock information
if [ -f /sys/class/drm/card0/device/pp_dpm_mclk ]; then
    echo "Memory Clock levels:"
    cat /sys/class/drm/card0/device/pp_dpm_mclk
fi
echo ""

# Power management
echo "4. Power Management:"
echo "=================="
if [ -f /sys/class/drm/card0/device/power_dpm_state ]; then
    echo "DPM State: $(cat /sys/class/drm/card0/device/power_dpm_state)"
fi
if [ -f /sys/class/drm/card0/device/power_dpm_force_performance_level ]; then
    echo "Performance Level: $(cat /sys/class/drm/card0/device/power_dpm_force_performance_level)"
fi
echo ""

echo "Monitoring completed"
EOF

chmod +x /usr/local/bin/monitor-amd-gpu

NVIDIA Graphics Configuration

# NVIDIA proprietary drivers (if available)
# Note: NVIDIA proprietary drivers may require additional setup

# Install open-source NVIDIA drivers
apk add xf86-video-nouveau mesa-dri-gallium

# Nouveau X11 configuration
cat > /etc/X11/xorg.conf.d/20-nouveau.conf << 'EOF'
Section "Device"
    Identifier  "NVIDIA Graphics"
    Driver      "nouveau"
    Option      "AccelMethod" "glamor"
    Option      "DRI" "3"
EndSection
EOF

# NVIDIA GPU monitoring script
cat > /usr/local/bin/monitor-nvidia-gpu << 'EOF'
#!/bin/sh

# NVIDIA GPU monitoring tool
echo "=== NVIDIA GPU Status ==="
echo "Date: $(date)"
echo ""

# GPU information
echo "1. GPU Information:"
echo "=================="
lspci | grep -i nvidia
echo ""

# Check for proprietary driver
echo "2. Driver Status:"
echo "================"
if lsmod | grep -q nvidia; then
    echo "✅ NVIDIA proprietary driver loaded"
    if command -v nvidia-smi >/dev/null 2>&1; then
        nvidia-smi
    fi
elif lsmod | grep -q nouveau; then
    echo "✅ Nouveau open-source driver loaded"
    echo "Driver version: $(modinfo nouveau | grep version | head -1)"
else
    echo "❌ No NVIDIA driver loaded"
fi
echo ""

# DRM information for nouveau
if lsmod | grep -q nouveau; then
    echo "3. Nouveau DRM Information:"
    echo "=========================="
    if [ -d /sys/class/drm ]; then
        for card in /sys/class/drm/card*; do
            if [ -f "$card/device/vendor" ] && [ "$(cat "$card/device/vendor")" = "0x10de" ]; then
                echo "NVIDIA card found: $(basename "$card")"
                if [ -f "$card/device/device" ]; then
                    echo "  Device ID: $(cat "$card/device/device")"
                fi
            fi
        done
    fi
fi

echo ""
echo "Monitoring completed"
EOF

chmod +x /usr/local/bin/monitor-nvidia-gpu

📊 Display Configuration and Multi-Monitor Setup

Monitor Detection and Configuration

# Install display configuration tools
apk add xrandr arandr

# Monitor detection script
cat > /usr/local/bin/detect-displays << 'EOF'
#!/bin/sh

# Display detection and configuration tool
echo "=== Display Detection ==="
echo "Date: $(date)"
echo ""

# Check if X is running
if ! pgrep -x "X\|Xorg" >/dev/null; then
    echo "❌ X server is not running"
    echo "Start X server first: startx"
    exit 1
fi

# Display information
echo "1. Connected Displays:"
echo "====================="
xrandr --listmonitors
echo ""

# Available outputs
echo "2. Available Outputs:"
echo "===================="
xrandr | grep " connected"
echo ""

# Current display configuration
echo "3. Current Configuration:"
echo "========================"
xrandr --current
echo ""

# EDID information
echo "4. EDID Information:"
echo "==================="
for output in $(xrandr | grep " connected" | cut -d' ' -f1); do
    echo "Output: $output"
    if command -v get-edid >/dev/null 2>&1; then
        get-edid | parse-edid 2>/dev/null || echo "  EDID parsing failed"
    else
        echo "  Install read-edid package for detailed EDID info"
    fi
    echo ""
done

# Generate xrandr configuration suggestions
echo "5. Configuration Suggestions:"
echo "============================"
primary_output=$(xrandr | grep " connected primary" | cut -d' ' -f1)
if [ -z "$primary_output" ]; then
    primary_output=$(xrandr | grep " connected" | head -1 | cut -d' ' -f1)
fi

echo "Primary display: $primary_output"

# Multi-monitor setup suggestions
connected_outputs=$(xrandr | grep " connected" | cut -d' ' -f1)
output_count=$(echo "$connected_outputs" | wc -l)

if [ "$output_count" -gt 1 ]; then
    echo ""
    echo "Multi-monitor setup commands:"
    first_output=$(echo "$connected_outputs" | head -1)
    second_output=$(echo "$connected_outputs" | tail -1)
    
    echo "# Extend desktop (side by side):"
    echo "xrandr --output $first_output --primary --output $second_output --right-of $first_output"
    echo ""
    echo "# Mirror displays:"
    echo "xrandr --output $first_output --primary --output $second_output --same-as $first_output"
    echo ""
    echo "# Use only external monitor:"
    echo "xrandr --output $first_output --off --output $second_output --primary --auto"
fi

echo ""
echo "Detection completed"
EOF

chmod +x /usr/local/bin/detect-displays

# Run display detection
detect-displays

Resolution and Refresh Rate Configuration

# Resolution configuration script
cat > /usr/local/bin/configure-resolution << 'EOF'
#!/bin/sh

# Resolution configuration tool
OUTPUT="$1"
RESOLUTION="$2"
REFRESH_RATE="$3"

if [ -z "$OUTPUT" ] || [ -z "$RESOLUTION" ]; then
    echo "Usage: $0 <output> <resolution> [refresh_rate]"
    echo ""
    echo "Available outputs:"
    xrandr | grep " connected" | cut -d' ' -f1
    echo ""
    echo "Example resolutions: 1920x1080, 2560x1440, 3840x2160"
    echo "Example refresh rates: 60, 75, 120, 144"
    echo ""
    echo "Examples:"
    echo "  $0 eDP-1 1920x1080 60"
    echo "  $0 HDMI-1 2560x1440"
    exit 1
fi

echo "Configuring display resolution..."
echo "Output: $OUTPUT"
echo "Resolution: $RESOLUTION"
echo "Refresh Rate: ${REFRESH_RATE:-auto}"
echo ""

# Check if output exists
if ! xrandr | grep -q "^$OUTPUT connected"; then
    echo "❌ Output $OUTPUT not found or not connected"
    echo "Available outputs:"
    xrandr | grep " connected"
    exit 1
fi

# Check if resolution is supported
if ! xrandr | grep -A 20 "^$OUTPUT" | grep -q "$RESOLUTION"; then
    echo "⚠️  Resolution $RESOLUTION not found in supported modes"
    echo "Creating custom mode..."
    
    # Calculate modeline using cvt
    if command -v cvt >/dev/null 2>&1; then
        width=$(echo "$RESOLUTION" | cut -d'x' -f1)
        height=$(echo "$RESOLUTION" | cut -d'x' -f2)
        refresh=${REFRESH_RATE:-60}
        
        modeline=$(cvt "$width" "$height" "$refresh" | grep "Modeline" | cut -d' ' -f2-)
        mode_name=$(echo "$modeline" | cut -d' ' -f1 | tr -d '"')
        
        echo "Creating mode: $mode_name"
        xrandr --newmode $modeline
        xrandr --addmode "$OUTPUT" "$mode_name"
        
        # Use the new mode
        xrandr --output "$OUTPUT" --mode "$mode_name"
    else
        echo "❌ cvt command not available for custom mode creation"
        echo "Install xorg-server-utils package"
        exit 1
    fi
else
    # Use existing mode
    if [ -n "$REFRESH_RATE" ]; then
        xrandr --output "$OUTPUT" --mode "$RESOLUTION" --rate "$REFRESH_RATE"
    else
        xrandr --output "$OUTPUT" --mode "$RESOLUTION"
    fi
fi

echo "✅ Resolution configuration completed"

# Verify the change
echo ""
echo "Current configuration:"
xrandr | grep -A 5 "^$OUTPUT"
EOF

chmod +x /usr/local/bin/configure-resolution

# Usage examples:
# configure-resolution eDP-1 1920x1080 60
# configure-resolution HDMI-1 2560x1440

🐛 Graphics Troubleshooting Workflows

Comprehensive Graphics Diagnostics

# Complete graphics diagnostic tool
cat > /usr/local/bin/diagnose-graphics << 'EOF'
#!/bin/sh

# Comprehensive graphics diagnostics for Alpine Linux
LOG_FILE="/tmp/graphics-diagnosis-$(date +%Y%m%d_%H%M%S).log"

log_and_echo() {
    echo "$1" | tee -a "$LOG_FILE"
}

log_and_echo "=== Alpine Linux Graphics Diagnostics ==="
log_and_echo "Date: $(date)"
log_and_echo "Hostname: $(hostname)"
log_and_echo "Kernel: $(uname -r)"
log_and_echo ""

# 1. Hardware detection
log_and_echo "1. Graphics Hardware Detection:"
log_and_echo "==============================="
lspci | grep -i -E "(vga|3d|display)" | tee -a "$LOG_FILE"
log_and_echo ""

# 2. Kernel modules
log_and_echo "2. Loaded Graphics Modules:"
log_and_echo "=========================="
lsmod | grep -E "(i915|amdgpu|radeon|nouveau|nvidia|drm)" | tee -a "$LOG_FILE"
log_and_echo ""

# 3. DRM devices
log_and_echo "3. DRM Devices:"
log_and_echo "=============="
if [ -d /dev/dri ]; then
    ls -la /dev/dri/ | tee -a "$LOG_FILE"
else
    log_and_echo "❌ No DRM devices found"
fi
log_and_echo ""

# 4. X server status
log_and_echo "4. X Server Status:"
log_and_echo "=================="
if pgrep -x "X\|Xorg" >/dev/null; then
    log_and_echo "✅ X server is running"
    ps aux | grep -E "(X|Xorg)" | grep -v grep | tee -a "$LOG_FILE"
    
    # X server log
    if [ -f /var/log/Xorg.0.log ]; then
        log_and_echo ""
        log_and_echo "X server log errors:"
        grep -E "(EE|WW)" /var/log/Xorg.0.log | tail -10 | tee -a "$LOG_FILE"
    fi
else
    log_and_echo "❌ X server is not running"
fi
log_and_echo ""

# 5. Wayland compositor status
log_and_echo "5. Wayland Compositor Status:"
log_and_echo "============================="
if pgrep -f "wayland\|weston\|sway" >/dev/null; then
    log_and_echo "✅ Wayland compositor running"
    ps aux | grep -E "(wayland|weston|sway)" | grep -v grep | tee -a "$LOG_FILE"
else
    log_and_echo "ℹ️  No Wayland compositor detected"
fi
log_and_echo ""

# 6. OpenGL information
log_and_echo "6. OpenGL Information:"
log_and_echo "====================="
if command -v glxinfo >/dev/null 2>&1; then
    if [ -n "$DISPLAY" ]; then
        glxinfo | grep -E "(vendor|renderer|version|direct)" | tee -a "$LOG_FILE"
    else
        log_and_echo "⚠️  DISPLAY not set - cannot query OpenGL info"
    fi
else
    log_and_echo "⚠️  glxinfo not available (install mesa-demos)"
fi
log_and_echo ""

# 7. Vulkan information
log_and_echo "7. Vulkan Information:"
log_and_echo "====================="
if command -v vulkaninfo >/dev/null 2>&1; then
    vulkaninfo --summary 2>/dev/null | head -20 | tee -a "$LOG_FILE"
else
    log_and_echo "⚠️  vulkaninfo not available"
fi
log_and_echo ""

# 8. Framebuffer information
log_and_echo "8. Framebuffer Information:"
log_and_echo "=========================="
if [ -f /proc/fb ]; then
    cat /proc/fb | tee -a "$LOG_FILE"
else
    log_and_echo "No framebuffer devices"
fi
log_and_echo ""

# 9. Display configuration
log_and_echo "9. Display Configuration:"
log_and_echo "========================"
if command -v xrandr >/dev/null 2>&1 && [ -n "$DISPLAY" ]; then
    xrandr | tee -a "$LOG_FILE"
else
    log_and_echo "⚠️  Cannot query display configuration"
fi
log_and_echo ""

# 10. Graphics memory usage
log_and_echo "10. Graphics Memory Usage:"
log_and_echo "========================="
if [ -f /sys/class/drm/card0/device/mem_info_vram_used ]; then
    log_and_echo "VRAM used: $(cat /sys/class/drm/card0/device/mem_info_vram_used)"
fi
if [ -f /sys/class/drm/card0/device/mem_info_gtt_used ]; then
    log_and_echo "GTT used: $(cat /sys/class/drm/card0/device/mem_info_gtt_used)"
fi
log_and_echo ""

# 11. Package information
log_and_echo "11. Installed Graphics Packages:"
log_and_echo "==============================="
apk info | grep -E "(xf86-video|mesa|intel|amd|nvidia)" | tee -a "$LOG_FILE"
log_and_echo ""

# 12. Common issues check
log_and_echo "12. Common Issues Check:"
log_and_echo "======================="

# Check for missing firmware
if dmesg | grep -i "firmware.*failed" >/dev/null; then
    log_and_echo "⚠️  Firmware loading failures detected"
    dmesg | grep -i "firmware.*failed" | tail -5 | tee -a "$LOG_FILE"
fi

# Check for graphics errors in dmesg
if dmesg | grep -i -E "(drm|gpu|graphics).*error" >/dev/null; then
    log_and_echo "⚠️  Graphics errors in kernel log"
    dmesg | grep -i -E "(drm|gpu|graphics).*error" | tail -5 | tee -a "$LOG_FILE"
fi

# Check if running in software rendering
if command -v glxinfo >/dev/null 2>&1 && [ -n "$DISPLAY" ]; then
    if glxinfo | grep -q "llvmpipe\|softpipe"; then
        log_and_echo "⚠️  Using software rendering (no hardware acceleration)"
    fi
fi

log_and_echo ""
log_and_echo "Graphics diagnostics completed"
log_and_echo "Full log saved to: $LOG_FILE"
EOF

chmod +x /usr/local/bin/diagnose-graphics

# Run comprehensive diagnostics
diagnose-graphics

Graphics Performance Testing

# Graphics performance testing suite
cat > /usr/local/bin/test-graphics-performance << 'EOF'
#!/bin/sh

# Graphics performance testing for Alpine Linux
TEST_DURATION="${1:-30}"

if [ -z "$DISPLAY" ]; then
    echo "❌ DISPLAY not set. Start X server first."
    exit 1
fi

echo "=== Graphics Performance Testing ==="
echo "Test duration: ${TEST_DURATION} seconds"
echo "Date: $(date)"
echo ""

# 1. OpenGL renderer test
echo "1. OpenGL Renderer Test:"
echo "======================="
if command -v glxinfo >/dev/null 2>&1; then
    echo "Renderer: $(glxinfo | grep "OpenGL renderer" | cut -d':' -f2 | xargs)"
    echo "Version: $(glxinfo | grep "OpenGL version" | cut -d':' -f2 | xargs)"
    echo "Vendor: $(glxinfo | grep "OpenGL vendor" | cut -d':' -f2 | xargs)"
    
    if glxinfo | grep -q "direct rendering: Yes"; then
        echo "✅ Hardware acceleration enabled"
    else
        echo "❌ Hardware acceleration disabled"
    fi
else
    echo "⚠️  glxinfo not available"
fi
echo ""

# 2. GLX gears test
echo "2. GLX Gears Performance:"
echo "========================"
if command -v glxgears >/dev/null 2>&1; then
    echo "Running GLX gears for $TEST_DURATION seconds..."
    timeout "$TEST_DURATION" glxgears -info 2>&1 | tail -5
else
    echo "⚠️  glxgears not available (install mesa-demos)"
fi
echo ""

# 3. GPU stress test
echo "3. GPU Stress Test:"
echo "=================="
if command -v gpu-burn >/dev/null 2>&1; then
    echo "Running GPU burn test for $TEST_DURATION seconds..."
    timeout "$TEST_DURATION" gpu-burn "$TEST_DURATION"
elif command -v glmark2 >/dev/null 2>&1; then
    echo "Running glmark2 benchmark..."
    glmark2 --run-forever --duration "$TEST_DURATION"
else
    echo "⚠️  No GPU stress testing tools available"
    echo "Install gpu-burn or glmark2 for stress testing"
fi
echo ""

# 4. Memory bandwidth test
echo "4. Graphics Memory Test:"
echo "======================="
if command -v glmark2 >/dev/null 2>&1; then
    echo "Testing memory bandwidth with glmark2..."
    glmark2 -b texture --duration 10
else
    echo "⚠️  Memory bandwidth test requires glmark2"
fi
echo ""

# 5. Display refresh rate test
echo "5. Display Refresh Rate:"
echo "======================="
if command -v xrandr >/dev/null 2>&1; then
    primary_output=$(xrandr | grep " connected primary" | cut -d' ' -f1)
    if [ -z "$primary_output" ]; then
        primary_output=$(xrandr | grep " connected" | head -1 | cut -d' ' -f1)
    fi
    
    current_mode=$(xrandr | grep "^$primary_output" -A 20 | grep "*" | xargs)
    echo "Primary display: $primary_output"
    echo "Current mode: $current_mode"
fi
echo ""

# 6. GPU temperature monitoring
echo "6. GPU Temperature:"
echo "=================="
if [ -d /sys/class/hwmon ]; then
    for hwmon in /sys/class/hwmon/hwmon*; do
        if [ -f "$hwmon/name" ]; then
            hwmon_name=$(cat "$hwmon/name")
            if echo "$hwmon_name" | grep -qi "gpu\|radeon\|nouveau\|amdgpu"; then
                echo "Sensor: $hwmon_name"
                for temp_file in "$hwmon"/temp*_input; do
                    if [ -f "$temp_file" ]; then
                        temp_celsius=$(( $(cat "$temp_file") / 1000 ))
                        echo "  Temperature: ${temp_celsius}°C"
                    fi
                done
            fi
        fi
    done
else
    echo "⚠️  Hardware monitoring not available"
fi
echo ""

echo "Performance testing completed"
EOF

chmod +x /usr/local/bin/test-graphics-performance

# Usage: test-graphics-performance [duration_seconds]
# test-graphics-performance 60

🚀 Advanced Graphics Optimization

GPU Power Management

# GPU power management configuration
cat > /usr/local/bin/configure-gpu-power << 'EOF'
#!/bin/sh

# GPU power management configuration
PROFILE="${1:-balanced}"

case "$PROFILE" in
    performance)
        echo "Setting performance power profile..."
        
        # Intel GPU
        if [ -f /sys/class/drm/card0/gt_max_freq_mhz ]; then
            max_freq=$(cat /sys/class/drm/card0/gt_max_freq_mhz)
            echo "$max_freq" > /sys/class/drm/card0/gt_min_freq_mhz
            echo "Intel GPU: Set to maximum performance"
        fi
        
        # AMD GPU
        if [ -f /sys/class/drm/card0/device/power_dpm_force_performance_level ]; then
            echo "high" > /sys/class/drm/card0/device/power_dpm_force_performance_level
            echo "AMD GPU: Set to high performance"
        fi
        ;;
        
    powersave)
        echo "Setting power save profile..."
        
        # Intel GPU
        if [ -f /sys/class/drm/card0/gt_min_freq_mhz ]; then
            min_freq=$(cat /sys/class/drm/card0/gt_min_freq_mhz)
            echo "$min_freq" > /sys/class/drm/card0/gt_max_freq_mhz
            echo "Intel GPU: Set to power save mode"
        fi
        
        # AMD GPU
        if [ -f /sys/class/drm/card0/device/power_dpm_force_performance_level ]; then
            echo "low" > /sys/class/drm/card0/device/power_dpm_force_performance_level
            echo "AMD GPU: Set to power save mode"
        fi
        ;;
        
    balanced)
        echo "Setting balanced power profile..."
        
        # Intel GPU
        if [ -f /sys/class/drm/card0/device/power_dpm_force_performance_level ]; then
            echo "auto" > /sys/class/drm/card0/device/power_dpm_force_performance_level
        fi
        
        # AMD GPU
        if [ -f /sys/class/drm/card0/device/power_dpm_force_performance_level ]; then
            echo "auto" > /sys/class/drm/card0/device/power_dpm_force_performance_level
            echo "AMD GPU: Set to automatic power management"
        fi
        ;;
        
    *)
        echo "Usage: $0 {performance|powersave|balanced}"
        echo ""
        echo "Profiles:"
        echo "  performance - Maximum GPU performance"
        echo "  powersave   - Minimum power consumption"
        echo "  balanced    - Automatic power management"
        exit 1
        ;;
esac

echo "GPU power profile set to: $PROFILE"
EOF

chmod +x /usr/local/bin/configure-gpu-power

# Usage examples:
# configure-gpu-power performance
# configure-gpu-power powersave
# configure-gpu-power balanced

Graphics Memory Optimization

# Graphics memory optimization script
cat > /usr/local/bin/optimize-graphics-memory << 'EOF'
#!/bin/sh

# Graphics memory optimization for Alpine Linux
echo "=== Graphics Memory Optimization ==="
echo "Date: $(date)"
echo ""

# 1. Check current memory usage
echo "1. Current Graphics Memory Usage:"
echo "================================="
if [ -f /sys/kernel/debug/dri/0/i915_gem_objects ]; then
    echo "Intel GPU memory usage:"
    head -10 /sys/kernel/debug/dri/0/i915_gem_objects
fi

if [ -f /sys/class/drm/card0/device/mem_info_vram_used ]; then
    vram_used=$(cat /sys/class/drm/card0/device/mem_info_vram_used)
    vram_total=$(cat /sys/class/drm/card0/device/mem_info_vram_total)
    echo "VRAM usage: $vram_used / $vram_total bytes"
fi
echo ""

# 2. Optimize memory settings
echo "2. Applying Memory Optimizations:"
echo "================================="

# Intel GPU optimizations
if lsmod | grep -q i915; then
    echo "Optimizing Intel GPU memory..."
    
    # Enable GPU memory compression
    if [ -f /sys/module/i915/parameters/enable_fbc ]; then
        echo 1 > /sys/module/i915/parameters/enable_fbc
        echo "✅ Frame buffer compression enabled"
    fi
    
    # Optimize memory frequency
    if [ -f /sys/class/drm/card0/gt_min_freq_mhz ]; then
        # Set minimum frequency for better memory efficiency
        echo 200 > /sys/class/drm/card0/gt_min_freq_mhz
        echo "✅ GPU minimum frequency optimized"
    fi
fi

# AMD GPU optimizations
if lsmod | grep -q amdgpu; then
    echo "Optimizing AMD GPU memory..."
    
    # Enable memory clock gating
    if [ -f /sys/class/drm/card0/device/pp_features ]; then
        echo "✅ Memory clock gating available"
    fi
fi

# 3. System memory optimizations for graphics
echo ""
echo "3. System Memory Optimizations:"
echo "==============================="

# Optimize swappiness for graphics workloads
current_swappiness=$(cat /proc/sys/vm/swappiness)
if [ "$current_swappiness" -gt 10 ]; then
    echo 10 > /proc/sys/vm/swappiness
    echo "✅ Reduced swappiness from $current_swappiness to 10"
fi

# Optimize dirty memory handling
echo 15 > /proc/sys/vm/dirty_ratio
echo 5 > /proc/sys/vm/dirty_background_ratio
echo "✅ Optimized dirty memory ratios"

# 4. Graphics buffer optimizations
echo ""
echo "4. Graphics Buffer Optimizations:"
echo "================================="

# X server memory optimizations
if pgrep -x "X\|Xorg" >/dev/null; then
    echo "X server detected - applying optimizations..."
    
    # Create optimized X11 configuration
    cat > /etc/X11/xorg.conf.d/99-memory-optimization.conf << 'XORG_EOF'
Section "Device"
    Identifier  "Graphics Memory Optimization"
    Option      "AccelMethod" "glamor"
    Option      "TearFree" "true"
    Option      "VariableRefresh" "true"
    # Optimize memory allocation
    Option      "BufferAge" "false"
    Option      "TripleBuffer" "true"
EndSection

Section "Screen"
    Identifier "Screen Memory Optimization"
    Option     "metamodes" "nvidia-auto-select +0+0 { ForceCompositionPipeline = On, ForceFullCompositionPipeline = On }"
EndSection
XORG_EOF
    
    echo "✅ X11 memory optimization configuration created"
fi

# 5. Memory pressure monitoring
echo ""
echo "5. Setting up Memory Monitoring:"
echo "==============================="

cat > /usr/local/bin/monitor-graphics-memory << 'MONITOR_EOF'
#!/bin/sh

# Graphics memory monitoring
while true; do
    echo "$(date): Graphics memory status"
    
    # System memory
    free -m | grep Mem
    
    # GPU memory if available
    if [ -f /sys/class/drm/card0/device/mem_info_vram_used ]; then
        vram_used=$(cat /sys/class/drm/card0/device/mem_info_vram_used)
        vram_total=$(cat /sys/class/drm/card0/device/mem_info_vram_total)
        vram_percent=$(( vram_used * 100 / vram_total ))
        echo "VRAM: ${vram_percent}% used"
    fi
    
    echo "---"
    sleep 60
done
MONITOR_EOF

chmod +x /usr/local/bin/monitor-graphics-memory
echo "✅ Graphics memory monitor created"

echo ""
echo "Graphics memory optimization completed"
echo "Restart X server or reboot for all changes to take effect"
EOF

chmod +x /usr/local/bin/optimize-graphics-memory

# Run graphics memory optimization
optimize-graphics-memory

🎯 Troubleshooting Common Graphics Issues

Black Screen and Boot Issues

# Black screen troubleshooting guide
cat > /usr/local/bin/fix-black-screen << 'EOF'
#!/bin/sh

# Black screen troubleshooting for Alpine Linux
echo "=== Black Screen Troubleshooting ==="
echo "This script helps diagnose and fix black screen issues"
echo ""

echo "1. Checking current display status..."
if [ -n "$DISPLAY" ]; then
    echo "✅ DISPLAY variable is set: $DISPLAY"
else
    echo "❌ DISPLAY variable not set"
    echo "Try: export DISPLAY=:0"
fi

echo ""
echo "2. Checking X server status..."
if pgrep -x "X\|Xorg" >/dev/null; then
    echo "✅ X server is running"
    echo "X server PID: $(pgrep -x 'X\|Xorg')"
else
    echo "❌ X server is not running"
    echo ""
    echo "Try starting X server:"
    echo "  startx"
    echo "  or"
    echo "  X :0 &"
fi

echo ""
echo "3. Common black screen fixes:"
echo "============================="
echo ""
echo "A. Add nomodeset to kernel parameters:"
echo "   Edit /etc/default/grub and add 'nomodeset' to GRUB_CMDLINE_LINUX"
echo "   Then run: grub-mkconfig -o /boot/grub/grub.cfg"
echo ""
echo "B. Force VESA driver (safe mode):"
cat > /tmp/xorg-vesa.conf << 'VESA_EOF'
Section "Device"
    Identifier  "Generic Video Card"
    Driver      "vesa"
EndSection
VESA_EOF
echo "   Created /tmp/xorg-vesa.conf - copy to /etc/X11/xorg.conf.d/"
echo ""
echo "C. Reset X11 configuration:"
echo "   rm /etc/X11/xorg.conf"
echo "   rm -rf /etc/X11/xorg.conf.d/*"
echo "   Let X auto-detect hardware"
echo ""
echo "D. Check kernel boot messages:"
echo "   dmesg | grep -i -E '(drm|gpu|fb|vga)'"
echo ""
echo "E. Try different graphics drivers:"
echo "   apk add xf86-video-modesetting  # Generic driver"
echo "   apk add xf86-video-fbdev         # Framebuffer driver"
echo ""

# Automated safe mode setup
echo "4. Automated Safe Mode Setup:"
echo "============================"
echo "Would you like to set up safe mode graphics? (y/N)"
read -r response
if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
    echo "Setting up safe mode graphics..."
    
    # Backup existing configuration
    if [ -f /etc/X11/xorg.conf ]; then
        cp /etc/X11/xorg.conf /etc/X11/xorg.conf.backup.$(date +%Y%m%d)
        echo "✅ Backed up existing xorg.conf"
    fi
    
    # Create safe mode configuration
    cat > /etc/X11/xorg.conf << 'SAFE_EOF'
Section "ServerLayout"
    Identifier     "Safe Layout"
    Screen      0  "Safe Screen"
    InputDevice    "Safe Keyboard" "CoreKeyboard"
    InputDevice    "Safe Mouse" "CorePointer"
EndSection

Section "InputDevice"
    Identifier  "Safe Keyboard"
    Driver      "kbd"
EndSection

Section "InputDevice"
    Identifier  "Safe Mouse"
    Driver      "mouse"
    Option      "Protocol" "auto"
    Option      "Device" "/dev/input/mice"
EndSection

Section "Monitor"
    Identifier   "Safe Monitor"
    HorizSync    30.0 - 83.0
    VertRefresh  56.0 - 75.0
EndSection

Section "Device"
    Identifier  "Safe Graphics"
    Driver      "vesa"
    Option      "UseFBDev" "true"
EndSection

Section "Screen"
    Identifier "Safe Screen"
    Device     "Safe Graphics"
    Monitor    "Safe Monitor"
    DefaultDepth     16
    SubSection "Display"
        Depth       16
        Modes       "1024x768" "800x600" "640x480"
    EndSubSection
EndSection
SAFE_EOF
    
    echo "✅ Safe mode X11 configuration created"
    echo "Try starting X with: startx"
fi

echo ""
echo "Black screen troubleshooting completed"
EOF

chmod +x /usr/local/bin/fix-black-screen

# Usage: fix-black-screen

🎉 Conclusion

Fixing graphics issues in Alpine Linux requires understanding the graphics stack, proper driver installation, and systematic troubleshooting approaches. With the right configuration and diagnostic tools, you can achieve reliable graphics performance for any workload.

Key takeaways:

  • Identify hardware correctly and install appropriate drivers 🔍
  • Use systematic diagnostic approaches 🛠️
  • Configure power management for your use case
  • Implement proper monitoring and testing 📊
  • Maintain fallback configurations for recovery 🔄

With properly configured graphics, your Alpine Linux systems will provide smooth visual experiences and efficient GPU utilization! 🚀