xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision a56de056)
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 "qemu/main-loop.h"
21 #endif
22 
23 #include "qemu-common.h"
24 #include "qemu/iov.h"
25 #include "trace.h"
26 #include "hw/usb.h"
27 #include "desc.h"
28 #include "qemu/units.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 /* MTP write stage, for internal use only */
40 enum mtp_write_status {
41     WRITE_START    = 1,
42     WRITE_CONTINUE = 2,
43     WRITE_END      = 3,
44 };
45 
46 enum mtp_code {
47     /* command codes */
48     CMD_GET_DEVICE_INFO            = 0x1001,
49     CMD_OPEN_SESSION               = 0x1002,
50     CMD_CLOSE_SESSION              = 0x1003,
51     CMD_GET_STORAGE_IDS            = 0x1004,
52     CMD_GET_STORAGE_INFO           = 0x1005,
53     CMD_GET_NUM_OBJECTS            = 0x1006,
54     CMD_GET_OBJECT_HANDLES         = 0x1007,
55     CMD_GET_OBJECT_INFO            = 0x1008,
56     CMD_GET_OBJECT                 = 0x1009,
57     CMD_DELETE_OBJECT              = 0x100b,
58     CMD_SEND_OBJECT_INFO           = 0x100c,
59     CMD_SEND_OBJECT                = 0x100d,
60     CMD_GET_PARTIAL_OBJECT         = 0x101b,
61     CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
62     CMD_GET_OBJECT_PROP_DESC       = 0x9802,
63     CMD_GET_OBJECT_PROP_VALUE      = 0x9803,
64 
65     /* response codes */
66     RES_OK                         = 0x2001,
67     RES_GENERAL_ERROR              = 0x2002,
68     RES_SESSION_NOT_OPEN           = 0x2003,
69     RES_INVALID_TRANSACTION_ID     = 0x2004,
70     RES_OPERATION_NOT_SUPPORTED    = 0x2005,
71     RES_PARAMETER_NOT_SUPPORTED    = 0x2006,
72     RES_INCOMPLETE_TRANSFER        = 0x2007,
73     RES_INVALID_STORAGE_ID         = 0x2008,
74     RES_INVALID_OBJECT_HANDLE      = 0x2009,
75     RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
76     RES_STORE_FULL                 = 0x200c,
77     RES_STORE_READ_ONLY            = 0x200e,
78     RES_PARTIAL_DELETE             = 0x2012,
79     RES_STORE_NOT_AVAILABLE        = 0x2013,
80     RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
81     RES_INVALID_OBJECTINFO         = 0x2015,
82     RES_DESTINATION_UNSUPPORTED    = 0x2020,
83     RES_INVALID_PARENT_OBJECT      = 0x201a,
84     RES_INVALID_PARAMETER          = 0x201d,
85     RES_SESSION_ALREADY_OPEN       = 0x201e,
86     RES_INVALID_OBJECT_PROP_CODE   = 0xA801,
87 
88     /* format codes */
89     FMT_UNDEFINED_OBJECT           = 0x3000,
90     FMT_ASSOCIATION                = 0x3001,
91 
92     /* event codes */
93     EVT_CANCEL_TRANSACTION         = 0x4001,
94     EVT_OBJ_ADDED                  = 0x4002,
95     EVT_OBJ_REMOVED                = 0x4003,
96     EVT_OBJ_INFO_CHANGED           = 0x4007,
97 
98     /* object properties */
99     PROP_STORAGE_ID                = 0xDC01,
100     PROP_OBJECT_FORMAT             = 0xDC02,
101     PROP_OBJECT_COMPRESSED_SIZE    = 0xDC04,
102     PROP_PARENT_OBJECT             = 0xDC0B,
103     PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
104     PROP_NAME                      = 0xDC44,
105 };
106 
107 enum mtp_data_type {
108     DATA_TYPE_UINT16  = 0x0004,
109     DATA_TYPE_UINT32  = 0x0006,
110     DATA_TYPE_UINT64  = 0x0008,
111     DATA_TYPE_UINT128 = 0x000a,
112     DATA_TYPE_STRING  = 0xffff,
113 };
114 
115 typedef struct {
116     uint32_t length;
117     uint16_t type;
118     uint16_t code;
119     uint32_t trans;
120 } QEMU_PACKED mtp_container;
121 
122 /* ----------------------------------------------------------------------- */
123 
124 typedef struct MTPState MTPState;
125 typedef struct MTPControl MTPControl;
126 typedef struct MTPData MTPData;
127 typedef struct MTPObject MTPObject;
128 
129 enum {
130     EP_DATA_IN = 1,
131     EP_DATA_OUT,
132     EP_EVENT,
133 };
134 
135 #ifdef CONFIG_INOTIFY1
136 typedef struct MTPMonEntry MTPMonEntry;
137 
138 struct MTPMonEntry {
139     uint32_t event;
140     uint32_t handle;
141 
142     QTAILQ_ENTRY(MTPMonEntry) next;
143 };
144 #endif
145 
146 struct MTPControl {
147     uint16_t     code;
148     uint32_t     trans;
149     int          argc;
150     uint32_t     argv[5];
151 };
152 
153 struct MTPData {
154     uint16_t     code;
155     uint32_t     trans;
156     uint64_t     offset;
157     uint64_t     length;
158     uint64_t     alloc;
159     uint8_t      *data;
160     bool         first;
161     /* Used for >4G file sizes */
162     bool         pending;
163     int          fd;
164     uint8_t      write_status;
165     /* Internal pointer per every MTP_WRITE_BUF_SZ */
166     uint64_t     data_offset;
167 };
168 
169 struct MTPObject {
170     uint32_t     handle;
171     uint16_t     format;
172     char         *name;
173     char         *path;
174     struct stat  stat;
175 #ifdef CONFIG_INOTIFY1
176     /* inotify watch cookie */
177     int          watchfd;
178 #endif
179     MTPObject    *parent;
180     uint32_t     nchildren;
181     QLIST_HEAD(, MTPObject) children;
182     QLIST_ENTRY(MTPObject) list;
183     bool         have_children;
184     QTAILQ_ENTRY(MTPObject) next;
185 };
186 
187 struct MTPState {
188     USBDevice    dev;
189     char         *root;
190     char         *desc;
191     uint32_t     flags;
192 
193     MTPData      *data_in;
194     MTPData      *data_out;
195     MTPControl   *result;
196     uint32_t     session;
197     uint32_t     next_handle;
198     bool         readonly;
199 
200     QTAILQ_HEAD(, MTPObject) objects;
201 #ifdef CONFIG_INOTIFY1
202     /* inotify descriptor */
203     int          inotifyfd;
204     QTAILQ_HEAD(, MTPMonEntry) events;
205 #endif
206     /* Responder is expecting a write operation */
207     bool write_pending;
208     struct {
209         uint32_t parent_handle;
210         uint16_t format;
211         uint32_t size;
212         char *filename;
213     } dataset;
214 };
215 
216 /*
217  * ObjectInfo dataset received from initiator
218  * Fields we don't care about are ignored
219  */
220 typedef struct {
221     uint32_t storage_id; /*unused*/
222     uint16_t format;
223     uint16_t protection_status; /*unused*/
224     uint32_t size;
225     uint16_t thumb_format; /*unused*/
226     uint32_t thumb_comp_sz; /*unused*/
227     uint32_t thumb_pix_width; /*unused*/
228     uint32_t thumb_pix_height; /*unused*/
229     uint32_t image_pix_width; /*unused*/
230     uint32_t image_pix_height; /*unused*/
231     uint32_t image_bit_depth; /*unused*/
232     uint32_t parent; /*unused*/
233     uint16_t assoc_type;
234     uint32_t assoc_desc;
235     uint32_t seq_no; /*unused*/
236     uint8_t length; /*part of filename field*/
237     uint16_t filename[0];
238     char date_created[0]; /*unused*/
239     char date_modified[0]; /*unused*/
240     char keywords[0]; /*unused*/
241     /* string and other data follows */
242 } QEMU_PACKED ObjectInfo;
243 
244 #define TYPE_USB_MTP "usb-mtp"
245 #define USB_MTP(obj) OBJECT_CHECK(MTPState, (obj), TYPE_USB_MTP)
246 
247 #define QEMU_STORAGE_ID 0x00010001
248 
249 #define MTP_FLAG_WRITABLE 0
250 
251 #define FLAG_SET(_mtp, _flag)  ((_mtp)->flags & (1 << (_flag)))
252 
253 /* ----------------------------------------------------------------------- */
254 
255 #define MTP_MANUFACTURER  "QEMU"
256 #define MTP_PRODUCT       "QEMU filesharing"
257 #define MTP_WRITE_BUF_SZ  (512 * KiB)
258 
259 enum {
260     STR_MANUFACTURER = 1,
261     STR_PRODUCT,
262     STR_SERIALNUMBER,
263     STR_MTP,
264     STR_CONFIG_FULL,
265     STR_CONFIG_HIGH,
266     STR_CONFIG_SUPER,
267 };
268 
269 static const USBDescStrings desc_strings = {
270     [STR_MANUFACTURER] = MTP_MANUFACTURER,
271     [STR_PRODUCT]      = MTP_PRODUCT,
272     [STR_SERIALNUMBER] = "34617",
273     [STR_MTP]          = "MTP",
274     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
275     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
276     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
277 };
278 
279 static const USBDescIface desc_iface_full = {
280     .bInterfaceNumber              = 0,
281     .bNumEndpoints                 = 3,
282     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
283     .bInterfaceSubClass            = 0x01,
284     .bInterfaceProtocol            = 0x01,
285     .iInterface                    = STR_MTP,
286     .eps = (USBDescEndpoint[]) {
287         {
288             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
289             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
290             .wMaxPacketSize        = 64,
291         },{
292             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
293             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
294             .wMaxPacketSize        = 64,
295         },{
296             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
297             .bmAttributes          = USB_ENDPOINT_XFER_INT,
298             .wMaxPacketSize        = 64,
299             .bInterval             = 0x0a,
300         },
301     }
302 };
303 
304 static const USBDescDevice desc_device_full = {
305     .bcdUSB                        = 0x0200,
306     .bMaxPacketSize0               = 8,
307     .bNumConfigurations            = 1,
308     .confs = (USBDescConfig[]) {
309         {
310             .bNumInterfaces        = 1,
311             .bConfigurationValue   = 1,
312             .iConfiguration        = STR_CONFIG_FULL,
313             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
314             .bMaxPower             = 2,
315             .nif = 1,
316             .ifs = &desc_iface_full,
317         },
318     },
319 };
320 
321 static const USBDescIface desc_iface_high = {
322     .bInterfaceNumber              = 0,
323     .bNumEndpoints                 = 3,
324     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
325     .bInterfaceSubClass            = 0x01,
326     .bInterfaceProtocol            = 0x01,
327     .iInterface                    = STR_MTP,
328     .eps = (USBDescEndpoint[]) {
329         {
330             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
331             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
332             .wMaxPacketSize        = 512,
333         },{
334             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
335             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
336             .wMaxPacketSize        = 512,
337         },{
338             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
339             .bmAttributes          = USB_ENDPOINT_XFER_INT,
340             .wMaxPacketSize        = 64,
341             .bInterval             = 0x0a,
342         },
343     }
344 };
345 
346 static const USBDescDevice desc_device_high = {
347     .bcdUSB                        = 0x0200,
348     .bMaxPacketSize0               = 64,
349     .bNumConfigurations            = 1,
350     .confs = (USBDescConfig[]) {
351         {
352             .bNumInterfaces        = 1,
353             .bConfigurationValue   = 1,
354             .iConfiguration        = STR_CONFIG_HIGH,
355             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
356             .bMaxPower             = 2,
357             .nif = 1,
358             .ifs = &desc_iface_high,
359         },
360     },
361 };
362 
363 static const USBDescMSOS desc_msos = {
364     .CompatibleID = "MTP",
365     .SelectiveSuspendEnabled = true,
366 };
367 
368 static const USBDesc desc = {
369     .id = {
370         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
371         .idProduct         = 0x0004,
372         .bcdDevice         = 0,
373         .iManufacturer     = STR_MANUFACTURER,
374         .iProduct          = STR_PRODUCT,
375         .iSerialNumber     = STR_SERIALNUMBER,
376     },
377     .full  = &desc_device_full,
378     .high  = &desc_device_high,
379     .str   = desc_strings,
380     .msos  = &desc_msos,
381 };
382 
383 /* ----------------------------------------------------------------------- */
384 
385 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
386                                        MTPObject *parent, char *name)
387 {
388     MTPObject *o = g_new0(MTPObject, 1);
389 
390     if (name[0] == '.') {
391         goto ignore;
392     }
393 
394     o->handle = handle;
395     o->parent = parent;
396     o->name = g_strdup(name);
397     if (parent == NULL) {
398         o->path = g_strdup(name);
399     } else {
400         o->path = g_strdup_printf("%s/%s", parent->path, name);
401     }
402 
403     if (lstat(o->path, &o->stat) != 0) {
404         goto ignore;
405     }
406     if (S_ISREG(o->stat.st_mode)) {
407         o->format = FMT_UNDEFINED_OBJECT;
408     } else if (S_ISDIR(o->stat.st_mode)) {
409         o->format = FMT_ASSOCIATION;
410     } else {
411         goto ignore;
412     }
413 
414     if (access(o->path, R_OK) != 0) {
415         goto ignore;
416     }
417 
418     trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
419 
420     QTAILQ_INSERT_TAIL(&s->objects, o, next);
421     return o;
422 
423 ignore:
424     g_free(o->name);
425     g_free(o->path);
426     g_free(o);
427     return NULL;
428 }
429 
430 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
431 {
432     MTPObject *iter;
433 
434     if (!o) {
435         return;
436     }
437 
438     trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
439 
440     QTAILQ_REMOVE(&s->objects, o, next);
441     if (o->parent) {
442         QLIST_REMOVE(o, list);
443         o->parent->nchildren--;
444     }
445 
446     while (!QLIST_EMPTY(&o->children)) {
447         iter = QLIST_FIRST(&o->children);
448         usb_mtp_object_free(s, iter);
449     }
450     g_free(o->name);
451     g_free(o->path);
452     g_free(o);
453 }
454 
455 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
456 {
457     MTPObject *o;
458 
459     QTAILQ_FOREACH(o, &s->objects, next) {
460         if (o->handle == handle) {
461             return o;
462         }
463     }
464     return NULL;
465 }
466 
467 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
468                                     char *name)
469 {
470     MTPObject *child =
471         usb_mtp_object_alloc(s, s->next_handle++, o, name);
472 
473     if (child) {
474         trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
475         QLIST_INSERT_HEAD(&o->children, child, list);
476         o->nchildren++;
477 
478         if (child->format == FMT_ASSOCIATION) {
479             QLIST_INIT(&child->children);
480         }
481     }
482 
483     return child;
484 }
485 
486 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
487                                              char *name, int len)
488 {
489     MTPObject *iter;
490 
491     QLIST_FOREACH(iter, &parent->children, list) {
492         if (strncmp(iter->name, name, len) == 0) {
493             return iter;
494         }
495     }
496 
497     return NULL;
498 }
499 
500 #ifdef CONFIG_INOTIFY1
501 static MTPObject *usb_mtp_object_lookup_wd(MTPState *s, int wd)
502 {
503     MTPObject *iter;
504 
505     QTAILQ_FOREACH(iter, &s->objects, next) {
506         if (iter->watchfd == wd) {
507             return iter;
508         }
509     }
510 
511     return NULL;
512 }
513 
514 static void inotify_watchfn(void *arg)
515 {
516     MTPState *s = arg;
517     ssize_t bytes;
518     /* From the man page: atleast one event can be read */
519     int pos;
520     char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
521 
522     for (;;) {
523         bytes = read(s->inotifyfd, buf, sizeof(buf));
524         pos = 0;
525 
526         if (bytes <= 0) {
527             /* Better luck next time */
528             return;
529         }
530 
531         /*
532          * TODO: Ignore initiator initiated events.
533          * For now we are good because the store is RO
534          */
535         while (bytes > 0) {
536             char *p = buf + pos;
537             struct inotify_event *event = (struct inotify_event *)p;
538             int watchfd = 0;
539             uint32_t mask = event->mask & (IN_CREATE | IN_DELETE |
540                                            IN_MODIFY | IN_IGNORED);
541             MTPObject *parent = usb_mtp_object_lookup_wd(s, event->wd);
542             MTPMonEntry *entry = NULL;
543             MTPObject *o;
544 
545             pos = pos + sizeof(struct inotify_event) + event->len;
546             bytes = bytes - pos;
547 
548             if (!parent) {
549                 continue;
550             }
551 
552             switch (mask) {
553             case IN_CREATE:
554                 if (usb_mtp_object_lookup_name
555                     (parent, event->name, event->len)) {
556                     /* Duplicate create event */
557                     continue;
558                 }
559                 entry = g_new0(MTPMonEntry, 1);
560                 entry->handle = s->next_handle;
561                 entry->event = EVT_OBJ_ADDED;
562                 o = usb_mtp_add_child(s, parent, event->name);
563                 if (!o) {
564                     g_free(entry);
565                     continue;
566                 }
567                 o->watchfd = watchfd;
568                 trace_usb_mtp_inotify_event(s->dev.addr, event->name,
569                                             event->mask, "Obj Added");
570                 break;
571 
572             case IN_DELETE:
573                 /*
574                  * The kernel issues a IN_IGNORED event
575                  * when a dir containing a watchpoint is
576                  * deleted, so we don't have to delete the
577                  * watchpoint
578                  */
579                 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
580                 if (!o) {
581                     continue;
582                 }
583                 entry = g_new0(MTPMonEntry, 1);
584                 entry->handle = o->handle;
585                 entry->event = EVT_OBJ_REMOVED;
586                 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
587                                       event->mask, "Obj Deleted");
588                 usb_mtp_object_free(s, o);
589                 break;
590 
591             case IN_MODIFY:
592                 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
593                 if (!o) {
594                     continue;
595                 }
596                 entry = g_new0(MTPMonEntry, 1);
597                 entry->handle = o->handle;
598                 entry->event = EVT_OBJ_INFO_CHANGED;
599                 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
600                                       event->mask, "Obj Modified");
601                 break;
602 
603             case IN_IGNORED:
604                 trace_usb_mtp_inotify_event(s->dev.addr, parent->path,
605                                       event->mask, "Obj parent dir ignored");
606                 break;
607 
608             default:
609                 fprintf(stderr, "usb-mtp: failed to parse inotify event\n");
610                 continue;
611             }
612 
613             if (entry) {
614                 QTAILQ_INSERT_HEAD(&s->events, entry, next);
615             }
616         }
617     }
618 }
619 
620 static int usb_mtp_inotify_init(MTPState *s)
621 {
622     int fd;
623 
624     fd = inotify_init1(IN_NONBLOCK);
625     if (fd == -1) {
626         return 1;
627     }
628 
629     QTAILQ_INIT(&s->events);
630     s->inotifyfd = fd;
631 
632     qemu_set_fd_handler(fd, inotify_watchfn, NULL, s);
633 
634     return 0;
635 }
636 
637 static void usb_mtp_inotify_cleanup(MTPState *s)
638 {
639     MTPMonEntry *e, *p;
640 
641     if (!s->inotifyfd) {
642         return;
643     }
644 
645     qemu_set_fd_handler(s->inotifyfd, NULL, NULL, s);
646     close(s->inotifyfd);
647 
648     QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
649         QTAILQ_REMOVE(&s->events, e, next);
650         g_free(e);
651     }
652 }
653 
654 static int usb_mtp_add_watch(int inotifyfd, char *path)
655 {
656     uint32_t mask = IN_CREATE | IN_DELETE | IN_MODIFY |
657         IN_ISDIR;
658 
659     return inotify_add_watch(inotifyfd, path, mask);
660 }
661 #endif
662 
663 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
664 {
665     struct dirent *entry;
666     DIR *dir;
667     int fd;
668 
669     if (o->have_children) {
670         return;
671     }
672     o->have_children = true;
673 
674     fd = open(o->path, O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
675     if (fd < 0) {
676         return;
677     }
678     dir = fdopendir(fd);
679     if (!dir) {
680         close(fd);
681         return;
682     }
683 #ifdef CONFIG_INOTIFY1
684     int watchfd = usb_mtp_add_watch(s->inotifyfd, o->path);
685     if (watchfd == -1) {
686         fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path);
687     } else {
688         trace_usb_mtp_inotify_event(s->dev.addr, o->path,
689                                     0, "Watch Added");
690         o->watchfd = watchfd;
691     }
692 #endif
693     while ((entry = readdir(dir)) != NULL) {
694         usb_mtp_add_child(s, o, entry->d_name);
695     }
696     closedir(dir);
697 }
698 
699 /* ----------------------------------------------------------------------- */
700 
701 static MTPData *usb_mtp_data_alloc(MTPControl *c)
702 {
703     MTPData *data = g_new0(MTPData, 1);
704 
705     data->code  = c->code;
706     data->trans = c->trans;
707     data->fd    = -1;
708     data->first = true;
709     return data;
710 }
711 
712 static void usb_mtp_data_free(MTPData *data)
713 {
714     if (data == NULL) {
715         return;
716     }
717     if (data->fd != -1) {
718         close(data->fd);
719     }
720     g_free(data->data);
721     g_free(data);
722 }
723 
724 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
725 {
726     if (data->length + bytes <= data->alloc) {
727         return;
728     }
729     data->alloc = (data->length + bytes + 0xff) & ~0xff;
730     data->data  = g_realloc(data->data, data->alloc);
731 }
732 
733 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
734 {
735     usb_mtp_realloc(data, 1);
736     data->data[data->length++] = val;
737 }
738 
739 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
740 {
741     usb_mtp_realloc(data, 2);
742     data->data[data->length++] = (val >> 0) & 0xff;
743     data->data[data->length++] = (val >> 8) & 0xff;
744 }
745 
746 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
747 {
748     usb_mtp_realloc(data, 4);
749     data->data[data->length++] = (val >>  0) & 0xff;
750     data->data[data->length++] = (val >>  8) & 0xff;
751     data->data[data->length++] = (val >> 16) & 0xff;
752     data->data[data->length++] = (val >> 24) & 0xff;
753 }
754 
755 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
756 {
757     usb_mtp_realloc(data, 8);
758     data->data[data->length++] = (val >>  0) & 0xff;
759     data->data[data->length++] = (val >>  8) & 0xff;
760     data->data[data->length++] = (val >> 16) & 0xff;
761     data->data[data->length++] = (val >> 24) & 0xff;
762     data->data[data->length++] = (val >> 32) & 0xff;
763     data->data[data->length++] = (val >> 40) & 0xff;
764     data->data[data->length++] = (val >> 48) & 0xff;
765     data->data[data->length++] = (val >> 56) & 0xff;
766 }
767 
768 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
769                                   const uint16_t *vals)
770 {
771     int i;
772 
773     usb_mtp_add_u32(data, len);
774     for (i = 0; i < len; i++) {
775         usb_mtp_add_u16(data, vals[i]);
776     }
777 }
778 
779 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
780                                   const uint32_t *vals)
781 {
782     int i;
783 
784     usb_mtp_add_u32(data, len);
785     for (i = 0; i < len; i++) {
786         usb_mtp_add_u32(data, vals[i]);
787     }
788 }
789 
790 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
791 {
792     uint32_t len = wcslen(str);
793     int i;
794 
795     if (len > 0) {
796         len++; /* include terminating L'\0' */
797     }
798 
799     usb_mtp_add_u8(data, len);
800     for (i = 0; i < len; i++) {
801         usb_mtp_add_u16(data, str[i]);
802     }
803 }
804 
805 static void usb_mtp_add_str(MTPData *data, const char *str)
806 {
807     uint32_t len = strlen(str)+1;
808     wchar_t *wstr = g_new(wchar_t, len);
809     size_t ret;
810 
811     ret = mbstowcs(wstr, str, len);
812     if (ret == -1) {
813         usb_mtp_add_wstr(data, L"Oops");
814     } else {
815         usb_mtp_add_wstr(data, wstr);
816     }
817 
818     g_free(wstr);
819 }
820 
821 static void usb_mtp_add_time(MTPData *data, time_t time)
822 {
823     char buf[16];
824     struct tm tm;
825 
826     gmtime_r(&time, &tm);
827     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
828     usb_mtp_add_str(data, buf);
829 }
830 
831 /* ----------------------------------------------------------------------- */
832 
833 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
834                                  int argc, uint32_t arg0, uint32_t arg1,
835                                  uint32_t arg2)
836 {
837     MTPControl *c = g_new0(MTPControl, 1);
838 
839     c->code  = code;
840     c->trans = trans;
841     c->argc  = argc;
842     if (argc > 0) {
843         c->argv[0] = arg0;
844     }
845     if (argc > 1) {
846         c->argv[1] = arg1;
847     }
848     if (argc > 2) {
849         c->argv[2] = arg2;
850     }
851 
852     assert(s->result == NULL);
853     s->result = c;
854 }
855 
856 /* ----------------------------------------------------------------------- */
857 
858 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
859 {
860     static const uint16_t ops[] = {
861         CMD_GET_DEVICE_INFO,
862         CMD_OPEN_SESSION,
863         CMD_CLOSE_SESSION,
864         CMD_GET_STORAGE_IDS,
865         CMD_GET_STORAGE_INFO,
866         CMD_GET_NUM_OBJECTS,
867         CMD_GET_OBJECT_HANDLES,
868         CMD_GET_OBJECT_INFO,
869         CMD_DELETE_OBJECT,
870         CMD_SEND_OBJECT_INFO,
871         CMD_SEND_OBJECT,
872         CMD_GET_OBJECT,
873         CMD_GET_PARTIAL_OBJECT,
874         CMD_GET_OBJECT_PROPS_SUPPORTED,
875         CMD_GET_OBJECT_PROP_DESC,
876         CMD_GET_OBJECT_PROP_VALUE,
877     };
878     static const uint16_t fmt[] = {
879         FMT_UNDEFINED_OBJECT,
880         FMT_ASSOCIATION,
881     };
882     MTPData *d = usb_mtp_data_alloc(c);
883 
884     trace_usb_mtp_op_get_device_info(s->dev.addr);
885 
886     usb_mtp_add_u16(d, 100);
887     usb_mtp_add_u32(d, 0x00000006);
888     usb_mtp_add_u16(d, 0x0064);
889     usb_mtp_add_wstr(d, L"");
890     usb_mtp_add_u16(d, 0x0000);
891 
892     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
893     usb_mtp_add_u16_array(d, 0, NULL);
894     usb_mtp_add_u16_array(d, 0, NULL);
895     usb_mtp_add_u16_array(d, 0, NULL);
896     usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
897 
898     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
899     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
900     usb_mtp_add_wstr(d, L"0.1");
901     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
902 
903     return d;
904 }
905 
906 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
907 {
908     static const uint32_t ids[] = {
909         QEMU_STORAGE_ID,
910     };
911     MTPData *d = usb_mtp_data_alloc(c);
912 
913     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
914 
915     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
916 
917     return d;
918 }
919 
920 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
921 {
922     MTPData *d = usb_mtp_data_alloc(c);
923     struct statvfs buf;
924     int rc;
925 
926     trace_usb_mtp_op_get_storage_info(s->dev.addr);
927 
928     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
929         usb_mtp_add_u16(d, 0x0003);
930         usb_mtp_add_u16(d, 0x0002);
931         usb_mtp_add_u16(d, 0x0000);
932     } else {
933         usb_mtp_add_u16(d, 0x0001);
934         usb_mtp_add_u16(d, 0x0002);
935         usb_mtp_add_u16(d, 0x0001);
936     }
937 
938     rc = statvfs(s->root, &buf);
939     if (rc == 0) {
940         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
941         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
942         usb_mtp_add_u32(d, buf.f_ffree);
943     } else {
944         usb_mtp_add_u64(d, 0xffffffff);
945         usb_mtp_add_u64(d, 0xffffffff);
946         usb_mtp_add_u32(d, 0xffffffff);
947     }
948 
949     usb_mtp_add_str(d, s->desc);
950     usb_mtp_add_wstr(d, L"123456789abcdef");
951     return d;
952 }
953 
954 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
955                                            MTPObject *o)
956 {
957     MTPData *d = usb_mtp_data_alloc(c);
958     uint32_t i = 0, handles[o->nchildren];
959     MTPObject *iter;
960 
961     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
962 
963     QLIST_FOREACH(iter, &o->children, list) {
964         handles[i++] = iter->handle;
965     }
966     assert(i == o->nchildren);
967     usb_mtp_add_u32_array(d, o->nchildren, handles);
968 
969     return d;
970 }
971 
972 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
973                                         MTPObject *o)
974 {
975     MTPData *d = usb_mtp_data_alloc(c);
976 
977     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
978 
979     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
980     usb_mtp_add_u16(d, o->format);
981     usb_mtp_add_u16(d, 0);
982 
983     if (o->stat.st_size > 0xFFFFFFFF) {
984         usb_mtp_add_u32(d, 0xFFFFFFFF);
985     } else {
986         usb_mtp_add_u32(d, o->stat.st_size);
987     }
988 
989     usb_mtp_add_u16(d, 0);
990     usb_mtp_add_u32(d, 0);
991     usb_mtp_add_u32(d, 0);
992     usb_mtp_add_u32(d, 0);
993     usb_mtp_add_u32(d, 0);
994     usb_mtp_add_u32(d, 0);
995     usb_mtp_add_u32(d, 0);
996 
997     if (o->parent) {
998         usb_mtp_add_u32(d, o->parent->handle);
999     } else {
1000         usb_mtp_add_u32(d, 0);
1001     }
1002     if (o->format == FMT_ASSOCIATION) {
1003         usb_mtp_add_u16(d, 0x0001);
1004         usb_mtp_add_u32(d, 0x00000001);
1005         usb_mtp_add_u32(d, 0);
1006     } else {
1007         usb_mtp_add_u16(d, 0);
1008         usb_mtp_add_u32(d, 0);
1009         usb_mtp_add_u32(d, 0);
1010     }
1011 
1012     usb_mtp_add_str(d, o->name);
1013     usb_mtp_add_time(d, o->stat.st_ctime);
1014     usb_mtp_add_time(d, o->stat.st_mtime);
1015     usb_mtp_add_wstr(d, L"");
1016 
1017     return d;
1018 }
1019 
1020 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
1021                                    MTPObject *o)
1022 {
1023     MTPData *d = usb_mtp_data_alloc(c);
1024 
1025     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
1026 
1027     d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
1028     if (d->fd == -1) {
1029         usb_mtp_data_free(d);
1030         return NULL;
1031     }
1032     d->length = o->stat.st_size;
1033     d->alloc  = 512;
1034     d->data   = g_malloc(d->alloc);
1035     return d;
1036 }
1037 
1038 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
1039                                            MTPObject *o)
1040 {
1041     MTPData *d;
1042     off_t offset;
1043 
1044     if (c->argc <= 2) {
1045         return NULL;
1046     }
1047     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
1048                                         c->argv[1], c->argv[2]);
1049 
1050     d = usb_mtp_data_alloc(c);
1051     d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
1052     if (d->fd == -1) {
1053         usb_mtp_data_free(d);
1054         return NULL;
1055     }
1056 
1057     offset = c->argv[1];
1058     if (offset > o->stat.st_size) {
1059         offset = o->stat.st_size;
1060     }
1061     if (lseek(d->fd, offset, SEEK_SET) < 0) {
1062         usb_mtp_data_free(d);
1063         return NULL;
1064     }
1065 
1066     d->length = c->argv[2];
1067     if (d->length > o->stat.st_size - offset) {
1068         d->length = o->stat.st_size - offset;
1069     }
1070 
1071     return d;
1072 }
1073 
1074 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1075 {
1076     static const uint16_t props[] = {
1077         PROP_STORAGE_ID,
1078         PROP_OBJECT_FORMAT,
1079         PROP_OBJECT_COMPRESSED_SIZE,
1080         PROP_PARENT_OBJECT,
1081         PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1082         PROP_NAME,
1083     };
1084     MTPData *d = usb_mtp_data_alloc(c);
1085     usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1086 
1087     return d;
1088 }
1089 
1090 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1091 {
1092     MTPData *d = usb_mtp_data_alloc(c);
1093     switch (c->argv[0]) {
1094     case PROP_STORAGE_ID:
1095         usb_mtp_add_u16(d, PROP_STORAGE_ID);
1096         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1097         usb_mtp_add_u8(d, 0x00);
1098         usb_mtp_add_u32(d, 0x00000000);
1099         usb_mtp_add_u32(d, 0x00000000);
1100         usb_mtp_add_u8(d, 0x00);
1101         break;
1102     case PROP_OBJECT_FORMAT:
1103         usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1104         usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1105         usb_mtp_add_u8(d, 0x00);
1106         usb_mtp_add_u16(d, 0x0000);
1107         usb_mtp_add_u32(d, 0x00000000);
1108         usb_mtp_add_u8(d, 0x00);
1109         break;
1110     case PROP_OBJECT_COMPRESSED_SIZE:
1111         usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1112         usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1113         usb_mtp_add_u8(d, 0x00);
1114         usb_mtp_add_u64(d, 0x0000000000000000);
1115         usb_mtp_add_u32(d, 0x00000000);
1116         usb_mtp_add_u8(d, 0x00);
1117         break;
1118     case PROP_PARENT_OBJECT:
1119         usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1120         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1121         usb_mtp_add_u8(d, 0x00);
1122         usb_mtp_add_u32(d, 0x00000000);
1123         usb_mtp_add_u32(d, 0x00000000);
1124         usb_mtp_add_u8(d, 0x00);
1125         break;
1126     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1127         usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1128         usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1129         usb_mtp_add_u8(d, 0x00);
1130         usb_mtp_add_u64(d, 0x0000000000000000);
1131         usb_mtp_add_u64(d, 0x0000000000000000);
1132         usb_mtp_add_u32(d, 0x00000000);
1133         usb_mtp_add_u8(d, 0x00);
1134         break;
1135     case PROP_NAME:
1136         usb_mtp_add_u16(d, PROP_NAME);
1137         usb_mtp_add_u16(d, DATA_TYPE_STRING);
1138         usb_mtp_add_u8(d, 0x00);
1139         usb_mtp_add_u8(d, 0x00);
1140         usb_mtp_add_u32(d, 0x00000000);
1141         usb_mtp_add_u8(d, 0x00);
1142         break;
1143     default:
1144         usb_mtp_data_free(d);
1145         return NULL;
1146     }
1147 
1148     return d;
1149 }
1150 
1151 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1152                                               MTPObject *o)
1153 {
1154     MTPData *d = usb_mtp_data_alloc(c);
1155     switch (c->argv[1]) {
1156     case PROP_STORAGE_ID:
1157         usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1158         break;
1159     case PROP_OBJECT_FORMAT:
1160         usb_mtp_add_u16(d, o->format);
1161         break;
1162     case PROP_OBJECT_COMPRESSED_SIZE:
1163         usb_mtp_add_u64(d, o->stat.st_size);
1164         break;
1165     case PROP_PARENT_OBJECT:
1166         if (o->parent == NULL) {
1167             usb_mtp_add_u32(d, 0x00000000);
1168         } else {
1169             usb_mtp_add_u32(d, o->parent->handle);
1170         }
1171         break;
1172     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1173         /* Should be persistent between sessions,
1174          * but using our objedt ID is "good enough"
1175          * for now */
1176         usb_mtp_add_u64(d, 0x0000000000000000);
1177         usb_mtp_add_u64(d, o->handle);
1178         break;
1179     case PROP_NAME:
1180         usb_mtp_add_str(d, o->name);
1181         break;
1182     default:
1183         usb_mtp_data_free(d);
1184         return NULL;
1185     }
1186 
1187     return d;
1188 }
1189 
1190 /* Return correct return code for a delete event */
1191 enum {
1192     ALL_DELETE,
1193     PARTIAL_DELETE,
1194     READ_ONLY,
1195 };
1196 
1197 /* Assumes that children, if any, have been already freed */
1198 static void usb_mtp_object_free_one(MTPState *s, MTPObject *o)
1199 {
1200 #ifndef CONFIG_INOTIFY1
1201     assert(o->nchildren == 0);
1202     QTAILQ_REMOVE(&s->objects, o, next);
1203     g_free(o->name);
1204     g_free(o->path);
1205     g_free(o);
1206 #endif
1207 }
1208 
1209 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1210 {
1211     MTPObject *iter, *iter2;
1212     bool partial_delete = false;
1213     bool success = false;
1214 
1215     /*
1216      * TODO: Add support for Protection Status
1217      */
1218 
1219     QLIST_FOREACH(iter, &o->children, list) {
1220         if (iter->format == FMT_ASSOCIATION) {
1221             QLIST_FOREACH(iter2, &iter->children, list) {
1222                 usb_mtp_deletefn(s, iter2, trans);
1223             }
1224         }
1225     }
1226 
1227     if (o->format == FMT_UNDEFINED_OBJECT) {
1228         if (remove(o->path)) {
1229             partial_delete = true;
1230         } else {
1231             usb_mtp_object_free_one(s, o);
1232             success = true;
1233         }
1234     }
1235 
1236     if (o->format == FMT_ASSOCIATION) {
1237         if (rmdir(o->path)) {
1238             partial_delete = true;
1239         } else {
1240             usb_mtp_object_free_one(s, o);
1241             success = true;
1242         }
1243     }
1244 
1245     if (success && partial_delete) {
1246         return PARTIAL_DELETE;
1247     }
1248     if (!success && partial_delete) {
1249         return READ_ONLY;
1250     }
1251     return ALL_DELETE;
1252 }
1253 
1254 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1255                                   uint32_t format_code, uint32_t trans)
1256 {
1257     MTPObject *o;
1258     int ret;
1259 
1260     /* Return error if store is read-only */
1261     if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1262         usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1263                              trans, 0, 0, 0, 0);
1264         return;
1265     }
1266 
1267     if (format_code != 0) {
1268         usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1269                              trans, 0, 0, 0, 0);
1270         return;
1271     }
1272 
1273     if (handle == 0xFFFFFFF) {
1274         o = QTAILQ_FIRST(&s->objects);
1275     } else {
1276         o = usb_mtp_object_lookup(s, handle);
1277     }
1278     if (o == NULL) {
1279         usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1280                              trans, 0, 0, 0, 0);
1281         return;
1282     }
1283 
1284     ret = usb_mtp_deletefn(s, o, trans);
1285     if (ret == PARTIAL_DELETE) {
1286         usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1287                              trans, 0, 0, 0, 0);
1288         return;
1289     } else if (ret == READ_ONLY) {
1290         usb_mtp_queue_result(s, RES_STORE_READ_ONLY, trans,
1291                              0, 0, 0, 0);
1292         return;
1293     } else {
1294         usb_mtp_queue_result(s, RES_OK, trans,
1295                              0, 0, 0, 0);
1296         return;
1297     }
1298 }
1299 
1300 static void usb_mtp_command(MTPState *s, MTPControl *c)
1301 {
1302     MTPData *data_in = NULL;
1303     MTPObject *o = NULL;
1304     uint32_t nres = 0, res0 = 0;
1305 
1306     /* sanity checks */
1307     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1308         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1309                              c->trans, 0, 0, 0, 0);
1310         return;
1311     }
1312 
1313     /* process commands */
1314     switch (c->code) {
1315     case CMD_GET_DEVICE_INFO:
1316         data_in = usb_mtp_get_device_info(s, c);
1317         break;
1318     case CMD_OPEN_SESSION:
1319         if (s->session) {
1320             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1321                                  c->trans, 1, s->session, 0, 0);
1322             return;
1323         }
1324         if (c->argv[0] == 0) {
1325             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1326                                  c->trans, 0, 0, 0, 0);
1327             return;
1328         }
1329         trace_usb_mtp_op_open_session(s->dev.addr);
1330         s->session = c->argv[0];
1331         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1332 #ifdef CONFIG_INOTIFY1
1333         if (usb_mtp_inotify_init(s)) {
1334             fprintf(stderr, "usb-mtp: file monitoring init failed\n");
1335         }
1336 #endif
1337         break;
1338     case CMD_CLOSE_SESSION:
1339         trace_usb_mtp_op_close_session(s->dev.addr);
1340         s->session = 0;
1341         s->next_handle = 0;
1342 #ifdef CONFIG_INOTIFY1
1343         usb_mtp_inotify_cleanup(s);
1344 #endif
1345         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1346         assert(QTAILQ_EMPTY(&s->objects));
1347         break;
1348     case CMD_GET_STORAGE_IDS:
1349         data_in = usb_mtp_get_storage_ids(s, c);
1350         break;
1351     case CMD_GET_STORAGE_INFO:
1352         if (c->argv[0] != QEMU_STORAGE_ID &&
1353             c->argv[0] != 0xffffffff) {
1354             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1355                                  c->trans, 0, 0, 0, 0);
1356             return;
1357         }
1358         data_in = usb_mtp_get_storage_info(s, c);
1359         break;
1360     case CMD_GET_NUM_OBJECTS:
1361     case CMD_GET_OBJECT_HANDLES:
1362         if (c->argv[0] != QEMU_STORAGE_ID &&
1363             c->argv[0] != 0xffffffff) {
1364             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1365                                  c->trans, 0, 0, 0, 0);
1366             return;
1367         }
1368         if (c->argv[1] != 0x00000000) {
1369             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1370                                  c->trans, 0, 0, 0, 0);
1371             return;
1372         }
1373         if (c->argv[2] == 0x00000000 ||
1374             c->argv[2] == 0xffffffff) {
1375             o = QTAILQ_FIRST(&s->objects);
1376         } else {
1377             o = usb_mtp_object_lookup(s, c->argv[2]);
1378         }
1379         if (o == NULL) {
1380             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1381                                  c->trans, 0, 0, 0, 0);
1382             return;
1383         }
1384         if (o->format != FMT_ASSOCIATION) {
1385             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1386                                  c->trans, 0, 0, 0, 0);
1387             return;
1388         }
1389         usb_mtp_object_readdir(s, o);
1390         if (c->code == CMD_GET_NUM_OBJECTS) {
1391             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1392             nres = 1;
1393             res0 = o->nchildren;
1394         } else {
1395             data_in = usb_mtp_get_object_handles(s, c, o);
1396         }
1397         break;
1398     case CMD_GET_OBJECT_INFO:
1399         o = usb_mtp_object_lookup(s, c->argv[0]);
1400         if (o == NULL) {
1401             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1402                                  c->trans, 0, 0, 0, 0);
1403             return;
1404         }
1405         data_in = usb_mtp_get_object_info(s, c, o);
1406         break;
1407     case CMD_GET_OBJECT:
1408         o = usb_mtp_object_lookup(s, c->argv[0]);
1409         if (o == NULL) {
1410             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1411                                  c->trans, 0, 0, 0, 0);
1412             return;
1413         }
1414         if (o->format == FMT_ASSOCIATION) {
1415             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1416                                  c->trans, 0, 0, 0, 0);
1417             return;
1418         }
1419         data_in = usb_mtp_get_object(s, c, o);
1420         if (data_in == NULL) {
1421             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1422                                  c->trans, 0, 0, 0, 0);
1423             return;
1424         }
1425         break;
1426     case CMD_DELETE_OBJECT:
1427         usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1428         return;
1429     case CMD_GET_PARTIAL_OBJECT:
1430         o = usb_mtp_object_lookup(s, c->argv[0]);
1431         if (o == NULL) {
1432             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1433                                  c->trans, 0, 0, 0, 0);
1434             return;
1435         }
1436         if (o->format == FMT_ASSOCIATION) {
1437             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1438                                  c->trans, 0, 0, 0, 0);
1439             return;
1440         }
1441         data_in = usb_mtp_get_partial_object(s, c, o);
1442         if (data_in == NULL) {
1443             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1444                                  c->trans, 0, 0, 0, 0);
1445             return;
1446         }
1447         nres = 1;
1448         res0 = data_in->length;
1449         break;
1450     case CMD_SEND_OBJECT_INFO:
1451         /* Return error if store is read-only */
1452         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1453             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1454                                  c->trans, 0, 0, 0, 0);
1455         } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1456             /* First parameter points to storage id or is 0 */
1457             usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1458                                  0, 0, 0, 0);
1459         } else if (c->argv[1] && !c->argv[0]) {
1460             /* If second parameter is specified, first must also be specified */
1461             usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1462                                  0, 0, 0, 0);
1463         } else {
1464             uint32_t handle = c->argv[1];
1465             if (handle == 0xFFFFFFFF || handle == 0) {
1466                 /* root object */
1467                 o = QTAILQ_FIRST(&s->objects);
1468             } else {
1469                 o = usb_mtp_object_lookup(s, handle);
1470             }
1471             if (o == NULL) {
1472                 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1473                                      0, 0, 0, 0);
1474             } else if (o->format != FMT_ASSOCIATION) {
1475                 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1476                                      0, 0, 0, 0);
1477             }
1478         }
1479         if (o) {
1480             s->dataset.parent_handle = o->handle;
1481         }
1482         s->data_out = usb_mtp_data_alloc(c);
1483         return;
1484     case CMD_SEND_OBJECT:
1485         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1486             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1487                                  c->trans, 0, 0, 0, 0);
1488             return;
1489         }
1490         if (!s->write_pending) {
1491             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1492                                  c->trans, 0, 0, 0, 0);
1493             return;
1494         }
1495         s->data_out = usb_mtp_data_alloc(c);
1496         return;
1497     case CMD_GET_OBJECT_PROPS_SUPPORTED:
1498         if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1499             c->argv[0] != FMT_ASSOCIATION) {
1500             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1501                                  c->trans, 0, 0, 0, 0);
1502             return;
1503         }
1504         data_in = usb_mtp_get_object_props_supported(s, c);
1505         break;
1506     case CMD_GET_OBJECT_PROP_DESC:
1507         if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1508             c->argv[1] != FMT_ASSOCIATION) {
1509             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1510                                  c->trans, 0, 0, 0, 0);
1511             return;
1512         }
1513         data_in = usb_mtp_get_object_prop_desc(s, c);
1514         if (data_in == NULL) {
1515             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1516                                  c->trans, 0, 0, 0, 0);
1517             return;
1518         }
1519         break;
1520     case CMD_GET_OBJECT_PROP_VALUE:
1521         o = usb_mtp_object_lookup(s, c->argv[0]);
1522         if (o == NULL) {
1523             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1524                                  c->trans, 0, 0, 0, 0);
1525             return;
1526         }
1527         data_in = usb_mtp_get_object_prop_value(s, c, o);
1528         if (data_in == NULL) {
1529             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1530                                  c->trans, 0, 0, 0, 0);
1531             return;
1532         }
1533         break;
1534     default:
1535         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1536         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1537                              c->trans, 0, 0, 0, 0);
1538         return;
1539     }
1540 
1541     /* return results on success */
1542     if (data_in) {
1543         assert(s->data_in == NULL);
1544         s->data_in = data_in;
1545     }
1546     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1547 }
1548 
1549 /* ----------------------------------------------------------------------- */
1550 
1551 static void usb_mtp_handle_reset(USBDevice *dev)
1552 {
1553     MTPState *s = USB_MTP(dev);
1554 
1555     trace_usb_mtp_reset(s->dev.addr);
1556 
1557 #ifdef CONFIG_INOTIFY1
1558     usb_mtp_inotify_cleanup(s);
1559 #endif
1560     usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1561     s->session = 0;
1562     usb_mtp_data_free(s->data_in);
1563     s->data_in = NULL;
1564     usb_mtp_data_free(s->data_out);
1565     s->data_out = NULL;
1566     g_free(s->result);
1567     s->result = NULL;
1568 }
1569 
1570 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1571                                    int request, int value, int index,
1572                                    int length, uint8_t *data)
1573 {
1574     int ret;
1575     MTPState *s = USB_MTP(dev);
1576     uint16_t *event = (uint16_t *)data;
1577 
1578     switch (request) {
1579     case ClassInterfaceOutRequest | 0x64:
1580         if (*event == EVT_CANCEL_TRANSACTION) {
1581             g_free(s->result);
1582             s->result = NULL;
1583             usb_mtp_data_free(s->data_in);
1584             s->data_in = NULL;
1585             if (s->write_pending) {
1586                 g_free(s->dataset.filename);
1587                 s->write_pending = false;
1588                 s->dataset.size = 0;
1589             }
1590             usb_mtp_data_free(s->data_out);
1591             s->data_out = NULL;
1592         } else {
1593             p->status = USB_RET_STALL;
1594         }
1595         break;
1596     default:
1597         ret = usb_desc_handle_control(dev, p, request,
1598                                       value, index, length, data);
1599         if (ret >= 0) {
1600             return;
1601         }
1602     }
1603 
1604     trace_usb_mtp_stall(dev->addr, "unknown control request");
1605 }
1606 
1607 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1608 {
1609     /* we don't use async packets, so this should never be called */
1610     fprintf(stderr, "%s\n", __func__);
1611 }
1612 
1613 static char *utf16_to_str(uint8_t len, uint16_t *arr)
1614 {
1615     wchar_t *wstr = g_new0(wchar_t, len + 1);
1616     int count, dlen;
1617     char *dest;
1618 
1619     for (count = 0; count < len; count++) {
1620         /* FIXME: not working for surrogate pairs */
1621         wstr[count] = (wchar_t)arr[count];
1622     }
1623     wstr[count] = 0;
1624 
1625     dlen = wcstombs(NULL, wstr, 0) + 1;
1626     dest = g_malloc(dlen);
1627     wcstombs(dest, wstr, dlen);
1628     g_free(wstr);
1629     return dest;
1630 }
1631 
1632 /* Wrapper around write, returns 0 on failure */
1633 static uint64_t write_retry(int fd, void *buf, uint64_t size, off_t offset)
1634 {
1635         uint64_t ret = 0;
1636 
1637         if (lseek(fd, offset, SEEK_SET) < 0) {
1638             goto done;
1639         }
1640 
1641         ret = qemu_write_full(fd, buf, size);
1642 
1643 done:
1644         return ret;
1645 }
1646 
1647 static void usb_mtp_update_object(MTPObject *parent, char *name)
1648 {
1649     MTPObject *o =
1650         usb_mtp_object_lookup_name(parent, name, strlen(name));
1651 
1652     if (o) {
1653         lstat(o->path, &o->stat);
1654     }
1655 }
1656 
1657 static void usb_mtp_write_data(MTPState *s)
1658 {
1659     MTPData *d = s->data_out;
1660     MTPObject *parent =
1661         usb_mtp_object_lookup(s, s->dataset.parent_handle);
1662     char *path = NULL;
1663     uint64_t rc;
1664     mode_t mask = 0644;
1665 
1666     assert(d != NULL);
1667 
1668     switch (d->write_status) {
1669     case WRITE_START:
1670         if (!parent || !s->write_pending) {
1671             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1672                 0, 0, 0, 0);
1673         return;
1674         }
1675 
1676         if (s->dataset.filename) {
1677             path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1678             if (s->dataset.format == FMT_ASSOCIATION) {
1679                 d->fd = mkdir(path, mask);
1680                 goto free;
1681             }
1682             d->fd = open(path, O_CREAT | O_WRONLY |
1683                          O_CLOEXEC | O_NOFOLLOW, mask);
1684             if (d->fd == -1) {
1685                 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1686                                      0, 0, 0, 0);
1687                 goto done;
1688             }
1689 
1690             /* Return success if initiator sent 0 sized data */
1691             if (!s->dataset.size) {
1692                 goto success;
1693             }
1694             if (d->length != MTP_WRITE_BUF_SZ && !d->pending) {
1695                 d->write_status = WRITE_END;
1696             }
1697         }
1698         /* fall through */
1699     case WRITE_CONTINUE:
1700     case WRITE_END:
1701         rc = write_retry(d->fd, d->data, d->data_offset,
1702                          d->offset - d->data_offset);
1703         if (rc != d->data_offset) {
1704             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1705                                  0, 0, 0, 0);
1706             goto done;
1707         }
1708         if (d->write_status != WRITE_END) {
1709             return;
1710         } else {
1711             /* Only for < 4G file sizes */
1712             if (s->dataset.size != 0xFFFFFFFF && d->offset != s->dataset.size) {
1713                 usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1714                                      0, 0, 0, 0);
1715                 goto done;
1716             }
1717             usb_mtp_update_object(parent, s->dataset.filename);
1718         }
1719     }
1720 
1721 success:
1722     usb_mtp_queue_result(s, RES_OK, d->trans,
1723                          0, 0, 0, 0);
1724 
1725 done:
1726     /*
1727      * The write dataset is kept around and freed only
1728      * on success or if another write request comes in
1729      */
1730     if (d->fd != -1) {
1731         close(d->fd);
1732     }
1733 free:
1734     g_free(s->dataset.filename);
1735     s->dataset.size = 0;
1736     g_free(path);
1737     s->write_pending = false;
1738 }
1739 
1740 static void usb_mtp_write_metadata(MTPState *s, uint64_t dlen)
1741 {
1742     MTPData *d = s->data_out;
1743     ObjectInfo *dataset = (ObjectInfo *)d->data;
1744     char *filename;
1745     MTPObject *o;
1746     MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1747     uint32_t next_handle = s->next_handle;
1748 
1749     assert(!s->write_pending);
1750     assert(p != NULL);
1751 
1752     filename = utf16_to_str(MIN(dataset->length,
1753                                 dlen - offsetof(ObjectInfo, filename)),
1754                             dataset->filename);
1755 
1756     if (strchr(filename, '/')) {
1757         usb_mtp_queue_result(s, RES_PARAMETER_NOT_SUPPORTED, d->trans,
1758                              0, 0, 0, 0);
1759         g_free(filename);
1760         return;
1761     }
1762 
1763     o = usb_mtp_object_lookup_name(p, filename, dataset->length);
1764     if (o != NULL) {
1765         next_handle = o->handle;
1766     }
1767 
1768     s->dataset.filename = filename;
1769     s->dataset.format = dataset->format;
1770     s->dataset.size = dataset->size;
1771     s->write_pending = true;
1772 
1773     if (s->dataset.format == FMT_ASSOCIATION) {
1774         usb_mtp_write_data(s);
1775         /* next_handle will be allocated to the newly created dir */
1776         if (d->fd == -1) {
1777             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1778                                  0, 0, 0, 0);
1779             return;
1780         }
1781         d->fd = -1;
1782     }
1783 
1784     usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1785                          s->dataset.parent_handle, next_handle);
1786 }
1787 
1788 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1789                              USBPacket *p)
1790 {
1791     MTPData *d = s->data_out;
1792     uint64_t dlen;
1793     uint32_t data_len = p->iov.size;
1794     uint64_t total_len;
1795 
1796     if (!d) {
1797             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1798                                  0, 0, 0, 0);
1799             return;
1800     }
1801     if (d->first) {
1802         /* Total length of incoming data */
1803         total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1804         /* Length of data in this packet */
1805         data_len -= sizeof(mtp_container);
1806         if (total_len < MTP_WRITE_BUF_SZ) {
1807                 usb_mtp_realloc(d, total_len);
1808                 d->length += total_len;
1809         } else {
1810                 usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - sizeof(mtp_container));
1811                 d->length += MTP_WRITE_BUF_SZ - sizeof(mtp_container);
1812         }
1813         d->offset = 0;
1814         d->first = false;
1815         d->pending = false;
1816         d->data_offset = 0;
1817         d->write_status = WRITE_START;
1818     }
1819 
1820     if (d->pending) {
1821         memset(d->data, 0, d->length);
1822         if (d->length != MTP_WRITE_BUF_SZ) {
1823             usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - d->length);
1824             d->length += (MTP_WRITE_BUF_SZ - d->length);
1825         }
1826         d->pending = false;
1827         d->write_status = WRITE_CONTINUE;
1828         d->data_offset = 0;
1829     }
1830 
1831     if (d->length - d->data_offset > data_len) {
1832         dlen = data_len;
1833     } else {
1834         dlen = d->length - d->data_offset;
1835     }
1836 
1837     switch (d->code) {
1838     case CMD_SEND_OBJECT_INFO:
1839         usb_packet_copy(p, d->data + d->data_offset, dlen);
1840         d->offset += dlen;
1841         d->data_offset += dlen;
1842         if (d->data_offset == d->length) {
1843             /* The operation might have already failed */
1844             if (!s->result) {
1845                 usb_mtp_write_metadata(s, dlen);
1846             }
1847             usb_mtp_data_free(s->data_out);
1848             s->data_out = NULL;
1849             return;
1850         }
1851         break;
1852     case CMD_SEND_OBJECT:
1853         usb_packet_copy(p, d->data + d->data_offset, dlen);
1854         d->offset += dlen;
1855         d->data_offset += dlen;
1856         if ((p->iov.size % 64) || !p->iov.size) {
1857             assert((s->dataset.size == 0xFFFFFFFF) ||
1858                    (s->dataset.size == d->offset));
1859 
1860             if (d->length == MTP_WRITE_BUF_SZ) {
1861                 d->write_status = WRITE_END;
1862             } else {
1863                 d->write_status = WRITE_START;
1864             }
1865             usb_mtp_write_data(s);
1866             usb_mtp_data_free(s->data_out);
1867             s->data_out = NULL;
1868             return;
1869         }
1870         if (d->data_offset == d->length) {
1871             d->pending = true;
1872             usb_mtp_write_data(s);
1873         }
1874         break;
1875     default:
1876         p->status = USB_RET_STALL;
1877         return;
1878     }
1879 }
1880 
1881 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1882 {
1883     MTPState *s = USB_MTP(dev);
1884     MTPControl cmd;
1885     mtp_container container;
1886     uint32_t params[5];
1887     uint16_t container_type;
1888     int i, rc;
1889 
1890     switch (p->ep->nr) {
1891     case EP_DATA_IN:
1892         if (s->data_out != NULL) {
1893             /* guest bug */
1894             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1895             p->status = USB_RET_STALL;
1896             return;
1897         }
1898         if (p->iov.size < sizeof(container)) {
1899             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1900             p->status = USB_RET_STALL;
1901             return;
1902         }
1903         if (s->data_in !=  NULL) {
1904             MTPData *d = s->data_in;
1905             uint64_t dlen = d->length - d->offset;
1906             if (d->first) {
1907                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1908                 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1909                     container.length = cpu_to_le32(0xFFFFFFFF);
1910                 } else {
1911                     container.length =
1912                         cpu_to_le32(d->length + sizeof(container));
1913                 }
1914                 container.type   = cpu_to_le16(TYPE_DATA);
1915                 container.code   = cpu_to_le16(d->code);
1916                 container.trans  = cpu_to_le32(d->trans);
1917                 usb_packet_copy(p, &container, sizeof(container));
1918                 d->first = false;
1919                 if (dlen > p->iov.size - sizeof(container)) {
1920                     dlen = p->iov.size - sizeof(container);
1921                 }
1922             } else {
1923                 if (dlen > p->iov.size) {
1924                     dlen = p->iov.size;
1925                 }
1926             }
1927             if (d->fd == -1) {
1928                 usb_packet_copy(p, d->data + d->offset, dlen);
1929             } else {
1930                 if (d->alloc < p->iov.size) {
1931                     d->alloc = p->iov.size;
1932                     d->data = g_realloc(d->data, d->alloc);
1933                 }
1934                 rc = read(d->fd, d->data, dlen);
1935                 if (rc != dlen) {
1936                     memset(d->data, 0, dlen);
1937                     s->result->code = RES_INCOMPLETE_TRANSFER;
1938                 }
1939                 usb_packet_copy(p, d->data, dlen);
1940             }
1941             d->offset += dlen;
1942             if (d->offset == d->length) {
1943                 usb_mtp_data_free(s->data_in);
1944                 s->data_in = NULL;
1945             }
1946         } else if (s->result != NULL) {
1947             MTPControl *r = s->result;
1948             int length = sizeof(container) + r->argc * sizeof(uint32_t);
1949             if (r->code == RES_OK) {
1950                 trace_usb_mtp_success(s->dev.addr, r->trans,
1951                                       (r->argc > 0) ? r->argv[0] : 0,
1952                                       (r->argc > 1) ? r->argv[1] : 0);
1953             } else {
1954                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1955                                     (r->argc > 0) ? r->argv[0] : 0,
1956                                     (r->argc > 1) ? r->argv[1] : 0);
1957             }
1958             container.length = cpu_to_le32(length);
1959             container.type   = cpu_to_le16(TYPE_RESPONSE);
1960             container.code   = cpu_to_le16(r->code);
1961             container.trans  = cpu_to_le32(r->trans);
1962             for (i = 0; i < r->argc; i++) {
1963                 params[i] = cpu_to_le32(r->argv[i]);
1964             }
1965             usb_packet_copy(p, &container, sizeof(container));
1966             usb_packet_copy(p, &params, length - sizeof(container));
1967             g_free(s->result);
1968             s->result = NULL;
1969         }
1970         break;
1971     case EP_DATA_OUT:
1972         if (p->iov.size < sizeof(container)) {
1973             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1974             p->status = USB_RET_STALL;
1975             return;
1976         }
1977         if ((s->data_out != NULL) && !s->data_out->first) {
1978             container_type = TYPE_DATA;
1979         } else {
1980             usb_packet_copy(p, &container, sizeof(container));
1981             container_type = le16_to_cpu(container.type);
1982         }
1983         switch (container_type) {
1984         case TYPE_COMMAND:
1985             if (s->data_in || s->data_out || s->result) {
1986                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1987                 p->status = USB_RET_STALL;
1988                 return;
1989             }
1990             cmd.code = le16_to_cpu(container.code);
1991             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1992                 / sizeof(uint32_t);
1993             cmd.trans = le32_to_cpu(container.trans);
1994             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1995                 cmd.argc = ARRAY_SIZE(cmd.argv);
1996             }
1997             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1998                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1999                 p->status = USB_RET_STALL;
2000                 return;
2001             }
2002             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
2003             for (i = 0; i < cmd.argc; i++) {
2004                 cmd.argv[i] = le32_to_cpu(params[i]);
2005             }
2006             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
2007                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
2008                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
2009                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
2010                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
2011                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
2012             usb_mtp_command(s, &cmd);
2013             break;
2014         case TYPE_DATA:
2015             /* One of the previous transfers has already errored but the
2016              * responder is still sending data associated with it
2017              */
2018             if (s->result != NULL) {
2019                 return;
2020             }
2021             usb_mtp_get_data(s, &container, p);
2022             break;
2023         default:
2024             /* not needed as long as the mtp device is read-only */
2025             p->status = USB_RET_STALL;
2026             return;
2027         }
2028         break;
2029     case EP_EVENT:
2030 #ifdef CONFIG_INOTIFY1
2031         if (!QTAILQ_EMPTY(&s->events)) {
2032             struct MTPMonEntry *e = QTAILQ_LAST(&s->events);
2033             uint32_t handle;
2034             int len = sizeof(container) + sizeof(uint32_t);
2035 
2036             if (p->iov.size < len) {
2037                 trace_usb_mtp_stall(s->dev.addr,
2038                                     "packet too small to send event");
2039                 p->status = USB_RET_STALL;
2040                 return;
2041             }
2042 
2043             QTAILQ_REMOVE(&s->events, e, next);
2044             container.length = cpu_to_le32(len);
2045             container.type = cpu_to_le32(TYPE_EVENT);
2046             container.code = cpu_to_le16(e->event);
2047             container.trans = 0; /* no trans specific events */
2048             handle = cpu_to_le32(e->handle);
2049             usb_packet_copy(p, &container, sizeof(container));
2050             usb_packet_copy(p, &handle, sizeof(uint32_t));
2051             g_free(e);
2052             return;
2053         }
2054 #endif
2055         p->status = USB_RET_NAK;
2056         return;
2057     default:
2058         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2059         p->status = USB_RET_STALL;
2060         return;
2061     }
2062 
2063     if (p->actual_length == 0) {
2064         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2065         p->status = USB_RET_NAK;
2066         return;
2067     } else {
2068         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2069                            p->iov.size);
2070         return;
2071     }
2072 }
2073 
2074 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2075 {
2076     MTPState *s = USB_MTP(dev);
2077 
2078     usb_desc_create_serial(dev);
2079     usb_desc_init(dev);
2080     QTAILQ_INIT(&s->objects);
2081     if (s->desc == NULL) {
2082         if (s->root == NULL) {
2083             error_setg(errp, "usb-mtp: rootdir property must be configured");
2084             return;
2085         }
2086         s->desc = strrchr(s->root, '/');
2087         if (s->desc && s->desc[0]) {
2088             s->desc = g_strdup(s->desc + 1);
2089         } else {
2090             s->desc = g_strdup("none");
2091         }
2092     }
2093     /* Mark store as RW */
2094     if (!s->readonly) {
2095         s->flags |= (1 << MTP_FLAG_WRITABLE);
2096     }
2097 
2098 }
2099 
2100 static const VMStateDescription vmstate_usb_mtp = {
2101     .name = "usb-mtp",
2102     .unmigratable = 1,
2103     .version_id = 1,
2104     .minimum_version_id = 1,
2105     .fields = (VMStateField[]) {
2106         VMSTATE_USB_DEVICE(dev, MTPState),
2107         VMSTATE_END_OF_LIST()
2108     }
2109 };
2110 
2111 static Property mtp_properties[] = {
2112     DEFINE_PROP_STRING("rootdir", MTPState, root),
2113     DEFINE_PROP_STRING("desc", MTPState, desc),
2114     DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2115     DEFINE_PROP_END_OF_LIST(),
2116 };
2117 
2118 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2119 {
2120     DeviceClass *dc = DEVICE_CLASS(klass);
2121     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2122 
2123     uc->realize        = usb_mtp_realize;
2124     uc->product_desc   = "QEMU USB MTP";
2125     uc->usb_desc       = &desc;
2126     uc->cancel_packet  = usb_mtp_cancel_packet;
2127     uc->handle_attach  = usb_desc_attach;
2128     uc->handle_reset   = usb_mtp_handle_reset;
2129     uc->handle_control = usb_mtp_handle_control;
2130     uc->handle_data    = usb_mtp_handle_data;
2131     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2132     dc->desc = "USB Media Transfer Protocol device";
2133     dc->fw_name = "mtp";
2134     dc->vmsd = &vmstate_usb_mtp;
2135     dc->props = mtp_properties;
2136 }
2137 
2138 static TypeInfo mtp_info = {
2139     .name          = TYPE_USB_MTP,
2140     .parent        = TYPE_USB_DEVICE,
2141     .instance_size = sizeof(MTPState),
2142     .class_init    = usb_mtp_class_initfn,
2143 };
2144 
2145 static void usb_mtp_register_types(void)
2146 {
2147     type_register_static(&mtp_info);
2148 }
2149 
2150 type_init(usb_mtp_register_types)
2151