• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * Hotplug functions for libusb
4  * Copyright © 2012-2013 Nathan Hjelm <hjelmn@mac.com>
5  * Copyright © 2012-2013 Peter Stuge <peter@stuge.se>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "libusbi.h"
23 #include "hotplug.h"
24 
25 /**
26  * @defgroup libusb_hotplug Device hotplug event notification
27  * This page details how to use the libusb hotplug interface, where available.
28  *
29  * Be mindful that not all platforms currently implement hotplug notification and
30  * that you should first call on \ref libusb_has_capability() with parameter
31  * \ref LIBUSB_CAP_HAS_HOTPLUG to confirm that hotplug support is available.
32  *
33  * \page libusb_hotplug Device hotplug event notification
34  *
35  * \section hotplug_intro Introduction
36  *
37  * Version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, has added support
38  * for hotplug events on <b>some</b> platforms (you should test if your platform
39  * supports hotplug notification by calling \ref libusb_has_capability() with
40  * parameter \ref LIBUSB_CAP_HAS_HOTPLUG).
41  *
42  * This interface allows you to request notification for the arrival and departure
43  * of matching USB devices.
44  *
45  * To receive hotplug notification you register a callback by calling
46  * \ref libusb_hotplug_register_callback(). This function will optionally return
47  * a callback handle that can be passed to \ref libusb_hotplug_deregister_callback().
48  *
49  * A callback function must return an int (0 or 1) indicating whether the callback is
50  * expecting additional events. Returning 0 will rearm the callback and 1 will cause
51  * the callback to be deregistered. Note that when callbacks are called from
52  * libusb_hotplug_register_callback() because of the \ref LIBUSB_HOTPLUG_ENUMERATE
53  * flag, the callback return value is ignored. In other words, you cannot cause a
54  * callback to be deregistered by returning 1 when it is called from
55  * libusb_hotplug_register_callback().
56  *
57  * Callbacks for a particular context are automatically deregistered by libusb_exit().
58  *
59  * As of 1.0.16 there are two supported hotplug events:
60  *  - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: A device has arrived and is ready to use
61  *  - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: A device has left and is no longer available
62  *
63  * A hotplug event can listen for either or both of these events.
64  *
65  * Note: If you receive notification that a device has left and you have any
66  * a libusb_device_handles for the device it is up to you to call libusb_close()
67  * on each device handle to free up any remaining resources associated with the device.
68  * Once a device has left any libusb_device_handle associated with the device
69  * are invalid and will remain so even if the device comes back.
70  *
71  * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered
72  * safe to call any libusb function that takes a libusb_device. It also safe to
73  * open a device and submit asynchronous transfers. However, most other functions
74  * that take a libusb_device_handle are <b>not</b> safe to call. Examples of such
75  * functions are any of the \ref libusb_syncio "synchronous API" functions or the blocking
76  * functions that retrieve various \ref libusb_desc "USB descriptors". These functions must
77  * be used outside of the context of the hotplug callback.
78  *
79  * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function
80  * is libusb_get_device_descriptor().
81  *
82  * The following code provides an example of the usage of the hotplug interface:
83 \code
84 #include <stdio.h>
85 #include <stdlib.h>
86 #include <time.h>
87 #include <libusb.h>
88 
89 static int count = 0;
90 
91 int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
92                      libusb_hotplug_event event, void *user_data) {
93   static libusb_device_handle *dev_handle = NULL;
94   struct libusb_device_descriptor desc;
95   int rc;
96 
97   (void)libusb_get_device_descriptor(dev, &desc);
98 
99   if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
100     rc = libusb_open(dev, &dev_handle);
101     if (LIBUSB_SUCCESS != rc) {
102       printf("Could not open USB device\n");
103     }
104   } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
105     if (dev_handle) {
106       libusb_close(dev_handle);
107       dev_handle = NULL;
108     }
109   } else {
110     printf("Unhandled event %d\n", event);
111   }
112   count++;
113 
114   return 0;
115 }
116 
117 int main (void) {
118   libusb_hotplug_callback_handle callback_handle;
119   int rc;
120 
121   libusb_init(NULL);
122 
123   rc = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
124                                         LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, 0x045a, 0x5005,
125                                         LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
126                                         &callback_handle);
127   if (LIBUSB_SUCCESS != rc) {
128     printf("Error creating a hotplug callback\n");
129     libusb_exit(NULL);
130     return EXIT_FAILURE;
131   }
132 
133   while (count < 2) {
134     libusb_handle_events_completed(NULL, NULL);
135     nanosleep(&(struct timespec){0, 10000000UL}, NULL);
136   }
137 
138   libusb_hotplug_deregister_callback(NULL, callback_handle);
139   libusb_exit(NULL);
140 
141   return 0;
142 }
143 \endcode
144  */
145 
146 #define VALID_HOTPLUG_EVENTS			\
147 	 (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |	\
148 	  LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
149 
150 #define VALID_HOTPLUG_FLAGS			\
151 	 (LIBUSB_HOTPLUG_ENUMERATE)
152 
usbi_hotplug_match_cb(struct libusb_context * ctx,struct libusb_device * dev,libusb_hotplug_event event,struct libusb_hotplug_callback * hotplug_cb)153 static int usbi_hotplug_match_cb(struct libusb_context *ctx,
154 	struct libusb_device *dev, libusb_hotplug_event event,
155 	struct libusb_hotplug_callback *hotplug_cb)
156 {
157 	if (!(hotplug_cb->flags & event)) {
158 		return 0;
159 	}
160 
161 	if ((hotplug_cb->flags & USBI_HOTPLUG_VENDOR_ID_VALID) &&
162 	    hotplug_cb->vendor_id != dev->device_descriptor.idVendor) {
163 		return 0;
164 	}
165 
166 	if ((hotplug_cb->flags & USBI_HOTPLUG_PRODUCT_ID_VALID) &&
167 	    hotplug_cb->product_id != dev->device_descriptor.idProduct) {
168 		return 0;
169 	}
170 
171 	if ((hotplug_cb->flags & USBI_HOTPLUG_DEV_CLASS_VALID) &&
172 	    hotplug_cb->dev_class != dev->device_descriptor.bDeviceClass) {
173 		return 0;
174 	}
175 
176 	return hotplug_cb->cb(ctx, dev, event, hotplug_cb->user_data);
177 }
178 
usbi_hotplug_match(struct libusb_context * ctx,struct libusb_device * dev,libusb_hotplug_event event)179 void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev,
180 	libusb_hotplug_event event)
181 {
182 	struct libusb_hotplug_callback *hotplug_cb, *next;
183 	int ret;
184 
185 	usbi_mutex_lock(&ctx->hotplug_cbs_lock);
186 
187 	for_each_hotplug_cb_safe(ctx, hotplug_cb, next) {
188 		if (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE) {
189 			/* process deregistration in usbi_hotplug_deregister() */
190 			continue;
191 		}
192 
193 		usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
194 		ret = usbi_hotplug_match_cb(ctx, dev, event, hotplug_cb);
195 		usbi_mutex_lock(&ctx->hotplug_cbs_lock);
196 
197 		if (ret) {
198 			list_del(&hotplug_cb->list);
199 			free(hotplug_cb);
200 		}
201 	}
202 
203 	usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
204 }
205 
usbi_hotplug_notification(struct libusb_context * ctx,struct libusb_device * dev,libusb_hotplug_event event)206 void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
207 	libusb_hotplug_event event)
208 {
209 	struct libusb_hotplug_message *message = calloc(1, sizeof(*message));
210 	unsigned int event_flags;
211 
212 	if (!message) {
213 		usbi_err(ctx, "error allocating hotplug message");
214 		return;
215 	}
216 
217 	message->event = event;
218 	message->device = dev;
219 
220 	/* Take the event data lock and add this message to the list.
221 	 * Only signal an event if there are no prior pending events. */
222 	usbi_mutex_lock(&ctx->event_data_lock);
223 	event_flags = ctx->event_flags;
224 	ctx->event_flags |= USBI_EVENT_HOTPLUG_MSG_PENDING;
225 	list_add_tail(&message->list, &ctx->hotplug_msgs);
226 	if (!event_flags)
227 		usbi_signal_event(&ctx->event);
228 	usbi_mutex_unlock(&ctx->event_data_lock);
229 }
230 
libusb_hotplug_register_callback(libusb_context * ctx,int events,int flags,int vendor_id,int product_id,int dev_class,libusb_hotplug_callback_fn cb_fn,void * user_data,libusb_hotplug_callback_handle * callback_handle)231 int API_EXPORTED libusb_hotplug_register_callback(libusb_context *ctx,
232 	int events, int flags,
233 	int vendor_id, int product_id, int dev_class,
234 	libusb_hotplug_callback_fn cb_fn, void *user_data,
235 	libusb_hotplug_callback_handle *callback_handle)
236 {
237 	struct libusb_hotplug_callback *new_callback;
238 
239 	/* check for sane values */
240 	if ((!events || (~VALID_HOTPLUG_EVENTS & events)) ||
241 	    (~VALID_HOTPLUG_FLAGS & flags) ||
242 	    (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id && (~0xffff & vendor_id)) ||
243 	    (LIBUSB_HOTPLUG_MATCH_ANY != product_id && (~0xffff & product_id)) ||
244 	    (LIBUSB_HOTPLUG_MATCH_ANY != dev_class && (~0xff & dev_class)) ||
245 	    !cb_fn) {
246 		return LIBUSB_ERROR_INVALID_PARAM;
247 	}
248 
249 	/* check for hotplug support */
250 	if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
251 		return LIBUSB_ERROR_NOT_SUPPORTED;
252 	}
253 
254 	ctx = usbi_get_context(ctx);
255 
256 	new_callback = calloc(1, sizeof(*new_callback));
257 	if (!new_callback) {
258 		return LIBUSB_ERROR_NO_MEM;
259 	}
260 
261 	new_callback->flags = (uint8_t)events;
262 	if (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id) {
263 		new_callback->flags |= USBI_HOTPLUG_VENDOR_ID_VALID;
264 		new_callback->vendor_id = (uint16_t)vendor_id;
265 	}
266 	if (LIBUSB_HOTPLUG_MATCH_ANY != product_id) {
267 		new_callback->flags |= USBI_HOTPLUG_PRODUCT_ID_VALID;
268 		new_callback->product_id = (uint16_t)product_id;
269 	}
270 	if (LIBUSB_HOTPLUG_MATCH_ANY != dev_class) {
271 		new_callback->flags |= USBI_HOTPLUG_DEV_CLASS_VALID;
272 		new_callback->dev_class = (uint8_t)dev_class;
273 	}
274 	new_callback->cb = cb_fn;
275 	new_callback->user_data = user_data;
276 
277 	usbi_mutex_lock(&ctx->hotplug_cbs_lock);
278 
279 	/* protect the handle by the context hotplug lock */
280 	new_callback->handle = ctx->next_hotplug_cb_handle++;
281 
282 	/* handle the unlikely case of overflow */
283 	if (ctx->next_hotplug_cb_handle < 0)
284 		ctx->next_hotplug_cb_handle = 1;
285 
286 	list_add(&new_callback->list, &ctx->hotplug_cbs);
287 
288 	usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
289 
290 	usbi_dbg("new hotplug cb %p with handle %d", new_callback, new_callback->handle);
291 
292 	if ((flags & LIBUSB_HOTPLUG_ENUMERATE) && (events & LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)) {
293 		ssize_t i, len;
294 		struct libusb_device **devs;
295 
296 		len = libusb_get_device_list(ctx, &devs);
297 		if (len < 0) {
298 			libusb_hotplug_deregister_callback(ctx,
299 							new_callback->handle);
300 			return (int)len;
301 		}
302 
303 		for (i = 0; i < len; i++) {
304 			usbi_hotplug_match_cb(ctx, devs[i],
305 					LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
306 					new_callback);
307 		}
308 
309 		libusb_free_device_list(devs, 1);
310 	}
311 
312 
313 	if (callback_handle)
314 		*callback_handle = new_callback->handle;
315 
316 	return LIBUSB_SUCCESS;
317 }
318 
libusb_hotplug_deregister_callback(libusb_context * ctx,libusb_hotplug_callback_handle callback_handle)319 void API_EXPORTED libusb_hotplug_deregister_callback(libusb_context *ctx,
320 	libusb_hotplug_callback_handle callback_handle)
321 {
322 	struct libusb_hotplug_callback *hotplug_cb;
323 	int deregistered = 0;
324 
325 	/* check for hotplug support */
326 	if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
327 		return;
328 	}
329 
330 	usbi_dbg("deregister hotplug cb %d", callback_handle);
331 
332 	ctx = usbi_get_context(ctx);
333 
334 	usbi_mutex_lock(&ctx->hotplug_cbs_lock);
335 	for_each_hotplug_cb(ctx, hotplug_cb) {
336 		if (callback_handle == hotplug_cb->handle) {
337 			/* Mark this callback for deregistration */
338 			hotplug_cb->flags |= USBI_HOTPLUG_NEEDS_FREE;
339 			deregistered = 1;
340 		}
341 	}
342 	usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
343 
344 	if (deregistered) {
345 		unsigned int event_flags;
346 
347 		usbi_mutex_lock(&ctx->event_data_lock);
348 		event_flags = ctx->event_flags;
349 		ctx->event_flags |= USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
350 		if (!event_flags)
351 			usbi_signal_event(&ctx->event);
352 		usbi_mutex_unlock(&ctx->event_data_lock);
353 	}
354 }
355 
356 DEFAULT_VISIBILITY
libusb_hotplug_get_user_data(libusb_context * ctx,libusb_hotplug_callback_handle callback_handle)357 void * LIBUSB_CALL libusb_hotplug_get_user_data(libusb_context *ctx,
358 	libusb_hotplug_callback_handle callback_handle)
359 {
360 	struct libusb_hotplug_callback *hotplug_cb;
361 	void *user_data = NULL;
362 
363 	/* check for hotplug support */
364 	if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
365 		return NULL;
366 	}
367 
368 	usbi_dbg("get hotplug user data %d", callback_handle);
369 
370 	ctx = usbi_get_context(ctx);
371 
372 	usbi_mutex_lock(&ctx->hotplug_cbs_lock);
373 	for_each_hotplug_cb(ctx, hotplug_cb) {
374 		if (callback_handle == hotplug_cb->handle) {
375 			user_data = hotplug_cb->user_data;
376 		}
377 	}
378 	usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
379 
380 	return user_data;
381 }
382 
usbi_hotplug_deregister(struct libusb_context * ctx,int forced)383 void usbi_hotplug_deregister(struct libusb_context *ctx, int forced)
384 {
385 	struct libusb_hotplug_callback *hotplug_cb, *next;
386 
387 	usbi_mutex_lock(&ctx->hotplug_cbs_lock);
388 	for_each_hotplug_cb_safe(ctx, hotplug_cb, next) {
389 		if (forced || (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE)) {
390 			usbi_dbg("freeing hotplug cb %p with handle %d", hotplug_cb,
391 				 hotplug_cb->handle);
392 			list_del(&hotplug_cb->list);
393 			free(hotplug_cb);
394 		}
395 	}
396 	usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
397 }
398