20d0d07a46fc75c5741fedeaf184d62c05e6fbe5
[sdk/emulator/qemu.git] / hw / 9pfs / 9p-maru.c
1 /*
2  * Virtio 9p backend for Maru
3  * Based on hw/9pfs/9p.c:
4  *
5  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
6  *
7  * Contact:
8  *  Sooyoung Ha <yoosah.ha@samsung.com>
9  *  SeokYeon Hwang <syeon.hwang@samsung.com>
10  *  YeongKyoon Lee <yeongkyoon.lee@samsung.com>
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25  *
26  * Contributors:
27  * - S-Core Co., Ltd
28  *
29  */
30
31 #include "qemu/osdep.h"
32 #include <glib/gprintf.h>
33 #include "hw/virtio/virtio.h"
34 #include "qapi/error.h"
35 #include "qemu/error-report.h"
36 #include "qemu/iov.h"
37 #include "qemu/sockets.h"
38 #include "virtio-9p.h"
39 #include "fsdev/qemu-fsdev.h"
40 #include "9p-xattr.h"
41 #include "coth.h"
42 #include "trace.h"
43 #include "migration/migration.h"
44
45 #ifdef CONFIG_WIN32
46 #include "tizen/src/resources_win32.h"
47
48 /* On windows, there's no mknod function. The device number is meaningless */
49 #define makedev(x,y) 0
50 #define major(x) 0
51 #define minor(x) 0
52
53 /* Old MinGW's struct dirent doesn't support d_type member */
54 #define WIN32_D_TYPE 0
55
56 extern uint64_t hostBytesPerSector;
57 #endif
58
59 #ifdef CONFIG_DARWIN
60 #define O_DIRECT 040000 /* Direct disk access */
61 #define O_NOATIME 01000000 /* Do not set atime */
62 #ifndef XATTR_SIZE_MAX
63 #define XATTR_SIZE_MAX 65536
64 #endif
65 #endif
66
67 #include "../../tizen/src/debug_ch.h"
68 MULTI_DEBUG_CHANNEL(tizen, 9pfs);
69
70 int open_fd_hw;
71 int total_open_fd;
72 static int open_fd_rc;
73
74 enum {
75     Oread   = 0x00,
76     Owrite  = 0x01,
77     Ordwr   = 0x02,
78     Oexec   = 0x03,
79     Oexcl   = 0x04,
80     Otrunc  = 0x10,
81     Orexec  = 0x20,
82     Orclose = 0x40,
83     Oappend = 0x80,
84 };
85
86 ssize_t pdu_marshal(V9fsPDU *pdu, size_t offset, const char *fmt, ...)
87 {
88     ssize_t ret;
89     va_list ap;
90
91     va_start(ap, fmt);
92     ret = virtio_pdu_vmarshal(pdu, offset, fmt, ap);
93     va_end(ap);
94
95     return ret;
96 }
97
98 ssize_t pdu_unmarshal(V9fsPDU *pdu, size_t offset, const char *fmt, ...)
99 {
100     ssize_t ret;
101     va_list ap;
102
103     va_start(ap, fmt);
104     ret = virtio_pdu_vunmarshal(pdu, offset, fmt, ap);
105     va_end(ap);
106
107     return ret;
108 }
109
110 static void pdu_push_and_notify(V9fsPDU *pdu)
111 {
112     virtio_9p_push_and_notify(pdu);
113 }
114
115 static int omode_to_uflags(int8_t mode)
116 {
117     int ret = 0;
118
119     switch (mode & 3) {
120     case Oread:
121         ret = O_RDONLY;
122         break;
123     case Ordwr:
124         ret = O_RDWR;
125         break;
126     case Owrite:
127         ret = O_WRONLY;
128         break;
129     case Oexec:
130         ret = O_RDONLY;
131         break;
132     }
133
134     if (mode & Otrunc) {
135         ret |= O_TRUNC;
136     }
137
138     if (mode & Oappend) {
139         ret |= O_APPEND;
140     }
141
142     if (mode & Oexcl) {
143         ret |= O_EXCL;
144     }
145
146     return ret;
147 }
148
149 struct dotl_openflag_map {
150     int dotl_flag;
151     int open_flag;
152 };
153
154 static int dotl_to_open_flags(int flags)
155 {
156     int i;
157     /*
158      * We have same bits for P9_DOTL_READONLY, P9_DOTL_WRONLY
159      * and P9_DOTL_NOACCESS
160      */
161     int oflags = flags & O_ACCMODE;
162
163     struct dotl_openflag_map dotl_oflag_map[] = {
164         { P9_DOTL_CREATE, O_CREAT },
165         { P9_DOTL_EXCL, O_EXCL },
166         { P9_DOTL_NOCTTY , O_NOCTTY },
167         { P9_DOTL_TRUNC, O_TRUNC },
168         { P9_DOTL_APPEND, O_APPEND },
169         { P9_DOTL_NONBLOCK, O_NONBLOCK } ,
170         { P9_DOTL_DSYNC, O_DSYNC },
171         { P9_DOTL_FASYNC, FASYNC },
172         { P9_DOTL_DIRECT, O_DIRECT },
173         { P9_DOTL_LARGEFILE, O_LARGEFILE },
174         { P9_DOTL_DIRECTORY, O_DIRECTORY },
175         { P9_DOTL_NOFOLLOW, O_NOFOLLOW },
176         { P9_DOTL_NOATIME, O_NOATIME },
177         { P9_DOTL_SYNC, O_SYNC },
178     };
179
180     for (i = 0; i < ARRAY_SIZE(dotl_oflag_map); i++) {
181         if (flags & dotl_oflag_map[i].dotl_flag) {
182             oflags |= dotl_oflag_map[i].open_flag;
183         }
184     }
185
186     return oflags;
187 }
188
189 void cred_init(FsCred *credp)
190 {
191     credp->fc_uid = -1;
192     credp->fc_gid = -1;
193     credp->fc_mode = -1;
194     credp->fc_rdev = -1;
195 }
196
197 static int get_dotl_openflags(V9fsState *s, int oflags)
198 {
199     int flags;
200     /*
201      * Filter the client open flags
202      */
203     flags = dotl_to_open_flags(oflags);
204     flags &= ~(O_NOCTTY | O_ASYNC | O_CREAT);
205     /*
206      * Ignore direct disk access hint until the server supports it.
207      */
208     flags &= ~O_DIRECT;
209     return flags;
210 }
211
212 void v9fs_path_init(V9fsPath *path)
213 {
214     path->data = NULL;
215     path->size = 0;
216 }
217
218 void v9fs_path_free(V9fsPath *path)
219 {
220     g_free(path->data);
221     path->data = NULL;
222     path->size = 0;
223 }
224
225
226 void GCC_FMT_ATTR(2, 3)
227 v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...)
228 {
229     va_list ap;
230
231     v9fs_path_free(path);
232
233     va_start(ap, fmt);
234     /* Bump the size for including terminating NULL */
235     path->size = g_vasprintf(&path->data, fmt, ap) + 1;
236     va_end(ap);
237 }
238
239 void v9fs_path_copy(V9fsPath *lhs, V9fsPath *rhs)
240 {
241     v9fs_path_free(lhs);
242     lhs->data = g_malloc(rhs->size);
243     memcpy(lhs->data, rhs->data, rhs->size);
244     lhs->size = rhs->size;
245 }
246
247 int v9fs_name_to_path(V9fsState *s, V9fsPath *dirpath,
248                       const char *name, V9fsPath *path)
249 {
250     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
251     int err;
252     err = s->ops->name_to_path(&s->ctx, dirpath, name, path); // local_name_to_path
253     if (err < 0) {
254         err = -errno;
255     }
256     return err;
257 }
258
259 /*
260  * Return TRUE if s1 is an ancestor of s2.
261  *
262  * E.g. "a/b" is an ancestor of "a/b/c" but not of "a/bc/d".
263  * As a special case, We treat s1 as ancestor of s2 if they are same!
264  */
265 static int v9fs_path_is_ancestor(V9fsPath *s1, V9fsPath *s2)
266 {
267     if (!strncmp(s1->data, s2->data, s1->size - 1)) {
268 #ifndef CONFIG_WIN32
269         if (s2->data[s1->size - 1] == '\0' || s2->data[s1->size - 1] == '/') {
270 #else
271         if (s2->data[s1->size - 1] == '\0' || s2->data[s1->size - 1] == '\\') {
272 #endif
273             return 1;
274         }
275     }
276     return 0;
277 }
278
279 static size_t v9fs_string_size(V9fsString *str)
280 {
281     return str->size;
282 }
283
284 /*
285  * returns 0 if fid got re-opened, 1 if not, < 0 on error */
286 static int coroutine_fn v9fs_reopen_fid(V9fsPDU *pdu, V9fsFidState *f)
287 {
288     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
289     int err = 1;
290     if (f->fid_type == P9_FID_FILE) {
291         if (f->fs.fd == -1) {
292             do {
293                 err = v9fs_co_open(pdu, f, f->open_flags);
294             } while (err == -EINTR && !pdu->cancelled);
295         }
296     } else if (f->fid_type == P9_FID_DIR) {
297         if (f->fs.dir.stream == NULL) {
298             do {
299                 err = v9fs_co_opendir(pdu, f);
300             } while (err == -EINTR && !pdu->cancelled);
301         }
302     }
303     return err;
304 }
305
306 static V9fsFidState *coroutine_fn get_fid(V9fsPDU *pdu, int32_t fid)
307 {
308     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
309     int err;
310     V9fsFidState *f;
311     V9fsState *s = pdu->s;
312
313     for (f = s->fid_list; f; f = f->next) {
314         BUG_ON(f->clunked);
315         if (f->fid == fid) {
316             /*
317              * Update the fid ref upfront so that
318              * we don't get reclaimed when we yield
319              * in open later.
320              */
321             f->ref++;
322             /*
323              * check whether we need to reopen the
324              * file. We might have closed the fd
325              * while trying to free up some file
326              * descriptors.
327              */
328             err = v9fs_reopen_fid(pdu, f);
329             if (err < 0) {
330                 ERR("[%d][ >> %s]\n", __LINE__, __func__);
331                 f->ref--;
332                 return NULL;
333             }
334             /*
335              * Mark the fid as referenced so that the LRU
336              * reclaim won't close the file descriptor
337              */
338             f->flags |= FID_REFERENCED;
339             return f;
340         }
341     }
342     return NULL;
343 }
344
345 static V9fsFidState *alloc_fid(V9fsState *s, int32_t fid)
346 {
347     V9fsFidState *f;
348
349     for (f = s->fid_list; f; f = f->next) {
350         /* If fid is already there return NULL */
351         BUG_ON(f->clunked);
352         if (f->fid == fid) {
353             ERR("[%d][ >> %s]\n", __LINE__, __func__);
354             return NULL;
355         }
356     }
357     f = g_malloc0(sizeof(V9fsFidState));
358     f->fid = fid;
359     f->fid_type = P9_FID_NONE;
360     f->ref = 1;
361     /*
362      * Mark the fid as referenced so that the LRU
363      * reclaim won't close the file descriptor
364      */
365     f->flags |= FID_REFERENCED;
366     f->next = s->fid_list;
367     s->fid_list = f;
368
369     v9fs_readdir_init(&f->fs.dir);
370     v9fs_readdir_init(&f->fs_reclaim.dir);
371
372     return f;
373 }
374
375 #ifndef CONFIG_WIN32
376 static int coroutine_fn v9fs_xattr_fid_clunk(V9fsPDU *pdu, V9fsFidState *fidp)
377 {
378     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
379     int retval = 0;
380
381     if (fidp->fs.xattr.xattrwalk_fid) {
382         /* getxattr/listxattr fid */
383         goto free_value;
384     }
385     /*
386      * if this is fid for setxattr. clunk should
387      * result in setxattr localcall
388      */
389     if (fidp->fs.xattr.len != fidp->fs.xattr.copied_len) {
390         /* clunk after partial write */
391         retval = -EINVAL;
392         goto free_out;
393     }
394     if (fidp->fs.xattr.len) {
395         retval = v9fs_co_lsetxattr(pdu, &fidp->path, &fidp->fs.xattr.name,
396                                    fidp->fs.xattr.value,
397                                    fidp->fs.xattr.len,
398                                    fidp->fs.xattr.flags);
399     } else {
400         retval = v9fs_co_lremovexattr(pdu, &fidp->path, &fidp->fs.xattr.name);
401     }
402 free_out:
403     v9fs_string_free(&fidp->fs.xattr.name);
404 free_value:
405     g_free(fidp->fs.xattr.value);
406     return retval;
407 }
408 #endif
409
410 static int coroutine_fn free_fid(V9fsPDU *pdu, V9fsFidState *fidp)
411 {
412     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
413     int retval = 0;
414
415     if (fidp->fid_type == P9_FID_FILE) {
416         /* If we reclaimed the fd no need to close */
417         if (fidp->fs.fd != -1) {
418             retval = v9fs_co_close(pdu, &fidp->fs);
419         }
420     } else if (fidp->fid_type == P9_FID_DIR) {
421         if (fidp->fs.dir.stream != NULL) {
422             retval = v9fs_co_closedir(pdu, &fidp->fs);
423         }
424     } else if (fidp->fid_type == P9_FID_XATTR) {
425 #ifndef CONFIG_WIN32
426         retval = v9fs_xattr_fid_clunk(pdu, fidp);
427 #else
428         retval = -1;
429 #endif
430     }
431     v9fs_path_free(&fidp->path);
432     g_free(fidp);
433     return retval;
434 }
435
436 static int coroutine_fn put_fid(V9fsPDU *pdu, V9fsFidState *fidp)
437 {
438     BUG_ON(!fidp->ref);
439     fidp->ref--;
440     /*
441      * Don't free the fid if it is in reclaim list
442      */
443     if (!fidp->ref && fidp->clunked) {
444         if (fidp->fid == pdu->s->root_fid) {
445             /*
446              * if the clunked fid is root fid then we
447              * have unmounted the fs on the client side.
448              * delete the migration blocker. Ideally, this
449              * should be hooked to transport close notification
450              */
451             if (pdu->s->migration_blocker) {
452                 migrate_del_blocker(pdu->s->migration_blocker);
453                 error_free(pdu->s->migration_blocker);
454                 pdu->s->migration_blocker = NULL;
455             }
456         }
457         return free_fid(pdu, fidp);
458     }
459     return 0;
460 }
461
462 static V9fsFidState *clunk_fid(V9fsState *s, int32_t fid)
463 {
464     V9fsFidState **fidpp, *fidp;
465
466     for (fidpp = &s->fid_list; *fidpp; fidpp = &(*fidpp)->next) {
467         if ((*fidpp)->fid == fid) {
468             break;
469         }
470     }
471     if (*fidpp == NULL) {
472         return NULL;
473     }
474     fidp = *fidpp;
475     *fidpp = fidp->next;
476     fidp->clunked = 1;
477     return fidp;
478 }
479
480 void coroutine_fn v9fs_reclaim_fd(V9fsPDU *pdu)
481 {
482     int reclaim_count = 0;
483     V9fsState *s = pdu->s;
484     V9fsFidState *f, *reclaim_list = NULL;
485
486     for (f = s->fid_list; f; f = f->next) {
487         /*
488          * Unlink fids cannot be reclaimed. Check
489          * for them and skip them. Also skip fids
490          * currently being operated on.
491          */
492         if (f->ref || f->flags & FID_NON_RECLAIMABLE) {
493             continue;
494         }
495         /*
496          * if it is a recently referenced fid
497          * we leave the fid untouched and clear the
498          * reference bit. We come back to it later
499          * in the next iteration. (a simple LRU without
500          * moving list elements around)
501          */
502         if (f->flags & FID_REFERENCED) {
503             f->flags &= ~FID_REFERENCED;
504             continue;
505         }
506         /*
507          * Add fids to reclaim list.
508          */
509         if (f->fid_type == P9_FID_FILE) {
510             if (f->fs.fd != -1) {
511                 /*
512                  * Up the reference count so that
513                  * a clunk request won't free this fid
514                  */
515                 f->ref++;
516                 f->rclm_lst = reclaim_list;
517                 reclaim_list = f;
518                 f->fs_reclaim.fd = f->fs.fd;
519                 f->fs.fd = -1;
520                 reclaim_count++;
521             }
522         } else if (f->fid_type == P9_FID_DIR) {
523             if (f->fs.dir.stream != NULL) {
524                 /*
525                  * Up the reference count so that
526                  * a clunk request won't free this fid
527                  */
528                 f->ref++;
529                 f->rclm_lst = reclaim_list;
530                 reclaim_list = f;
531                 f->fs_reclaim.dir.stream = f->fs.dir.stream;
532                 f->fs.dir.stream = NULL;
533                 reclaim_count++;
534             }
535         }
536         if (reclaim_count >= open_fd_rc) {
537             break;
538         }
539     }
540     /*
541      * Now close the fid in reclaim list. Free them if they
542      * are already clunked.
543      */
544     while (reclaim_list) {
545         f = reclaim_list;
546         reclaim_list = f->rclm_lst;
547         if (f->fid_type == P9_FID_FILE) {
548             v9fs_co_close(pdu, &f->fs_reclaim);
549         } else if (f->fid_type == P9_FID_DIR) {
550             v9fs_co_closedir(pdu, &f->fs_reclaim);
551         }
552         f->rclm_lst = NULL;
553         /*
554          * Now drop the fid reference, free it
555          * if clunked.
556          */
557         put_fid(pdu, f);
558     }
559 }
560
561 static int coroutine_fn v9fs_mark_fids_unreclaim(V9fsPDU *pdu, V9fsPath *path)
562 {
563     TRACE("[%d][ >> %s]\n", __LINE__, __func__);
564     int err;
565     V9fsState *s = pdu->s;
566     V9fsFidState *fidp, head_fid;
567
568     head_fid.next = s->fid_list;
569     for (fidp = s->fid_list; fidp; fidp = fidp->next) {
570         if (fidp->path.size != path->size) {
571             continue;
572         }
573         if (!memcmp(fidp->path.data, path->data, path->size)) {
574             /* Mark the fid non reclaimable. */
575             fidp->flags |= FID_NON_RECLAIMABLE;
576
577             /* reopen the file/dir if already closed */
578             err = v9fs_reopen_fid(pdu, fidp);
579             if (err < 0) {
580                 return -1;
581             }
582             /*
583              * Go back to head of fid list because
584              * the list could have got updated when
585              * switched to the worker thread
586              */
587             if (err == 0) {
588                 fidp = &head_fid;
589             }
590         }
591     }
592     return 0;
593 }
594
595 static void coroutine_fn virtfs_reset(V9fsPDU *pdu)
596 {
597     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
598     V9fsState *s = pdu->s;
599     V9fsFidState *fidp;
600
601     /* Free all fids */
602     while (s->fid_list) {
603         fidp = s->fid_list;
604         s->fid_list = fidp->next;
605
606         if (fidp->ref) {
607             fidp->clunked = 1;
608         } else {
609             free_fid(pdu, fidp);
610         }
611     }
612 }
613
614 #define P9_QID_TYPE_DIR         0x80
615 #define P9_QID_TYPE_SYMLINK     0x02
616
617 #define P9_STAT_MODE_DIR        0x80000000
618 #define P9_STAT_MODE_APPEND     0x40000000
619 #define P9_STAT_MODE_EXCL       0x20000000
620 #define P9_STAT_MODE_MOUNT      0x10000000
621 #define P9_STAT_MODE_AUTH       0x08000000
622 #define P9_STAT_MODE_TMP        0x04000000
623 #define P9_STAT_MODE_SYMLINK    0x02000000
624 #define P9_STAT_MODE_LINK       0x01000000
625 #define P9_STAT_MODE_DEVICE     0x00800000
626 #define P9_STAT_MODE_NAMED_PIPE 0x00200000
627 #define P9_STAT_MODE_SOCKET     0x00100000
628 #define P9_STAT_MODE_SETUID     0x00080000
629 #define P9_STAT_MODE_SETGID     0x00040000
630 #define P9_STAT_MODE_SETVTX     0x00010000
631
632 #define P9_STAT_MODE_TYPE_BITS (P9_STAT_MODE_DIR |          \
633                                 P9_STAT_MODE_SYMLINK |      \
634                                 P9_STAT_MODE_LINK |         \
635                                 P9_STAT_MODE_DEVICE |       \
636                                 P9_STAT_MODE_NAMED_PIPE |   \
637                                 P9_STAT_MODE_SOCKET)
638
639 /* This is the algorithm from ufs in spfs */
640 static void stat_to_qid(const struct stat *stbuf, V9fsQID *qidp)
641 {
642     size_t size;
643
644     memset(&qidp->path, 0, sizeof(qidp->path));
645     size = MIN(sizeof(stbuf->st_ino), sizeof(qidp->path));
646     memcpy(&qidp->path, &stbuf->st_ino, size);
647     qidp->version = stbuf->st_mtime ^ (stbuf->st_size << 8);
648     qidp->type = 0;
649     if (S_ISDIR(stbuf->st_mode)) {
650         qidp->type |= P9_QID_TYPE_DIR;
651     }
652 #ifndef CONFIG_WIN32
653     if (S_ISLNK(stbuf->st_mode)) {
654 #else
655     if (((stbuf->st_mode) & S_IFMT) == 0xA000) {
656 #endif
657         qidp->type |= P9_QID_TYPE_SYMLINK;
658     }
659 }
660
661 static int coroutine_fn fid_to_qid(V9fsPDU *pdu, V9fsFidState *fidp,
662                                    V9fsQID *qidp)
663 {
664     TRACE("[%d][ >> %s]\n", __LINE__, __func__);
665     struct stat stbuf;
666     int err;
667
668     err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
669     if (err < 0) {
670         return err;
671     }
672     stat_to_qid(&stbuf, qidp);
673     return 0;
674 }
675
676 V9fsPDU *pdu_alloc(V9fsState *s)
677 {
678     V9fsPDU *pdu = NULL;
679
680     if (!QLIST_EMPTY(&s->free_list)) {
681         pdu = QLIST_FIRST(&s->free_list);
682         QLIST_REMOVE(pdu, next);
683         QLIST_INSERT_HEAD(&s->active_list, pdu, next);
684     }
685     return pdu;
686 }
687
688 void pdu_free(V9fsPDU *pdu)
689 {
690     V9fsState *s = pdu->s;
691
692     g_assert(!pdu->cancelled);
693     QLIST_REMOVE(pdu, next);
694     QLIST_INSERT_HEAD(&s->free_list, pdu, next);
695 }
696
697 /*
698  * We don't do error checking for pdu_marshal/unmarshal here
699  * because we always expect to have enough space to encode
700  * error details
701  */
702 static void coroutine_fn pdu_complete(V9fsPDU *pdu, ssize_t len)
703 {
704     int8_t id = pdu->id + 1; /* Response */
705     V9fsState *s = pdu->s;
706
707     if (len < 0) {
708         WARN("[%d][ >> %s]\n", __LINE__, __func__);
709         int err = -len;
710         len = 7;
711
712         if (s->proto_version != V9FS_PROTO_2000L) {
713             V9fsString str;
714
715             str.data = strerror(err);
716             str.size = strlen(str.data);
717
718             len += pdu_marshal(pdu, len, "s", &str);
719             id = P9_RERROR;
720         }
721
722         len += pdu_marshal(pdu, len, "d", err);
723
724         if (s->proto_version == V9FS_PROTO_2000L) {
725             id = P9_RLERROR;
726         }
727         trace_v9fs_rerror(pdu->tag, pdu->id, err); /* Trace ERROR */
728     }
729
730     /* fill out the header */
731     pdu_marshal(pdu, 0, "dbw", (int32_t)len, id, pdu->tag);
732
733     /* keep these in sync */
734     pdu->size = len;
735     pdu->id = id;
736
737     pdu_push_and_notify(pdu);
738
739     /* Now wakeup anybody waiting in flush for this request */
740     if (!qemu_co_queue_next(&pdu->complete)) {
741         pdu_free(pdu);
742     }
743 }
744
745 #ifndef CONFIG_WIN32
746 static mode_t v9mode_to_mode(uint32_t mode, V9fsString *extension)
747 {
748     mode_t ret;
749
750     ret = mode & 0777;
751     if (mode & P9_STAT_MODE_DIR) {
752         ret |= S_IFDIR;
753     }
754
755     if (mode & P9_STAT_MODE_SYMLINK) {
756         ret |= S_IFLNK;
757     }
758     if (mode & P9_STAT_MODE_SOCKET) {
759         ret |= S_IFSOCK;
760     }
761     if (mode & P9_STAT_MODE_NAMED_PIPE) {
762         ret |= S_IFIFO;
763     }
764     if (mode & P9_STAT_MODE_DEVICE) {
765         if (extension->size && extension->data[0] == 'c') {
766             ret |= S_IFCHR;
767         } else {
768             ret |= S_IFBLK;
769         }
770     }
771
772     if (!(ret&~0777)) {
773         ret |= S_IFREG;
774     }
775
776     if (mode & P9_STAT_MODE_SETUID) {
777         ret |= S_ISUID;
778     }
779     if (mode & P9_STAT_MODE_SETGID) {
780         ret |= S_ISGID;
781     }
782     if (mode & P9_STAT_MODE_SETVTX) {
783         ret |= S_ISVTX;
784     }
785
786     return ret;
787 }
788 #endif
789
790 static int donttouch_stat(V9fsStat *stat)
791 {
792     if (stat->type == -1 &&
793         stat->dev == -1 &&
794         stat->qid.type == -1 &&
795         stat->qid.version == -1 &&
796         stat->qid.path == -1 &&
797         stat->mode == -1 &&
798         stat->atime == -1 &&
799         stat->mtime == -1 &&
800         stat->length == -1 &&
801         !stat->name.size &&
802         !stat->uid.size &&
803         !stat->gid.size &&
804         !stat->muid.size &&
805         stat->n_uid == -1 &&
806         stat->n_gid == -1 &&
807         stat->n_muid == -1) {
808         return 1;
809     }
810
811     return 0;
812 }
813
814 static void v9fs_stat_init(V9fsStat *stat)
815 {
816     v9fs_string_init(&stat->name);
817     v9fs_string_init(&stat->uid);
818     v9fs_string_init(&stat->gid);
819     v9fs_string_init(&stat->muid);
820     v9fs_string_init(&stat->extension);
821 }
822
823 static void v9fs_stat_free(V9fsStat *stat)
824 {
825     v9fs_string_free(&stat->name);
826     v9fs_string_free(&stat->uid);
827     v9fs_string_free(&stat->gid);
828     v9fs_string_free(&stat->muid);
829     v9fs_string_free(&stat->extension);
830 }
831
832 static uint32_t stat_to_v9mode(const struct stat *stbuf)
833 {
834     uint32_t mode;
835
836     mode = stbuf->st_mode & 0777;
837 #ifndef CONFIG_WIN32
838     if (S_ISDIR(stbuf->st_mode)) {
839         mode |= P9_STAT_MODE_DIR;
840     }
841
842     if (S_ISLNK(stbuf->st_mode)) {
843         mode |= P9_STAT_MODE_SYMLINK;
844     }
845
846     if (S_ISSOCK(stbuf->st_mode)) {
847         mode |= P9_STAT_MODE_SOCKET;
848     }
849
850     if (S_ISFIFO(stbuf->st_mode)) {
851         mode |= P9_STAT_MODE_NAMED_PIPE;
852     }
853
854     if (S_ISBLK(stbuf->st_mode) || S_ISCHR(stbuf->st_mode)) {
855         mode |= P9_STAT_MODE_DEVICE;
856     }
857
858     if (stbuf->st_mode & S_ISUID) {
859         mode |= P9_STAT_MODE_SETUID;
860     }
861
862     if (stbuf->st_mode & S_ISGID) {
863         mode |= P9_STAT_MODE_SETGID;
864     }
865
866     if (stbuf->st_mode & S_ISVTX) {
867         mode |= P9_STAT_MODE_SETVTX;
868     }
869
870 #endif
871     return mode;
872 }
873
874 static int coroutine_fn stat_to_v9stat(V9fsPDU *pdu, V9fsPath *name,
875                                        const struct stat *stbuf,
876                                        V9fsStat *v9stat)
877 {
878     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
879     int err;
880     const char *str;
881
882     memset(v9stat, 0, sizeof(*v9stat));
883
884     stat_to_qid(stbuf, &v9stat->qid);
885     v9stat->mode = stat_to_v9mode(stbuf);
886     v9stat->atime = stbuf->st_atime;
887     v9stat->mtime = stbuf->st_mtime;
888     v9stat->length = stbuf->st_size;
889
890     v9fs_string_free(&v9stat->uid);
891     v9fs_string_free(&v9stat->gid);
892     v9fs_string_free(&v9stat->muid);
893
894     v9stat->n_uid = stbuf->st_uid;
895     v9stat->n_gid = stbuf->st_gid;
896     v9stat->n_muid = 0;
897
898     v9fs_string_free(&v9stat->extension);
899
900     if (v9stat->mode & P9_STAT_MODE_SYMLINK) {
901         err = v9fs_co_readlink(pdu, name, &v9stat->extension);
902         if (err < 0) {
903             return err;
904         }
905     } else if (v9stat->mode & P9_STAT_MODE_DEVICE) {
906         v9fs_string_sprintf(&v9stat->extension, "%c %u %u",
907                 S_ISCHR(stbuf->st_mode) ? 'c' : 'b',
908                 major(stbuf->st_rdev), minor(stbuf->st_rdev));
909     } else if (S_ISDIR(stbuf->st_mode) || S_ISREG(stbuf->st_mode)) {
910         v9fs_string_sprintf(&v9stat->extension, "%s %lu",
911                 "HARDLINKCOUNT", (unsigned long)stbuf->st_nlink);
912     }
913
914     str = strrchr(name->data, '/');
915     if (str) {
916         str += 1;
917     } else {
918         str = name->data;
919     }
920
921     v9fs_string_sprintf(&v9stat->name, "%s", str);
922
923     v9stat->size = 61 +
924         v9fs_string_size(&v9stat->name) +
925         v9fs_string_size(&v9stat->uid) +
926         v9fs_string_size(&v9stat->gid) +
927         v9fs_string_size(&v9stat->muid) +
928         v9fs_string_size(&v9stat->extension);
929     return 0;
930 }
931
932 #define P9_STATS_MODE          0x00000001ULL
933 #define P9_STATS_NLINK         0x00000002ULL
934 #define P9_STATS_UID           0x00000004ULL
935 #define P9_STATS_GID           0x00000008ULL
936 #define P9_STATS_RDEV          0x00000010ULL
937 #define P9_STATS_ATIME         0x00000020ULL
938 #define P9_STATS_MTIME         0x00000040ULL
939 #define P9_STATS_CTIME         0x00000080ULL
940 #define P9_STATS_INO           0x00000100ULL
941 #define P9_STATS_SIZE          0x00000200ULL
942 #define P9_STATS_BLOCKS        0x00000400ULL
943
944 #define P9_STATS_BTIME         0x00000800ULL
945 #define P9_STATS_GEN           0x00001000ULL
946 #define P9_STATS_DATA_VERSION  0x00002000ULL
947
948 #define P9_STATS_BASIC         0x000007ffULL /* Mask for fields up to BLOCKS */
949 #define P9_STATS_ALL           0x00003fffULL /* Mask for All fields above */
950
951
952 static void stat_to_v9stat_dotl(V9fsState *s, const struct stat *stbuf,
953                                 V9fsStatDotl *v9lstat)
954 {
955     memset(v9lstat, 0, sizeof(*v9lstat));
956
957     v9lstat->st_mode = stbuf->st_mode;
958     v9lstat->st_nlink = stbuf->st_nlink;
959     v9lstat->st_uid = stbuf->st_uid;
960     v9lstat->st_gid = stbuf->st_gid;
961     v9lstat->st_rdev = stbuf->st_rdev;
962     v9lstat->st_size = stbuf->st_size;
963 #ifndef CONFIG_WIN32
964     v9lstat->st_blksize = stbuf->st_blksize;
965     v9lstat->st_blocks = stbuf->st_blocks;
966 #else
967     v9lstat->st_blksize = hostBytesPerSector;
968     v9lstat->st_blocks = (uint64_t)(v9lstat->st_size / 512
969                             + (v9lstat->st_size % 512 ? 1 : 0)); //round up
970 #endif
971 #ifdef CONFIG_LINUX
972     v9lstat->st_atime_sec = stbuf->st_atime;
973     v9lstat->st_atime_nsec = stbuf->st_atim.tv_nsec;
974     v9lstat->st_mtime_sec = stbuf->st_mtime;
975     v9lstat->st_mtime_nsec = stbuf->st_mtim.tv_nsec;
976     v9lstat->st_ctime_sec = stbuf->st_ctime;
977     v9lstat->st_ctime_nsec = stbuf->st_ctim.tv_nsec;
978 #else // darwin
979 #ifndef CONFIG_WIN32
980     v9lstat->st_atime_sec = stbuf->st_atimespec.tv_sec;
981     v9lstat->st_atime_nsec = stbuf->st_atimespec.tv_nsec;
982     v9lstat->st_mtime_sec = stbuf->st_mtimespec.tv_sec;
983     v9lstat->st_mtime_nsec = stbuf->st_mtimespec.tv_nsec;
984     v9lstat->st_ctime_sec = stbuf->st_ctimespec.tv_sec;
985     v9lstat->st_ctime_nsec = stbuf->st_ctimespec.tv_nsec;
986 #else
987     v9lstat->st_atime_sec = stbuf->st_atime;
988     v9lstat->st_atime_nsec = 0;
989     v9lstat->st_mtime_sec = stbuf->st_mtime;
990     v9lstat->st_mtime_nsec = 0;
991     v9lstat->st_ctime_sec = stbuf->st_ctime;
992     v9lstat->st_ctime_nsec = 0;
993 #endif
994 #endif
995
996     /* Currently we only support BASIC fields in stat */
997     v9lstat->st_result_mask = P9_STATS_BASIC;
998
999     stat_to_qid(stbuf, &v9lstat->qid);
1000 }
1001
1002 static void print_sg(struct iovec *sg, int cnt)
1003 {
1004     int i;
1005
1006     printf("sg[%d]: {", cnt);
1007     for (i = 0; i < cnt; i++) {
1008         if (i) {
1009             printf(", ");
1010         }
1011         printf("(%p, %zd)", sg[i].iov_base, sg[i].iov_len);
1012     }
1013     printf("}\n");
1014 }
1015
1016 /* Will call this only for path name based fid */
1017 static void v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len)
1018 {
1019     V9fsPath str;
1020     v9fs_path_init(&str);
1021     v9fs_path_copy(&str, dst);
1022     v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len);
1023     v9fs_path_free(&str);
1024 }
1025
1026 static inline bool is_ro_export(FsContext *ctx)
1027 {
1028     return ctx->export_flags & V9FS_RDONLY;
1029 }
1030
1031 static void coroutine_fn v9fs_version(void *opaque)
1032 {
1033     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1034     ssize_t err;
1035     V9fsPDU *pdu = opaque;
1036     V9fsState *s = pdu->s;
1037     V9fsString version;
1038     size_t offset = 7;
1039
1040     v9fs_string_init(&version);
1041     err = pdu_unmarshal(pdu, offset, "ds", &s->msize, &version);
1042     if (err < 0) {
1043         offset = err;
1044         goto out;
1045     }
1046     trace_v9fs_version(pdu->tag, pdu->id, s->msize, version.data);
1047
1048     virtfs_reset(pdu);
1049
1050     if (!strcmp(version.data, "9P2000.u")) {
1051         s->proto_version = V9FS_PROTO_2000U;
1052     } else if (!strcmp(version.data, "9P2000.L")) {
1053         s->proto_version = V9FS_PROTO_2000L;
1054     } else {
1055         v9fs_string_sprintf(&version, "unknown");
1056     }
1057
1058     err = pdu_marshal(pdu, offset, "ds", s->msize, &version);
1059     if (err < 0) {
1060         offset = err;
1061         goto out;
1062     }
1063     offset += err;
1064     trace_v9fs_version_return(pdu->tag, pdu->id, s->msize, version.data);
1065 out:
1066     pdu_complete(pdu, offset);
1067     v9fs_string_free(&version);
1068 }
1069
1070 static void coroutine_fn v9fs_attach(void *opaque)
1071 {
1072     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1073     V9fsPDU *pdu = opaque;
1074     V9fsState *s = pdu->s;
1075     int32_t fid, afid, n_uname;
1076     V9fsString uname, aname;
1077     V9fsFidState *fidp;
1078     size_t offset = 7;
1079     V9fsQID qid;
1080     ssize_t err;
1081
1082     v9fs_string_init(&uname);
1083     v9fs_string_init(&aname);
1084     err = pdu_unmarshal(pdu, offset, "ddssd", &fid,
1085                         &afid, &uname, &aname, &n_uname);
1086     if (err < 0) {
1087         goto out_nofid;
1088     }
1089     trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data);
1090
1091     fidp = alloc_fid(s, fid);
1092     if (fidp == NULL) {
1093         err = -EINVAL;
1094         goto out_nofid;
1095     }
1096     fidp->uid = n_uname;
1097 #ifndef CONFIG_WIN32
1098     err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path);
1099 #else
1100     err = v9fs_co_name_to_path(pdu, NULL, "\\", &fidp->path);
1101 #endif
1102     if (err < 0) {
1103         err = -EINVAL;
1104         clunk_fid(s, fid);
1105         goto out;
1106     }
1107     err = fid_to_qid(pdu, fidp, &qid);
1108     if (err < 0) {
1109         err = -EINVAL;
1110         clunk_fid(s, fid);
1111         goto out;
1112     }
1113     err = pdu_marshal(pdu, offset, "Q", &qid);
1114     if (err < 0) {
1115         clunk_fid(s, fid);
1116         goto out;
1117     }
1118     err += offset;
1119     memcpy(&s->root_qid, &qid, sizeof(qid));
1120     trace_v9fs_attach_return(pdu->tag, pdu->id,
1121                              qid.type, qid.version, qid.path);
1122     /*
1123      * disable migration if we haven't done already.
1124      * attach could get called multiple times for the same export.
1125      */
1126     if (!s->migration_blocker) {
1127         s->root_fid = fid;
1128         error_setg(&s->migration_blocker,
1129                    "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'",
1130                    s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag);
1131         migrate_add_blocker(s->migration_blocker);
1132     }
1133 out:
1134     put_fid(pdu, fidp);
1135 out_nofid:
1136     pdu_complete(pdu, err);
1137     v9fs_string_free(&uname);
1138     v9fs_string_free(&aname);
1139 }
1140
1141 static void coroutine_fn v9fs_stat(void *opaque)
1142 {
1143     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1144     int32_t fid;
1145     V9fsStat v9stat;
1146     ssize_t err = 0;
1147     size_t offset = 7;
1148     struct stat stbuf;
1149     V9fsFidState *fidp;
1150     V9fsPDU *pdu = opaque;
1151
1152     err = pdu_unmarshal(pdu, offset, "d", &fid);
1153     if (err < 0) {
1154         goto out_nofid;
1155     }
1156     trace_v9fs_stat(pdu->tag, pdu->id, fid);
1157
1158     fidp = get_fid(pdu, fid);
1159     if (fidp == NULL) {
1160         err = -ENOENT;
1161         goto out_nofid;
1162     }
1163     err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1164     if (err < 0) {
1165         goto out;
1166     }
1167     err = stat_to_v9stat(pdu, &fidp->path, &stbuf, &v9stat);
1168     if (err < 0) {
1169         goto out;
1170     }
1171     err = pdu_marshal(pdu, offset, "wS", 0, &v9stat);
1172     if (err < 0) {
1173         v9fs_stat_free(&v9stat);
1174         goto out;
1175     }
1176     trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode,
1177                            v9stat.atime, v9stat.mtime, v9stat.length);
1178     err += offset;
1179     v9fs_stat_free(&v9stat);
1180 out:
1181     put_fid(pdu, fidp);
1182 out_nofid:
1183     pdu_complete(pdu, err);
1184 }
1185
1186 static void coroutine_fn v9fs_getattr(void *opaque)
1187 {
1188     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1189     int32_t fid;
1190     size_t offset = 7;
1191     ssize_t retval = 0;
1192     struct stat stbuf;
1193     V9fsFidState *fidp;
1194     uint64_t request_mask;
1195     V9fsStatDotl v9stat_dotl;
1196     V9fsPDU *pdu = opaque;
1197     V9fsState *s = pdu->s;
1198
1199     retval = pdu_unmarshal(pdu, offset, "dq", &fid, &request_mask);
1200     if (retval < 0) {
1201         goto out_nofid;
1202     }
1203     trace_v9fs_getattr(pdu->tag, pdu->id, fid, request_mask);
1204
1205     fidp = get_fid(pdu, fid);
1206     if (fidp == NULL) {
1207         retval = -ENOENT;
1208         goto out_nofid;
1209     }
1210     /*
1211      * Currently we only support BASIC fields in stat, so there is no
1212      * need to look at request_mask.
1213      */
1214     retval = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1215     if (retval < 0) {
1216         goto out;
1217     }
1218     stat_to_v9stat_dotl(s, &stbuf, &v9stat_dotl);
1219
1220     /*  fill st_gen if requested and supported by underlying fs */
1221     if (request_mask & P9_STATS_GEN) {
1222         retval = v9fs_co_st_gen(pdu, &fidp->path, stbuf.st_mode, &v9stat_dotl);
1223         switch (retval) {
1224         case 0:
1225             /* we have valid st_gen: update result mask */
1226             v9stat_dotl.st_result_mask |= P9_STATS_GEN;
1227             break;
1228         case -EINTR:
1229             /* request cancelled, e.g. by Tflush */
1230             goto out;
1231         default:
1232             /* failed to get st_gen: not fatal, ignore */
1233             break;
1234         }
1235     }
1236     retval = pdu_marshal(pdu, offset, "A", &v9stat_dotl);
1237     if (retval < 0) {
1238         goto out;
1239     }
1240     retval += offset;
1241     trace_v9fs_getattr_return(pdu->tag, pdu->id, v9stat_dotl.st_result_mask,
1242                               v9stat_dotl.st_mode, v9stat_dotl.st_uid,
1243                               v9stat_dotl.st_gid);
1244 out:
1245     put_fid(pdu, fidp);
1246 out_nofid:
1247     pdu_complete(pdu, retval);
1248 }
1249
1250 /* Attribute flags */
1251 #define P9_ATTR_MODE       (1 << 0)
1252 #define P9_ATTR_UID        (1 << 1)
1253 #define P9_ATTR_GID        (1 << 2)
1254 #define P9_ATTR_SIZE       (1 << 3)
1255 #define P9_ATTR_ATIME      (1 << 4)
1256 #define P9_ATTR_MTIME      (1 << 5)
1257 #define P9_ATTR_CTIME      (1 << 6)
1258 #define P9_ATTR_ATIME_SET  (1 << 7)
1259 #define P9_ATTR_MTIME_SET  (1 << 8)
1260
1261 #define P9_ATTR_MASK    127
1262
1263 static void coroutine_fn v9fs_setattr(void *opaque)
1264 {
1265     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1266     int err = 0;
1267     int32_t fid;
1268     V9fsFidState *fidp;
1269     size_t offset = 7;
1270     V9fsIattr v9iattr;
1271     V9fsPDU *pdu = opaque;
1272
1273     err = pdu_unmarshal(pdu, offset, "dI", &fid, &v9iattr);
1274     if (err < 0) {
1275         goto out_nofid;
1276     }
1277
1278     fidp = get_fid(pdu, fid);
1279     if (fidp == NULL) {
1280         err = -EINVAL;
1281         goto out_nofid;
1282     }
1283     if (v9iattr.valid & P9_ATTR_MODE) {
1284 #ifndef CONFIG_WIN32
1285         err = v9fs_co_chmod(pdu, &fidp->path, v9iattr.mode);
1286 #else
1287         err = -EPERM;
1288 #endif
1289         if (err < 0) {
1290             goto out;
1291         }
1292     }
1293     if (v9iattr.valid & (P9_ATTR_ATIME | P9_ATTR_MTIME)) {
1294         struct timespec times[2];
1295         if (v9iattr.valid & P9_ATTR_ATIME) {
1296             if (v9iattr.valid & P9_ATTR_ATIME_SET) {
1297                 times[0].tv_sec = v9iattr.atime_sec;
1298                 times[0].tv_nsec = v9iattr.atime_nsec;
1299             } else {
1300                 times[0].tv_nsec = UTIME_NOW;
1301             }
1302         } else {
1303             times[0].tv_nsec = UTIME_OMIT;
1304         }
1305         if (v9iattr.valid & P9_ATTR_MTIME) {
1306             if (v9iattr.valid & P9_ATTR_MTIME_SET) {
1307                 times[1].tv_sec = v9iattr.mtime_sec;
1308                 times[1].tv_nsec = v9iattr.mtime_nsec;
1309             } else {
1310                 times[1].tv_nsec = UTIME_NOW;
1311             }
1312         } else {
1313             times[1].tv_nsec = UTIME_OMIT;
1314         }
1315         err = v9fs_co_utimensat(pdu, &fidp->path, times);
1316         if (err < 0) {
1317             goto out;
1318         }
1319     }
1320     /*
1321      * If the only valid entry in iattr is ctime we can call
1322      * chown(-1,-1) to update the ctime of the file
1323      */
1324     if ((v9iattr.valid & (P9_ATTR_UID | P9_ATTR_GID)) ||
1325         ((v9iattr.valid & P9_ATTR_CTIME)
1326          && !((v9iattr.valid & P9_ATTR_MASK) & ~P9_ATTR_CTIME))) {
1327         if (!(v9iattr.valid & P9_ATTR_UID)) {
1328             v9iattr.uid = -1;
1329         }
1330         if (!(v9iattr.valid & P9_ATTR_GID)) {
1331             v9iattr.gid = -1;
1332         }
1333 #ifndef CONFIG_WIN32
1334         err = v9fs_co_chown(pdu, &fidp->path, v9iattr.uid,
1335                             v9iattr.gid);
1336 #else
1337         err = -EPERM;
1338 #endif
1339         if (err < 0) {
1340             goto out;
1341         }
1342     }
1343     if (v9iattr.valid & (P9_ATTR_SIZE)) {
1344         err = v9fs_co_truncate(pdu, &fidp->path, v9iattr.size);
1345         if (err < 0) {
1346             goto out;
1347         }
1348     }
1349     err = offset;
1350 out:
1351     put_fid(pdu, fidp);
1352 out_nofid:
1353     pdu_complete(pdu, err);
1354 }
1355
1356 static int v9fs_walk_marshal(V9fsPDU *pdu, uint16_t nwnames, V9fsQID *qids)
1357 {
1358     int i;
1359     ssize_t err;
1360     size_t offset = 7;
1361
1362     err = pdu_marshal(pdu, offset, "w", nwnames);
1363     if (err < 0) {
1364         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1365         return err;
1366     }
1367     offset += err;
1368     for (i = 0; i < nwnames; i++) {
1369         err = pdu_marshal(pdu, offset, "Q", &qids[i]);
1370         if (err < 0) {
1371             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1372             return err;
1373         }
1374         offset += err;
1375     }
1376     return offset;
1377 }
1378
1379 static bool name_is_illegal(const char *name)
1380 {
1381 #ifndef CONFIG_WIN32
1382     return !*name || strchr(name, '/') != NULL;
1383 #else
1384     return !*name || strchr(name, '\\') != NULL;
1385 #endif
1386 }
1387
1388 static bool not_same_qid(const V9fsQID *qid1, const V9fsQID *qid2)
1389 {
1390     return
1391         qid1->type != qid2->type ||
1392         qid1->version != qid2->version ||
1393         qid1->path != qid2->path;
1394 }
1395
1396 static void coroutine_fn v9fs_walk(void *opaque)
1397 {
1398     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1399     int name_idx;
1400     V9fsQID *qids = NULL;
1401     int i, err = 0;
1402     V9fsPath dpath, path;
1403     uint16_t nwnames;
1404     struct stat stbuf;
1405     size_t offset = 7;
1406     int32_t fid, newfid;
1407     V9fsString *wnames = NULL;
1408     V9fsFidState *fidp;
1409     V9fsFidState *newfidp = NULL;
1410     V9fsPDU *pdu = opaque;
1411     V9fsState *s = pdu->s;
1412     V9fsQID qid;
1413
1414     err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
1415     if (err < 0) {
1416         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1417         pdu_complete(pdu, err);
1418         return ;
1419     }
1420     offset += err;
1421
1422     trace_v9fs_walk(pdu->tag, pdu->id, fid, newfid, nwnames);
1423
1424     if (nwnames && nwnames <= P9_MAXWELEM) {
1425         wnames = g_malloc0(sizeof(wnames[0]) * nwnames);
1426         qids   = g_malloc0(sizeof(qids[0]) * nwnames);
1427         for (i = 0; i < nwnames; i++) {
1428             err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
1429             if (err < 0) {
1430                 ERR("[%d][ >> %s]\n", __LINE__, __func__);
1431                 goto out_nofid;
1432             }
1433             if (name_is_illegal(wnames[i].data)) {
1434                 err = -ENOENT;
1435                 goto out_nofid;
1436             }
1437             offset += err;
1438         }
1439     } else if (nwnames > P9_MAXWELEM) {
1440         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1441         err = -EINVAL;
1442         goto out_nofid;
1443     }
1444     fidp = get_fid(pdu, fid);
1445     if (fidp == NULL) {
1446         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1447         err = -ENOENT;
1448         goto out_nofid;
1449     }
1450
1451     v9fs_path_init(&dpath);
1452     v9fs_path_init(&path);
1453
1454     err = fid_to_qid(pdu, fidp, &qid);
1455     if (err < 0) {
1456         goto out;
1457     }
1458
1459     /*
1460      * Both dpath and path initially poin to fidp.
1461      * Needed to handle request with nwnames == 0
1462      */
1463     v9fs_path_copy(&dpath, &fidp->path);
1464     v9fs_path_copy(&path, &fidp->path);
1465     for (name_idx = 0; name_idx < nwnames; name_idx++) {
1466         if (not_same_qid(&pdu->s->root_qid, &qid) ||
1467             strcmp("..", wnames[name_idx].data)) {
1468             err = v9fs_co_name_to_path(pdu, &dpath, wnames[name_idx].data,
1469                                        &path);
1470             if (err < 0) {
1471                 ERR("[%d][ >> %s]\n", __LINE__, __func__);
1472                 goto out;
1473             }
1474
1475             err = v9fs_co_lstat(pdu, &path, &stbuf);
1476             if (err < 0) {
1477                 goto out;
1478             }
1479             stat_to_qid(&stbuf, &qid);
1480             v9fs_path_copy(&dpath, &path);
1481         }
1482         memcpy(&qids[name_idx], &qid, sizeof(qid));
1483     }
1484     if (fid == newfid) {
1485         if (fidp->fid_type != P9_FID_NONE) {
1486             err = -EINVAL;
1487             goto out;
1488         }
1489         WARN("[%d][ >> %s]\n", __LINE__, __func__);
1490         v9fs_path_copy(&fidp->path, &path);
1491     } else {
1492         newfidp = alloc_fid(s, newfid);
1493         if (newfidp == NULL) {
1494             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1495             err = -EINVAL;
1496             goto out;
1497         }
1498         newfidp->uid = fidp->uid;
1499         v9fs_path_copy(&newfidp->path, &path);
1500     }
1501     err = v9fs_walk_marshal(pdu, nwnames, qids);
1502     trace_v9fs_walk_return(pdu->tag, pdu->id, nwnames, qids);
1503 out:
1504     put_fid(pdu, fidp);
1505     if (newfidp) {
1506         put_fid(pdu, newfidp);
1507     }
1508     v9fs_path_free(&dpath);
1509     v9fs_path_free(&path);
1510 out_nofid:
1511     pdu_complete(pdu, err);
1512     if (nwnames && nwnames <= P9_MAXWELEM) {
1513         for (name_idx = 0; name_idx < nwnames; name_idx++) {
1514             v9fs_string_free(&wnames[name_idx]);
1515         }
1516         g_free(wnames);
1517         g_free(qids);
1518     }
1519 }
1520
1521 static int32_t coroutine_fn get_iounit(V9fsPDU *pdu, V9fsPath *path)
1522 {
1523     struct statfs stbuf;
1524     int32_t iounit = 0;
1525     V9fsState *s = pdu->s;
1526
1527     /*
1528      * iounit should be multiples of f_bsize (host filesystem block size
1529      * and as well as less than (client msize - P9_IOHDRSZ))
1530      */
1531     if (!v9fs_co_statfs(pdu, path, &stbuf)) {
1532         iounit = stbuf.f_bsize;
1533         iounit *= (s->msize - P9_IOHDRSZ)/stbuf.f_bsize;
1534     }
1535     if (!iounit) {
1536         iounit = s->msize - P9_IOHDRSZ;
1537     }
1538     return iounit;
1539 }
1540
1541 static void coroutine_fn v9fs_open(void *opaque)
1542 {
1543     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1544     int flags;
1545     int32_t fid;
1546     int32_t mode;
1547     V9fsQID qid;
1548     int iounit = 0;
1549     ssize_t err = 0;
1550     size_t offset = 7;
1551     struct stat stbuf;
1552     V9fsFidState *fidp;
1553     V9fsPDU *pdu = opaque;
1554     V9fsState *s = pdu->s;
1555
1556     if (s->proto_version == V9FS_PROTO_2000L) {
1557         err = pdu_unmarshal(pdu, offset, "dd", &fid, &mode);
1558     } else {
1559         uint8_t modebyte;
1560         err = pdu_unmarshal(pdu, offset, "db", &fid, &modebyte);
1561         mode = modebyte;
1562     }
1563     if (err < 0) {
1564         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1565         goto out_nofid;
1566     }
1567     trace_v9fs_open(pdu->tag, pdu->id, fid, mode);
1568
1569     fidp = get_fid(pdu, fid);
1570     if (fidp == NULL) {
1571         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1572         err = -ENOENT;
1573         goto out_nofid;
1574     }
1575     if (fidp->fid_type != P9_FID_NONE) {
1576         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1577         err = -EINVAL;
1578         goto out;
1579     }
1580
1581     err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1582     if (err < 0) {
1583         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1584         goto out;
1585     }
1586     stat_to_qid(&stbuf, &qid);
1587     if (S_ISDIR(stbuf.st_mode)) {
1588         err = v9fs_co_opendir(pdu, fidp);
1589         if (err < 0) {
1590             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1591             goto out;
1592         }
1593         fidp->fid_type = P9_FID_DIR;
1594         err = pdu_marshal(pdu, offset, "Qd", &qid, 0);
1595         if (err < 0) {
1596             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1597             goto out;
1598         }
1599         err += offset;
1600     } else {
1601         if (s->proto_version == V9FS_PROTO_2000L) {
1602             flags = get_dotl_openflags(s, mode);
1603         } else {
1604             flags = omode_to_uflags(mode);
1605         }
1606         if (is_ro_export(&s->ctx)) {
1607             if (mode & O_WRONLY || mode & O_RDWR ||
1608                 mode & O_APPEND || mode & O_TRUNC) {
1609                 ERR("[%d][ >> %s]\n", __LINE__, __func__);
1610                 err = -EROFS;
1611                 goto out;
1612             }
1613         }
1614         err = v9fs_co_open(pdu, fidp, flags);
1615         if (err < 0) {
1616             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1617             goto out;
1618         }
1619         fidp->fid_type = P9_FID_FILE;
1620         fidp->open_flags = flags;
1621         if (flags & O_EXCL) {
1622             /*
1623              * We let the host file system do O_EXCL check
1624              * We should not reclaim such fd
1625              */
1626             fidp->flags |= FID_NON_RECLAIMABLE;
1627         }
1628         iounit = get_iounit(pdu, &fidp->path);
1629         err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
1630         if (err < 0) {
1631             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1632             goto out;
1633         }
1634         err += offset;
1635     }
1636     trace_v9fs_open_return(pdu->tag, pdu->id,
1637                            qid.type, qid.version, qid.path, iounit);
1638 out:
1639     put_fid(pdu, fidp);
1640 out_nofid:
1641     pdu_complete(pdu, err);
1642 }
1643
1644 static void coroutine_fn v9fs_lcreate(void *opaque)
1645 {
1646     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1647     int32_t dfid, flags, mode;
1648     gid_t gid;
1649     ssize_t err = 0;
1650     ssize_t offset = 7;
1651     V9fsString name;
1652     V9fsFidState *fidp;
1653     struct stat stbuf;
1654     V9fsQID qid;
1655     int32_t iounit;
1656     V9fsPDU *pdu = opaque;
1657
1658     v9fs_string_init(&name);
1659     err = pdu_unmarshal(pdu, offset, "dsddd", &dfid,
1660                         &name, &flags, &mode, &gid);
1661     if (err < 0) {
1662         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1663         goto out_nofid;
1664     }
1665     trace_v9fs_lcreate(pdu->tag, pdu->id, dfid, flags, mode, gid);
1666
1667     if (name_is_illegal(name.data)) {
1668         err = -ENOENT;
1669         goto out_nofid;
1670     }
1671
1672     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
1673         err = -EEXIST;
1674         goto out_nofid;
1675     }
1676
1677     fidp = get_fid(pdu, dfid);
1678     if (fidp == NULL) {
1679         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1680         err = -ENOENT;
1681         goto out_nofid;
1682     }
1683
1684     flags = get_dotl_openflags(pdu->s, flags);
1685     err = v9fs_co_open2(pdu, fidp, &name, gid,
1686                         flags | O_CREAT, mode, &stbuf);
1687     if (err < 0) {
1688         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1689         goto out;
1690     }
1691     fidp->fid_type = P9_FID_FILE;
1692     fidp->open_flags = flags;
1693     if (flags & O_EXCL) {
1694         /*
1695          * We let the host file system do O_EXCL check
1696          * We should not reclaim such fd
1697          */
1698         fidp->flags |= FID_NON_RECLAIMABLE;
1699     }
1700     iounit =  get_iounit(pdu, &fidp->path);
1701     stat_to_qid(&stbuf, &qid);
1702     err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
1703     if (err < 0) {
1704         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1705         goto out;
1706     }
1707     err += offset;
1708     trace_v9fs_lcreate_return(pdu->tag, pdu->id,
1709                               qid.type, qid.version, qid.path, iounit);
1710 out:
1711     put_fid(pdu, fidp);
1712 out_nofid:
1713     pdu_complete(pdu, err);
1714     v9fs_string_free(&name);
1715 }
1716
1717 static void v9fs_fsync(void *opaque)
1718 {
1719     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1720     int err;
1721     int32_t fid;
1722     int datasync;
1723     size_t offset = 7;
1724     V9fsFidState *fidp;
1725     V9fsPDU *pdu = opaque;
1726
1727     err = pdu_unmarshal(pdu, offset, "dd", &fid, &datasync);
1728     if (err < 0) {
1729         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1730         goto out_nofid;
1731     }
1732     trace_v9fs_fsync(pdu->tag, pdu->id, fid, datasync);
1733
1734     fidp = get_fid(pdu, fid);
1735     if (fidp == NULL) {
1736         err = -ENOENT;
1737         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1738         goto out_nofid;
1739     }
1740     err = v9fs_co_fsync(pdu, fidp, datasync);
1741     if (!err) {
1742         err = offset;
1743     }
1744     put_fid(pdu, fidp);
1745 out_nofid:
1746     pdu_complete(pdu, err);
1747 }
1748
1749 static void coroutine_fn v9fs_clunk(void *opaque)
1750 {
1751     int err;
1752     int32_t fid;
1753     size_t offset = 7;
1754     V9fsFidState *fidp;
1755     V9fsPDU *pdu = opaque;
1756     V9fsState *s = pdu->s;
1757
1758     err = pdu_unmarshal(pdu, offset, "d", &fid);
1759     if (err < 0) {
1760         goto out_nofid;
1761     }
1762     trace_v9fs_clunk(pdu->tag, pdu->id, fid);
1763
1764     fidp = clunk_fid(s, fid);
1765     if (fidp == NULL) {
1766         err = -ENOENT;
1767         goto out_nofid;
1768     }
1769     /*
1770      * Bump the ref so that put_fid will
1771      * free the fid.
1772      */
1773     fidp->ref++;
1774     err = put_fid(pdu, fidp);
1775     if (!err) {
1776         err = offset;
1777     }
1778 out_nofid:
1779     pdu_complete(pdu, err);
1780 }
1781
1782 #ifndef CONFIG_WIN32
1783 static int v9fs_xattr_read(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp,
1784                            uint64_t off, uint32_t max_count)
1785 {
1786     ssize_t err;
1787     size_t offset = 7;
1788     uint64_t read_count;
1789     V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);
1790     VirtQueueElement *elem = v->elems[pdu->idx];
1791
1792     if (fidp->fs.xattr.len < off) {
1793         read_count = 0;
1794     } else {
1795         read_count = fidp->fs.xattr.len - off;
1796     }
1797     if (read_count > max_count) {
1798         read_count = max_count;
1799     }
1800     err = pdu_marshal(pdu, offset, "d", read_count);
1801     if (err < 0) {
1802         return err;
1803     }
1804     offset += err;
1805
1806     err = v9fs_pack(elem->in_sg, elem->in_num, offset,
1807                     ((char *)fidp->fs.xattr.value) + off,
1808                     read_count);
1809     if (err < 0) {
1810         return err;
1811     }
1812     offset += err;
1813     return offset;
1814 }
1815 #endif
1816
1817 static int coroutine_fn v9fs_do_readdir_with_stat(V9fsPDU *pdu,
1818                                                   V9fsFidState *fidp,
1819                                                   uint32_t max_count)
1820 {
1821     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1822     V9fsPath path;
1823     V9fsStat v9stat;
1824     int len, err = 0;
1825     int32_t count = 0;
1826     struct stat stbuf;
1827     off_t saved_dir_pos;
1828     struct dirent *dent;
1829
1830     /* save the directory position */
1831     saved_dir_pos = v9fs_co_telldir(pdu, fidp);
1832     if (saved_dir_pos < 0) {
1833         return saved_dir_pos;
1834     }
1835
1836     while (1) {
1837         v9fs_path_init(&path);
1838
1839         v9fs_readdir_lock(&fidp->fs.dir);
1840
1841         err = v9fs_co_readdir(pdu, fidp, &dent);
1842         if (err || !dent) {
1843             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1844             break;
1845         }
1846         err = v9fs_co_name_to_path(pdu, &fidp->path, dent->d_name, &path);
1847         if (err < 0) {
1848             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1849             break;
1850         }
1851         err = v9fs_co_lstat(pdu, &path, &stbuf);
1852         if (err < 0) {
1853             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1854             break;
1855         }
1856         err = stat_to_v9stat(pdu, &path, &stbuf, &v9stat);
1857         if (err < 0) {
1858             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1859             break;
1860         }
1861         /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */
1862         len = pdu_marshal(pdu, 11 + count, "S", &v9stat);
1863
1864         v9fs_readdir_unlock(&fidp->fs.dir);
1865
1866         if ((len != (v9stat.size + 2)) || ((count + len) > max_count)) {
1867             /* Ran out of buffer. Set dir back to old position and return */
1868             v9fs_co_seekdir(pdu, fidp, saved_dir_pos);
1869             v9fs_stat_free(&v9stat);
1870             v9fs_path_free(&path);
1871             return count;
1872         }
1873         count += len;
1874         v9fs_stat_free(&v9stat);
1875         v9fs_path_free(&path);
1876 #ifdef CONFIG_LINUX
1877         saved_dir_pos = dent->d_off;
1878 #else
1879         saved_dir_pos = v9fs_co_telldir(pdu, fidp);
1880 #endif
1881     }
1882
1883     v9fs_readdir_unlock(&fidp->fs.dir);
1884
1885     v9fs_path_free(&path);
1886     if (err < 0) {
1887         return err;
1888     }
1889     return count;
1890 }
1891
1892 /*
1893  * Create a QEMUIOVector for a sub-region of PDU iovecs
1894  *
1895  * @qiov:       uninitialized QEMUIOVector
1896  * @skip:       number of bytes to skip from beginning of PDU
1897  * @size:       number of bytes to include
1898  * @is_write:   true - write, false - read
1899  *
1900  * The resulting QEMUIOVector has heap-allocated iovecs and must be cleaned up
1901  * with qemu_iovec_destroy().
1902  */
1903 static void v9fs_init_qiov_from_pdu(QEMUIOVector *qiov, V9fsPDU *pdu,
1904                                     size_t skip, size_t size,
1905                                     bool is_write)
1906 {
1907     QEMUIOVector elem;
1908     struct iovec *iov;
1909     unsigned int niov;
1910
1911     virtio_init_iov_from_pdu(pdu, &iov, &niov, is_write);
1912
1913     qemu_iovec_init_external(&elem, iov, niov);
1914     qemu_iovec_init(qiov, niov);
1915     qemu_iovec_concat(qiov, &elem, skip, size);
1916 }
1917
1918 static void coroutine_fn v9fs_read(void *opaque)
1919 {
1920     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
1921     int32_t fid;
1922     uint64_t off;
1923     ssize_t err = 0;
1924     int32_t count = 0;
1925     size_t offset = 7;
1926     uint32_t max_count;
1927     V9fsFidState *fidp;
1928     V9fsPDU *pdu = opaque;
1929 #ifndef CONFIG_WIN32
1930     V9fsState *s = pdu->s;
1931 #endif
1932
1933     err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
1934     if (err < 0) {
1935         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1936         goto out_nofid;
1937     }
1938     trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
1939
1940     fidp = get_fid(pdu, fid);
1941     if (fidp == NULL) {
1942         ERR("[%d][ >> %s]\n", __LINE__, __func__);
1943         err = -EINVAL;
1944         goto out_nofid;
1945     }
1946     if (fidp->fid_type == P9_FID_DIR) {
1947
1948         if (off == 0) {
1949             v9fs_co_rewinddir(pdu, fidp);
1950         }
1951         count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
1952         if (count < 0) {
1953             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1954             err = count;
1955             goto out;
1956         }
1957         err = pdu_marshal(pdu, offset, "d", count);
1958         if (err < 0) {
1959             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1960             goto out;
1961         }
1962         err += offset + count;
1963     } else if (fidp->fid_type == P9_FID_FILE) {
1964         QEMUIOVector qiov_full;
1965         QEMUIOVector qiov;
1966         int32_t len;
1967
1968         v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
1969         qemu_iovec_init(&qiov, qiov_full.niov);
1970         do {
1971             qemu_iovec_reset(&qiov);
1972             qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
1973             if (0) {
1974                 print_sg(qiov.iov, qiov.niov);
1975             }
1976             /* Loop in case of EINTR */
1977             do {
1978                 len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
1979                 if (len >= 0) {
1980                     off   += len;
1981                     count += len;
1982                 }
1983             } while (len == -EINTR && !pdu->cancelled);
1984             if (len < 0) {
1985                 /* IO error return the error */
1986                 ERR("[%d][ >> %s]\n", __LINE__, __func__);
1987                 err = len;
1988                 goto out_free_iovec;
1989             }
1990         } while (count < max_count && len > 0);
1991         err = pdu_marshal(pdu, offset, "d", count);
1992         if (err < 0) {
1993             ERR("[%d][ >> %s]\n", __LINE__, __func__);
1994             goto out_free_iovec;
1995         }
1996         err += offset + count;
1997 out_free_iovec:
1998         qemu_iovec_destroy(&qiov);
1999         qemu_iovec_destroy(&qiov_full);
2000 #ifndef CONFIG_WIN32
2001     } else if (fidp->fid_type == P9_FID_XATTR) {
2002         err = v9fs_xattr_read(s, pdu, fidp, off, max_count);
2003 #endif
2004     } else {
2005         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2006         err = -EINVAL;
2007     }
2008     trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
2009 out:
2010     put_fid(pdu, fidp);
2011 out_nofid:
2012     pdu_complete(pdu, err);
2013 }
2014
2015 static size_t v9fs_readdir_data_size(V9fsString *name)
2016 {
2017     /*
2018      * Size of each dirent on the wire: size of qid (13) + size of offset (8)
2019      * size of type (1) + size of name.size (2) + strlen(name.data)
2020      */
2021     return 24 + v9fs_string_size(name);
2022 }
2023
2024 static int coroutine_fn v9fs_do_readdir(V9fsPDU *pdu, V9fsFidState *fidp,
2025                                         int32_t max_count)
2026 {
2027     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2028     size_t size;
2029     V9fsQID qid;
2030     V9fsString name;
2031     int len, err = 0;
2032     int32_t count = 0;
2033     off_t saved_dir_pos;
2034     struct dirent *dent;
2035 #ifndef CONFIG_LINUX
2036     uint64_t d_offset = 0;
2037 #endif
2038
2039     /* save the directory position */
2040     saved_dir_pos = v9fs_co_telldir(pdu, fidp);
2041     if (saved_dir_pos < 0) {
2042         return saved_dir_pos;
2043     }
2044
2045     while (1) {
2046         v9fs_readdir_lock(&fidp->fs.dir);
2047
2048         err = v9fs_co_readdir(pdu, fidp, &dent);
2049         if (err || !dent) {
2050             break;
2051         }
2052         v9fs_string_init(&name);
2053         v9fs_string_sprintf(&name, "%s", dent->d_name);
2054         if ((count + v9fs_readdir_data_size(&name)) > max_count) {
2055             v9fs_readdir_unlock(&fidp->fs.dir);
2056
2057             /* Ran out of buffer. Set dir back to old position and return */
2058             v9fs_co_seekdir(pdu, fidp, saved_dir_pos);
2059             v9fs_string_free(&name);
2060             return count;
2061         }
2062         /*
2063          * Fill up just the path field of qid because the client uses
2064          * only that. To fill the entire qid structure we will have
2065          * to stat each dirent found, which is expensive
2066          */
2067         size = MIN(sizeof(dent->d_ino), sizeof(qid.path));
2068         memcpy(&qid.path, &dent->d_ino, size);
2069         /* Fill the other fields with dummy values */
2070         qid.type = 0;
2071         qid.version = 0;
2072
2073         /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */
2074 #ifdef CONFIG_LINUX
2075         len = pdu_marshal(pdu, 11 + count, "Qqbs",
2076                           &qid, dent->d_off,
2077                           dent->d_type, &name);
2078 #else
2079         d_offset = v9fs_co_telldir(pdu, fidp);
2080 #ifndef CONFIG_WIN32
2081         len = pdu_marshal(pdu, 11 + count, "Qqbs",
2082                           &qid, d_offset,
2083                           dent->d_type, &name);
2084 #else
2085         len = pdu_marshal(pdu, 11 + count, "Qqbs",
2086                           &qid, d_offset,
2087                           WIN32_D_TYPE, &name);
2088 #endif
2089 #endif
2090
2091         v9fs_readdir_unlock(&fidp->fs.dir);
2092
2093         if (len < 0) {
2094             v9fs_co_seekdir(pdu, fidp, saved_dir_pos);
2095             v9fs_string_free(&name);
2096             return len;
2097         }
2098         count += len;
2099         v9fs_string_free(&name);
2100 #ifdef CONFIG_LINUX
2101         saved_dir_pos = dent->d_off;
2102 #else
2103         saved_dir_pos = d_offset;
2104 #endif
2105     }
2106
2107     v9fs_readdir_unlock(&fidp->fs.dir);
2108
2109     if (err < 0) {
2110         return err;
2111     }
2112     return count;
2113 }
2114
2115 static void coroutine_fn v9fs_readdir(void *opaque)
2116 {
2117     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2118     int32_t fid;
2119     V9fsFidState *fidp;
2120     ssize_t retval = 0;
2121     size_t offset = 7;
2122     uint64_t initial_offset;
2123     int32_t count;
2124     uint32_t max_count;
2125     V9fsPDU *pdu = opaque;
2126
2127     retval = pdu_unmarshal(pdu, offset, "dqd", &fid,
2128                            &initial_offset, &max_count);
2129     if (retval < 0) {
2130         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2131         goto out_nofid;
2132     }
2133     trace_v9fs_readdir(pdu->tag, pdu->id, fid, initial_offset, max_count);
2134
2135     fidp = get_fid(pdu, fid);
2136     if (fidp == NULL) {
2137         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2138         retval = -EINVAL;
2139         goto out_nofid;
2140     }
2141     if (!fidp->fs.dir.stream) {
2142         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2143         retval = -EINVAL;
2144         goto out;
2145     }
2146     if (initial_offset == 0) {
2147         v9fs_co_rewinddir(pdu, fidp);
2148     } else {
2149         v9fs_co_seekdir(pdu, fidp, initial_offset);
2150     }
2151     count = v9fs_do_readdir(pdu, fidp, max_count);
2152     if (count < 0) {
2153         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2154         retval = count;
2155         goto out;
2156     }
2157     retval = pdu_marshal(pdu, offset, "d", count);
2158     if (retval < 0) {
2159         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2160         goto out;
2161     }
2162     retval += count + offset;
2163     trace_v9fs_readdir_return(pdu->tag, pdu->id, count, retval);
2164 out:
2165     put_fid(pdu, fidp);
2166 out_nofid:
2167     pdu_complete(pdu, retval);
2168 }
2169
2170 #ifndef CONFIG_WIN32
2171 static int v9fs_xattr_write(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp,
2172                             uint64_t off, uint32_t count,
2173                             struct iovec *sg, int cnt)
2174 {
2175     int i, to_copy;
2176     ssize_t err = 0;
2177     uint64_t write_count;
2178     size_t offset = 7;
2179
2180
2181     if (fidp->fs.xattr.len < off) {
2182         err = -ENOSPC;
2183         goto out;
2184     }
2185     write_count = fidp->fs.xattr.len - off;
2186     if (write_count > count) {
2187         write_count = count;
2188     }
2189     err = pdu_marshal(pdu, offset, "d", write_count);
2190     if (err < 0) {
2191         return err;
2192     }
2193     err += offset;
2194     fidp->fs.xattr.copied_len += write_count;
2195     /*
2196      * Now copy the content from sg list
2197      */
2198     for (i = 0; i < cnt; i++) {
2199         if (write_count > sg[i].iov_len) {
2200             to_copy = sg[i].iov_len;
2201         } else {
2202             to_copy = write_count;
2203         }
2204         memcpy((char *)fidp->fs.xattr.value + off, sg[i].iov_base, to_copy);
2205         /* updating vs->off since we are not using below */
2206         off += to_copy;
2207         write_count -= to_copy;
2208     }
2209 out:
2210     return err;
2211 }
2212 #endif
2213
2214 static void coroutine_fn v9fs_write(void *opaque)
2215 {
2216     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2217     ssize_t err;
2218     int32_t fid;
2219     uint64_t off;
2220     uint32_t count;
2221     int32_t len = 0;
2222     int32_t total = 0;
2223     size_t offset = 7;
2224     V9fsFidState *fidp;
2225     V9fsPDU *pdu = opaque;
2226 #ifndef CONFIG_WIN32
2227     V9fsState *s = pdu->s;
2228 #endif
2229     QEMUIOVector qiov_full;
2230     QEMUIOVector qiov;
2231
2232     err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);
2233     if (err < 0) {
2234         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2235         pdu_complete(pdu, err);
2236         return;
2237     }
2238     offset += err;
2239     v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);
2240     trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);
2241
2242     fidp = get_fid(pdu, fid);
2243     if (fidp == NULL) {
2244         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2245         err = -EINVAL;
2246         goto out_nofid;
2247     }
2248     if (fidp->fid_type == P9_FID_FILE) {
2249         if (fidp->fs.fd == -1) {
2250             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2251             err = -EINVAL;
2252             goto out;
2253         }
2254     } else if (fidp->fid_type == P9_FID_XATTR) {
2255         /*
2256          * setxattr operation
2257          */
2258 #ifndef CONFIG_WIN32
2259         err = v9fs_xattr_write(s, pdu, fidp, off, count,
2260                                qiov_full.iov, qiov_full.niov);
2261 #endif
2262         goto out;
2263     } else {
2264         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2265         err = -EINVAL;
2266         goto out;
2267     }
2268     qemu_iovec_init(&qiov, qiov_full.niov);
2269     do {
2270         qemu_iovec_reset(&qiov);
2271         qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
2272         if (0) {
2273             print_sg(qiov.iov, qiov.niov);
2274         }
2275         /* Loop in case of EINTR */
2276         do {
2277             len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);
2278             if (len >= 0) {
2279                 off   += len;
2280                 total += len;
2281             }
2282         } while (len == -EINTR && !pdu->cancelled);
2283         if (len < 0) {
2284             /* IO error return the error */
2285             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2286             err = len;
2287             goto out_qiov;
2288         }
2289     } while (total < count && len > 0);
2290
2291     offset = 7;
2292     err = pdu_marshal(pdu, offset, "d", total);
2293     if (err < 0) {
2294         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2295         goto out_qiov;
2296     }
2297     err += offset;
2298     trace_v9fs_write_return(pdu->tag, pdu->id, total, err);
2299 out_qiov:
2300     qemu_iovec_destroy(&qiov);
2301 out:
2302     put_fid(pdu, fidp);
2303 out_nofid:
2304     qemu_iovec_destroy(&qiov_full);
2305     pdu_complete(pdu, err);
2306 }
2307
2308 static void coroutine_fn v9fs_create(void *opaque)
2309 {
2310     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2311     int32_t fid;
2312     int err = 0;
2313     size_t offset = 7;
2314     V9fsFidState *fidp;
2315     V9fsQID qid;
2316     int32_t perm;
2317     int8_t mode;
2318     V9fsPath path;
2319     struct stat stbuf;
2320     V9fsString name;
2321     V9fsString extension;
2322     int iounit;
2323     V9fsPDU *pdu = opaque;
2324
2325     v9fs_path_init(&path);
2326     v9fs_string_init(&name);
2327     v9fs_string_init(&extension);
2328     err = pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name,
2329                         &perm, &mode, &extension);
2330     if (err < 0) {
2331         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2332         goto out_nofid;
2333     }
2334     trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode);
2335
2336     if (name_is_illegal(name.data)) {
2337         err = -ENOENT;
2338         goto out_nofid;
2339     }
2340
2341     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2342         err = -EEXIST;
2343         goto out_nofid;
2344     }
2345
2346     fidp = get_fid(pdu, fid);
2347     if (fidp == NULL) {
2348         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2349         err = -EINVAL;
2350         goto out_nofid;
2351     }
2352     if (perm & P9_STAT_MODE_DIR) {
2353         err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777,
2354                             fidp->uid, -1, &stbuf);
2355         if (err < 0) {
2356             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2357             goto out;
2358         }
2359         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2360         if (err < 0) {
2361             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2362             goto out;
2363         }
2364         v9fs_path_copy(&fidp->path, &path);
2365         err = v9fs_co_opendir(pdu, fidp);
2366         if (err < 0) {
2367             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2368             goto out;
2369         }
2370         fidp->fid_type = P9_FID_DIR;
2371 #ifndef CONFIG_WIN32
2372     } else if (perm & P9_STAT_MODE_SYMLINK) {
2373         err = v9fs_co_symlink(pdu, fidp, &name,
2374                               extension.data, -1 , &stbuf);
2375         if (err < 0) {
2376             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2377             goto out;
2378         }
2379         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2380         if (err < 0) {
2381             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2382             goto out;
2383         }
2384         v9fs_path_copy(&fidp->path, &path);
2385     } else if (perm & P9_STAT_MODE_LINK) {
2386         int32_t ofid = atoi(extension.data);
2387         V9fsFidState *ofidp = get_fid(pdu, ofid);
2388         if (ofidp == NULL) {
2389             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2390             err = -EINVAL;
2391             goto out;
2392         }
2393         err = v9fs_co_link(pdu, ofidp, fidp, &name);
2394         put_fid(pdu, ofidp);
2395         if (err < 0) {
2396             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2397             goto out;
2398         }
2399         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2400         if (err < 0) {
2401             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2402             fidp->fid_type = P9_FID_NONE;
2403             goto out;
2404         }
2405         v9fs_path_copy(&fidp->path, &path);
2406         err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
2407         if (err < 0) {
2408             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2409             fidp->fid_type = P9_FID_NONE;
2410             goto out;
2411         }
2412     } else if (perm & P9_STAT_MODE_DEVICE) {
2413         char ctype;
2414         uint32_t major, minor;
2415         mode_t nmode = 0;
2416
2417         if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) {
2418             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2419             err = -errno;
2420             goto out;
2421         }
2422
2423         switch (ctype) {
2424         case 'c':
2425             nmode = S_IFCHR;
2426             break;
2427         case 'b':
2428             nmode = S_IFBLK;
2429             break;
2430         default:
2431             err = -EIO;
2432             goto out;
2433         }
2434
2435         nmode |= perm & 0777;
2436         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2437                             makedev(major, minor), nmode, &stbuf);
2438         if (err < 0) {
2439             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2440             goto out;
2441         }
2442         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2443         if (err < 0) {
2444             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2445             goto out;
2446         }
2447         v9fs_path_copy(&fidp->path, &path);
2448     } else if (perm & P9_STAT_MODE_NAMED_PIPE) {
2449         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2450                             0, S_IFIFO | (perm & 0777), &stbuf);
2451         if (err < 0) {
2452             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2453             goto out;
2454         }
2455         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2456         if (err < 0) {
2457             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2458             goto out;
2459         }
2460         v9fs_path_copy(&fidp->path, &path);
2461     } else if (perm & P9_STAT_MODE_SOCKET) {
2462         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2463                             0, S_IFSOCK | (perm & 0777), &stbuf);
2464         if (err < 0) {
2465             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2466             goto out;
2467         }
2468         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2469         if (err < 0) {
2470             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2471             goto out;
2472         }
2473         v9fs_path_copy(&fidp->path, &path);
2474 #endif
2475     } else {
2476         err = v9fs_co_open2(pdu, fidp, &name, -1,
2477                             omode_to_uflags(mode)|O_CREAT, perm, &stbuf);
2478         if (err < 0) {
2479             ERR("[%d][ >> %s]\n", __LINE__, __func__);
2480             goto out;
2481         }
2482         fidp->fid_type = P9_FID_FILE;
2483         fidp->open_flags = omode_to_uflags(mode);
2484         if (fidp->open_flags & O_EXCL) {
2485             /*
2486              * We let the host file system do O_EXCL check
2487              * We should not reclaim such fd
2488              */
2489             fidp->flags |= FID_NON_RECLAIMABLE;
2490         }
2491     }
2492     iounit = get_iounit(pdu, &fidp->path);
2493     stat_to_qid(&stbuf, &qid);
2494     err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
2495     if (err < 0) {
2496         ERR("[%d][ >> %s]\n", __LINE__, __func__);
2497         goto out;
2498     }
2499     err += offset;
2500     trace_v9fs_create_return(pdu->tag, pdu->id,
2501                              qid.type, qid.version, qid.path, iounit);
2502 out:
2503     put_fid(pdu, fidp);
2504 out_nofid:
2505    pdu_complete(pdu, err);
2506    v9fs_string_free(&name);
2507    v9fs_string_free(&extension);
2508    v9fs_path_free(&path);
2509 }
2510
2511 static void coroutine_fn v9fs_symlink(void *opaque)
2512 {
2513     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2514     V9fsPDU *pdu = opaque;
2515     V9fsString name;
2516     V9fsString symname;
2517     V9fsFidState *dfidp;
2518     V9fsQID qid;
2519     struct stat stbuf;
2520     int32_t dfid;
2521     int err = 0;
2522     gid_t gid;
2523     size_t offset = 7;
2524
2525     v9fs_string_init(&name);
2526     v9fs_string_init(&symname);
2527     err = pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid);
2528     if (err < 0) {
2529         goto out_nofid;
2530     }
2531     trace_v9fs_symlink(pdu->tag, pdu->id, dfid, name.data, symname.data, gid);
2532
2533     if (name_is_illegal(name.data)) {
2534         err = -ENOENT;
2535         goto out_nofid;
2536     }
2537
2538     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2539         err = -EEXIST;
2540         goto out_nofid;
2541     }
2542
2543     dfidp = get_fid(pdu, dfid);
2544     if (dfidp == NULL) {
2545         err = -EINVAL;
2546         goto out_nofid;
2547     }
2548 #ifndef CONFIG_WIN32
2549     err = v9fs_co_symlink(pdu, dfidp, &name, symname.data, gid, &stbuf);
2550 #else
2551     err = -EPERM;
2552 #endif
2553     if (err < 0) {
2554         goto out;
2555     }
2556     stat_to_qid(&stbuf, &qid);
2557     err =  pdu_marshal(pdu, offset, "Q", &qid);
2558     if (err < 0) {
2559         goto out;
2560     }
2561     err += offset;
2562     trace_v9fs_symlink_return(pdu->tag, pdu->id,
2563                               qid.type, qid.version, qid.path);
2564 out:
2565     put_fid(pdu, dfidp);
2566 out_nofid:
2567     pdu_complete(pdu, err);
2568     v9fs_string_free(&name);
2569     v9fs_string_free(&symname);
2570 }
2571
2572 static void v9fs_flush(void *opaque)
2573 {
2574     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2575     ssize_t err;
2576     int16_t tag;
2577     size_t offset = 7;
2578     V9fsPDU *cancel_pdu;
2579     V9fsPDU *pdu = opaque;
2580     V9fsState *s = pdu->s;
2581
2582     err = pdu_unmarshal(pdu, offset, "w", &tag);
2583     if (err < 0) {
2584         pdu_complete(pdu, err);
2585         return;
2586     }
2587     trace_v9fs_flush(pdu->tag, pdu->id, tag);
2588
2589     QLIST_FOREACH(cancel_pdu, &s->active_list, next) {
2590         if (cancel_pdu->tag == tag) {
2591             break;
2592         }
2593     }
2594     if (cancel_pdu) {
2595         cancel_pdu->cancelled = 1;
2596         /*
2597          * Wait for pdu to complete.
2598          */
2599         qemu_co_queue_wait(&cancel_pdu->complete);
2600         cancel_pdu->cancelled = 0;
2601         pdu_free(cancel_pdu);
2602     }
2603     pdu_complete(pdu, 7);
2604 }
2605
2606 static void coroutine_fn v9fs_link(void *opaque)
2607 {
2608     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2609     V9fsPDU *pdu = opaque;
2610     int32_t dfid, oldfid;
2611     V9fsFidState *dfidp, *oldfidp;
2612     V9fsString name;
2613     size_t offset = 7;
2614     int err = 0;
2615
2616     v9fs_string_init(&name);
2617     err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
2618     if (err < 0) {
2619         goto out_nofid;
2620     }
2621     trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
2622
2623     if (name_is_illegal(name.data)) {
2624         err = -ENOENT;
2625         goto out_nofid;
2626     }
2627
2628     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2629         err = -EEXIST;
2630         goto out_nofid;
2631     }
2632
2633     dfidp = get_fid(pdu, dfid);
2634     if (dfidp == NULL) {
2635         err = -ENOENT;
2636         goto out_nofid;
2637     }
2638
2639     oldfidp = get_fid(pdu, oldfid);
2640     if (oldfidp == NULL) {
2641         err = -ENOENT;
2642         goto out;
2643     }
2644     err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
2645     if (!err) {
2646         err = offset;
2647     }
2648     put_fid(pdu, oldfidp);
2649 out:
2650     put_fid(pdu, dfidp);
2651 out_nofid:
2652     v9fs_string_free(&name);
2653     pdu_complete(pdu, err);
2654 }
2655
2656 /* Only works with path name based fid */
2657 static void coroutine_fn v9fs_remove(void *opaque)
2658 {
2659     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2660     int32_t fid;
2661     int err = 0;
2662     size_t offset = 7;
2663     V9fsFidState *fidp;
2664     V9fsPDU *pdu = opaque;
2665
2666     err = pdu_unmarshal(pdu, offset, "d", &fid);
2667     if (err < 0) {
2668         goto out_nofid;
2669     }
2670     trace_v9fs_remove(pdu->tag, pdu->id, fid);
2671
2672     fidp = get_fid(pdu, fid);
2673     if (fidp == NULL) {
2674         err = -EINVAL;
2675         goto out_nofid;
2676     }
2677     /* if fs driver is not path based, return EOPNOTSUPP */
2678     if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {
2679         err = -EOPNOTSUPP;
2680         goto out_err;
2681     }
2682     /*
2683      * IF the file is unlinked, we cannot reopen
2684      * the file later. So don't reclaim fd
2685      */
2686     err = v9fs_mark_fids_unreclaim(pdu, &fidp->path);
2687     if (err < 0) {
2688         goto out_err;
2689     }
2690     err = v9fs_co_remove(pdu, &fidp->path);
2691     if (!err) {
2692         err = offset;
2693     }
2694 out_err:
2695     /* For TREMOVE we need to clunk the fid even on failed remove */
2696     clunk_fid(pdu->s, fidp->fid);
2697     put_fid(pdu, fidp);
2698 out_nofid:
2699     pdu_complete(pdu, err);
2700 }
2701
2702 static void coroutine_fn v9fs_unlinkat(void *opaque)
2703 {
2704     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2705     int err = 0;
2706     V9fsString name;
2707     int32_t dfid, flags;
2708     size_t offset = 7;
2709     V9fsPath path;
2710     V9fsFidState *dfidp;
2711     V9fsPDU *pdu = opaque;
2712
2713     v9fs_string_init(&name);
2714     err = pdu_unmarshal(pdu, offset, "dsd", &dfid, &name, &flags);
2715     if (err < 0) {
2716         goto out_nofid;
2717     }
2718
2719     if (name_is_illegal(name.data)) {
2720         err = -ENOENT;
2721         goto out_nofid;
2722     }
2723
2724     if (!strcmp(".", name.data)) {
2725         err = -EINVAL;
2726         goto out_nofid;
2727     }
2728
2729     if (!strcmp("..", name.data)) {
2730         err = -ENOTEMPTY;
2731         goto out_nofid;
2732     }
2733
2734     dfidp = get_fid(pdu, dfid);
2735     if (dfidp == NULL) {
2736         err = -EINVAL;
2737         goto out_nofid;
2738     }
2739     /*
2740      * IF the file is unlinked, we cannot reopen
2741      * the file later. So don't reclaim fd
2742      */
2743     v9fs_path_init(&path);
2744     err = v9fs_co_name_to_path(pdu, &dfidp->path, name.data, &path);
2745     if (err < 0) {
2746         goto out_err;
2747     }
2748     err = v9fs_mark_fids_unreclaim(pdu, &path);
2749     if (err < 0) {
2750         goto out_err;
2751     }
2752     err = v9fs_co_unlinkat(pdu, &dfidp->path, &name, flags);
2753     if (!err) {
2754         err = offset;
2755     }
2756 out_err:
2757     put_fid(pdu, dfidp);
2758     v9fs_path_free(&path);
2759 out_nofid:
2760     pdu_complete(pdu, err);
2761     v9fs_string_free(&name);
2762 }
2763
2764
2765 /* Only works with path name based fid */
2766 static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp,
2767                                              int32_t newdirfid,
2768                                              V9fsString *name)
2769 {
2770     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2771     char *end;
2772     int err = 0;
2773     V9fsPath new_path;
2774     V9fsFidState *tfidp;
2775     V9fsState *s = pdu->s;
2776     V9fsFidState *dirfidp = NULL;
2777     char *old_name, *new_name;
2778
2779     v9fs_path_init(&new_path);
2780     if (newdirfid != -1) {
2781         dirfidp = get_fid(pdu, newdirfid);
2782         if (dirfidp == NULL) {
2783             err = -ENOENT;
2784             goto out_nofid;
2785         }
2786         if (fidp->fid_type != P9_FID_NONE) {
2787             err = -EINVAL;
2788             goto out;
2789         }
2790         v9fs_co_name_to_path(pdu, &dirfidp->path, name->data, &new_path);
2791     } else {
2792         old_name = fidp->path.data;
2793         end = strrchr(old_name, '/');
2794         if (end) {
2795             end++;
2796         } else {
2797             end = old_name;
2798         }
2799         new_name = g_malloc0(end - old_name + name->size + 1);
2800         strncat(new_name, old_name, end - old_name);
2801         strncat(new_name + (end - old_name), name->data, name->size);
2802         v9fs_co_name_to_path(pdu, NULL, new_name, &new_path);
2803         g_free(new_name);
2804     }
2805     err = v9fs_co_rename(pdu, &fidp->path, &new_path);
2806     if (err < 0) {
2807         goto out;
2808     }
2809     /*
2810      * Fixup fid's pointing to the old name to
2811      * start pointing to the new name
2812      */
2813     for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {
2814         if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) {
2815             /* replace the name */
2816             v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data));
2817         }
2818     }
2819 out:
2820     if (dirfidp) {
2821         put_fid(pdu, dirfidp);
2822     }
2823     v9fs_path_free(&new_path);
2824 out_nofid:
2825     return err;
2826 }
2827
2828 /* Only works with path name based fid */
2829 static void coroutine_fn v9fs_rename(void *opaque)
2830 {
2831     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2832     int32_t fid;
2833     ssize_t err = 0;
2834     size_t offset = 7;
2835     V9fsString name;
2836     int32_t newdirfid;
2837     V9fsFidState *fidp;
2838     V9fsPDU *pdu = opaque;
2839     V9fsState *s = pdu->s;
2840
2841     v9fs_string_init(&name);
2842     err = pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name);
2843     if (err < 0) {
2844         goto out_nofid;
2845     }
2846
2847     if (name_is_illegal(name.data)) {
2848         err = -ENOENT;
2849         goto out_nofid;
2850     }
2851
2852     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2853         err = -EISDIR;
2854         goto out_nofid;
2855     }
2856
2857     fidp = get_fid(pdu, fid);
2858     if (fidp == NULL) {
2859         err = -ENOENT;
2860         goto out_nofid;
2861     }
2862     if (fidp->fid_type != P9_FID_NONE) {
2863         err = -EINVAL;
2864         goto out;
2865     }
2866     /* if fs driver is not path based, return EOPNOTSUPP */
2867     if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {
2868         err = -EOPNOTSUPP;
2869         goto out;
2870     }
2871     v9fs_path_write_lock(s);
2872     err = v9fs_complete_rename(pdu, fidp, newdirfid, &name);
2873     v9fs_path_unlock(s);
2874     if (!err) {
2875         err = offset;
2876     }
2877 out:
2878     put_fid(pdu, fidp);
2879 out_nofid:
2880     pdu_complete(pdu, err);
2881     v9fs_string_free(&name);
2882 }
2883
2884 static void coroutine_fn v9fs_fix_fid_paths(V9fsPDU *pdu, V9fsPath *olddir,
2885                                             V9fsString *old_name,
2886                                             V9fsPath *newdir,
2887                                             V9fsString *new_name)
2888 {
2889     V9fsFidState *tfidp;
2890     V9fsPath oldpath, newpath;
2891     V9fsState *s = pdu->s;
2892
2893
2894     v9fs_path_init(&oldpath);
2895     v9fs_path_init(&newpath);
2896     v9fs_co_name_to_path(pdu, olddir, old_name->data, &oldpath);
2897     v9fs_co_name_to_path(pdu, newdir, new_name->data, &newpath);
2898
2899     /*
2900      * Fixup fid's pointing to the old name to
2901      * start pointing to the new name
2902      */
2903     for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {
2904         if (v9fs_path_is_ancestor(&oldpath, &tfidp->path)) {
2905             /* replace the name */
2906             v9fs_fix_path(&tfidp->path, &newpath, strlen(oldpath.data));
2907         }
2908     }
2909     v9fs_path_free(&oldpath);
2910     v9fs_path_free(&newpath);
2911 }
2912
2913 static int coroutine_fn v9fs_complete_renameat(V9fsPDU *pdu, int32_t olddirfid,
2914                                                V9fsString *old_name,
2915                                                int32_t newdirfid,
2916                                                V9fsString *new_name)
2917 {
2918     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2919     int err = 0;
2920     V9fsState *s = pdu->s;
2921     V9fsFidState *newdirfidp = NULL, *olddirfidp = NULL;
2922
2923     olddirfidp = get_fid(pdu, olddirfid);
2924     if (olddirfidp == NULL) {
2925         err = -ENOENT;
2926         goto out;
2927     }
2928     if (newdirfid != -1) {
2929         newdirfidp = get_fid(pdu, newdirfid);
2930         if (newdirfidp == NULL) {
2931             err = -ENOENT;
2932             goto out;
2933         }
2934     } else {
2935         newdirfidp = get_fid(pdu, olddirfid);
2936     }
2937
2938     err = v9fs_co_renameat(pdu, &olddirfidp->path, old_name,
2939                            &newdirfidp->path, new_name);
2940     if (err < 0) {
2941         goto out;
2942     }
2943     if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) {
2944         /* Only for path based fid  we need to do the below fixup */
2945         v9fs_fix_fid_paths(pdu, &olddirfidp->path, old_name,
2946                            &newdirfidp->path, new_name);
2947     }
2948 out:
2949     if (olddirfidp) {
2950         put_fid(pdu, olddirfidp);
2951     }
2952     if (newdirfidp) {
2953         put_fid(pdu, newdirfidp);
2954     }
2955     return err;
2956 }
2957
2958 static void coroutine_fn v9fs_renameat(void *opaque)
2959 {
2960     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
2961     ssize_t err = 0;
2962     size_t offset = 7;
2963     V9fsPDU *pdu = opaque;
2964     V9fsState *s = pdu->s;
2965     int32_t olddirfid, newdirfid;
2966     V9fsString old_name, new_name;
2967
2968     v9fs_string_init(&old_name);
2969     v9fs_string_init(&new_name);
2970     err = pdu_unmarshal(pdu, offset, "dsds", &olddirfid,
2971                         &old_name, &newdirfid, &new_name);
2972     if (err < 0) {
2973         goto out_err;
2974     }
2975
2976     if (name_is_illegal(old_name.data) || name_is_illegal(new_name.data)) {
2977         err = -ENOENT;
2978         goto out_err;
2979     }
2980
2981     if (!strcmp(".", old_name.data) || !strcmp("..", old_name.data) ||
2982         !strcmp(".", new_name.data) || !strcmp("..", new_name.data)) {
2983         err = -EISDIR;
2984         goto out_err;
2985     }
2986
2987     v9fs_path_write_lock(s);
2988     err = v9fs_complete_renameat(pdu, olddirfid,
2989                                  &old_name, newdirfid, &new_name);
2990     v9fs_path_unlock(s);
2991     if (!err) {
2992         err = offset;
2993     }
2994
2995 out_err:
2996     pdu_complete(pdu, err);
2997     v9fs_string_free(&old_name);
2998     v9fs_string_free(&new_name);
2999 }
3000
3001 static void coroutine_fn v9fs_wstat(void *opaque)
3002 {
3003     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3004     int32_t fid;
3005     int err = 0;
3006     int16_t unused;
3007     V9fsStat v9stat;
3008     size_t offset = 7;
3009     struct stat stbuf;
3010     V9fsFidState *fidp;
3011     V9fsPDU *pdu = opaque;
3012
3013     v9fs_stat_init(&v9stat);
3014     err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat);
3015     if (err < 0) {
3016         goto out_nofid;
3017     }
3018     trace_v9fs_wstat(pdu->tag, pdu->id, fid,
3019                      v9stat.mode, v9stat.atime, v9stat.mtime);
3020
3021     fidp = get_fid(pdu, fid);
3022     if (fidp == NULL) {
3023         err = -EINVAL;
3024         goto out_nofid;
3025     }
3026     /* do we need to sync the file? */
3027     if (donttouch_stat(&v9stat)) {
3028         err = v9fs_co_fsync(pdu, fidp, 0);
3029         goto out;
3030     }
3031     if (v9stat.mode != -1) {
3032         uint32_t v9_mode;
3033         err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
3034         if (err < 0) {
3035             goto out;
3036         }
3037         v9_mode = stat_to_v9mode(&stbuf);
3038         if ((v9stat.mode & P9_STAT_MODE_TYPE_BITS) !=
3039             (v9_mode & P9_STAT_MODE_TYPE_BITS)) {
3040             /* Attempting to change the type */
3041             err = -EIO;
3042             goto out;
3043         }
3044 #ifndef CONFIG_WIN32
3045         err = v9fs_co_chmod(pdu, &fidp->path,
3046                             v9mode_to_mode(v9stat.mode,
3047                                            &v9stat.extension));
3048 #else
3049         err = -EPERM;
3050 #endif
3051         if (err < 0) {
3052             goto out;
3053         }
3054     }
3055     if (v9stat.mtime != -1 || v9stat.atime != -1) {
3056         struct timespec times[2];
3057         if (v9stat.atime != -1) {
3058             times[0].tv_sec = v9stat.atime;
3059             times[0].tv_nsec = 0;
3060         } else {
3061             times[0].tv_nsec = UTIME_OMIT;
3062         }
3063         if (v9stat.mtime != -1) {
3064             times[1].tv_sec = v9stat.mtime;
3065             times[1].tv_nsec = 0;
3066         } else {
3067             times[1].tv_nsec = UTIME_OMIT;
3068         }
3069         err = v9fs_co_utimensat(pdu, &fidp->path, times);
3070         if (err < 0) {
3071             goto out;
3072         }
3073     }
3074     if (v9stat.n_gid != -1 || v9stat.n_uid != -1) {
3075 #ifndef CONFIG_WIN32
3076         err = v9fs_co_chown(pdu, &fidp->path, v9stat.n_uid, v9stat.n_gid);
3077 #else
3078         err = -EPERM;
3079 #endif
3080         if (err < 0) {
3081             goto out;
3082         }
3083     }
3084     if (v9stat.name.size != 0) {
3085         err = v9fs_complete_rename(pdu, fidp, -1, &v9stat.name);
3086         if (err < 0) {
3087             goto out;
3088         }
3089     }
3090     if (v9stat.length != -1) {
3091         err = v9fs_co_truncate(pdu, &fidp->path, v9stat.length);
3092         if (err < 0) {
3093             goto out;
3094         }
3095     }
3096     err = offset;
3097 out:
3098     put_fid(pdu, fidp);
3099 out_nofid:
3100     v9fs_stat_free(&v9stat);
3101     pdu_complete(pdu, err);
3102 }
3103
3104 static int v9fs_fill_statfs(V9fsState *s, V9fsPDU *pdu, struct statfs *stbuf)
3105 {
3106     uint32_t f_type;
3107     uint32_t f_bsize;
3108     uint64_t f_blocks;
3109     uint64_t f_bfree;
3110     uint64_t f_bavail;
3111     uint64_t f_files;
3112     uint64_t f_ffree;
3113     uint64_t fsid_val;
3114     uint32_t f_namelen;
3115     size_t offset = 7;
3116     int32_t bsize_factor;
3117
3118     /*
3119      * compute bsize factor based on host file system block size
3120      * and client msize
3121      */
3122     bsize_factor = (s->msize - P9_IOHDRSZ)/stbuf->f_bsize;
3123     if (!bsize_factor) {
3124         bsize_factor = 1;
3125     }
3126     f_type  = stbuf->f_type;
3127     f_bsize = stbuf->f_bsize;
3128     f_bsize *= bsize_factor;
3129     /*
3130      * f_bsize is adjusted(multiplied) by bsize factor, so we need to
3131      * adjust(divide) the number of blocks, free blocks and available
3132      * blocks by bsize factor
3133      */
3134     f_blocks = stbuf->f_blocks/bsize_factor;
3135     f_bfree  = stbuf->f_bfree/bsize_factor;
3136     f_bavail = stbuf->f_bavail/bsize_factor;
3137     f_files  = stbuf->f_files;
3138     f_ffree  = stbuf->f_ffree;
3139 #ifdef CONFIG_LINUX
3140     fsid_val = (unsigned int) stbuf->f_fsid.__val[0] |
3141                (unsigned long long)stbuf->f_fsid.__val[1] << 32;
3142     f_namelen = stbuf->f_namelen;
3143 #else
3144     fsid_val = (unsigned int) stbuf->f_fsid.val[0] |
3145                (unsigned long long)stbuf->f_fsid.val[1] << 32;
3146     f_namelen = 255;
3147 #endif
3148
3149     return pdu_marshal(pdu, offset, "ddqqqqqqd",
3150                        f_type, f_bsize, f_blocks, f_bfree,
3151                        f_bavail, f_files, f_ffree,
3152                        fsid_val, f_namelen);
3153 }
3154
3155 static void coroutine_fn v9fs_statfs(void *opaque)
3156 {
3157     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3158     int32_t fid;
3159     ssize_t retval = 0;
3160     size_t offset = 7;
3161     V9fsFidState *fidp;
3162     struct statfs stbuf;
3163     V9fsPDU *pdu = opaque;
3164     V9fsState *s = pdu->s;
3165
3166     retval = pdu_unmarshal(pdu, offset, "d", &fid);
3167     if (retval < 0) {
3168         goto out_nofid;
3169     }
3170     fidp = get_fid(pdu, fid);
3171     if (fidp == NULL) {
3172         retval = -ENOENT;
3173         goto out_nofid;
3174     }
3175     retval = v9fs_co_statfs(pdu, &fidp->path, &stbuf);
3176     if (retval < 0) {
3177         goto out;
3178     }
3179     retval = v9fs_fill_statfs(s, pdu, &stbuf);
3180     if (retval < 0) {
3181         goto out;
3182     }
3183     retval += offset;
3184 out:
3185     put_fid(pdu, fidp);
3186 out_nofid:
3187     pdu_complete(pdu, retval);
3188 }
3189
3190 static void coroutine_fn v9fs_mknod(void *opaque)
3191 {
3192     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3193
3194     int mode;
3195     gid_t gid;
3196     int32_t fid;
3197     V9fsQID qid;
3198     int err = 0;
3199     int major, minor;
3200     size_t offset = 7;
3201     V9fsString name;
3202     struct stat stbuf;
3203     V9fsFidState *fidp;
3204     V9fsPDU *pdu = opaque;
3205
3206     v9fs_string_init(&name);
3207     err = pdu_unmarshal(pdu, offset, "dsdddd", &fid, &name, &mode,
3208                         &major, &minor, &gid);
3209     if (err < 0) {
3210         goto out_nofid;
3211     }
3212     trace_v9fs_mknod(pdu->tag, pdu->id, fid, mode, major, minor);
3213
3214     if (name_is_illegal(name.data)) {
3215         err = -ENOENT;
3216         goto out_nofid;
3217     }
3218
3219     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
3220         err = -EEXIST;
3221         goto out_nofid;
3222     }
3223
3224     fidp = get_fid(pdu, fid);
3225     if (fidp == NULL) {
3226         err = -ENOENT;
3227         goto out_nofid;
3228     }
3229 #ifndef CONFIG_WIN32
3230     err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, gid,
3231                         makedev(major, minor), mode, &stbuf);
3232 #else
3233     err = -EPERM;
3234 #endif
3235     if (err < 0) {
3236         goto out;
3237     }
3238     stat_to_qid(&stbuf, &qid);
3239     err = pdu_marshal(pdu, offset, "Q", &qid);
3240     if (err < 0) {
3241         goto out;
3242     }
3243     err += offset;
3244     trace_v9fs_mknod_return(pdu->tag, pdu->id,
3245                             qid.type, qid.version, qid.path);
3246 out:
3247     put_fid(pdu, fidp);
3248 out_nofid:
3249     pdu_complete(pdu, err);
3250     v9fs_string_free(&name);
3251 }
3252
3253 /*
3254  * Implement posix byte range locking code
3255  * Server side handling of locking code is very simple, because 9p server in
3256  * QEMU can handle only one client. And most of the lock handling
3257  * (like conflict, merging) etc is done by the VFS layer itself, so no need to
3258  * do any thing in * qemu 9p server side lock code path.
3259  * So when a TLOCK request comes, always return success
3260  */
3261 static void coroutine_fn v9fs_lock(void *opaque)
3262 {
3263     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3264     int8_t status;
3265     V9fsFlock flock;
3266     size_t offset = 7;
3267     struct stat stbuf;
3268     V9fsFidState *fidp;
3269     int32_t fid, err = 0;
3270     V9fsPDU *pdu = opaque;
3271
3272     status = P9_LOCK_ERROR;
3273     v9fs_string_init(&flock.client_id);
3274     err = pdu_unmarshal(pdu, offset, "dbdqqds", &fid, &flock.type,
3275                         &flock.flags, &flock.start, &flock.length,
3276                         &flock.proc_id, &flock.client_id);
3277     if (err < 0) {
3278         goto out_nofid;
3279     }
3280     trace_v9fs_lock(pdu->tag, pdu->id, fid,
3281                     flock.type, flock.start, flock.length);
3282
3283
3284     /* We support only block flag now (that too ignored currently) */
3285     if (flock.flags & ~P9_LOCK_FLAGS_BLOCK) {
3286         err = -EINVAL;
3287         goto out_nofid;
3288     }
3289     fidp = get_fid(pdu, fid);
3290     if (fidp == NULL) {
3291         err = -ENOENT;
3292         goto out_nofid;
3293     }
3294     err = v9fs_co_fstat(pdu, fidp, &stbuf);
3295     if (err < 0) {
3296         goto out;
3297     }
3298     status = P9_LOCK_SUCCESS;
3299 out:
3300     put_fid(pdu, fidp);
3301 out_nofid:
3302     err = pdu_marshal(pdu, offset, "b", status);
3303     if (err > 0) {
3304         err += offset;
3305     }
3306     trace_v9fs_lock_return(pdu->tag, pdu->id, status);
3307     pdu_complete(pdu, err);
3308     v9fs_string_free(&flock.client_id);
3309 }
3310
3311 /*
3312  * When a TGETLOCK request comes, always return success because all lock
3313  * handling is done by client's VFS layer.
3314  */
3315 static void coroutine_fn v9fs_getlock(void *opaque)
3316 {
3317     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3318     size_t offset = 7;
3319     struct stat stbuf;
3320     V9fsFidState *fidp;
3321     V9fsGetlock glock;
3322     int32_t fid, err = 0;
3323     V9fsPDU *pdu = opaque;
3324
3325     v9fs_string_init(&glock.client_id);
3326     err = pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock.type,
3327                         &glock.start, &glock.length, &glock.proc_id,
3328                         &glock.client_id);
3329     if (err < 0) {
3330         goto out_nofid;
3331     }
3332     trace_v9fs_getlock(pdu->tag, pdu->id, fid,
3333                        glock.type, glock.start, glock.length);
3334
3335     fidp = get_fid(pdu, fid);
3336     if (fidp == NULL) {
3337         err = -ENOENT;
3338         goto out_nofid;
3339     }
3340     err = v9fs_co_fstat(pdu, fidp, &stbuf);
3341     if (err < 0) {
3342         goto out;
3343     }
3344     glock.type = P9_LOCK_TYPE_UNLCK;
3345     err = pdu_marshal(pdu, offset, "bqqds", glock.type,
3346                           glock.start, glock.length, glock.proc_id,
3347                           &glock.client_id);
3348     if (err < 0) {
3349         goto out;
3350     }
3351     err += offset;
3352     trace_v9fs_getlock_return(pdu->tag, pdu->id, glock.type, glock.start,
3353                               glock.length, glock.proc_id);
3354 out:
3355     put_fid(pdu, fidp);
3356 out_nofid:
3357     pdu_complete(pdu, err);
3358     v9fs_string_free(&glock.client_id);
3359 }
3360
3361 static void coroutine_fn v9fs_mkdir(void *opaque)
3362 {
3363     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3364     V9fsPDU *pdu = opaque;
3365     size_t offset = 7;
3366     int32_t fid;
3367     struct stat stbuf;
3368     V9fsQID qid;
3369     V9fsString name;
3370     V9fsFidState *fidp;
3371     gid_t gid;
3372     int mode;
3373     int err = 0;
3374
3375     v9fs_string_init(&name);
3376     err = pdu_unmarshal(pdu, offset, "dsdd", &fid, &name, &mode, &gid);
3377     if (err < 0) {
3378         goto out_nofid;
3379     }
3380     trace_v9fs_mkdir(pdu->tag, pdu->id, fid, name.data, mode, gid);
3381
3382     if (name_is_illegal(name.data)) {
3383         err = -ENOENT;
3384         goto out_nofid;
3385     }
3386
3387     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
3388         err = -EEXIST;
3389         goto out_nofid;
3390     }
3391
3392     fidp = get_fid(pdu, fid);
3393     if (fidp == NULL) {
3394         err = -ENOENT;
3395         goto out_nofid;
3396     }
3397     err = v9fs_co_mkdir(pdu, fidp, &name, mode, fidp->uid, gid, &stbuf);
3398     if (err < 0) {
3399         goto out;
3400     }
3401     stat_to_qid(&stbuf, &qid);
3402     err = pdu_marshal(pdu, offset, "Q", &qid);
3403     if (err < 0) {
3404         goto out;
3405     }
3406     err += offset;
3407     trace_v9fs_mkdir_return(pdu->tag, pdu->id,
3408                             qid.type, qid.version, qid.path, err);
3409 out:
3410     put_fid(pdu, fidp);
3411 out_nofid:
3412     pdu_complete(pdu, err);
3413     v9fs_string_free(&name);
3414 }
3415
3416 #ifndef CONFIG_WIN32
3417 static void coroutine_fn v9fs_xattrwalk(void *opaque)
3418 {
3419     int64_t size;
3420     V9fsString name;
3421     ssize_t err = 0;
3422     size_t offset = 7;
3423     int32_t fid, newfid;
3424     V9fsFidState *file_fidp;
3425     V9fsFidState *xattr_fidp = NULL;
3426     V9fsPDU *pdu = opaque;
3427     V9fsState *s = pdu->s;
3428
3429     v9fs_string_init(&name);
3430     err = pdu_unmarshal(pdu, offset, "dds", &fid, &newfid, &name);
3431     if (err < 0) {
3432         goto out_nofid;
3433     }
3434     trace_v9fs_xattrwalk(pdu->tag, pdu->id, fid, newfid, name.data);
3435
3436     file_fidp = get_fid(pdu, fid);
3437     if (file_fidp == NULL) {
3438         err = -ENOENT;
3439         goto out_nofid;
3440     }
3441     xattr_fidp = alloc_fid(s, newfid);
3442     if (xattr_fidp == NULL) {
3443         err = -EINVAL;
3444         goto out;
3445     }
3446     v9fs_path_copy(&xattr_fidp->path, &file_fidp->path);
3447     if (!v9fs_string_size(&name)) {
3448         /*
3449          * listxattr request. Get the size first
3450          */
3451         size = v9fs_co_llistxattr(pdu, &xattr_fidp->path, NULL, 0);
3452         if (size < 0) {
3453             err = size;
3454             clunk_fid(s, xattr_fidp->fid);
3455             goto out;
3456         }
3457         /*
3458          * Read the xattr value
3459          */
3460         xattr_fidp->fs.xattr.len = size;
3461         xattr_fidp->fid_type = P9_FID_XATTR;
3462         xattr_fidp->fs.xattr.xattrwalk_fid = true;
3463         if (size) {
3464             xattr_fidp->fs.xattr.value = g_malloc(size);
3465             err = v9fs_co_llistxattr(pdu, &xattr_fidp->path,
3466                                      xattr_fidp->fs.xattr.value,
3467                                      xattr_fidp->fs.xattr.len);
3468             if (err < 0) {
3469                 clunk_fid(s, xattr_fidp->fid);
3470                 goto out;
3471             }
3472         }
3473         err = pdu_marshal(pdu, offset, "q", size);
3474         if (err < 0) {
3475             goto out;
3476         }
3477         err += offset;
3478     } else {
3479         /*
3480          * specific xattr fid. We check for xattr
3481          * presence also collect the xattr size
3482          */
3483         size = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
3484                                  &name, NULL, 0);
3485         if (size < 0) {
3486             err = size;
3487             clunk_fid(s, xattr_fidp->fid);
3488             goto out;
3489         }
3490         /*
3491          * Read the xattr value
3492          */
3493         xattr_fidp->fs.xattr.len = size;
3494         xattr_fidp->fid_type = P9_FID_XATTR;
3495         xattr_fidp->fs.xattr.xattrwalk_fid = true;
3496         if (size) {
3497             xattr_fidp->fs.xattr.value = g_malloc(size);
3498             err = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
3499                                     &name, xattr_fidp->fs.xattr.value,
3500                                     xattr_fidp->fs.xattr.len);
3501             if (err < 0) {
3502                 clunk_fid(s, xattr_fidp->fid);
3503                 goto out;
3504             }
3505         }
3506         err = pdu_marshal(pdu, offset, "q", size);
3507         if (err < 0) {
3508             goto out;
3509         }
3510         err += offset;
3511     }
3512     trace_v9fs_xattrwalk_return(pdu->tag, pdu->id, size);
3513 out:
3514     put_fid(pdu, file_fidp);
3515     if (xattr_fidp) {
3516         put_fid(pdu, xattr_fidp);
3517     }
3518 out_nofid:
3519     pdu_complete(pdu, err);
3520     v9fs_string_free(&name);
3521 }
3522
3523 static void coroutine_fn v9fs_xattrcreate(void *opaque)
3524 {
3525     int flags;
3526     int32_t fid;
3527     uint64_t size;
3528     ssize_t err = 0;
3529     V9fsString name;
3530     size_t offset = 7;
3531     V9fsFidState *file_fidp;
3532     V9fsFidState *xattr_fidp;
3533     V9fsPDU *pdu = opaque;
3534
3535     v9fs_string_init(&name);
3536     err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
3537     if (err < 0) {
3538         goto out_nofid;
3539     }
3540     trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
3541
3542     if (size > XATTR_SIZE_MAX) {
3543         err = -E2BIG;
3544         goto out_nofid;
3545     }
3546
3547     file_fidp = get_fid(pdu, fid);
3548     if (file_fidp == NULL) {
3549         err = -EINVAL;
3550         goto out_nofid;
3551     }
3552     if (file_fidp->fid_type != P9_FID_NONE) {
3553         err = -EINVAL;
3554         goto out_put_fid;
3555     }
3556
3557     /* Make the file fid point to xattr */
3558     xattr_fidp = file_fidp;
3559     xattr_fidp->fid_type = P9_FID_XATTR;
3560     xattr_fidp->fs.xattr.copied_len = 0;
3561     xattr_fidp->fs.xattr.xattrwalk_fid = false;
3562     xattr_fidp->fs.xattr.len = size;
3563     xattr_fidp->fs.xattr.flags = flags;
3564     v9fs_string_init(&xattr_fidp->fs.xattr.name);
3565     v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
3566     xattr_fidp->fs.xattr.value = g_malloc0(size);
3567     err = offset;
3568 out_put_fid:
3569     put_fid(pdu, file_fidp);
3570 out_nofid:
3571     pdu_complete(pdu, err);
3572     v9fs_string_free(&name);
3573 }
3574 #endif
3575
3576 static void coroutine_fn v9fs_readlink(void *opaque)
3577 {
3578     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3579     V9fsPDU *pdu = opaque;
3580     size_t offset = 7;
3581     V9fsString target;
3582     int32_t fid;
3583     int err = 0;
3584     V9fsFidState *fidp;
3585
3586     err = pdu_unmarshal(pdu, offset, "d", &fid);
3587     if (err < 0) {
3588         goto out_nofid;
3589     }
3590     trace_v9fs_readlink(pdu->tag, pdu->id, fid);
3591     fidp = get_fid(pdu, fid);
3592     if (fidp == NULL) {
3593         err = -ENOENT;
3594         goto out_nofid;
3595     }
3596
3597     v9fs_string_init(&target);
3598     err = v9fs_co_readlink(pdu, &fidp->path, &target);
3599     if (err < 0) {
3600         goto out;
3601     }
3602     err = pdu_marshal(pdu, offset, "s", &target);
3603     if (err < 0) {
3604         v9fs_string_free(&target);
3605         goto out;
3606     }
3607     err += offset;
3608     trace_v9fs_readlink_return(pdu->tag, pdu->id, target.data);
3609     v9fs_string_free(&target);
3610 out:
3611     put_fid(pdu, fidp);
3612 out_nofid:
3613     pdu_complete(pdu, err);
3614 }
3615
3616 static CoroutineEntry *pdu_co_handlers[] = {
3617     [P9_TREADDIR] = v9fs_readdir,
3618     [P9_TSTATFS] = v9fs_statfs,
3619     [P9_TGETATTR] = v9fs_getattr,
3620     [P9_TSETATTR] = v9fs_setattr,
3621 #ifndef CONFIG_WIN32
3622     [P9_TXATTRWALK] = v9fs_xattrwalk,
3623     [P9_TXATTRCREATE] = v9fs_xattrcreate,
3624 #endif
3625     [P9_TMKNOD] = v9fs_mknod,
3626     [P9_TRENAME] = v9fs_rename,
3627     [P9_TLOCK] = v9fs_lock,
3628     [P9_TGETLOCK] = v9fs_getlock,
3629     [P9_TRENAMEAT] = v9fs_renameat,
3630     [P9_TREADLINK] = v9fs_readlink,
3631     [P9_TUNLINKAT] = v9fs_unlinkat,
3632     [P9_TMKDIR] = v9fs_mkdir,
3633     [P9_TVERSION] = v9fs_version,
3634     [P9_TLOPEN] = v9fs_open,
3635     [P9_TATTACH] = v9fs_attach,
3636     [P9_TSTAT] = v9fs_stat,
3637     [P9_TWALK] = v9fs_walk,
3638     [P9_TCLUNK] = v9fs_clunk,
3639     [P9_TFSYNC] = v9fs_fsync,
3640     [P9_TOPEN] = v9fs_open,
3641     [P9_TREAD] = v9fs_read,
3642 #if 0
3643     [P9_TAUTH] = v9fs_auth,
3644 #endif
3645     [P9_TFLUSH] = v9fs_flush,
3646     [P9_TLINK] = v9fs_link,
3647     [P9_TSYMLINK] = v9fs_symlink,
3648     [P9_TCREATE] = v9fs_create,
3649     [P9_TLCREATE] = v9fs_lcreate,
3650     [P9_TWRITE] = v9fs_write,
3651     [P9_TWSTAT] = v9fs_wstat,
3652     [P9_TREMOVE] = v9fs_remove,
3653 };
3654
3655 static void coroutine_fn v9fs_op_not_supp(void *opaque)
3656 {
3657     WARN("[%d][%s] >> This operation is not supported.\n", __LINE__, __func__);
3658     V9fsPDU *pdu = opaque;
3659     pdu_complete(pdu, -EOPNOTSUPP);
3660 }
3661
3662 static void coroutine_fn v9fs_fs_ro(void *opaque)
3663 {
3664     WARN("[%d][%s] >> This is the read-only operation.\n", __LINE__, __func__);
3665     V9fsPDU *pdu = opaque;
3666     pdu_complete(pdu, -EROFS);
3667 }
3668
3669 static inline bool is_read_only_op(V9fsPDU *pdu)
3670 {
3671     switch (pdu->id) {
3672     case P9_TREADDIR:
3673     case P9_TSTATFS:
3674     case P9_TGETATTR:
3675     case P9_TXATTRWALK:
3676     case P9_TLOCK:
3677     case P9_TGETLOCK:
3678     case P9_TREADLINK:
3679     case P9_TVERSION:
3680     case P9_TLOPEN:
3681     case P9_TATTACH:
3682     case P9_TSTAT:
3683     case P9_TWALK:
3684     case P9_TCLUNK:
3685     case P9_TFSYNC:
3686     case P9_TOPEN:
3687     case P9_TREAD:
3688     case P9_TAUTH:
3689     case P9_TFLUSH:
3690         return 1;
3691     default:
3692         return 0;
3693     }
3694 }
3695
3696 void pdu_submit(V9fsPDU *pdu)
3697 {
3698     Coroutine *co;
3699     CoroutineEntry *handler;
3700     V9fsState *s = pdu->s;
3701
3702     if (pdu->id >= ARRAY_SIZE(pdu_co_handlers) ||
3703         (pdu_co_handlers[pdu->id] == NULL)) {
3704         handler = v9fs_op_not_supp;
3705     } else {
3706         handler = pdu_co_handlers[pdu->id];
3707     }
3708
3709     if (is_ro_export(&s->ctx) && !is_read_only_op(pdu)) {
3710         handler = v9fs_fs_ro;
3711     }
3712     co = qemu_coroutine_create(handler, pdu);
3713     qemu_coroutine_enter(co);
3714 }
3715
3716 /* Returns 0 on success, 1 on failure. */
3717 int v9fs_device_realize_common(V9fsState *s, Error **errp)
3718 {
3719     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3720     V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);
3721     int i, len;
3722     struct stat stat;
3723     FsDriverEntry *fse;
3724     V9fsPath path;
3725     int rc = 1;
3726
3727     /* initialize pdu allocator */
3728     QLIST_INIT(&s->free_list);
3729     QLIST_INIT(&s->active_list);
3730     for (i = 0; i < (MAX_REQ - 1); i++) {
3731         QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next);
3732         v->pdus[i].s = s;
3733         v->pdus[i].idx = i;
3734     }
3735
3736     v9fs_path_init(&path);
3737
3738     fse = get_fsdev_fsentry(s->fsconf.fsdev_id);
3739
3740     if (!fse) {
3741         /* We don't have a fsdev identified by fsdev_id */
3742         error_setg(errp, "9pfs device couldn't find fsdev with the "
3743                    "id = %s",
3744                    s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL");
3745         goto out;
3746     }
3747
3748     if (!s->fsconf.tag) {
3749         /* we haven't specified a mount_tag */
3750         error_setg(errp, "fsdev with id %s needs mount_tag arguments",
3751                    s->fsconf.fsdev_id);
3752         goto out;
3753     }
3754
3755     s->ctx.export_flags = fse->export_flags;
3756     s->ctx.fs_root = g_strdup(fse->path);
3757     s->ctx.exops.get_st_gen = NULL;
3758     len = strlen(s->fsconf.tag);
3759     if (len > MAX_TAG_LEN - 1) {
3760         error_setg(errp, "mount tag '%s' (%d bytes) is longer than "
3761                    "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1);
3762         goto out;
3763     }
3764
3765     s->tag = g_strdup(s->fsconf.tag);
3766     s->ctx.uid = -1;
3767
3768     s->ops = fse->ops;
3769
3770     s->fid_list = NULL;
3771     qemu_co_rwlock_init(&s->rename_lock);
3772
3773     if (s->ops->init(&s->ctx) < 0) {
3774         error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s"
3775                    " and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root);
3776         goto out;
3777     }
3778
3779     /*
3780      * Check details of export path, We need to use fs driver
3781      * call back to do that. Since we are in the init path, we don't
3782      * use co-routines here.
3783      */
3784 #ifndef CONFIG_WIN32
3785     if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) {
3786 #else
3787     if (s->ops->name_to_path(&s->ctx, NULL, "\\", &path) < 0) {
3788 #endif
3789         error_setg(errp,
3790                    "error in converting name to path %s", strerror(errno));
3791         goto out;
3792     }
3793     if (s->ops->lstat(&s->ctx, &path, &stat)) {
3794         error_setg(errp, "share path %s does not exist", fse->path);
3795         goto out;
3796     } else if (!S_ISDIR(stat.st_mode)) {
3797         error_setg(errp, "share path %s is not a directory", fse->path);
3798         goto out;
3799     }
3800     v9fs_path_free(&path);
3801
3802     rc = 0;
3803 out:
3804     if (rc) {
3805         if (s->ops->cleanup && s->ctx.private) {
3806             s->ops->cleanup(&s->ctx);
3807         }
3808         g_free(s->tag);
3809         g_free(s->ctx.fs_root);
3810         v9fs_path_free(&path);
3811     }
3812     return rc;
3813 }
3814
3815 void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
3816 {
3817     TRACE("[%d][ Enter >> %s]\n", __LINE__, __func__);
3818     if (s->ops->cleanup) {
3819         s->ops->cleanup(&s->ctx);
3820     }
3821     g_free(s->tag);
3822     g_free(s->ctx.fs_root);
3823 }
3824
3825 typedef struct VirtfsCoResetData {
3826     V9fsPDU pdu;
3827     bool done;
3828 } VirtfsCoResetData;
3829
3830 static void coroutine_fn virtfs_co_reset(void *opaque)
3831 {
3832     VirtfsCoResetData *data = opaque;
3833
3834     virtfs_reset(&data->pdu);
3835     data->done = true;
3836 }
3837
3838 void v9fs_reset(V9fsState *s)
3839 {
3840     VirtfsCoResetData data = { .pdu = { .s = s }, .done = false };
3841     Coroutine *co;
3842
3843     while (!QLIST_EMPTY(&s->active_list)) {
3844         aio_poll(qemu_get_aio_context(), true);
3845     }
3846
3847     co = qemu_coroutine_create(virtfs_co_reset, &data);
3848     qemu_coroutine_enter(co);
3849
3850     while (!data.done) {
3851         aio_poll(qemu_get_aio_context(), true);
3852     }
3853 }
3854
3855 static void __attribute__((__constructor__)) v9fs_set_fd_limit(void)
3856 {
3857 #ifndef CONFIG_WIN32
3858     struct rlimit rlim;
3859     if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
3860         error_report("Failed to get the resource limit");
3861         exit(1);
3862     }
3863     open_fd_hw = rlim.rlim_cur - MIN(400, rlim.rlim_cur/3);
3864     open_fd_rc = rlim.rlim_cur/2;
3865 #else
3866     open_fd_hw = 3696; // 4096 - 400
3867     open_fd_rc = 2048; // 4096 / 2
3868 #endif
3869 }