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