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