Hotplugger: Real USB Port Passthrough for VFIO/QEMU!

Related tags

Hardwarehotplugger
Overview

Hotplugger: Real USB Port Passthrough for VFIO/QEMU!

Welcome to Hotplugger! This app, as the name might tell you, is a combination of some scripts (python, yaml, udev rules and some QEMU args) to allow you to pass through an actual USB port into a VM. Instead of passing the USB root hub (which could have the side effect of passing all the ports, including the ones you didn't want to) or another PCIe hub or something, you can just pass a specific USB port to a VM and have the others free for anything else. Plus, it saves you from using the vfio-pci driver for the USB root hub, so you can keep using it for evdev or other things on the VM host.

Requirements

  • monitor.py and hotplugger.py require Python 3
  • Only tested with QEMU 5.0.0. Untested with older or newer versions.

Quick start (Ubuntu 20.10)

  1. git clone https://github.com/darkguy2008/hotplugger.git

  2. (Optional) run python3 monitor.py and follow the prompts. Basically once you hit Enter you have to plug and unplug an USB device (a thumbdrive or audio device preferred) into the USB ports that you want to know their DEVPATH route from. This will help you identify them so you can write them into config.yaml in the ports array. This array only accepts DEVPATH routes that UDEV generates.

  3. Edit config.yaml. It must stay in the same folder as monitor.py and hotplugger.py. Look at the current example: It's set for a Windows VM (the name doesn't matter, as long as it's unique within the entries of the same file). Make sure the socket property matches the file path of the QEMU chardev device pointing to an Unix domain socket file and in the ports array put the list of the udev DEVPATH of the USB ports you want to pass through to that VM:

    virtual_machines:
    
      windows:
        socket: /home/dragon/vm/test/qmp-sock
        ports:
          - /devices/pci0000:00/0000:00:14.0/usb3/3-1
          - /devices/pci0000:00/0000:00:14.0/usb3/3-2
          - /devices/pci0000:00/0000:00:14.0/usb4/4-1
          - /devices/pci0000:00/0000:00:14.0/usb4/4-2
    
  4. Create an /etc/udev/rules.d/99-zzz-local.rules file with the following content:

    SUBSYSTEM=="usb", ACTION=="add", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py >> /tmp/hotplugger.log' 2>&1"
    SUBSYSTEM=="usb", ACTION=="remove", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py >> /tmp/hotplugger.log' 2>&1"
    

    Make sure to change path-to-hotplugger with the path where you cloned the repo to, or installed the package. It can be simplified, but this one is useful in case you want to debug and see what's going on. Otherwise, proceed with a simpler file:

    SUBSYSTEM=="usb", ACTION=="add", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py'"
    SUBSYSTEM=="usb", ACTION=="remove", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py'"
    
  5. Create the QMP monitor Unix domain socket if you haven't already in your QEMU args. I use this:

    -chardev socket,id=mon1,server,nowait,path=./qmp-sock
    -mon chardev=mon1,mode=control,pretty=on
    
  6. Have a coffee!

Libvirt setup

This is a work in progress, but here's some steps to get you started:

  1. Edit your VM's XML config like this:

    1. <domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
        <name>QEMUGuest1name>
        <uuid>c7a5fdbd-edaf-9455-926a-d65c16db1809uuid>
        ...
        <qemu:commandline>
          <qemu:arg value='-chardev'/>
          <qemu:arg value='socket,id=mon1,server,nowait,path=/tmp/my-vm-sock'/>
          <qemu:arg value='-mon'/>
          <qemu:arg value='chardev=mon1,mode=control,pretty=on'/>
        qemu:commandline>
      domain>

      Add the xmlns attribute and the QEMU commandline arguments like that. The /tmp/my-vm-sock is the name of an unix domain socket. You can use any, just make sure to also put the same path in the config.yaml file.

  2. If you get a permissions issue, edit /etc/libvirt/qemu.conf and add security_driver = "none"to it to fix apparmor being annoying about it.

How it works

  1. The udev rule launches the script on every USB event. For each USB add/remove action there's around 3 to 5+ events. This allows the app to act at any step in the action lifecycle.
  2. In the first step it gets the kernel environment variables from udev and stores them in a temp file. In those variables, the DEVPATH, the DEVNUM (host address in QEMU, it seems to change and is sequential...) and the BUSNUM (bus address in QEMU) are captured. For the subsequent events, the following steps are run:
    1. It requests QEMU through the Unix socket and the info usbhost QMP command the USB info from the host. This gives it an extra field: The host port where the device is also connected to. Since I got the host and bus addresses in the first event, I can use that to parse through the info usbhost command's output and find the port connected to the device.
    2. If the port is found, using the device_add command, a new usb-host device is added using the USB bus and port we got in the previous step, and assigns it a predictable ID that it can use to unplug the device afterwards. To add this of course, the VM should have a usb-xhci device I think. Not sure if it's required or not, but I prefer to add it as I have USB 3.0 ports and devices.
    3. The temp file is cleared once the device_add command has run successfully.

Steps 2.1, 2.2 and 2.3 are run on every udev event. For instance, for an audio device it gets 3 or 4 events: One for the HID device, and two or so for the audio devices. My audio device (Corsair Void Elite Wireless) has both stereo audio and a communications device (mono audio, for mic) so for a single dongle like that I get those many events. Since these steps are ran on all the events, there's multiple chances to do the hotplug action. When one of them succeeds, the others will silently fail as QEMU will say that the same device ID is being used, so all is good.

Troubleshooting

If for some reason the app doesn't seem to work, try these methods:

  • Remove the /tmp folder where hotplugger.py is located
  • Reboot the computer
  • Reboot udev: sudo udevadm control --reload-rules && sudo udevadm trigger
  • View udev's logfile: sudo service udev restart && sudo udevadm control --log-priority=debug && journalctl -f | grep -i hotplugger
  • If you want to see what will be run when you plug a device, try with this command to simulate an udev event: udevadm test $(udevadm info -a --path=/devices/pci0000:00/0000:00:14.0/usb3/3-1/3-1:1.0) --action=add replacing --path with the path of the USB port down to the device itself (in this case, I had a device connected to the usb3/3-1 port, identified as 3-1:1.0.

Thank you!

A lot of work and sleepless nights were involved in this procedure, so if this app helps you in any way or another, please consider sending a small donation, it helps a lot in these tough times!

Changelog

(2020-02-05)

  • Initial changelog writing
  • App was refactored a bit with improved python mad skillz. It also seems to be a bit more stable and robust, it doesn't hang much anymore and USB detection seems to work better. This is due to the fact that I added a stupid 1-second delay after all the USB UDEV events have gone through. Since there's no way to know when UDEV has "finished" sending all the events (and there could be a lot more) the commands being sent to QEMU to add the device will have to wait 1 second now. While it's not ideal, it should be enough to avoid a VM hanging up and I can live with that.
Owner
DARKGuy (Alemar)
DARKGuy (Alemar)
Monorepo for my Raspberry Pi dashboard and GPS satellite listener.

🥧 pi dashboard My blog post: Listening to Satellites with my Raspberry Pi This is the monorepo for my Raspberry Pi dashboard!

Andrew Healey 27 Jun 08, 2022
Point Density-Aware Voxels for LiDAR 3D Object Detection (CVPR 2022)

PDV PDV is LiDAR 3D object detection method. This repository is based off [OpenPCDet]. Point Density-Aware Voxels for LiDAR 3D Object Detection Jordan

Toronto Robotics and AI Laboratory 114 Dec 21, 2022
This is a collection of python modules that interact with the Ryze Tello drone.

This is a collection of python modules that interact with the Ryze Tello drone.

DJI-SDK 1.2k Jan 03, 2023
DOS-like OS for RP2040 basic microcontroller boards

Micropython DOS-like OS for RP2040 microcontroller boards. Check out the demo video at https://www.youtube.com/watch?v=Az_oiq8GE4Y To start the OS typ

RetiredWizard 58 Dec 27, 2022
Code reimplementation of some papers published in SAIL-Lab

SAIL SAIL-Lab统一代码库 Motivation 创建这个项目的动机最早来源于实验室组内成员相互Debug代码的时候遇到的麻烦。

Jianwen Chen 8 Nov 15, 2022
Jarvis: a personal assistant which can help you to manage your system

Jarvis Jarvis is personal AI based assistant which can help you to manage stuff in your computer. This is demo but I decided to make it more better so

2 Jun 02, 2022
Python Wrapper for Homeassistant's REST API

HomeassistantAPI Python Wrapper for Homeassistant's REST API Please ⭐️ the repo if you find this project useful or cool! Here is a quick example. from

Nate 29 Dec 31, 2022
New armachat based on Raspberry Pi PICO an Circuitpython code

Armachat-circuitpython New Armachat based on Raspberry Pi PICO an Circuitpython code Software working features: send message with header and store to

Peter Misenko 44 Dec 24, 2022
Minimal and clean dashboard to visualize some stats of Pi-Hole with an E-Ink display attached to your Raspberry Pi

Clean Dashboard for Pi-Hole Minimal and clean dashboard to visualize some stats of Pi-Hole with an E-Ink display attached to your Raspberry Pi.

Alessio Santoru 104 Dec 14, 2022
Robot Framework keyword library wrapper for atlassian-python-api

Robot Framework keyword library wrapper for atlassian-python-api

Marcin Koperski 3 Jul 29, 2022
Small Robot, with LIDAR and DepthCamera. Using ROS for Maping and Navigation

🤖 RoboCop 🤖 Small Robot, with LIDAR and DepthCamera. Using ROS for Maping and Navigation Made by Clemente Donoso, 📍 Chile 🇨🇱 RoboCop Lateral Fron

Clemente Donoso Krauss 2 Jan 04, 2022
Plug and Play on Internet of Things with LoRa wireless modulation.

IoT-PnP Plug and Play on Internet of Things with LoRa wireless modulation. Device Side In the '505_PnP' folder has a modified ardunino template code s

Lambert Yang 1 May 19, 2022
🌱 - WebhookHard◞ Fines Educativos ◟

v1.0.0 WebhookHardware ¿Que es WebhookHardware? WebhookHardware se trata de un proyecto tratado para sacar informacion sobre el hardware de tus victim

3 Jun 14, 2021
Ha-rpi gpio - Home Assistant Raspberry Pi GPIO Integration

Home Assistant Raspberry Pi GPIO custom integration This is a spin-off from the

Shay Levy 98 Dec 24, 2022
Workshop for student hackathons focused on IoT dev

Scenario: The Mutt Matcher (IoT version) According to the World Health Organization there are more than 200 million stray dogs worldwide. The American

Microsoft 15 Aug 10, 2022
An embedded application for toy-car controlling based on Raspberry Pi 3 Model B and AlphaBot2-Pi.

An embedded application for toy-car controlling based on Raspberry Pi 3 Model B and AlphaBot2-Pi. This is the source codes of my programming assignmen

StardustDL 4 Oct 19, 2022
circuitpython version of PyBasic for microcontrollers

cPyBasic Circuitpython version of PyBasic for microcontrollers Current version work only for Adafruit titano & CardKB for now. The origninal PyBasic w

BeBoXoS 3 Nov 14, 2021
Play a song with a 3D printer.

MIDI to GCODE Play a song with a FDM 3D printer. SLA printers don't have motors, so they cannot play music. Warning: Be ready to turn off the 3D print

Patrick 6 Apr 11, 2022
Software framework to enable agile robotic assembly applications.

ConnTact Software framework to enable agile robotic assembly applications. (Connect + Tactile) Overview Installation Development of framework was done

Southwest Research Institute Robotics 29 Dec 01, 2022
LifeSaver automatically, periodically saves USB flash drive data into the PC

LifeSaver automatically, periodically saves USB flash drive data into the PC. Theoriticaly it will work with any any connected drive ex - Hard Disk ,SSD ... But, can't handle Backing up multipatition

siddharth dhaka 4 Sep 26, 2021