52ce6267ab4e61892315f2b68583bcae2f88cc17
[platform/upstream/libusb.git] / libusb / hotplug.c
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
24 /**
25  * @defgroup libusb_hotplug Device hotplug event notification
26  * This page details how to use the libusb hotplug interface, where available.
27  *
28  * Be mindful that not all platforms currently implement hotplug notification and
29  * that you should first call on \ref libusb_has_capability() with parameter
30  * \ref LIBUSB_CAP_HAS_HOTPLUG to confirm that hotplug support is available.
31  *
32  * \page libusb_hotplug Device hotplug event notification
33  *
34  * \section hotplug_intro Introduction
35  *
36  * Version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, has added support
37  * for hotplug events on <b>some</b> platforms (you should test if your platform
38  * supports hotplug notification by calling \ref libusb_has_capability() with
39  * parameter \ref LIBUSB_CAP_HAS_HOTPLUG).
40  *
41  * This interface allows you to request notification for the arrival and departure
42  * of matching USB devices.
43  *
44  * To receive hotplug notification you register a callback by calling
45  * \ref libusb_hotplug_register_callback(). This function will optionally return
46  * a callback handle that can be passed to \ref libusb_hotplug_deregister_callback().
47  *
48  * A callback function must return an int (0 or 1) indicating whether the callback is
49  * expecting additional events. Returning 0 will rearm the callback and 1 will cause
50  * the callback to be deregistered. Note that when callbacks are called from
51  * libusb_hotplug_register_callback() because of the \ref LIBUSB_HOTPLUG_ENUMERATE
52  * flag, the callback return value is ignored. In other words, you cannot cause a
53  * callback to be deregistered by returning 1 when it is called from
54  * libusb_hotplug_register_callback().
55  *
56  * Callbacks for a particular context are automatically deregistered by libusb_exit().
57  *
58  * As of 1.0.16 there are two supported hotplug events:
59  *  - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: A device has arrived and is ready to use
60  *  - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: A device has left and is no longer available
61  *
62  * A hotplug event can listen for either or both of these events.
63  *
64  * Note: If you receive notification that a device has left and you have any
65  * a libusb_device_handles for the device it is up to you to call libusb_close()
66  * on each device handle to free up any remaining resources associated with the device.
67  * Once a device has left any libusb_device_handle associated with the device
68  * are invalid and will remain so even if the device comes back.
69  *
70  * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered
71  * safe to call any libusb function that takes a libusb_device. It also safe to
72  * open a device and submit asynchronous transfers. However, most other functions
73  * that take a libusb_device_handle are <b>not</b> safe to call. Examples of such
74  * functions are any of the \ref libusb_syncio "synchronous API" functions or the blocking
75  * functions that retrieve various \ref libusb_desc "USB descriptors". These functions must
76  * be used outside of the context of the hotplug callback.
77  *
78  * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function
79  * is libusb_get_device_descriptor().
80  *
81  * The following code provides an example of the usage of the hotplug interface:
82 \code
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <time.h>
86 #include <libusb.h>
87
88 static int count = 0;
89
90 int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
91                      libusb_hotplug_event event, void *user_data) {
92   static libusb_device_handle *dev_handle = NULL;
93   struct libusb_device_descriptor desc;
94   int rc;
95
96   (void)libusb_get_device_descriptor(dev, &desc);
97
98   if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
99     rc = libusb_open(dev, &dev_handle);
100     if (LIBUSB_SUCCESS != rc) {
101       printf("Could not open USB device\n");
102     }
103   } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
104     if (dev_handle) {
105       libusb_close(dev_handle);
106       dev_handle = NULL;
107     }
108   } else {
109     printf("Unhandled event %d\n", event);
110   }
111   count++;
112
113   return 0;
114 }
115
116 int main (void) {
117   libusb_hotplug_callback_handle callback_handle;
118   int rc;
119
120   libusb_init(NULL);
121
122   rc = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
123                                         LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, 0x045a, 0x5005,
124                                         LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
125                                         &callback_handle);
126   if (LIBUSB_SUCCESS != rc) {
127     printf("Error creating a hotplug callback\n");
128     libusb_exit(NULL);
129     return EXIT_FAILURE;
130   }
131
132   while (count < 2) {
133     libusb_handle_events_completed(NULL, NULL);
134     nanosleep(&(struct timespec){0, 10000000UL}, NULL);
135   }
136
137   libusb_hotplug_deregister_callback(NULL, callback_handle);
138   libusb_exit(NULL);
139
140   return 0;
141 }
142 \endcode
143  */
144
145 #define VALID_HOTPLUG_EVENTS                    \
146         (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |  \
147          LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
148
149 #define VALID_HOTPLUG_FLAGS                     \
150         (LIBUSB_HOTPLUG_ENUMERATE)
151
152 void usbi_hotplug_init(struct libusb_context *ctx)
153 {
154         /* check for hotplug support */
155         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
156                 return;
157
158         usbi_mutex_init(&ctx->hotplug_cbs_lock);
159         list_init(&ctx->hotplug_cbs);
160         ctx->next_hotplug_cb_handle = 1;
161         usbi_atomic_store(&ctx->hotplug_ready, 1);
162 }
163
164 void usbi_hotplug_exit(struct libusb_context *ctx)
165 {
166         struct usbi_hotplug_callback *hotplug_cb, *next_cb;
167         struct usbi_hotplug_message *msg;
168         struct libusb_device *dev, *next_dev;
169
170         /* check for hotplug support */
171         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
172                 return;
173
174         /* free all registered hotplug callbacks */
175         for_each_hotplug_cb_safe(ctx, hotplug_cb, next_cb) {
176                 list_del(&hotplug_cb->list);
177                 free(hotplug_cb);
178         }
179
180         /* free all pending hotplug messages */
181         while (!list_empty(&ctx->hotplug_msgs)) {
182                 msg = list_first_entry(&ctx->hotplug_msgs, struct usbi_hotplug_message, list);
183
184                 /* if the device left, the message holds a reference
185                  * and we must drop it */
186                 if (msg->event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
187                         libusb_unref_device(msg->device);
188
189                 list_del(&msg->list);
190                 free(msg);
191         }
192
193         /* free all discovered devices. due to parent references loop until no devices are freed. */
194         for_each_device_safe(ctx, dev, next_dev) {
195                 /* remove the device from the usb_devs list only if there are no
196                  * references held, otherwise leave it on the list so that a
197                  * warning message will be shown */
198                 if (usbi_atomic_load(&dev->refcnt) == 1) {
199                         list_del(&dev->list);
200                 }
201                 if (dev->parent_dev && usbi_atomic_load(&dev->parent_dev->refcnt) == 1) {
202                         /* the parent was before this device in the list and will be released.
203                            remove it from the list. this is safe as parent_dev can not be
204                            equal to next_dev. */
205                         assert (dev->parent_dev != next_dev);
206                         list_del(&dev->parent_dev->list);
207                 }
208                 libusb_unref_device(dev);
209         }
210
211         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
212 }
213
214 static int usbi_hotplug_match_cb(struct libusb_device *dev,
215         libusb_hotplug_event event, struct usbi_hotplug_callback *hotplug_cb)
216 {
217         if (!(hotplug_cb->flags & event)) {
218                 return 0;
219         }
220
221         if ((hotplug_cb->flags & USBI_HOTPLUG_VENDOR_ID_VALID) &&
222             hotplug_cb->vendor_id != dev->device_descriptor.idVendor) {
223                 return 0;
224         }
225
226         if ((hotplug_cb->flags & USBI_HOTPLUG_PRODUCT_ID_VALID) &&
227             hotplug_cb->product_id != dev->device_descriptor.idProduct) {
228                 return 0;
229         }
230
231         if ((hotplug_cb->flags & USBI_HOTPLUG_DEV_CLASS_VALID) &&
232             hotplug_cb->dev_class != dev->device_descriptor.bDeviceClass) {
233                 return 0;
234         }
235
236         return hotplug_cb->cb(DEVICE_CTX(dev), dev, event, hotplug_cb->user_data);
237 }
238
239 void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
240         libusb_hotplug_event event)
241 {
242         struct usbi_hotplug_message *msg;
243         unsigned int event_flags;
244
245         /* Only generate a notification if hotplug is ready. This prevents hotplug
246          * notifications from being generated during initial enumeration or if the
247          * backend does not support hotplug. */
248         if (!usbi_atomic_load(&ctx->hotplug_ready))
249                 return;
250
251         msg = calloc(1, sizeof(*msg));
252         if (!msg) {
253                 usbi_err(ctx, "error allocating hotplug message");
254                 return;
255         }
256
257         msg->event = event;
258         msg->device = dev;
259
260         /* Take the event data lock and add this message to the list.
261          * Only signal an event if there are no prior pending events. */
262         usbi_mutex_lock(&ctx->event_data_lock);
263         event_flags = ctx->event_flags;
264         ctx->event_flags |= USBI_EVENT_HOTPLUG_MSG_PENDING;
265         list_add_tail(&msg->list, &ctx->hotplug_msgs);
266         if (!event_flags)
267                 usbi_signal_event(&ctx->event);
268         usbi_mutex_unlock(&ctx->event_data_lock);
269 }
270
271 void usbi_hotplug_process(struct libusb_context *ctx, struct list_head *hotplug_msgs)
272 {
273         struct usbi_hotplug_callback *hotplug_cb, *next_cb;
274         struct usbi_hotplug_message *msg;
275         int r;
276
277         usbi_mutex_lock(&ctx->hotplug_cbs_lock);
278
279         /* dispatch all pending hotplug messages */
280         while (!list_empty(hotplug_msgs)) {
281                 msg = list_first_entry(hotplug_msgs, struct usbi_hotplug_message, list);
282
283                 for_each_hotplug_cb_safe(ctx, hotplug_cb, next_cb) {
284                         /* skip callbacks that have unregistered */
285                         if (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE)
286                                 continue;
287
288                         usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
289                         r = usbi_hotplug_match_cb(msg->device, msg->event, hotplug_cb);
290                         usbi_mutex_lock(&ctx->hotplug_cbs_lock);
291
292                         if (r) {
293                                 list_del(&hotplug_cb->list);
294                                 free(hotplug_cb);
295                         }
296                 }
297
298                 /* if the device left, the message holds a reference
299                  * and we must drop it */
300                 if (msg->event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
301                         libusb_unref_device(msg->device);
302
303                 list_del(&msg->list);
304                 free(msg);
305         }
306
307         /* free any callbacks that have unregistered */
308         for_each_hotplug_cb_safe(ctx, hotplug_cb, next_cb) {
309                 if (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE) {
310                         usbi_dbg("freeing hotplug cb %p with handle %d",
311                                 hotplug_cb, hotplug_cb->handle);
312                         list_del(&hotplug_cb->list);
313                         free(hotplug_cb);
314                 }
315         }
316
317         usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
318 }
319
320 int API_EXPORTED libusb_hotplug_register_callback(libusb_context *ctx,
321         int events, int flags,
322         int vendor_id, int product_id, int dev_class,
323         libusb_hotplug_callback_fn cb_fn, void *user_data,
324         libusb_hotplug_callback_handle *callback_handle)
325 {
326         struct usbi_hotplug_callback *hotplug_cb;
327
328         /* check for sane values */
329         if (!events || (~VALID_HOTPLUG_EVENTS & events) ||
330             (~VALID_HOTPLUG_FLAGS & flags) ||
331             (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id && (~0xffff & vendor_id)) ||
332             (LIBUSB_HOTPLUG_MATCH_ANY != product_id && (~0xffff & product_id)) ||
333             (LIBUSB_HOTPLUG_MATCH_ANY != dev_class && (~0xff & dev_class)) ||
334             !cb_fn) {
335                 return LIBUSB_ERROR_INVALID_PARAM;
336         }
337
338         /* check for hotplug support */
339         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
340                 return LIBUSB_ERROR_NOT_SUPPORTED;
341
342         ctx = usbi_get_context(ctx);
343
344         hotplug_cb = calloc(1, sizeof(*hotplug_cb));
345         if (!hotplug_cb)
346                 return LIBUSB_ERROR_NO_MEM;
347
348         hotplug_cb->flags = (uint8_t)events;
349         if (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id) {
350                 hotplug_cb->flags |= USBI_HOTPLUG_VENDOR_ID_VALID;
351                 hotplug_cb->vendor_id = (uint16_t)vendor_id;
352         }
353         if (LIBUSB_HOTPLUG_MATCH_ANY != product_id) {
354                 hotplug_cb->flags |= USBI_HOTPLUG_PRODUCT_ID_VALID;
355                 hotplug_cb->product_id = (uint16_t)product_id;
356         }
357         if (LIBUSB_HOTPLUG_MATCH_ANY != dev_class) {
358                 hotplug_cb->flags |= USBI_HOTPLUG_DEV_CLASS_VALID;
359                 hotplug_cb->dev_class = (uint8_t)dev_class;
360         }
361         hotplug_cb->cb = cb_fn;
362         hotplug_cb->user_data = user_data;
363
364         usbi_mutex_lock(&ctx->hotplug_cbs_lock);
365
366         /* protect the handle by the context hotplug lock */
367         hotplug_cb->handle = ctx->next_hotplug_cb_handle++;
368
369         /* handle the unlikely case of overflow */
370         if (ctx->next_hotplug_cb_handle < 0)
371                 ctx->next_hotplug_cb_handle = 1;
372
373         list_add(&hotplug_cb->list, &ctx->hotplug_cbs);
374
375         usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
376
377         usbi_dbg("new hotplug cb %p with handle %d", hotplug_cb, hotplug_cb->handle);
378
379         if ((flags & LIBUSB_HOTPLUG_ENUMERATE) && (events & LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)) {
380                 ssize_t i, len;
381                 struct libusb_device **devs;
382
383                 len = libusb_get_device_list(ctx, &devs);
384                 if (len < 0) {
385                         libusb_hotplug_deregister_callback(ctx, hotplug_cb->handle);
386                         return (int)len;
387                 }
388
389                 for (i = 0; i < len; i++) {
390                         usbi_hotplug_match_cb(devs[i],
391                                         LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
392                                         hotplug_cb);
393                 }
394
395                 libusb_free_device_list(devs, 1);
396         }
397
398         if (callback_handle)
399                 *callback_handle = hotplug_cb->handle;
400
401         return LIBUSB_SUCCESS;
402 }
403
404 void API_EXPORTED libusb_hotplug_deregister_callback(libusb_context *ctx,
405         libusb_hotplug_callback_handle callback_handle)
406 {
407         struct usbi_hotplug_callback *hotplug_cb;
408         int deregistered = 0;
409
410         /* check for hotplug support */
411         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
412                 return;
413
414         usbi_dbg("deregister hotplug cb %d", callback_handle);
415
416         ctx = usbi_get_context(ctx);
417
418         usbi_mutex_lock(&ctx->hotplug_cbs_lock);
419         for_each_hotplug_cb(ctx, hotplug_cb) {
420                 if (callback_handle == hotplug_cb->handle) {
421                         /* mark this callback for deregistration */
422                         hotplug_cb->flags |= USBI_HOTPLUG_NEEDS_FREE;
423                         deregistered = 1;
424                         break;
425                 }
426         }
427         usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
428
429         if (deregistered) {
430                 unsigned int event_flags;
431
432                 usbi_mutex_lock(&ctx->event_data_lock);
433                 event_flags = ctx->event_flags;
434                 ctx->event_flags |= USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
435                 if (!event_flags)
436                         usbi_signal_event(&ctx->event);
437                 usbi_mutex_unlock(&ctx->event_data_lock);
438         }
439 }
440
441 DEFAULT_VISIBILITY
442 void * LIBUSB_CALL libusb_hotplug_get_user_data(libusb_context *ctx,
443         libusb_hotplug_callback_handle callback_handle)
444 {
445         struct usbi_hotplug_callback *hotplug_cb;
446         void *user_data = NULL;
447
448         /* check for hotplug support */
449         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
450                 return NULL;
451
452         usbi_dbg("get hotplug cb %d user data", callback_handle);
453
454         ctx = usbi_get_context(ctx);
455
456         usbi_mutex_lock(&ctx->hotplug_cbs_lock);
457         for_each_hotplug_cb(ctx, hotplug_cb) {
458                 if (callback_handle == hotplug_cb->handle) {
459                         user_data = hotplug_cb->user_data;
460                         break;
461                 }
462         }
463         usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
464
465         return user_data;
466 }