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