Debian Codegraph @

src/platform/windows_winusb/hotplug.rs

raw symbols SCIP
1 use std::{
2 collections::VecDeque,
3 ffi::c_void,
4 io::ErrorKind,
5 mem::size_of,
6 ptr::addr_of,
7 sync::Mutex,
8 task::{Context, Poll},
9 };
10
11 use atomic_waker::AtomicWaker;
12 use log::{debug, error};
13 use windows_sys::Win32::{
14 Devices::{
15 DeviceAndDriverInstallation::{
16 CM_Register_Notification, CM_Unregister_Notification, CM_NOTIFY_ACTION,
17 CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL, CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL,
18 CM_NOTIFY_EVENT_DATA, CM_NOTIFY_FILTER, CM_NOTIFY_FILTER_0, CM_NOTIFY_FILTER_0_2,
19 CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE, CR_SUCCESS, HCMNOTIFICATION,
20 },
21 Properties::DEVPKEY_Device_InstanceId,
22 Usb::GUID_DEVINTERFACE_USB_DEVICE,
23 },
24 Foundation::ERROR_SUCCESS,
25 };
26
27 use crate::{
28 hotplug::HotplugEvent,
29 platform::windows_winusb::{cfgmgr32::get_device_interface_property, util::WCString},
30 DeviceId, Error,
31 };
32
33 use super::{enumeration::probe_device, util::WCStr};
34
35 use super::DevInst;
36
37 pub(crate) struct WindowsHotplugWatch {
38 inner: *mut HotplugInner,
39 registration: HCMNOTIFICATION,
40 }
41
42 struct HotplugInner {
43 waker: AtomicWaker,
44 events: Mutex<VecDeque<(Action, DevInst)>>,
45 }
46
47 #[derive(Debug)]
48 enum Action {
49 Connect,
50 Disconnect,
51 }
52
53 impl WindowsHotplugWatch {
54 pub fn new() -> Result<WindowsHotplugWatch, Error> {
55 let inner = Box::into_raw(Box::new(HotplugInner {
56 events: Mutex::new(VecDeque::new()),
57 waker: AtomicWaker::new(),
58 }));
59
60 let mut registration = 0;
61 let filter = CM_NOTIFY_FILTER {
62 cbSize: size_of::<CM_NOTIFY_FILTER>() as u32,
63 Flags: 0,
64 FilterType: CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE,
65 Reserved: 0,
66 u: CM_NOTIFY_FILTER_0 {
67 DeviceInterface: CM_NOTIFY_FILTER_0_2 {
68 ClassGuid: GUID_DEVINTERFACE_USB_DEVICE,
69 },
70 },
71 };
72
73 let cr = unsafe {
74 CM_Register_Notification(
75 &filter,
76 inner as *mut c_void,
77 Some(hotplug_callback),
78 &mut registration,
79 )
80 };
81
82 if cr != CR_SUCCESS {
83 error!("CM_Register_Notification failed: {cr}");
84 return Err(Error::new(
85 ErrorKind::Other,
86 "Failed to initialize hotplug notifications",
87 ));
88 }
89
90 Ok(WindowsHotplugWatch {
91 inner,
92 registration,
93 })
94 }
95
96 fn inner(&self) -> &HotplugInner {
97 unsafe { &*self.inner }
98 }
99
100 pub fn poll_next(&mut self, cx: &mut Context) -> Poll<HotplugEvent> {
101 self.inner().waker.register(cx.waker());
102 let event = self.inner().events.lock().unwrap().pop_front();
103 match event {
104 Some((Action::Connect, devinst)) => {
105 if let Some(dev) = probe_device(devinst) {
106 return Poll::Ready(HotplugEvent::Connected(dev));
107 };
108 }
109 Some((Action::Disconnect, devinst)) => {
110 return Poll::Ready(HotplugEvent::Disconnected(DeviceId(devinst)));
111 }
112 None => {}
113 }
114 Poll::Pending
115 }
116 }
117
118 // Safety: Effectively a Box<HotplugInner>, which is Send+Sync;
119 // `registration` is accessed only in `Drop` and `CM_Unregister_Notification`
120 // docs mention using a threadpool to call the function.
121 unsafe impl Send for WindowsHotplugWatch {}
122 unsafe impl Sync for WindowsHotplugWatch {}
123
124 impl Drop for WindowsHotplugWatch {
125 fn drop(&mut self) {
126 unsafe {
127 // According to [1], `CM_Unregister_Notification` waits for
128 // callbacks to finish, so it should be safe to drop `inner`
129 // immediately afterward without races.
130 // [1]: https://learn.microsoft.com/en-us/windows/win32/api/cfgmgr32/nf-cfgmgr32-cm_unregister_notification
131 CM_Unregister_Notification(self.registration);
132 drop(Box::from_raw(self.inner));
133 }
134 }
135 }
136
137 unsafe extern "system" fn hotplug_callback(
138 _hnotify: HCMNOTIFICATION,
139 context: *const ::core::ffi::c_void,
140 action: CM_NOTIFY_ACTION,
141 eventdata: *const CM_NOTIFY_EVENT_DATA,
142 _eventdatasize: u32,
143 ) -> u32 {
144 let inner = unsafe { &*(context as *const HotplugInner) };
145
146 let action = match action {
147 CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL => Action::Connect,
148 CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL => Action::Disconnect,
149 _ => {
150 debug!("Hotplug callback: unknown action {action}");
151 return ERROR_SUCCESS;
152 }
153 };
154
155 let device_interface =
156 unsafe { WCStr::from_ptr(addr_of!((*eventdata).u.DeviceInterface.SymbolicLink[0])) };
157
158 let device_instance =
159 get_device_interface_property::<WCString>(device_interface, DEVPKEY_Device_InstanceId)
160 .unwrap();
161 let devinst = DevInst::from_instance_id(&device_instance).unwrap();
162
163 debug!("Hotplug callback: action={action:?}, instance={device_instance}");
164 inner.events.lock().unwrap().push_back((action, devinst));
165 inner.waker.wake();
166 return ERROR_SUCCESS;
167 }