xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 0bdb12c7)
1 /*
2  * Media Transfer Protocol implementation, backed by host filesystem.
3  *
4  * Copyright Red Hat, Inc 2014
5  *
6  * Author:
7  *   Gerd Hoffmann <kraxel@redhat.com>
8  *
9  * This code is licensed under the GPL v2 or later.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include <wchar.h>
15 #include <dirent.h>
16 
17 #include <sys/statvfs.h>
18 #ifdef CONFIG_INOTIFY1
19 #include <sys/inotify.h>
20 #include "qapi/error.h"
21 #include "qemu/main-loop.h"
22 #endif
23 
24 #include "qemu-common.h"
25 #include "qemu/iov.h"
26 #include "trace.h"
27 #include "hw/usb.h"
28 #include "hw/usb/desc.h"
29 
30 /* ----------------------------------------------------------------------- */
31 
32 enum mtp_container_type {
33     TYPE_COMMAND  = 1,
34     TYPE_DATA     = 2,
35     TYPE_RESPONSE = 3,
36     TYPE_EVENT    = 4,
37 };
38 
39 enum mtp_code {
40     /* command codes */
41     CMD_GET_DEVICE_INFO            = 0x1001,
42     CMD_OPEN_SESSION               = 0x1002,
43     CMD_CLOSE_SESSION              = 0x1003,
44     CMD_GET_STORAGE_IDS            = 0x1004,
45     CMD_GET_STORAGE_INFO           = 0x1005,
46     CMD_GET_NUM_OBJECTS            = 0x1006,
47     CMD_GET_OBJECT_HANDLES         = 0x1007,
48     CMD_GET_OBJECT_INFO            = 0x1008,
49     CMD_GET_OBJECT                 = 0x1009,
50     CMD_GET_PARTIAL_OBJECT         = 0x101b,
51     CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
52     CMD_GET_OBJECT_PROP_DESC       = 0x9802,
53     CMD_GET_OBJECT_PROP_VALUE      = 0x9803,
54 
55     /* response codes */
56     RES_OK                         = 0x2001,
57     RES_GENERAL_ERROR              = 0x2002,
58     RES_SESSION_NOT_OPEN           = 0x2003,
59     RES_INVALID_TRANSACTION_ID     = 0x2004,
60     RES_OPERATION_NOT_SUPPORTED    = 0x2005,
61     RES_PARAMETER_NOT_SUPPORTED    = 0x2006,
62     RES_INCOMPLETE_TRANSFER        = 0x2007,
63     RES_INVALID_STORAGE_ID         = 0x2008,
64     RES_INVALID_OBJECT_HANDLE      = 0x2009,
65     RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
66     RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
67     RES_INVALID_PARENT_OBJECT      = 0x201a,
68     RES_INVALID_PARAMETER          = 0x201d,
69     RES_SESSION_ALREADY_OPEN       = 0x201e,
70     RES_INVALID_OBJECT_PROP_CODE   = 0xA801,
71 
72     /* format codes */
73     FMT_UNDEFINED_OBJECT           = 0x3000,
74     FMT_ASSOCIATION                = 0x3001,
75 
76     /* event codes */
77     EVT_OBJ_ADDED                  = 0x4002,
78     EVT_OBJ_REMOVED                = 0x4003,
79     EVT_OBJ_INFO_CHANGED           = 0x4007,
80 
81     /* object properties */
82     PROP_STORAGE_ID                = 0xDC01,
83     PROP_OBJECT_FORMAT             = 0xDC02,
84     PROP_OBJECT_COMPRESSED_SIZE    = 0xDC04,
85     PROP_PARENT_OBJECT             = 0xDC0B,
86     PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
87     PROP_NAME                      = 0xDC44,
88 };
89 
90 enum mtp_data_type {
91     DATA_TYPE_UINT16  = 0x0004,
92     DATA_TYPE_UINT32  = 0x0006,
93     DATA_TYPE_UINT64  = 0x0008,
94     DATA_TYPE_UINT128 = 0x000a,
95     DATA_TYPE_STRING  = 0xffff,
96 };
97 
98 typedef struct {
99     uint32_t length;
100     uint16_t type;
101     uint16_t code;
102     uint32_t trans;
103 } QEMU_PACKED mtp_container;
104 
105 /* ----------------------------------------------------------------------- */
106 
107 typedef struct MTPState MTPState;
108 typedef struct MTPControl MTPControl;
109 typedef struct MTPData MTPData;
110 typedef struct MTPObject MTPObject;
111 
112 enum {
113     EP_DATA_IN = 1,
114     EP_DATA_OUT,
115     EP_EVENT,
116 };
117 
118 #ifdef CONFIG_INOTIFY1
119 typedef struct MTPMonEntry MTPMonEntry;
120 
121 struct MTPMonEntry {
122     uint32_t event;
123     uint32_t handle;
124 
125     QTAILQ_ENTRY(MTPMonEntry) next;
126 };
127 #endif
128 
129 struct MTPControl {
130     uint16_t     code;
131     uint32_t     trans;
132     int          argc;
133     uint32_t     argv[5];
134 };
135 
136 struct MTPData {
137     uint16_t     code;
138     uint32_t     trans;
139     uint64_t     offset;
140     uint64_t     length;
141     uint32_t     alloc;
142     uint8_t      *data;
143     bool         first;
144     int          fd;
145 };
146 
147 struct MTPObject {
148     uint32_t     handle;
149     uint16_t     format;
150     char         *name;
151     char         *path;
152     struct stat  stat;
153 #ifdef CONFIG_INOTIFY1
154     /* inotify watch cookie */
155     int          watchfd;
156 #endif
157     MTPObject    *parent;
158     uint32_t     nchildren;
159     QLIST_HEAD(, MTPObject) children;
160     QLIST_ENTRY(MTPObject) list;
161     bool         have_children;
162     QTAILQ_ENTRY(MTPObject) next;
163 };
164 
165 struct MTPState {
166     USBDevice    dev;
167     char         *root;
168     char         *desc;
169     uint32_t     flags;
170 
171     MTPData      *data_in;
172     MTPData      *data_out;
173     MTPControl   *result;
174     uint32_t     session;
175     uint32_t     next_handle;
176 
177     QTAILQ_HEAD(, MTPObject) objects;
178 #ifdef CONFIG_INOTIFY1
179     /* inotify descriptor */
180     int          inotifyfd;
181     QTAILQ_HEAD(events, MTPMonEntry) events;
182 #endif
183 };
184 
185 #define TYPE_USB_MTP "usb-mtp"
186 #define USB_MTP(obj) OBJECT_CHECK(MTPState, (obj), TYPE_USB_MTP)
187 
188 #define QEMU_STORAGE_ID 0x00010001
189 
190 #define MTP_FLAG_WRITABLE 0
191 
192 #define FLAG_SET(_mtp, _flag)  ((_mtp)->flags & (1 << (_flag)))
193 
194 /* ----------------------------------------------------------------------- */
195 
196 #define MTP_MANUFACTURER  "QEMU"
197 #define MTP_PRODUCT       "QEMU filesharing"
198 
199 enum {
200     STR_MANUFACTURER = 1,
201     STR_PRODUCT,
202     STR_SERIALNUMBER,
203     STR_MTP,
204     STR_CONFIG_FULL,
205     STR_CONFIG_HIGH,
206     STR_CONFIG_SUPER,
207 };
208 
209 static const USBDescStrings desc_strings = {
210     [STR_MANUFACTURER] = MTP_MANUFACTURER,
211     [STR_PRODUCT]      = MTP_PRODUCT,
212     [STR_SERIALNUMBER] = "34617",
213     [STR_MTP]          = "MTP",
214     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
215     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
216     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
217 };
218 
219 static const USBDescIface desc_iface_full = {
220     .bInterfaceNumber              = 0,
221     .bNumEndpoints                 = 3,
222     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
223     .bInterfaceSubClass            = 0x01,
224     .bInterfaceProtocol            = 0x01,
225     .iInterface                    = STR_MTP,
226     .eps = (USBDescEndpoint[]) {
227         {
228             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
229             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
230             .wMaxPacketSize        = 64,
231         },{
232             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
233             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
234             .wMaxPacketSize        = 64,
235         },{
236             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
237             .bmAttributes          = USB_ENDPOINT_XFER_INT,
238             .wMaxPacketSize        = 64,
239             .bInterval             = 0x0a,
240         },
241     }
242 };
243 
244 static const USBDescDevice desc_device_full = {
245     .bcdUSB                        = 0x0200,
246     .bMaxPacketSize0               = 8,
247     .bNumConfigurations            = 1,
248     .confs = (USBDescConfig[]) {
249         {
250             .bNumInterfaces        = 1,
251             .bConfigurationValue   = 1,
252             .iConfiguration        = STR_CONFIG_FULL,
253             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
254             .bMaxPower             = 2,
255             .nif = 1,
256             .ifs = &desc_iface_full,
257         },
258     },
259 };
260 
261 static const USBDescIface desc_iface_high = {
262     .bInterfaceNumber              = 0,
263     .bNumEndpoints                 = 3,
264     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
265     .bInterfaceSubClass            = 0x01,
266     .bInterfaceProtocol            = 0x01,
267     .iInterface                    = STR_MTP,
268     .eps = (USBDescEndpoint[]) {
269         {
270             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
271             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
272             .wMaxPacketSize        = 512,
273         },{
274             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
275             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
276             .wMaxPacketSize        = 512,
277         },{
278             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
279             .bmAttributes          = USB_ENDPOINT_XFER_INT,
280             .wMaxPacketSize        = 64,
281             .bInterval             = 0x0a,
282         },
283     }
284 };
285 
286 static const USBDescDevice desc_device_high = {
287     .bcdUSB                        = 0x0200,
288     .bMaxPacketSize0               = 64,
289     .bNumConfigurations            = 1,
290     .confs = (USBDescConfig[]) {
291         {
292             .bNumInterfaces        = 1,
293             .bConfigurationValue   = 1,
294             .iConfiguration        = STR_CONFIG_HIGH,
295             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
296             .bMaxPower             = 2,
297             .nif = 1,
298             .ifs = &desc_iface_high,
299         },
300     },
301 };
302 
303 static const USBDescMSOS desc_msos = {
304     .CompatibleID = "MTP",
305     .SelectiveSuspendEnabled = true,
306 };
307 
308 static const USBDesc desc = {
309     .id = {
310         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
311         .idProduct         = 0x0004,
312         .bcdDevice         = 0,
313         .iManufacturer     = STR_MANUFACTURER,
314         .iProduct          = STR_PRODUCT,
315         .iSerialNumber     = STR_SERIALNUMBER,
316     },
317     .full  = &desc_device_full,
318     .high  = &desc_device_high,
319     .str   = desc_strings,
320     .msos  = &desc_msos,
321 };
322 
323 /* ----------------------------------------------------------------------- */
324 
325 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
326                                        MTPObject *parent, char *name)
327 {
328     MTPObject *o = g_new0(MTPObject, 1);
329 
330     if (name[0] == '.') {
331         goto ignore;
332     }
333 
334     o->handle = handle;
335     o->parent = parent;
336     o->name = g_strdup(name);
337     if (parent == NULL) {
338         o->path = g_strdup(name);
339     } else {
340         o->path = g_strdup_printf("%s/%s", parent->path, name);
341     }
342 
343     if (lstat(o->path, &o->stat) != 0) {
344         goto ignore;
345     }
346     if (S_ISREG(o->stat.st_mode)) {
347         o->format = FMT_UNDEFINED_OBJECT;
348     } else if (S_ISDIR(o->stat.st_mode)) {
349         o->format = FMT_ASSOCIATION;
350     } else {
351         goto ignore;
352     }
353 
354     if (access(o->path, R_OK) != 0) {
355         goto ignore;
356     }
357 
358     trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
359 
360     QTAILQ_INSERT_TAIL(&s->objects, o, next);
361     return o;
362 
363 ignore:
364     g_free(o->name);
365     g_free(o->path);
366     g_free(o);
367     return NULL;
368 }
369 
370 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
371 {
372     MTPObject *iter;
373 
374     if (!o) {
375         return;
376     }
377 
378     trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
379 
380     QTAILQ_REMOVE(&s->objects, o, next);
381     if (o->parent) {
382         QLIST_REMOVE(o, list);
383         o->parent->nchildren--;
384     }
385 
386     while (!QLIST_EMPTY(&o->children)) {
387         iter = QLIST_FIRST(&o->children);
388         usb_mtp_object_free(s, iter);
389     }
390     g_free(o->name);
391     g_free(o->path);
392     g_free(o);
393 }
394 
395 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
396 {
397     MTPObject *o;
398 
399     QTAILQ_FOREACH(o, &s->objects, next) {
400         if (o->handle == handle) {
401             return o;
402         }
403     }
404     return NULL;
405 }
406 
407 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
408                                     char *name)
409 {
410     MTPObject *child =
411         usb_mtp_object_alloc(s, s->next_handle++, o, name);
412 
413     if (child) {
414         trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
415         QLIST_INSERT_HEAD(&o->children, child, list);
416         o->nchildren++;
417 
418         if (child->format == FMT_ASSOCIATION) {
419             QLIST_INIT(&child->children);
420         }
421     }
422 
423     return child;
424 }
425 
426 #ifdef CONFIG_INOTIFY1
427 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
428                                              char *name, int len)
429 {
430     MTPObject *iter;
431 
432     QLIST_FOREACH(iter, &parent->children, list) {
433         if (strncmp(iter->name, name, len) == 0) {
434             return iter;
435         }
436     }
437 
438     return NULL;
439 }
440 
441 static MTPObject *usb_mtp_object_lookup_wd(MTPState *s, int wd)
442 {
443     MTPObject *iter;
444 
445     QTAILQ_FOREACH(iter, &s->objects, next) {
446         if (iter->watchfd == wd) {
447             return iter;
448         }
449     }
450 
451     return NULL;
452 }
453 
454 static void inotify_watchfn(void *arg)
455 {
456     MTPState *s = arg;
457     ssize_t bytes;
458     /* From the man page: atleast one event can be read */
459     int pos;
460     char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
461 
462     for (;;) {
463         bytes = read(s->inotifyfd, buf, sizeof(buf));
464         pos = 0;
465 
466         if (bytes <= 0) {
467             /* Better luck next time */
468             return;
469         }
470 
471         /*
472          * TODO: Ignore initiator initiated events.
473          * For now we are good because the store is RO
474          */
475         while (bytes > 0) {
476             char *p = buf + pos;
477             struct inotify_event *event = (struct inotify_event *)p;
478             int watchfd = 0;
479             uint32_t mask = event->mask & (IN_CREATE | IN_DELETE |
480                                            IN_MODIFY | IN_IGNORED);
481             MTPObject *parent = usb_mtp_object_lookup_wd(s, event->wd);
482             MTPMonEntry *entry = NULL;
483             MTPObject *o;
484 
485             pos = pos + sizeof(struct inotify_event) + event->len;
486             bytes = bytes - pos;
487 
488             if (!parent) {
489                 continue;
490             }
491 
492             switch (mask) {
493             case IN_CREATE:
494                 if (usb_mtp_object_lookup_name
495                     (parent, event->name, event->len)) {
496                     /* Duplicate create event */
497                     continue;
498                 }
499                 entry = g_new0(MTPMonEntry, 1);
500                 entry->handle = s->next_handle;
501                 entry->event = EVT_OBJ_ADDED;
502                 o = usb_mtp_add_child(s, parent, event->name);
503                 if (!o) {
504                     g_free(entry);
505                     continue;
506                 }
507                 o->watchfd = watchfd;
508                 trace_usb_mtp_inotify_event(s->dev.addr, event->name,
509                                             event->mask, "Obj Added");
510                 break;
511 
512             case IN_DELETE:
513                 /*
514                  * The kernel issues a IN_IGNORED event
515                  * when a dir containing a watchpoint is
516                  * deleted, so we don't have to delete the
517                  * watchpoint
518                  */
519                 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
520                 if (!o) {
521                     continue;
522                 }
523                 entry = g_new0(MTPMonEntry, 1);
524                 entry->handle = o->handle;
525                 entry->event = EVT_OBJ_REMOVED;
526                 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
527                                       event->mask, "Obj Deleted");
528                 usb_mtp_object_free(s, o);
529                 break;
530 
531             case IN_MODIFY:
532                 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
533                 if (!o) {
534                     continue;
535                 }
536                 entry = g_new0(MTPMonEntry, 1);
537                 entry->handle = o->handle;
538                 entry->event = EVT_OBJ_INFO_CHANGED;
539                 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
540                                       event->mask, "Obj Modified");
541                 break;
542 
543             case IN_IGNORED:
544                 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
545                 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
546                                       event->mask, "Obj ignored");
547                 break;
548 
549             default:
550                 fprintf(stderr, "usb-mtp: failed to parse inotify event\n");
551                 continue;
552             }
553 
554             if (entry) {
555                 QTAILQ_INSERT_HEAD(&s->events, entry, next);
556             }
557         }
558     }
559 }
560 
561 static int usb_mtp_inotify_init(MTPState *s)
562 {
563     int fd;
564 
565     fd = inotify_init1(IN_NONBLOCK);
566     if (fd == -1) {
567         return 1;
568     }
569 
570     QTAILQ_INIT(&s->events);
571     s->inotifyfd = fd;
572 
573     qemu_set_fd_handler(fd, inotify_watchfn, NULL, s);
574 
575     return 0;
576 }
577 
578 static void usb_mtp_inotify_cleanup(MTPState *s)
579 {
580     MTPMonEntry *e, *p;
581 
582     if (!s->inotifyfd) {
583         return;
584     }
585 
586     qemu_set_fd_handler(s->inotifyfd, NULL, NULL, s);
587     close(s->inotifyfd);
588 
589     QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
590         QTAILQ_REMOVE(&s->events, e, next);
591         g_free(e);
592     }
593 }
594 
595 static int usb_mtp_add_watch(int inotifyfd, char *path)
596 {
597     uint32_t mask = IN_CREATE | IN_DELETE | IN_MODIFY |
598         IN_ISDIR;
599 
600     return inotify_add_watch(inotifyfd, path, mask);
601 }
602 #endif
603 
604 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
605 {
606     struct dirent *entry;
607     DIR *dir;
608 
609     if (o->have_children) {
610         return;
611     }
612     o->have_children = true;
613 
614     dir = opendir(o->path);
615     if (!dir) {
616         return;
617     }
618 #ifdef CONFIG_INOTIFY1
619     int watchfd = usb_mtp_add_watch(s->inotifyfd, o->path);
620     if (watchfd == -1) {
621         fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path);
622     } else {
623         trace_usb_mtp_inotify_event(s->dev.addr, o->path,
624                                     0, "Watch Added");
625         o->watchfd = watchfd;
626     }
627 #endif
628     while ((entry = readdir(dir)) != NULL) {
629         usb_mtp_add_child(s, o, entry->d_name);
630     }
631     closedir(dir);
632 }
633 
634 /* ----------------------------------------------------------------------- */
635 
636 static MTPData *usb_mtp_data_alloc(MTPControl *c)
637 {
638     MTPData *data = g_new0(MTPData, 1);
639 
640     data->code  = c->code;
641     data->trans = c->trans;
642     data->fd    = -1;
643     data->first = true;
644     return data;
645 }
646 
647 static void usb_mtp_data_free(MTPData *data)
648 {
649     if (data == NULL) {
650         return;
651     }
652     if (data->fd != -1) {
653         close(data->fd);
654     }
655     g_free(data->data);
656     g_free(data);
657 }
658 
659 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
660 {
661     if (data->length + bytes <= data->alloc) {
662         return;
663     }
664     data->alloc = (data->length + bytes + 0xff) & ~0xff;
665     data->data  = g_realloc(data->data, data->alloc);
666 }
667 
668 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
669 {
670     usb_mtp_realloc(data, 1);
671     data->data[data->length++] = val;
672 }
673 
674 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
675 {
676     usb_mtp_realloc(data, 2);
677     data->data[data->length++] = (val >> 0) & 0xff;
678     data->data[data->length++] = (val >> 8) & 0xff;
679 }
680 
681 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
682 {
683     usb_mtp_realloc(data, 4);
684     data->data[data->length++] = (val >>  0) & 0xff;
685     data->data[data->length++] = (val >>  8) & 0xff;
686     data->data[data->length++] = (val >> 16) & 0xff;
687     data->data[data->length++] = (val >> 24) & 0xff;
688 }
689 
690 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
691 {
692     usb_mtp_realloc(data, 8);
693     data->data[data->length++] = (val >>  0) & 0xff;
694     data->data[data->length++] = (val >>  8) & 0xff;
695     data->data[data->length++] = (val >> 16) & 0xff;
696     data->data[data->length++] = (val >> 24) & 0xff;
697     data->data[data->length++] = (val >> 32) & 0xff;
698     data->data[data->length++] = (val >> 40) & 0xff;
699     data->data[data->length++] = (val >> 48) & 0xff;
700     data->data[data->length++] = (val >> 56) & 0xff;
701 }
702 
703 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
704                                   const uint16_t *vals)
705 {
706     int i;
707 
708     usb_mtp_add_u32(data, len);
709     for (i = 0; i < len; i++) {
710         usb_mtp_add_u16(data, vals[i]);
711     }
712 }
713 
714 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
715                                   const uint32_t *vals)
716 {
717     int i;
718 
719     usb_mtp_add_u32(data, len);
720     for (i = 0; i < len; i++) {
721         usb_mtp_add_u32(data, vals[i]);
722     }
723 }
724 
725 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
726 {
727     uint32_t len = wcslen(str);
728     int i;
729 
730     if (len > 0) {
731         len++; /* include terminating L'\0' */
732     }
733 
734     usb_mtp_add_u8(data, len);
735     for (i = 0; i < len; i++) {
736         usb_mtp_add_u16(data, str[i]);
737     }
738 }
739 
740 static void usb_mtp_add_str(MTPData *data, const char *str)
741 {
742     uint32_t len = strlen(str)+1;
743     wchar_t *wstr = g_new(wchar_t, len);
744     size_t ret;
745 
746     ret = mbstowcs(wstr, str, len);
747     if (ret == -1) {
748         usb_mtp_add_wstr(data, L"Oops");
749     } else {
750         usb_mtp_add_wstr(data, wstr);
751     }
752 
753     g_free(wstr);
754 }
755 
756 static void usb_mtp_add_time(MTPData *data, time_t time)
757 {
758     char buf[16];
759     struct tm tm;
760 
761     gmtime_r(&time, &tm);
762     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
763     usb_mtp_add_str(data, buf);
764 }
765 
766 /* ----------------------------------------------------------------------- */
767 
768 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
769                                  int argc, uint32_t arg0, uint32_t arg1)
770 {
771     MTPControl *c = g_new0(MTPControl, 1);
772 
773     c->code  = code;
774     c->trans = trans;
775     c->argc  = argc;
776     if (argc > 0) {
777         c->argv[0] = arg0;
778     }
779     if (argc > 1) {
780         c->argv[1] = arg1;
781     }
782 
783     assert(s->result == NULL);
784     s->result = c;
785 }
786 
787 /* ----------------------------------------------------------------------- */
788 
789 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
790 {
791     static const uint16_t ops[] = {
792         CMD_GET_DEVICE_INFO,
793         CMD_OPEN_SESSION,
794         CMD_CLOSE_SESSION,
795         CMD_GET_STORAGE_IDS,
796         CMD_GET_STORAGE_INFO,
797         CMD_GET_NUM_OBJECTS,
798         CMD_GET_OBJECT_HANDLES,
799         CMD_GET_OBJECT_INFO,
800         CMD_GET_OBJECT,
801         CMD_GET_PARTIAL_OBJECT,
802         CMD_GET_OBJECT_PROPS_SUPPORTED,
803         CMD_GET_OBJECT_PROP_DESC,
804         CMD_GET_OBJECT_PROP_VALUE,
805     };
806     static const uint16_t fmt[] = {
807         FMT_UNDEFINED_OBJECT,
808         FMT_ASSOCIATION,
809     };
810     MTPData *d = usb_mtp_data_alloc(c);
811 
812     trace_usb_mtp_op_get_device_info(s->dev.addr);
813 
814     usb_mtp_add_u16(d, 100);
815     usb_mtp_add_u32(d, 0x00000006);
816     usb_mtp_add_u16(d, 0x0064);
817     usb_mtp_add_wstr(d, L"");
818     usb_mtp_add_u16(d, 0x0000);
819 
820     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
821     usb_mtp_add_u16_array(d, 0, NULL);
822     usb_mtp_add_u16_array(d, 0, NULL);
823     usb_mtp_add_u16_array(d, 0, NULL);
824     usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
825 
826     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
827     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
828     usb_mtp_add_wstr(d, L"0.1");
829     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
830 
831     return d;
832 }
833 
834 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
835 {
836     static const uint32_t ids[] = {
837         QEMU_STORAGE_ID,
838     };
839     MTPData *d = usb_mtp_data_alloc(c);
840 
841     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
842 
843     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
844 
845     return d;
846 }
847 
848 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
849 {
850     MTPData *d = usb_mtp_data_alloc(c);
851     struct statvfs buf;
852     int rc;
853 
854     trace_usb_mtp_op_get_storage_info(s->dev.addr);
855 
856     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
857         usb_mtp_add_u16(d, 0x0003);
858         usb_mtp_add_u16(d, 0x0002);
859         usb_mtp_add_u16(d, 0x0000);
860     } else {
861         usb_mtp_add_u16(d, 0x0001);
862         usb_mtp_add_u16(d, 0x0002);
863         usb_mtp_add_u16(d, 0x0001);
864     }
865 
866     rc = statvfs(s->root, &buf);
867     if (rc == 0) {
868         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
869         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
870         usb_mtp_add_u32(d, buf.f_ffree);
871     } else {
872         usb_mtp_add_u64(d, 0xffffffff);
873         usb_mtp_add_u64(d, 0xffffffff);
874         usb_mtp_add_u32(d, 0xffffffff);
875     }
876 
877     usb_mtp_add_str(d, s->desc);
878     usb_mtp_add_wstr(d, L"123456789abcdef");
879     return d;
880 }
881 
882 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
883                                            MTPObject *o)
884 {
885     MTPData *d = usb_mtp_data_alloc(c);
886     uint32_t i = 0, handles[o->nchildren];
887     MTPObject *iter;
888 
889     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
890 
891     QLIST_FOREACH(iter, &o->children, list) {
892         handles[i++] = iter->handle;
893     }
894     assert(i == o->nchildren);
895     usb_mtp_add_u32_array(d, o->nchildren, handles);
896 
897     return d;
898 }
899 
900 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
901                                         MTPObject *o)
902 {
903     MTPData *d = usb_mtp_data_alloc(c);
904 
905     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
906 
907     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
908     usb_mtp_add_u16(d, o->format);
909     usb_mtp_add_u16(d, 0);
910 
911     if (o->stat.st_size > 0xFFFFFFFF) {
912         usb_mtp_add_u32(d, 0xFFFFFFFF);
913     } else {
914         usb_mtp_add_u32(d, o->stat.st_size);
915     }
916 
917     usb_mtp_add_u16(d, 0);
918     usb_mtp_add_u32(d, 0);
919     usb_mtp_add_u32(d, 0);
920     usb_mtp_add_u32(d, 0);
921     usb_mtp_add_u32(d, 0);
922     usb_mtp_add_u32(d, 0);
923     usb_mtp_add_u32(d, 0);
924 
925     if (o->parent) {
926         usb_mtp_add_u32(d, o->parent->handle);
927     } else {
928         usb_mtp_add_u32(d, 0);
929     }
930     if (o->format == FMT_ASSOCIATION) {
931         usb_mtp_add_u16(d, 0x0001);
932         usb_mtp_add_u32(d, 0x00000001);
933         usb_mtp_add_u32(d, 0);
934     } else {
935         usb_mtp_add_u16(d, 0);
936         usb_mtp_add_u32(d, 0);
937         usb_mtp_add_u32(d, 0);
938     }
939 
940     usb_mtp_add_str(d, o->name);
941     usb_mtp_add_time(d, o->stat.st_ctime);
942     usb_mtp_add_time(d, o->stat.st_mtime);
943     usb_mtp_add_wstr(d, L"");
944 
945     return d;
946 }
947 
948 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
949                                    MTPObject *o)
950 {
951     MTPData *d = usb_mtp_data_alloc(c);
952 
953     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
954 
955     d->fd = open(o->path, O_RDONLY);
956     if (d->fd == -1) {
957         usb_mtp_data_free(d);
958         return NULL;
959     }
960     d->length = o->stat.st_size;
961     d->alloc  = 512;
962     d->data   = g_malloc(d->alloc);
963     return d;
964 }
965 
966 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
967                                            MTPObject *o)
968 {
969     MTPData *d = usb_mtp_data_alloc(c);
970     off_t offset;
971 
972     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
973                                         c->argv[1], c->argv[2]);
974 
975     d->fd = open(o->path, O_RDONLY);
976     if (d->fd == -1) {
977         usb_mtp_data_free(d);
978         return NULL;
979     }
980 
981     offset = c->argv[1];
982     if (offset > o->stat.st_size) {
983         offset = o->stat.st_size;
984     }
985     if (lseek(d->fd, offset, SEEK_SET) < 0) {
986         usb_mtp_data_free(d);
987         return NULL;
988     }
989 
990     d->length = c->argv[2];
991     if (d->length > o->stat.st_size - offset) {
992         d->length = o->stat.st_size - offset;
993     }
994 
995     return d;
996 }
997 
998 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
999 {
1000     static const uint16_t props[] = {
1001         PROP_STORAGE_ID,
1002         PROP_OBJECT_FORMAT,
1003         PROP_OBJECT_COMPRESSED_SIZE,
1004         PROP_PARENT_OBJECT,
1005         PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1006         PROP_NAME,
1007     };
1008     MTPData *d = usb_mtp_data_alloc(c);
1009     usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1010 
1011     return d;
1012 }
1013 
1014 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1015 {
1016     MTPData *d = usb_mtp_data_alloc(c);
1017     switch (c->argv[0]) {
1018     case PROP_STORAGE_ID:
1019         usb_mtp_add_u16(d, PROP_STORAGE_ID);
1020         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1021         usb_mtp_add_u8(d, 0x00);
1022         usb_mtp_add_u32(d, 0x00000000);
1023         usb_mtp_add_u32(d, 0x00000000);
1024         usb_mtp_add_u8(d, 0x00);
1025         break;
1026     case PROP_OBJECT_FORMAT:
1027         usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1028         usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1029         usb_mtp_add_u8(d, 0x00);
1030         usb_mtp_add_u16(d, 0x0000);
1031         usb_mtp_add_u32(d, 0x00000000);
1032         usb_mtp_add_u8(d, 0x00);
1033         break;
1034     case PROP_OBJECT_COMPRESSED_SIZE:
1035         usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1036         usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1037         usb_mtp_add_u8(d, 0x00);
1038         usb_mtp_add_u64(d, 0x0000000000000000);
1039         usb_mtp_add_u32(d, 0x00000000);
1040         usb_mtp_add_u8(d, 0x00);
1041         break;
1042     case PROP_PARENT_OBJECT:
1043         usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1044         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1045         usb_mtp_add_u8(d, 0x00);
1046         usb_mtp_add_u32(d, 0x00000000);
1047         usb_mtp_add_u32(d, 0x00000000);
1048         usb_mtp_add_u8(d, 0x00);
1049         break;
1050     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1051         usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1052         usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1053         usb_mtp_add_u8(d, 0x00);
1054         usb_mtp_add_u64(d, 0x0000000000000000);
1055         usb_mtp_add_u64(d, 0x0000000000000000);
1056         usb_mtp_add_u32(d, 0x00000000);
1057         usb_mtp_add_u8(d, 0x00);
1058         break;
1059     case PROP_NAME:
1060         usb_mtp_add_u16(d, PROP_NAME);
1061         usb_mtp_add_u16(d, DATA_TYPE_STRING);
1062         usb_mtp_add_u8(d, 0x00);
1063         usb_mtp_add_u8(d, 0x00);
1064         usb_mtp_add_u32(d, 0x00000000);
1065         usb_mtp_add_u8(d, 0x00);
1066         break;
1067     default:
1068         usb_mtp_data_free(d);
1069         return NULL;
1070     }
1071 
1072     return d;
1073 }
1074 
1075 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1076                                               MTPObject *o)
1077 {
1078     MTPData *d = usb_mtp_data_alloc(c);
1079     switch (c->argv[1]) {
1080     case PROP_STORAGE_ID:
1081         usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1082         break;
1083     case PROP_OBJECT_FORMAT:
1084         usb_mtp_add_u16(d, o->format);
1085         break;
1086     case PROP_OBJECT_COMPRESSED_SIZE:
1087         usb_mtp_add_u64(d, o->stat.st_size);
1088         break;
1089     case PROP_PARENT_OBJECT:
1090         if (o->parent == NULL) {
1091             usb_mtp_add_u32(d, 0x00000000);
1092         } else {
1093             usb_mtp_add_u32(d, o->parent->handle);
1094         }
1095         break;
1096     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1097         /* Should be persistant between sessions,
1098          * but using our objedt ID is "good enough"
1099          * for now */
1100         usb_mtp_add_u64(d, 0x0000000000000000);
1101         usb_mtp_add_u64(d, o->handle);
1102         break;
1103     case PROP_NAME:
1104         usb_mtp_add_str(d, o->name);
1105         break;
1106     default:
1107         usb_mtp_data_free(d);
1108         return NULL;
1109     }
1110 
1111     return d;
1112 }
1113 
1114 static void usb_mtp_command(MTPState *s, MTPControl *c)
1115 {
1116     MTPData *data_in = NULL;
1117     MTPObject *o;
1118     uint32_t nres = 0, res0 = 0;
1119 
1120     /* sanity checks */
1121     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1122         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1123                              c->trans, 0, 0, 0);
1124         return;
1125     }
1126 
1127     /* process commands */
1128     switch (c->code) {
1129     case CMD_GET_DEVICE_INFO:
1130         data_in = usb_mtp_get_device_info(s, c);
1131         break;
1132     case CMD_OPEN_SESSION:
1133         if (s->session) {
1134             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1135                                  c->trans, 1, s->session, 0);
1136             return;
1137         }
1138         if (c->argv[0] == 0) {
1139             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1140                                  c->trans, 0, 0, 0);
1141             return;
1142         }
1143         trace_usb_mtp_op_open_session(s->dev.addr);
1144         s->session = c->argv[0];
1145         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1146 #ifdef CONFIG_INOTIFY1
1147         if (usb_mtp_inotify_init(s)) {
1148             fprintf(stderr, "usb-mtp: file monitoring init failed\n");
1149         }
1150 #endif
1151         break;
1152     case CMD_CLOSE_SESSION:
1153         trace_usb_mtp_op_close_session(s->dev.addr);
1154         s->session = 0;
1155         s->next_handle = 0;
1156 #ifdef CONFIG_INOTIFY1
1157         usb_mtp_inotify_cleanup(s);
1158 #endif
1159         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1160         assert(QTAILQ_EMPTY(&s->objects));
1161         break;
1162     case CMD_GET_STORAGE_IDS:
1163         data_in = usb_mtp_get_storage_ids(s, c);
1164         break;
1165     case CMD_GET_STORAGE_INFO:
1166         if (c->argv[0] != QEMU_STORAGE_ID &&
1167             c->argv[0] != 0xffffffff) {
1168             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1169                                  c->trans, 0, 0, 0);
1170             return;
1171         }
1172         data_in = usb_mtp_get_storage_info(s, c);
1173         break;
1174     case CMD_GET_NUM_OBJECTS:
1175     case CMD_GET_OBJECT_HANDLES:
1176         if (c->argv[0] != QEMU_STORAGE_ID &&
1177             c->argv[0] != 0xffffffff) {
1178             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1179                                  c->trans, 0, 0, 0);
1180             return;
1181         }
1182         if (c->argv[1] != 0x00000000) {
1183             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1184                                  c->trans, 0, 0, 0);
1185             return;
1186         }
1187         if (c->argv[2] == 0x00000000 ||
1188             c->argv[2] == 0xffffffff) {
1189             o = QTAILQ_FIRST(&s->objects);
1190         } else {
1191             o = usb_mtp_object_lookup(s, c->argv[2]);
1192         }
1193         if (o == NULL) {
1194             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1195                                  c->trans, 0, 0, 0);
1196             return;
1197         }
1198         if (o->format != FMT_ASSOCIATION) {
1199             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1200                                  c->trans, 0, 0, 0);
1201             return;
1202         }
1203         usb_mtp_object_readdir(s, o);
1204         if (c->code == CMD_GET_NUM_OBJECTS) {
1205             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1206             nres = 1;
1207             res0 = o->nchildren;
1208         } else {
1209             data_in = usb_mtp_get_object_handles(s, c, o);
1210         }
1211         break;
1212     case CMD_GET_OBJECT_INFO:
1213         o = usb_mtp_object_lookup(s, c->argv[0]);
1214         if (o == NULL) {
1215             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1216                                  c->trans, 0, 0, 0);
1217             return;
1218         }
1219         data_in = usb_mtp_get_object_info(s, c, o);
1220         break;
1221     case CMD_GET_OBJECT:
1222         o = usb_mtp_object_lookup(s, c->argv[0]);
1223         if (o == NULL) {
1224             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1225                                  c->trans, 0, 0, 0);
1226             return;
1227         }
1228         if (o->format == FMT_ASSOCIATION) {
1229             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1230                                  c->trans, 0, 0, 0);
1231             return;
1232         }
1233         data_in = usb_mtp_get_object(s, c, o);
1234         if (data_in == NULL) {
1235             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1236                                  c->trans, 0, 0, 0);
1237             return;
1238         }
1239         break;
1240     case CMD_GET_PARTIAL_OBJECT:
1241         o = usb_mtp_object_lookup(s, c->argv[0]);
1242         if (o == NULL) {
1243             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1244                                  c->trans, 0, 0, 0);
1245             return;
1246         }
1247         if (o->format == FMT_ASSOCIATION) {
1248             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1249                                  c->trans, 0, 0, 0);
1250             return;
1251         }
1252         data_in = usb_mtp_get_partial_object(s, c, o);
1253         if (data_in == NULL) {
1254             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1255                                  c->trans, 0, 0, 0);
1256             return;
1257         }
1258         nres = 1;
1259         res0 = data_in->length;
1260         break;
1261     case CMD_GET_OBJECT_PROPS_SUPPORTED:
1262         if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1263             c->argv[0] != FMT_ASSOCIATION) {
1264             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1265                                  c->trans, 0, 0, 0);
1266             return;
1267         }
1268         data_in = usb_mtp_get_object_props_supported(s, c);
1269         break;
1270     case CMD_GET_OBJECT_PROP_DESC:
1271         if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1272             c->argv[1] != FMT_ASSOCIATION) {
1273             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1274                                  c->trans, 0, 0, 0);
1275             return;
1276         }
1277         data_in = usb_mtp_get_object_prop_desc(s, c);
1278         if (data_in == NULL) {
1279             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1280                                  c->trans, 0, 0, 0);
1281             return;
1282         }
1283         break;
1284     case CMD_GET_OBJECT_PROP_VALUE:
1285         o = usb_mtp_object_lookup(s, c->argv[0]);
1286         if (o == NULL) {
1287             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1288                                  c->trans, 0, 0, 0);
1289             return;
1290         }
1291         data_in = usb_mtp_get_object_prop_value(s, c, o);
1292         if (data_in == NULL) {
1293             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1294                                  c->trans, 0, 0, 0);
1295             return;
1296         }
1297         break;
1298     default:
1299         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1300         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1301                              c->trans, 0, 0, 0);
1302         return;
1303     }
1304 
1305     /* return results on success */
1306     if (data_in) {
1307         assert(s->data_in == NULL);
1308         s->data_in = data_in;
1309     }
1310     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0);
1311 }
1312 
1313 /* ----------------------------------------------------------------------- */
1314 
1315 static void usb_mtp_handle_reset(USBDevice *dev)
1316 {
1317     MTPState *s = USB_MTP(dev);
1318 
1319     trace_usb_mtp_reset(s->dev.addr);
1320 
1321 #ifdef CONFIG_INOTIFY1
1322     usb_mtp_inotify_cleanup(s);
1323 #endif
1324     usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1325     s->session = 0;
1326     usb_mtp_data_free(s->data_in);
1327     s->data_in = NULL;
1328     usb_mtp_data_free(s->data_out);
1329     s->data_out = NULL;
1330     g_free(s->result);
1331     s->result = NULL;
1332 }
1333 
1334 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1335                                    int request, int value, int index,
1336                                    int length, uint8_t *data)
1337 {
1338     int ret;
1339 
1340     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
1341     if (ret >= 0) {
1342         return;
1343     }
1344 
1345     trace_usb_mtp_stall(dev->addr, "unknown control request");
1346     p->status = USB_RET_STALL;
1347 }
1348 
1349 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1350 {
1351     /* we don't use async packets, so this should never be called */
1352     fprintf(stderr, "%s\n", __func__);
1353 }
1354 
1355 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1356 {
1357     MTPState *s = USB_MTP(dev);
1358     MTPControl cmd;
1359     mtp_container container;
1360     uint32_t params[5];
1361     int i, rc;
1362 
1363     switch (p->ep->nr) {
1364     case EP_DATA_IN:
1365         if (s->data_out != NULL) {
1366             /* guest bug */
1367             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1368             p->status = USB_RET_STALL;
1369             return;
1370         }
1371         if (p->iov.size < sizeof(container)) {
1372             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1373             p->status = USB_RET_STALL;
1374             return;
1375         }
1376         if (s->data_in !=  NULL) {
1377             MTPData *d = s->data_in;
1378             uint64_t dlen = d->length - d->offset;
1379             if (d->first) {
1380                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1381                 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1382                     container.length = cpu_to_le32(0xFFFFFFFF);
1383                 } else {
1384                     container.length =
1385                         cpu_to_le32(d->length + sizeof(container));
1386                 }
1387                 container.type   = cpu_to_le16(TYPE_DATA);
1388                 container.code   = cpu_to_le16(d->code);
1389                 container.trans  = cpu_to_le32(d->trans);
1390                 usb_packet_copy(p, &container, sizeof(container));
1391                 d->first = false;
1392                 if (dlen > p->iov.size - sizeof(container)) {
1393                     dlen = p->iov.size - sizeof(container);
1394                 }
1395             } else {
1396                 if (dlen > p->iov.size) {
1397                     dlen = p->iov.size;
1398                 }
1399             }
1400             if (d->fd == -1) {
1401                 usb_packet_copy(p, d->data + d->offset, dlen);
1402             } else {
1403                 if (d->alloc < p->iov.size) {
1404                     d->alloc = p->iov.size;
1405                     d->data = g_realloc(d->data, d->alloc);
1406                 }
1407                 rc = read(d->fd, d->data, dlen);
1408                 if (rc != dlen) {
1409                     memset(d->data, 0, dlen);
1410                     s->result->code = RES_INCOMPLETE_TRANSFER;
1411                 }
1412                 usb_packet_copy(p, d->data, dlen);
1413             }
1414             d->offset += dlen;
1415             if (d->offset == d->length) {
1416                 usb_mtp_data_free(s->data_in);
1417                 s->data_in = NULL;
1418             }
1419         } else if (s->result != NULL) {
1420             MTPControl *r = s->result;
1421             int length = sizeof(container) + r->argc * sizeof(uint32_t);
1422             if (r->code == RES_OK) {
1423                 trace_usb_mtp_success(s->dev.addr, r->trans,
1424                                       (r->argc > 0) ? r->argv[0] : 0,
1425                                       (r->argc > 1) ? r->argv[1] : 0);
1426             } else {
1427                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1428                                     (r->argc > 0) ? r->argv[0] : 0,
1429                                     (r->argc > 1) ? r->argv[1] : 0);
1430             }
1431             container.length = cpu_to_le32(length);
1432             container.type   = cpu_to_le16(TYPE_RESPONSE);
1433             container.code   = cpu_to_le16(r->code);
1434             container.trans  = cpu_to_le32(r->trans);
1435             for (i = 0; i < r->argc; i++) {
1436                 params[i] = cpu_to_le32(r->argv[i]);
1437             }
1438             usb_packet_copy(p, &container, sizeof(container));
1439             usb_packet_copy(p, &params, length - sizeof(container));
1440             g_free(s->result);
1441             s->result = NULL;
1442         }
1443         break;
1444     case EP_DATA_OUT:
1445         if (p->iov.size < sizeof(container)) {
1446             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1447             p->status = USB_RET_STALL;
1448             return;
1449         }
1450         usb_packet_copy(p, &container, sizeof(container));
1451         switch (le16_to_cpu(container.type)) {
1452         case TYPE_COMMAND:
1453             if (s->data_in || s->data_out || s->result) {
1454                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1455                 p->status = USB_RET_STALL;
1456                 return;
1457             }
1458             cmd.code = le16_to_cpu(container.code);
1459             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1460                 / sizeof(uint32_t);
1461             cmd.trans = le32_to_cpu(container.trans);
1462             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1463                 cmd.argc = ARRAY_SIZE(cmd.argv);
1464             }
1465             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1466                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1467                 p->status = USB_RET_STALL;
1468                 return;
1469             }
1470             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1471             for (i = 0; i < cmd.argc; i++) {
1472                 cmd.argv[i] = le32_to_cpu(params[i]);
1473             }
1474             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1475                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1476                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1477                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1478                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1479                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1480             usb_mtp_command(s, &cmd);
1481             break;
1482         default:
1483             /* not needed as long as the mtp device is read-only */
1484             p->status = USB_RET_STALL;
1485             return;
1486         }
1487         break;
1488     case EP_EVENT:
1489 #ifdef CONFIG_INOTIFY1
1490         if (!QTAILQ_EMPTY(&s->events)) {
1491             struct MTPMonEntry *e = QTAILQ_LAST(&s->events, events);
1492             uint32_t handle;
1493             int len = sizeof(container) + sizeof(uint32_t);
1494 
1495             if (p->iov.size < len) {
1496                 trace_usb_mtp_stall(s->dev.addr,
1497                                     "packet too small to send event");
1498                 p->status = USB_RET_STALL;
1499                 return;
1500             }
1501 
1502             QTAILQ_REMOVE(&s->events, e, next);
1503             container.length = cpu_to_le32(len);
1504             container.type = cpu_to_le32(TYPE_EVENT);
1505             container.code = cpu_to_le16(e->event);
1506             container.trans = 0; /* no trans specific events */
1507             handle = cpu_to_le32(e->handle);
1508             usb_packet_copy(p, &container, sizeof(container));
1509             usb_packet_copy(p, &handle, sizeof(uint32_t));
1510             g_free(e);
1511             return;
1512         }
1513 #endif
1514         p->status = USB_RET_NAK;
1515         return;
1516     default:
1517         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
1518         p->status = USB_RET_STALL;
1519         return;
1520     }
1521 
1522     if (p->actual_length == 0) {
1523         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
1524         p->status = USB_RET_NAK;
1525         return;
1526     } else {
1527         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
1528                            p->iov.size);
1529         return;
1530     }
1531 }
1532 
1533 static void usb_mtp_realize(USBDevice *dev, Error **errp)
1534 {
1535     MTPState *s = USB_MTP(dev);
1536 
1537     usb_desc_create_serial(dev);
1538     usb_desc_init(dev);
1539     QTAILQ_INIT(&s->objects);
1540     if (s->desc == NULL) {
1541         if (s->root == NULL) {
1542             error_setg(errp, "usb-mtp: x-root property must be configured");
1543             return;
1544         }
1545         s->desc = strrchr(s->root, '/');
1546         if (s->desc && s->desc[0]) {
1547             s->desc = g_strdup(s->desc + 1);
1548         } else {
1549             s->desc = g_strdup("none");
1550         }
1551     }
1552 }
1553 
1554 static const VMStateDescription vmstate_usb_mtp = {
1555     .name = "usb-mtp",
1556     .unmigratable = 1,
1557     .version_id = 1,
1558     .minimum_version_id = 1,
1559     .fields = (VMStateField[]) {
1560         VMSTATE_USB_DEVICE(dev, MTPState),
1561         VMSTATE_END_OF_LIST()
1562     }
1563 };
1564 
1565 static Property mtp_properties[] = {
1566     DEFINE_PROP_STRING("x-root", MTPState, root),
1567     DEFINE_PROP_STRING("desc", MTPState, desc),
1568     DEFINE_PROP_END_OF_LIST(),
1569 };
1570 
1571 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
1572 {
1573     DeviceClass *dc = DEVICE_CLASS(klass);
1574     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1575 
1576     uc->realize        = usb_mtp_realize;
1577     uc->product_desc   = "QEMU USB MTP";
1578     uc->usb_desc       = &desc;
1579     uc->cancel_packet  = usb_mtp_cancel_packet;
1580     uc->handle_attach  = usb_desc_attach;
1581     uc->handle_reset   = usb_mtp_handle_reset;
1582     uc->handle_control = usb_mtp_handle_control;
1583     uc->handle_data    = usb_mtp_handle_data;
1584     dc->fw_name = "mtp";
1585     dc->vmsd = &vmstate_usb_mtp;
1586     dc->props = mtp_properties;
1587 }
1588 
1589 static TypeInfo mtp_info = {
1590     .name          = TYPE_USB_MTP,
1591     .parent        = TYPE_USB_DEVICE,
1592     .instance_size = sizeof(MTPState),
1593     .class_init    = usb_mtp_class_initfn,
1594 };
1595 
1596 static void usb_mtp_register_types(void)
1597 {
1598     type_register_static(&mtp_info);
1599 }
1600 
1601 type_init(usb_mtp_register_types)
1602