xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 754cb9c0)
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     }
1181 
1182     if (o->format == FMT_ASSOCIATION) {
1183         if (rmdir(o->path)) {
1184             partial_delete = true;
1185         } else {
1186             usb_mtp_object_free_one(s, o);
1187             success = true;
1188         }
1189     }
1190 
1191     if (success && partial_delete) {
1192         return PARTIAL_DELETE;
1193     }
1194     if (!success && partial_delete) {
1195         return READ_ONLY;
1196     }
1197     return ALL_DELETE;
1198 }
1199 
1200 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1201                                   uint32_t format_code, uint32_t trans)
1202 {
1203     MTPObject *o;
1204     int ret;
1205 
1206     /* Return error if store is read-only */
1207     if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1208         usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1209                              trans, 0, 0, 0, 0);
1210         return;
1211     }
1212 
1213     if (format_code != 0) {
1214         usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1215                              trans, 0, 0, 0, 0);
1216         return;
1217     }
1218 
1219     if (handle == 0xFFFFFFF) {
1220         o = QTAILQ_FIRST(&s->objects);
1221     } else {
1222         o = usb_mtp_object_lookup(s, handle);
1223     }
1224     if (o == NULL) {
1225         usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1226                              trans, 0, 0, 0, 0);
1227         return;
1228     }
1229 
1230     ret = usb_mtp_deletefn(s, o, trans);
1231     if (ret == PARTIAL_DELETE) {
1232         usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1233                              trans, 0, 0, 0, 0);
1234         return;
1235     } else if (ret == READ_ONLY) {
1236         usb_mtp_queue_result(s, RES_STORE_READ_ONLY, trans,
1237                              0, 0, 0, 0);
1238         return;
1239     } else {
1240         usb_mtp_queue_result(s, RES_OK, trans,
1241                              0, 0, 0, 0);
1242         return;
1243     }
1244 }
1245 
1246 static void usb_mtp_command(MTPState *s, MTPControl *c)
1247 {
1248     MTPData *data_in = NULL;
1249     MTPObject *o = NULL;
1250     uint32_t nres = 0, res0 = 0;
1251     Error *err = NULL;
1252 
1253     /* sanity checks */
1254     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1255         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1256                              c->trans, 0, 0, 0, 0);
1257         return;
1258     }
1259 
1260     /* process commands */
1261     switch (c->code) {
1262     case CMD_GET_DEVICE_INFO:
1263         data_in = usb_mtp_get_device_info(s, c);
1264         break;
1265     case CMD_OPEN_SESSION:
1266         if (s->session) {
1267             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1268                                  c->trans, 1, s->session, 0, 0);
1269             return;
1270         }
1271         if (c->argv[0] == 0) {
1272             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1273                                  c->trans, 0, 0, 0, 0);
1274             return;
1275         }
1276         trace_usb_mtp_op_open_session(s->dev.addr);
1277         s->session = c->argv[0];
1278         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1279 
1280         s->file_monitor = qemu_file_monitor_new(&err);
1281         if (err) {
1282             error_report("usb-mtp: file monitoring init failed: %s",
1283                          error_get_pretty(err));
1284             error_free(err);
1285         } else {
1286             QTAILQ_INIT(&s->events);
1287         }
1288         break;
1289     case CMD_CLOSE_SESSION:
1290         trace_usb_mtp_op_close_session(s->dev.addr);
1291         s->session = 0;
1292         s->next_handle = 0;
1293         usb_mtp_file_monitor_cleanup(s);
1294         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1295         assert(QTAILQ_EMPTY(&s->objects));
1296         break;
1297     case CMD_GET_STORAGE_IDS:
1298         data_in = usb_mtp_get_storage_ids(s, c);
1299         break;
1300     case CMD_GET_STORAGE_INFO:
1301         if (c->argv[0] != QEMU_STORAGE_ID &&
1302             c->argv[0] != 0xffffffff) {
1303             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1304                                  c->trans, 0, 0, 0, 0);
1305             return;
1306         }
1307         data_in = usb_mtp_get_storage_info(s, c);
1308         break;
1309     case CMD_GET_NUM_OBJECTS:
1310     case CMD_GET_OBJECT_HANDLES:
1311         if (c->argv[0] != QEMU_STORAGE_ID &&
1312             c->argv[0] != 0xffffffff) {
1313             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1314                                  c->trans, 0, 0, 0, 0);
1315             return;
1316         }
1317         if (c->argv[1] != 0x00000000) {
1318             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1319                                  c->trans, 0, 0, 0, 0);
1320             return;
1321         }
1322         if (c->argv[2] == 0x00000000 ||
1323             c->argv[2] == 0xffffffff) {
1324             o = QTAILQ_FIRST(&s->objects);
1325         } else {
1326             o = usb_mtp_object_lookup(s, c->argv[2]);
1327         }
1328         if (o == NULL) {
1329             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1330                                  c->trans, 0, 0, 0, 0);
1331             return;
1332         }
1333         if (o->format != FMT_ASSOCIATION) {
1334             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1335                                  c->trans, 0, 0, 0, 0);
1336             return;
1337         }
1338         usb_mtp_object_readdir(s, o);
1339         if (c->code == CMD_GET_NUM_OBJECTS) {
1340             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1341             nres = 1;
1342             res0 = o->nchildren;
1343         } else {
1344             data_in = usb_mtp_get_object_handles(s, c, o);
1345         }
1346         break;
1347     case CMD_GET_OBJECT_INFO:
1348         o = usb_mtp_object_lookup(s, c->argv[0]);
1349         if (o == NULL) {
1350             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1351                                  c->trans, 0, 0, 0, 0);
1352             return;
1353         }
1354         data_in = usb_mtp_get_object_info(s, c, o);
1355         break;
1356     case CMD_GET_OBJECT:
1357         o = usb_mtp_object_lookup(s, c->argv[0]);
1358         if (o == NULL) {
1359             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1360                                  c->trans, 0, 0, 0, 0);
1361             return;
1362         }
1363         if (o->format == FMT_ASSOCIATION) {
1364             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1365                                  c->trans, 0, 0, 0, 0);
1366             return;
1367         }
1368         data_in = usb_mtp_get_object(s, c, o);
1369         if (data_in == NULL) {
1370             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1371                                  c->trans, 0, 0, 0, 0);
1372             return;
1373         }
1374         break;
1375     case CMD_DELETE_OBJECT:
1376         usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1377         return;
1378     case CMD_GET_PARTIAL_OBJECT:
1379         o = usb_mtp_object_lookup(s, c->argv[0]);
1380         if (o == NULL) {
1381             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1382                                  c->trans, 0, 0, 0, 0);
1383             return;
1384         }
1385         if (o->format == FMT_ASSOCIATION) {
1386             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1387                                  c->trans, 0, 0, 0, 0);
1388             return;
1389         }
1390         data_in = usb_mtp_get_partial_object(s, c, o);
1391         if (data_in == NULL) {
1392             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1393                                  c->trans, 0, 0, 0, 0);
1394             return;
1395         }
1396         nres = 1;
1397         res0 = data_in->length;
1398         break;
1399     case CMD_SEND_OBJECT_INFO:
1400         /* Return error if store is read-only */
1401         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1402             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1403                                  c->trans, 0, 0, 0, 0);
1404         } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1405             /* First parameter points to storage id or is 0 */
1406             usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1407                                  0, 0, 0, 0);
1408         } else if (c->argv[1] && !c->argv[0]) {
1409             /* If second parameter is specified, first must also be specified */
1410             usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1411                                  0, 0, 0, 0);
1412         } else {
1413             uint32_t handle = c->argv[1];
1414             if (handle == 0xFFFFFFFF || handle == 0) {
1415                 /* root object */
1416                 o = QTAILQ_FIRST(&s->objects);
1417             } else {
1418                 o = usb_mtp_object_lookup(s, handle);
1419             }
1420             if (o == NULL) {
1421                 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1422                                      0, 0, 0, 0);
1423             } else if (o->format != FMT_ASSOCIATION) {
1424                 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1425                                      0, 0, 0, 0);
1426             }
1427         }
1428         if (o) {
1429             s->dataset.parent_handle = o->handle;
1430         }
1431         s->data_out = usb_mtp_data_alloc(c);
1432         return;
1433     case CMD_SEND_OBJECT:
1434         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1435             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1436                                  c->trans, 0, 0, 0, 0);
1437             return;
1438         }
1439         if (!s->write_pending) {
1440             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1441                                  c->trans, 0, 0, 0, 0);
1442             return;
1443         }
1444         s->data_out = usb_mtp_data_alloc(c);
1445         return;
1446     case CMD_GET_OBJECT_PROPS_SUPPORTED:
1447         if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1448             c->argv[0] != FMT_ASSOCIATION) {
1449             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1450                                  c->trans, 0, 0, 0, 0);
1451             return;
1452         }
1453         data_in = usb_mtp_get_object_props_supported(s, c);
1454         break;
1455     case CMD_GET_OBJECT_PROP_DESC:
1456         if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1457             c->argv[1] != FMT_ASSOCIATION) {
1458             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1459                                  c->trans, 0, 0, 0, 0);
1460             return;
1461         }
1462         data_in = usb_mtp_get_object_prop_desc(s, c);
1463         if (data_in == NULL) {
1464             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1465                                  c->trans, 0, 0, 0, 0);
1466             return;
1467         }
1468         break;
1469     case CMD_GET_OBJECT_PROP_VALUE:
1470         o = usb_mtp_object_lookup(s, c->argv[0]);
1471         if (o == NULL) {
1472             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1473                                  c->trans, 0, 0, 0, 0);
1474             return;
1475         }
1476         data_in = usb_mtp_get_object_prop_value(s, c, o);
1477         if (data_in == NULL) {
1478             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1479                                  c->trans, 0, 0, 0, 0);
1480             return;
1481         }
1482         break;
1483     default:
1484         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1485         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1486                              c->trans, 0, 0, 0, 0);
1487         return;
1488     }
1489 
1490     /* return results on success */
1491     if (data_in) {
1492         assert(s->data_in == NULL);
1493         s->data_in = data_in;
1494     }
1495     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1496 }
1497 
1498 /* ----------------------------------------------------------------------- */
1499 
1500 static void usb_mtp_handle_reset(USBDevice *dev)
1501 {
1502     MTPState *s = USB_MTP(dev);
1503 
1504     trace_usb_mtp_reset(s->dev.addr);
1505 
1506     usb_mtp_file_monitor_cleanup(s);
1507     usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1508     s->session = 0;
1509     usb_mtp_data_free(s->data_in);
1510     s->data_in = NULL;
1511     usb_mtp_data_free(s->data_out);
1512     s->data_out = NULL;
1513     g_free(s->result);
1514     s->result = NULL;
1515 }
1516 
1517 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1518                                    int request, int value, int index,
1519                                    int length, uint8_t *data)
1520 {
1521     int ret;
1522     MTPState *s = USB_MTP(dev);
1523     uint16_t *event = (uint16_t *)data;
1524 
1525     switch (request) {
1526     case ClassInterfaceOutRequest | 0x64:
1527         if (*event == EVT_CANCEL_TRANSACTION) {
1528             g_free(s->result);
1529             s->result = NULL;
1530             usb_mtp_data_free(s->data_in);
1531             s->data_in = NULL;
1532             if (s->write_pending) {
1533                 g_free(s->dataset.filename);
1534                 s->write_pending = false;
1535                 s->dataset.size = 0;
1536             }
1537             usb_mtp_data_free(s->data_out);
1538             s->data_out = NULL;
1539         } else {
1540             p->status = USB_RET_STALL;
1541         }
1542         break;
1543     default:
1544         ret = usb_desc_handle_control(dev, p, request,
1545                                       value, index, length, data);
1546         if (ret >= 0) {
1547             return;
1548         }
1549     }
1550 
1551     trace_usb_mtp_stall(dev->addr, "unknown control request");
1552 }
1553 
1554 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1555 {
1556     /* we don't use async packets, so this should never be called */
1557     fprintf(stderr, "%s\n", __func__);
1558 }
1559 
1560 static char *utf16_to_str(uint8_t len, uint16_t *arr)
1561 {
1562     wchar_t *wstr = g_new0(wchar_t, len + 1);
1563     int count, dlen;
1564     char *dest;
1565 
1566     for (count = 0; count < len; count++) {
1567         /* FIXME: not working for surrogate pairs */
1568         wstr[count] = (wchar_t)arr[count];
1569     }
1570     wstr[count] = 0;
1571 
1572     dlen = wcstombs(NULL, wstr, 0) + 1;
1573     dest = g_malloc(dlen);
1574     wcstombs(dest, wstr, dlen);
1575     g_free(wstr);
1576     return dest;
1577 }
1578 
1579 /* Wrapper around write, returns 0 on failure */
1580 static uint64_t write_retry(int fd, void *buf, uint64_t size, off_t offset)
1581 {
1582         uint64_t ret = 0;
1583 
1584         if (lseek(fd, offset, SEEK_SET) < 0) {
1585             goto done;
1586         }
1587 
1588         ret = qemu_write_full(fd, buf, size);
1589 
1590 done:
1591         return ret;
1592 }
1593 
1594 static void usb_mtp_update_object(MTPObject *parent, char *name)
1595 {
1596     MTPObject *o =
1597         usb_mtp_object_lookup_name(parent, name, strlen(name));
1598 
1599     if (o) {
1600         lstat(o->path, &o->stat);
1601     }
1602 }
1603 
1604 static void usb_mtp_write_data(MTPState *s)
1605 {
1606     MTPData *d = s->data_out;
1607     MTPObject *parent =
1608         usb_mtp_object_lookup(s, s->dataset.parent_handle);
1609     char *path = NULL;
1610     uint64_t rc;
1611     mode_t mask = 0644;
1612 
1613     assert(d != NULL);
1614 
1615     switch (d->write_status) {
1616     case WRITE_START:
1617         if (!parent || !s->write_pending) {
1618             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1619                 0, 0, 0, 0);
1620         return;
1621         }
1622 
1623         if (s->dataset.filename) {
1624             path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1625             if (s->dataset.format == FMT_ASSOCIATION) {
1626                 d->fd = mkdir(path, mask);
1627                 goto free;
1628             }
1629             d->fd = open(path, O_CREAT | O_WRONLY |
1630                          O_CLOEXEC | O_NOFOLLOW, mask);
1631             if (d->fd == -1) {
1632                 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1633                                      0, 0, 0, 0);
1634                 goto done;
1635             }
1636 
1637             /* Return success if initiator sent 0 sized data */
1638             if (!s->dataset.size) {
1639                 goto success;
1640             }
1641             if (d->length != MTP_WRITE_BUF_SZ && !d->pending) {
1642                 d->write_status = WRITE_END;
1643             }
1644         }
1645         /* fall through */
1646     case WRITE_CONTINUE:
1647     case WRITE_END:
1648         rc = write_retry(d->fd, d->data, d->data_offset,
1649                          d->offset - d->data_offset);
1650         if (rc != d->data_offset) {
1651             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1652                                  0, 0, 0, 0);
1653             goto done;
1654         }
1655         if (d->write_status != WRITE_END) {
1656             return;
1657         } else {
1658             /* Only for < 4G file sizes */
1659             if (s->dataset.size != 0xFFFFFFFF && d->offset != s->dataset.size) {
1660                 usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1661                                      0, 0, 0, 0);
1662                 goto done;
1663             }
1664             usb_mtp_update_object(parent, s->dataset.filename);
1665         }
1666     }
1667 
1668 success:
1669     usb_mtp_queue_result(s, RES_OK, d->trans,
1670                          0, 0, 0, 0);
1671 
1672 done:
1673     /*
1674      * The write dataset is kept around and freed only
1675      * on success or if another write request comes in
1676      */
1677     if (d->fd != -1) {
1678         close(d->fd);
1679     }
1680 free:
1681     g_free(s->dataset.filename);
1682     s->dataset.size = 0;
1683     g_free(path);
1684     s->write_pending = false;
1685 }
1686 
1687 static void usb_mtp_write_metadata(MTPState *s, uint64_t dlen)
1688 {
1689     MTPData *d = s->data_out;
1690     ObjectInfo *dataset = (ObjectInfo *)d->data;
1691     char *filename;
1692     MTPObject *o;
1693     MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1694     uint32_t next_handle = s->next_handle;
1695 
1696     assert(!s->write_pending);
1697     assert(p != NULL);
1698 
1699     filename = utf16_to_str(MIN(dataset->length,
1700                                 dlen - offsetof(ObjectInfo, filename)),
1701                             dataset->filename);
1702 
1703     if (strchr(filename, '/')) {
1704         usb_mtp_queue_result(s, RES_PARAMETER_NOT_SUPPORTED, d->trans,
1705                              0, 0, 0, 0);
1706         g_free(filename);
1707         return;
1708     }
1709 
1710     o = usb_mtp_object_lookup_name(p, filename, dataset->length);
1711     if (o != NULL) {
1712         next_handle = o->handle;
1713     }
1714 
1715     s->dataset.filename = filename;
1716     s->dataset.format = dataset->format;
1717     s->dataset.size = dataset->size;
1718     s->write_pending = true;
1719 
1720     if (s->dataset.format == FMT_ASSOCIATION) {
1721         usb_mtp_write_data(s);
1722         /* next_handle will be allocated to the newly created dir */
1723         if (d->fd == -1) {
1724             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1725                                  0, 0, 0, 0);
1726             return;
1727         }
1728         d->fd = -1;
1729     }
1730 
1731     usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1732                          s->dataset.parent_handle, next_handle);
1733 }
1734 
1735 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1736                              USBPacket *p)
1737 {
1738     MTPData *d = s->data_out;
1739     uint64_t dlen;
1740     uint32_t data_len = p->iov.size;
1741     uint64_t total_len;
1742 
1743     if (!d) {
1744             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1745                                  0, 0, 0, 0);
1746             return;
1747     }
1748     if (d->first) {
1749         /* Total length of incoming data */
1750         total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1751         /* Length of data in this packet */
1752         data_len -= sizeof(mtp_container);
1753         if (total_len < MTP_WRITE_BUF_SZ) {
1754                 usb_mtp_realloc(d, total_len);
1755                 d->length += total_len;
1756         } else {
1757                 usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - sizeof(mtp_container));
1758                 d->length += MTP_WRITE_BUF_SZ - sizeof(mtp_container);
1759         }
1760         d->offset = 0;
1761         d->first = false;
1762         d->pending = false;
1763         d->data_offset = 0;
1764         d->write_status = WRITE_START;
1765     }
1766 
1767     if (d->pending) {
1768         memset(d->data, 0, d->length);
1769         if (d->length != MTP_WRITE_BUF_SZ) {
1770             usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - d->length);
1771             d->length += (MTP_WRITE_BUF_SZ - d->length);
1772         }
1773         d->pending = false;
1774         d->write_status = WRITE_CONTINUE;
1775         d->data_offset = 0;
1776     }
1777 
1778     if (d->length - d->data_offset > data_len) {
1779         dlen = data_len;
1780     } else {
1781         dlen = d->length - d->data_offset;
1782     }
1783 
1784     switch (d->code) {
1785     case CMD_SEND_OBJECT_INFO:
1786         usb_packet_copy(p, d->data + d->data_offset, dlen);
1787         d->offset += dlen;
1788         d->data_offset += dlen;
1789         if (d->data_offset == d->length) {
1790             /* The operation might have already failed */
1791             if (!s->result) {
1792                 usb_mtp_write_metadata(s, dlen);
1793             }
1794             usb_mtp_data_free(s->data_out);
1795             s->data_out = NULL;
1796             return;
1797         }
1798         break;
1799     case CMD_SEND_OBJECT:
1800         usb_packet_copy(p, d->data + d->data_offset, dlen);
1801         d->offset += dlen;
1802         d->data_offset += dlen;
1803         if ((p->iov.size % 64) || !p->iov.size) {
1804             assert((s->dataset.size == 0xFFFFFFFF) ||
1805                    (s->dataset.size == d->offset));
1806 
1807             if (d->length == MTP_WRITE_BUF_SZ) {
1808                 d->write_status = WRITE_END;
1809             } else {
1810                 d->write_status = WRITE_START;
1811             }
1812             usb_mtp_write_data(s);
1813             usb_mtp_data_free(s->data_out);
1814             s->data_out = NULL;
1815             return;
1816         }
1817         if (d->data_offset == d->length) {
1818             d->pending = true;
1819             usb_mtp_write_data(s);
1820         }
1821         break;
1822     default:
1823         p->status = USB_RET_STALL;
1824         return;
1825     }
1826 }
1827 
1828 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1829 {
1830     MTPState *s = USB_MTP(dev);
1831     MTPControl cmd;
1832     mtp_container container;
1833     uint32_t params[5];
1834     uint16_t container_type;
1835     int i, rc;
1836 
1837     switch (p->ep->nr) {
1838     case EP_DATA_IN:
1839         if (s->data_out != NULL) {
1840             /* guest bug */
1841             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1842             p->status = USB_RET_STALL;
1843             return;
1844         }
1845         if (p->iov.size < sizeof(container)) {
1846             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1847             p->status = USB_RET_STALL;
1848             return;
1849         }
1850         if (s->data_in !=  NULL) {
1851             MTPData *d = s->data_in;
1852             uint64_t dlen = d->length - d->offset;
1853             if (d->first) {
1854                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1855                 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1856                     container.length = cpu_to_le32(0xFFFFFFFF);
1857                 } else {
1858                     container.length =
1859                         cpu_to_le32(d->length + sizeof(container));
1860                 }
1861                 container.type   = cpu_to_le16(TYPE_DATA);
1862                 container.code   = cpu_to_le16(d->code);
1863                 container.trans  = cpu_to_le32(d->trans);
1864                 usb_packet_copy(p, &container, sizeof(container));
1865                 d->first = false;
1866                 if (dlen > p->iov.size - sizeof(container)) {
1867                     dlen = p->iov.size - sizeof(container);
1868                 }
1869             } else {
1870                 if (dlen > p->iov.size) {
1871                     dlen = p->iov.size;
1872                 }
1873             }
1874             if (d->fd == -1) {
1875                 usb_packet_copy(p, d->data + d->offset, dlen);
1876             } else {
1877                 if (d->alloc < p->iov.size) {
1878                     d->alloc = p->iov.size;
1879                     d->data = g_realloc(d->data, d->alloc);
1880                 }
1881                 rc = read(d->fd, d->data, dlen);
1882                 if (rc != dlen) {
1883                     memset(d->data, 0, dlen);
1884                     s->result->code = RES_INCOMPLETE_TRANSFER;
1885                 }
1886                 usb_packet_copy(p, d->data, dlen);
1887             }
1888             d->offset += dlen;
1889             if (d->offset == d->length) {
1890                 usb_mtp_data_free(s->data_in);
1891                 s->data_in = NULL;
1892             }
1893         } else if (s->result != NULL) {
1894             MTPControl *r = s->result;
1895             int length = sizeof(container) + r->argc * sizeof(uint32_t);
1896             if (r->code == RES_OK) {
1897                 trace_usb_mtp_success(s->dev.addr, r->trans,
1898                                       (r->argc > 0) ? r->argv[0] : 0,
1899                                       (r->argc > 1) ? r->argv[1] : 0);
1900             } else {
1901                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1902                                     (r->argc > 0) ? r->argv[0] : 0,
1903                                     (r->argc > 1) ? r->argv[1] : 0);
1904             }
1905             container.length = cpu_to_le32(length);
1906             container.type   = cpu_to_le16(TYPE_RESPONSE);
1907             container.code   = cpu_to_le16(r->code);
1908             container.trans  = cpu_to_le32(r->trans);
1909             for (i = 0; i < r->argc; i++) {
1910                 params[i] = cpu_to_le32(r->argv[i]);
1911             }
1912             usb_packet_copy(p, &container, sizeof(container));
1913             usb_packet_copy(p, &params, length - sizeof(container));
1914             g_free(s->result);
1915             s->result = NULL;
1916         }
1917         break;
1918     case EP_DATA_OUT:
1919         if (p->iov.size < sizeof(container)) {
1920             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1921             p->status = USB_RET_STALL;
1922             return;
1923         }
1924         if ((s->data_out != NULL) && !s->data_out->first) {
1925             container_type = TYPE_DATA;
1926         } else {
1927             usb_packet_copy(p, &container, sizeof(container));
1928             container_type = le16_to_cpu(container.type);
1929         }
1930         switch (container_type) {
1931         case TYPE_COMMAND:
1932             if (s->data_in || s->data_out || s->result) {
1933                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1934                 p->status = USB_RET_STALL;
1935                 return;
1936             }
1937             cmd.code = le16_to_cpu(container.code);
1938             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1939                 / sizeof(uint32_t);
1940             cmd.trans = le32_to_cpu(container.trans);
1941             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1942                 cmd.argc = ARRAY_SIZE(cmd.argv);
1943             }
1944             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1945                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1946                 p->status = USB_RET_STALL;
1947                 return;
1948             }
1949             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1950             for (i = 0; i < cmd.argc; i++) {
1951                 cmd.argv[i] = le32_to_cpu(params[i]);
1952             }
1953             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1954                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1955                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1956                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1957                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1958                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1959             usb_mtp_command(s, &cmd);
1960             break;
1961         case TYPE_DATA:
1962             /* One of the previous transfers has already errored but the
1963              * responder is still sending data associated with it
1964              */
1965             if (s->result != NULL) {
1966                 return;
1967             }
1968             usb_mtp_get_data(s, &container, p);
1969             break;
1970         default:
1971             /* not needed as long as the mtp device is read-only */
1972             p->status = USB_RET_STALL;
1973             return;
1974         }
1975         break;
1976     case EP_EVENT:
1977         if (!QTAILQ_EMPTY(&s->events)) {
1978             struct MTPMonEntry *e = QTAILQ_LAST(&s->events);
1979             uint32_t handle;
1980             int len = sizeof(container) + sizeof(uint32_t);
1981 
1982             if (p->iov.size < len) {
1983                 trace_usb_mtp_stall(s->dev.addr,
1984                                     "packet too small to send event");
1985                 p->status = USB_RET_STALL;
1986                 return;
1987             }
1988 
1989             QTAILQ_REMOVE(&s->events, e, next);
1990             container.length = cpu_to_le32(len);
1991             container.type = cpu_to_le32(TYPE_EVENT);
1992             container.code = cpu_to_le16(e->event);
1993             container.trans = 0; /* no trans specific events */
1994             handle = cpu_to_le32(e->handle);
1995             usb_packet_copy(p, &container, sizeof(container));
1996             usb_packet_copy(p, &handle, sizeof(uint32_t));
1997             g_free(e);
1998             return;
1999         }
2000         p->status = USB_RET_NAK;
2001         return;
2002     default:
2003         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2004         p->status = USB_RET_STALL;
2005         return;
2006     }
2007 
2008     if (p->actual_length == 0) {
2009         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2010         p->status = USB_RET_NAK;
2011         return;
2012     } else {
2013         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2014                            p->iov.size);
2015         return;
2016     }
2017 }
2018 
2019 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2020 {
2021     MTPState *s = USB_MTP(dev);
2022 
2023     usb_desc_create_serial(dev);
2024     usb_desc_init(dev);
2025     QTAILQ_INIT(&s->objects);
2026     if (s->desc == NULL) {
2027         if (s->root == NULL) {
2028             error_setg(errp, "usb-mtp: rootdir property must be configured");
2029             return;
2030         }
2031         s->desc = strrchr(s->root, '/');
2032         if (s->desc && s->desc[0]) {
2033             s->desc = g_strdup(s->desc + 1);
2034         } else {
2035             s->desc = g_strdup("none");
2036         }
2037     }
2038     /* Mark store as RW */
2039     if (!s->readonly) {
2040         s->flags |= (1 << MTP_FLAG_WRITABLE);
2041     }
2042 
2043 }
2044 
2045 static const VMStateDescription vmstate_usb_mtp = {
2046     .name = "usb-mtp",
2047     .unmigratable = 1,
2048     .version_id = 1,
2049     .minimum_version_id = 1,
2050     .fields = (VMStateField[]) {
2051         VMSTATE_USB_DEVICE(dev, MTPState),
2052         VMSTATE_END_OF_LIST()
2053     }
2054 };
2055 
2056 static Property mtp_properties[] = {
2057     DEFINE_PROP_STRING("rootdir", MTPState, root),
2058     DEFINE_PROP_STRING("desc", MTPState, desc),
2059     DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2060     DEFINE_PROP_END_OF_LIST(),
2061 };
2062 
2063 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2064 {
2065     DeviceClass *dc = DEVICE_CLASS(klass);
2066     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2067 
2068     uc->realize        = usb_mtp_realize;
2069     uc->product_desc   = "QEMU USB MTP";
2070     uc->usb_desc       = &desc;
2071     uc->cancel_packet  = usb_mtp_cancel_packet;
2072     uc->handle_attach  = usb_desc_attach;
2073     uc->handle_reset   = usb_mtp_handle_reset;
2074     uc->handle_control = usb_mtp_handle_control;
2075     uc->handle_data    = usb_mtp_handle_data;
2076     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2077     dc->desc = "USB Media Transfer Protocol device";
2078     dc->fw_name = "mtp";
2079     dc->vmsd = &vmstate_usb_mtp;
2080     dc->props = mtp_properties;
2081 }
2082 
2083 static TypeInfo mtp_info = {
2084     .name          = TYPE_USB_MTP,
2085     .parent        = TYPE_USB_DEVICE,
2086     .instance_size = sizeof(MTPState),
2087     .class_init    = usb_mtp_class_initfn,
2088 };
2089 
2090 static void usb_mtp_register_types(void)
2091 {
2092     type_register_static(&mtp_info);
2093 }
2094 
2095 type_init(usb_mtp_register_types)
2096