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