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