xref: /openbmc/qemu/hw/9pfs/9p.c (revision 5a894dd7)
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(s->proto_version, &f->fs.dir);
318     v9fs_readdir_init(s->proto_version, &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 V9fsPDU *pdu_alloc(V9fsState *s)
976 {
977     V9fsPDU *pdu = NULL;
978 
979     if (!QLIST_EMPTY(&s->free_list)) {
980         pdu = QLIST_FIRST(&s->free_list);
981         QLIST_REMOVE(pdu, next);
982         QLIST_INSERT_HEAD(&s->active_list, pdu, next);
983     }
984     return pdu;
985 }
986 
987 void pdu_free(V9fsPDU *pdu)
988 {
989     V9fsState *s = pdu->s;
990 
991     g_assert(!pdu->cancelled);
992     QLIST_REMOVE(pdu, next);
993     QLIST_INSERT_HEAD(&s->free_list, pdu, next);
994 }
995 
996 static void coroutine_fn pdu_complete(V9fsPDU *pdu, ssize_t len)
997 {
998     int8_t id = pdu->id + 1; /* Response */
999     V9fsState *s = pdu->s;
1000     int ret;
1001 
1002     /*
1003      * The 9p spec requires that successfully cancelled pdus receive no reply.
1004      * Sending a reply would confuse clients because they would
1005      * assume that any EINTR is the actual result of the operation,
1006      * rather than a consequence of the cancellation. However, if
1007      * the operation completed (succesfully or with an error other
1008      * than caused be cancellation), we do send out that reply, both
1009      * for efficiency and to avoid confusing the rest of the state machine
1010      * that assumes passing a non-error here will mean a successful
1011      * transmission of the reply.
1012      */
1013     bool discard = pdu->cancelled && len == -EINTR;
1014     if (discard) {
1015         trace_v9fs_rcancel(pdu->tag, pdu->id);
1016         pdu->size = 0;
1017         goto out_notify;
1018     }
1019 
1020     if (len < 0) {
1021         int err = -len;
1022         len = 7;
1023 
1024         if (s->proto_version != V9FS_PROTO_2000L) {
1025             V9fsString str;
1026 
1027             str.data = strerror(err);
1028             str.size = strlen(str.data);
1029 
1030             ret = pdu_marshal(pdu, len, "s", &str);
1031             if (ret < 0) {
1032                 goto out_notify;
1033             }
1034             len += ret;
1035             id = P9_RERROR;
1036         }
1037 
1038         ret = pdu_marshal(pdu, len, "d", err);
1039         if (ret < 0) {
1040             goto out_notify;
1041         }
1042         len += ret;
1043 
1044         if (s->proto_version == V9FS_PROTO_2000L) {
1045             id = P9_RLERROR;
1046         }
1047         trace_v9fs_rerror(pdu->tag, pdu->id, err); /* Trace ERROR */
1048     }
1049 
1050     /* fill out the header */
1051     if (pdu_marshal(pdu, 0, "dbw", (int32_t)len, id, pdu->tag) < 0) {
1052         goto out_notify;
1053     }
1054 
1055     /* keep these in sync */
1056     pdu->size = len;
1057     pdu->id = id;
1058 
1059 out_notify:
1060     pdu->s->transport->push_and_notify(pdu);
1061 
1062     /* Now wakeup anybody waiting in flush for this request */
1063     if (!qemu_co_queue_next(&pdu->complete)) {
1064         pdu_free(pdu);
1065     }
1066 }
1067 
1068 static mode_t v9mode_to_mode(uint32_t mode, V9fsString *extension)
1069 {
1070     mode_t ret;
1071 
1072     ret = mode & 0777;
1073     if (mode & P9_STAT_MODE_DIR) {
1074         ret |= S_IFDIR;
1075     }
1076 
1077     if (mode & P9_STAT_MODE_SYMLINK) {
1078         ret |= S_IFLNK;
1079     }
1080     if (mode & P9_STAT_MODE_SOCKET) {
1081         ret |= S_IFSOCK;
1082     }
1083     if (mode & P9_STAT_MODE_NAMED_PIPE) {
1084         ret |= S_IFIFO;
1085     }
1086     if (mode & P9_STAT_MODE_DEVICE) {
1087         if (extension->size && extension->data[0] == 'c') {
1088             ret |= S_IFCHR;
1089         } else {
1090             ret |= S_IFBLK;
1091         }
1092     }
1093 
1094     if (!(ret&~0777)) {
1095         ret |= S_IFREG;
1096     }
1097 
1098     if (mode & P9_STAT_MODE_SETUID) {
1099         ret |= S_ISUID;
1100     }
1101     if (mode & P9_STAT_MODE_SETGID) {
1102         ret |= S_ISGID;
1103     }
1104     if (mode & P9_STAT_MODE_SETVTX) {
1105         ret |= S_ISVTX;
1106     }
1107 
1108     return ret;
1109 }
1110 
1111 static int donttouch_stat(V9fsStat *stat)
1112 {
1113     if (stat->type == -1 &&
1114         stat->dev == -1 &&
1115         stat->qid.type == 0xff &&
1116         stat->qid.version == (uint32_t) -1 &&
1117         stat->qid.path == (uint64_t) -1 &&
1118         stat->mode == -1 &&
1119         stat->atime == -1 &&
1120         stat->mtime == -1 &&
1121         stat->length == -1 &&
1122         !stat->name.size &&
1123         !stat->uid.size &&
1124         !stat->gid.size &&
1125         !stat->muid.size &&
1126         stat->n_uid == -1 &&
1127         stat->n_gid == -1 &&
1128         stat->n_muid == -1) {
1129         return 1;
1130     }
1131 
1132     return 0;
1133 }
1134 
1135 static void v9fs_stat_init(V9fsStat *stat)
1136 {
1137     v9fs_string_init(&stat->name);
1138     v9fs_string_init(&stat->uid);
1139     v9fs_string_init(&stat->gid);
1140     v9fs_string_init(&stat->muid);
1141     v9fs_string_init(&stat->extension);
1142 }
1143 
1144 static void v9fs_stat_free(V9fsStat *stat)
1145 {
1146     v9fs_string_free(&stat->name);
1147     v9fs_string_free(&stat->uid);
1148     v9fs_string_free(&stat->gid);
1149     v9fs_string_free(&stat->muid);
1150     v9fs_string_free(&stat->extension);
1151 }
1152 
1153 static uint32_t stat_to_v9mode(const struct stat *stbuf)
1154 {
1155     uint32_t mode;
1156 
1157     mode = stbuf->st_mode & 0777;
1158     if (S_ISDIR(stbuf->st_mode)) {
1159         mode |= P9_STAT_MODE_DIR;
1160     }
1161 
1162     if (S_ISLNK(stbuf->st_mode)) {
1163         mode |= P9_STAT_MODE_SYMLINK;
1164     }
1165 
1166     if (S_ISSOCK(stbuf->st_mode)) {
1167         mode |= P9_STAT_MODE_SOCKET;
1168     }
1169 
1170     if (S_ISFIFO(stbuf->st_mode)) {
1171         mode |= P9_STAT_MODE_NAMED_PIPE;
1172     }
1173 
1174     if (S_ISBLK(stbuf->st_mode) || S_ISCHR(stbuf->st_mode)) {
1175         mode |= P9_STAT_MODE_DEVICE;
1176     }
1177 
1178     if (stbuf->st_mode & S_ISUID) {
1179         mode |= P9_STAT_MODE_SETUID;
1180     }
1181 
1182     if (stbuf->st_mode & S_ISGID) {
1183         mode |= P9_STAT_MODE_SETGID;
1184     }
1185 
1186     if (stbuf->st_mode & S_ISVTX) {
1187         mode |= P9_STAT_MODE_SETVTX;
1188     }
1189 
1190     return mode;
1191 }
1192 
1193 static int coroutine_fn stat_to_v9stat(V9fsPDU *pdu, V9fsPath *path,
1194                                        const char *basename,
1195                                        const struct stat *stbuf,
1196                                        V9fsStat *v9stat)
1197 {
1198     int err;
1199 
1200     memset(v9stat, 0, sizeof(*v9stat));
1201 
1202     err = stat_to_qid(pdu, stbuf, &v9stat->qid);
1203     if (err < 0) {
1204         return err;
1205     }
1206     v9stat->mode = stat_to_v9mode(stbuf);
1207     v9stat->atime = stbuf->st_atime;
1208     v9stat->mtime = stbuf->st_mtime;
1209     v9stat->length = stbuf->st_size;
1210 
1211     v9fs_string_free(&v9stat->uid);
1212     v9fs_string_free(&v9stat->gid);
1213     v9fs_string_free(&v9stat->muid);
1214 
1215     v9stat->n_uid = stbuf->st_uid;
1216     v9stat->n_gid = stbuf->st_gid;
1217     v9stat->n_muid = 0;
1218 
1219     v9fs_string_free(&v9stat->extension);
1220 
1221     if (v9stat->mode & P9_STAT_MODE_SYMLINK) {
1222         err = v9fs_co_readlink(pdu, path, &v9stat->extension);
1223         if (err < 0) {
1224             return err;
1225         }
1226     } else if (v9stat->mode & P9_STAT_MODE_DEVICE) {
1227         v9fs_string_sprintf(&v9stat->extension, "%c %u %u",
1228                 S_ISCHR(stbuf->st_mode) ? 'c' : 'b',
1229                 major(stbuf->st_rdev), minor(stbuf->st_rdev));
1230     } else if (S_ISDIR(stbuf->st_mode) || S_ISREG(stbuf->st_mode)) {
1231         v9fs_string_sprintf(&v9stat->extension, "%s %lu",
1232                 "HARDLINKCOUNT", (unsigned long)stbuf->st_nlink);
1233     }
1234 
1235     v9fs_string_sprintf(&v9stat->name, "%s", basename);
1236 
1237     v9stat->size = 61 +
1238         v9fs_string_size(&v9stat->name) +
1239         v9fs_string_size(&v9stat->uid) +
1240         v9fs_string_size(&v9stat->gid) +
1241         v9fs_string_size(&v9stat->muid) +
1242         v9fs_string_size(&v9stat->extension);
1243     return 0;
1244 }
1245 
1246 #define P9_STATS_MODE          0x00000001ULL
1247 #define P9_STATS_NLINK         0x00000002ULL
1248 #define P9_STATS_UID           0x00000004ULL
1249 #define P9_STATS_GID           0x00000008ULL
1250 #define P9_STATS_RDEV          0x00000010ULL
1251 #define P9_STATS_ATIME         0x00000020ULL
1252 #define P9_STATS_MTIME         0x00000040ULL
1253 #define P9_STATS_CTIME         0x00000080ULL
1254 #define P9_STATS_INO           0x00000100ULL
1255 #define P9_STATS_SIZE          0x00000200ULL
1256 #define P9_STATS_BLOCKS        0x00000400ULL
1257 
1258 #define P9_STATS_BTIME         0x00000800ULL
1259 #define P9_STATS_GEN           0x00001000ULL
1260 #define P9_STATS_DATA_VERSION  0x00002000ULL
1261 
1262 #define P9_STATS_BASIC         0x000007ffULL /* Mask for fields up to BLOCKS */
1263 #define P9_STATS_ALL           0x00003fffULL /* Mask for All fields above */
1264 
1265 
1266 static int stat_to_v9stat_dotl(V9fsPDU *pdu, const struct stat *stbuf,
1267                                 V9fsStatDotl *v9lstat)
1268 {
1269     memset(v9lstat, 0, sizeof(*v9lstat));
1270 
1271     v9lstat->st_mode = stbuf->st_mode;
1272     v9lstat->st_nlink = stbuf->st_nlink;
1273     v9lstat->st_uid = stbuf->st_uid;
1274     v9lstat->st_gid = stbuf->st_gid;
1275     v9lstat->st_rdev = stbuf->st_rdev;
1276     v9lstat->st_size = stbuf->st_size;
1277     v9lstat->st_blksize = stbuf->st_blksize;
1278     v9lstat->st_blocks = stbuf->st_blocks;
1279     v9lstat->st_atime_sec = stbuf->st_atime;
1280     v9lstat->st_atime_nsec = stbuf->st_atim.tv_nsec;
1281     v9lstat->st_mtime_sec = stbuf->st_mtime;
1282     v9lstat->st_mtime_nsec = stbuf->st_mtim.tv_nsec;
1283     v9lstat->st_ctime_sec = stbuf->st_ctime;
1284     v9lstat->st_ctime_nsec = stbuf->st_ctim.tv_nsec;
1285     /* Currently we only support BASIC fields in stat */
1286     v9lstat->st_result_mask = P9_STATS_BASIC;
1287 
1288     return stat_to_qid(pdu, stbuf, &v9lstat->qid);
1289 }
1290 
1291 static void print_sg(struct iovec *sg, int cnt)
1292 {
1293     int i;
1294 
1295     printf("sg[%d]: {", cnt);
1296     for (i = 0; i < cnt; i++) {
1297         if (i) {
1298             printf(", ");
1299         }
1300         printf("(%p, %zd)", sg[i].iov_base, sg[i].iov_len);
1301     }
1302     printf("}\n");
1303 }
1304 
1305 /* Will call this only for path name based fid */
1306 static void v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len)
1307 {
1308     V9fsPath str;
1309     v9fs_path_init(&str);
1310     v9fs_path_copy(&str, dst);
1311     v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len);
1312     v9fs_path_free(&str);
1313 }
1314 
1315 static inline bool is_ro_export(FsContext *ctx)
1316 {
1317     return ctx->export_flags & V9FS_RDONLY;
1318 }
1319 
1320 static void coroutine_fn v9fs_version(void *opaque)
1321 {
1322     ssize_t err;
1323     V9fsPDU *pdu = opaque;
1324     V9fsState *s = pdu->s;
1325     V9fsString version;
1326     size_t offset = 7;
1327 
1328     v9fs_string_init(&version);
1329     err = pdu_unmarshal(pdu, offset, "ds", &s->msize, &version);
1330     if (err < 0) {
1331         goto out;
1332     }
1333     trace_v9fs_version(pdu->tag, pdu->id, s->msize, version.data);
1334 
1335     virtfs_reset(pdu);
1336 
1337     if (!strcmp(version.data, "9P2000.u")) {
1338         s->proto_version = V9FS_PROTO_2000U;
1339     } else if (!strcmp(version.data, "9P2000.L")) {
1340         s->proto_version = V9FS_PROTO_2000L;
1341     } else {
1342         v9fs_string_sprintf(&version, "unknown");
1343         /* skip min. msize check, reporting invalid version has priority */
1344         goto marshal;
1345     }
1346 
1347     if (s->msize < P9_MIN_MSIZE) {
1348         err = -EMSGSIZE;
1349         error_report(
1350             "9pfs: Client requested msize < minimum msize ("
1351             stringify(P9_MIN_MSIZE) ") supported by this server."
1352         );
1353         goto out;
1354     }
1355 
1356 marshal:
1357     err = pdu_marshal(pdu, offset, "ds", s->msize, &version);
1358     if (err < 0) {
1359         goto out;
1360     }
1361     err += offset;
1362     trace_v9fs_version_return(pdu->tag, pdu->id, s->msize, version.data);
1363 out:
1364     pdu_complete(pdu, err);
1365     v9fs_string_free(&version);
1366 }
1367 
1368 static void coroutine_fn v9fs_attach(void *opaque)
1369 {
1370     V9fsPDU *pdu = opaque;
1371     V9fsState *s = pdu->s;
1372     int32_t fid, afid, n_uname;
1373     V9fsString uname, aname;
1374     V9fsFidState *fidp;
1375     size_t offset = 7;
1376     V9fsQID qid;
1377     ssize_t err;
1378 
1379     v9fs_string_init(&uname);
1380     v9fs_string_init(&aname);
1381     err = pdu_unmarshal(pdu, offset, "ddssd", &fid,
1382                         &afid, &uname, &aname, &n_uname);
1383     if (err < 0) {
1384         goto out_nofid;
1385     }
1386     trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data);
1387 
1388     fidp = alloc_fid(s, fid);
1389     if (fidp == NULL) {
1390         err = -EINVAL;
1391         goto out_nofid;
1392     }
1393     fidp->uid = n_uname;
1394     err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path);
1395     if (err < 0) {
1396         err = -EINVAL;
1397         clunk_fid(s, fid);
1398         goto out;
1399     }
1400     err = fid_to_qid(pdu, fidp, &qid);
1401     if (err < 0) {
1402         err = -EINVAL;
1403         clunk_fid(s, fid);
1404         goto out;
1405     }
1406 
1407     /*
1408      * disable migration if we haven't done already.
1409      * attach could get called multiple times for the same export.
1410      */
1411     if (!s->migration_blocker) {
1412         error_setg(&s->migration_blocker,
1413                    "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'",
1414                    s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag);
1415         err = migrate_add_blocker(s->migration_blocker, NULL);
1416         if (err < 0) {
1417             error_free(s->migration_blocker);
1418             s->migration_blocker = NULL;
1419             clunk_fid(s, fid);
1420             goto out;
1421         }
1422         s->root_fid = fid;
1423     }
1424 
1425     err = pdu_marshal(pdu, offset, "Q", &qid);
1426     if (err < 0) {
1427         clunk_fid(s, fid);
1428         goto out;
1429     }
1430     err += offset;
1431 
1432     memcpy(&s->root_qid, &qid, sizeof(qid));
1433     trace_v9fs_attach_return(pdu->tag, pdu->id,
1434                              qid.type, qid.version, qid.path);
1435 out:
1436     put_fid(pdu, fidp);
1437 out_nofid:
1438     pdu_complete(pdu, err);
1439     v9fs_string_free(&uname);
1440     v9fs_string_free(&aname);
1441 }
1442 
1443 static void coroutine_fn v9fs_stat(void *opaque)
1444 {
1445     int32_t fid;
1446     V9fsStat v9stat;
1447     ssize_t err = 0;
1448     size_t offset = 7;
1449     struct stat stbuf;
1450     V9fsFidState *fidp;
1451     V9fsPDU *pdu = opaque;
1452     char *basename;
1453 
1454     err = pdu_unmarshal(pdu, offset, "d", &fid);
1455     if (err < 0) {
1456         goto out_nofid;
1457     }
1458     trace_v9fs_stat(pdu->tag, pdu->id, fid);
1459 
1460     fidp = get_fid(pdu, fid);
1461     if (fidp == NULL) {
1462         err = -ENOENT;
1463         goto out_nofid;
1464     }
1465     err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1466     if (err < 0) {
1467         goto out;
1468     }
1469     basename = g_path_get_basename(fidp->path.data);
1470     err = stat_to_v9stat(pdu, &fidp->path, basename, &stbuf, &v9stat);
1471     g_free(basename);
1472     if (err < 0) {
1473         goto out;
1474     }
1475     err = pdu_marshal(pdu, offset, "wS", 0, &v9stat);
1476     if (err < 0) {
1477         v9fs_stat_free(&v9stat);
1478         goto out;
1479     }
1480     trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode,
1481                            v9stat.atime, v9stat.mtime, v9stat.length);
1482     err += offset;
1483     v9fs_stat_free(&v9stat);
1484 out:
1485     put_fid(pdu, fidp);
1486 out_nofid:
1487     pdu_complete(pdu, err);
1488 }
1489 
1490 static void coroutine_fn v9fs_getattr(void *opaque)
1491 {
1492     int32_t fid;
1493     size_t offset = 7;
1494     ssize_t retval = 0;
1495     struct stat stbuf;
1496     V9fsFidState *fidp;
1497     uint64_t request_mask;
1498     V9fsStatDotl v9stat_dotl;
1499     V9fsPDU *pdu = opaque;
1500 
1501     retval = pdu_unmarshal(pdu, offset, "dq", &fid, &request_mask);
1502     if (retval < 0) {
1503         goto out_nofid;
1504     }
1505     trace_v9fs_getattr(pdu->tag, pdu->id, fid, request_mask);
1506 
1507     fidp = get_fid(pdu, fid);
1508     if (fidp == NULL) {
1509         retval = -ENOENT;
1510         goto out_nofid;
1511     }
1512     /*
1513      * Currently we only support BASIC fields in stat, so there is no
1514      * need to look at request_mask.
1515      */
1516     retval = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1517     if (retval < 0) {
1518         goto out;
1519     }
1520     retval = stat_to_v9stat_dotl(pdu, &stbuf, &v9stat_dotl);
1521     if (retval < 0) {
1522         goto out;
1523     }
1524 
1525     /*  fill st_gen if requested and supported by underlying fs */
1526     if (request_mask & P9_STATS_GEN) {
1527         retval = v9fs_co_st_gen(pdu, &fidp->path, stbuf.st_mode, &v9stat_dotl);
1528         switch (retval) {
1529         case 0:
1530             /* we have valid st_gen: update result mask */
1531             v9stat_dotl.st_result_mask |= P9_STATS_GEN;
1532             break;
1533         case -EINTR:
1534             /* request cancelled, e.g. by Tflush */
1535             goto out;
1536         default:
1537             /* failed to get st_gen: not fatal, ignore */
1538             break;
1539         }
1540     }
1541     retval = pdu_marshal(pdu, offset, "A", &v9stat_dotl);
1542     if (retval < 0) {
1543         goto out;
1544     }
1545     retval += offset;
1546     trace_v9fs_getattr_return(pdu->tag, pdu->id, v9stat_dotl.st_result_mask,
1547                               v9stat_dotl.st_mode, v9stat_dotl.st_uid,
1548                               v9stat_dotl.st_gid);
1549 out:
1550     put_fid(pdu, fidp);
1551 out_nofid:
1552     pdu_complete(pdu, retval);
1553 }
1554 
1555 /* Attribute flags */
1556 #define P9_ATTR_MODE       (1 << 0)
1557 #define P9_ATTR_UID        (1 << 1)
1558 #define P9_ATTR_GID        (1 << 2)
1559 #define P9_ATTR_SIZE       (1 << 3)
1560 #define P9_ATTR_ATIME      (1 << 4)
1561 #define P9_ATTR_MTIME      (1 << 5)
1562 #define P9_ATTR_CTIME      (1 << 6)
1563 #define P9_ATTR_ATIME_SET  (1 << 7)
1564 #define P9_ATTR_MTIME_SET  (1 << 8)
1565 
1566 #define P9_ATTR_MASK    127
1567 
1568 static void coroutine_fn v9fs_setattr(void *opaque)
1569 {
1570     int err = 0;
1571     int32_t fid;
1572     V9fsFidState *fidp;
1573     size_t offset = 7;
1574     V9fsIattr v9iattr;
1575     V9fsPDU *pdu = opaque;
1576 
1577     err = pdu_unmarshal(pdu, offset, "dI", &fid, &v9iattr);
1578     if (err < 0) {
1579         goto out_nofid;
1580     }
1581 
1582     trace_v9fs_setattr(pdu->tag, pdu->id, fid,
1583                        v9iattr.valid, v9iattr.mode, v9iattr.uid, v9iattr.gid,
1584                        v9iattr.size, v9iattr.atime_sec, v9iattr.mtime_sec);
1585 
1586     fidp = get_fid(pdu, fid);
1587     if (fidp == NULL) {
1588         err = -EINVAL;
1589         goto out_nofid;
1590     }
1591     if (v9iattr.valid & P9_ATTR_MODE) {
1592         err = v9fs_co_chmod(pdu, &fidp->path, v9iattr.mode);
1593         if (err < 0) {
1594             goto out;
1595         }
1596     }
1597     if (v9iattr.valid & (P9_ATTR_ATIME | P9_ATTR_MTIME)) {
1598         struct timespec times[2];
1599         if (v9iattr.valid & P9_ATTR_ATIME) {
1600             if (v9iattr.valid & P9_ATTR_ATIME_SET) {
1601                 times[0].tv_sec = v9iattr.atime_sec;
1602                 times[0].tv_nsec = v9iattr.atime_nsec;
1603             } else {
1604                 times[0].tv_nsec = UTIME_NOW;
1605             }
1606         } else {
1607             times[0].tv_nsec = UTIME_OMIT;
1608         }
1609         if (v9iattr.valid & P9_ATTR_MTIME) {
1610             if (v9iattr.valid & P9_ATTR_MTIME_SET) {
1611                 times[1].tv_sec = v9iattr.mtime_sec;
1612                 times[1].tv_nsec = v9iattr.mtime_nsec;
1613             } else {
1614                 times[1].tv_nsec = UTIME_NOW;
1615             }
1616         } else {
1617             times[1].tv_nsec = UTIME_OMIT;
1618         }
1619         err = v9fs_co_utimensat(pdu, &fidp->path, times);
1620         if (err < 0) {
1621             goto out;
1622         }
1623     }
1624     /*
1625      * If the only valid entry in iattr is ctime we can call
1626      * chown(-1,-1) to update the ctime of the file
1627      */
1628     if ((v9iattr.valid & (P9_ATTR_UID | P9_ATTR_GID)) ||
1629         ((v9iattr.valid & P9_ATTR_CTIME)
1630          && !((v9iattr.valid & P9_ATTR_MASK) & ~P9_ATTR_CTIME))) {
1631         if (!(v9iattr.valid & P9_ATTR_UID)) {
1632             v9iattr.uid = -1;
1633         }
1634         if (!(v9iattr.valid & P9_ATTR_GID)) {
1635             v9iattr.gid = -1;
1636         }
1637         err = v9fs_co_chown(pdu, &fidp->path, v9iattr.uid,
1638                             v9iattr.gid);
1639         if (err < 0) {
1640             goto out;
1641         }
1642     }
1643     if (v9iattr.valid & (P9_ATTR_SIZE)) {
1644         err = v9fs_co_truncate(pdu, &fidp->path, v9iattr.size);
1645         if (err < 0) {
1646             goto out;
1647         }
1648     }
1649     err = offset;
1650     trace_v9fs_setattr_return(pdu->tag, pdu->id);
1651 out:
1652     put_fid(pdu, fidp);
1653 out_nofid:
1654     pdu_complete(pdu, err);
1655 }
1656 
1657 static int v9fs_walk_marshal(V9fsPDU *pdu, uint16_t nwnames, V9fsQID *qids)
1658 {
1659     int i;
1660     ssize_t err;
1661     size_t offset = 7;
1662 
1663     err = pdu_marshal(pdu, offset, "w", nwnames);
1664     if (err < 0) {
1665         return err;
1666     }
1667     offset += err;
1668     for (i = 0; i < nwnames; i++) {
1669         err = pdu_marshal(pdu, offset, "Q", &qids[i]);
1670         if (err < 0) {
1671             return err;
1672         }
1673         offset += err;
1674     }
1675     return offset;
1676 }
1677 
1678 static bool name_is_illegal(const char *name)
1679 {
1680     return !*name || strchr(name, '/') != NULL;
1681 }
1682 
1683 static bool not_same_qid(const V9fsQID *qid1, const V9fsQID *qid2)
1684 {
1685     return
1686         qid1->type != qid2->type ||
1687         qid1->version != qid2->version ||
1688         qid1->path != qid2->path;
1689 }
1690 
1691 static void coroutine_fn v9fs_walk(void *opaque)
1692 {
1693     int name_idx;
1694     V9fsQID *qids = NULL;
1695     int i, err = 0;
1696     V9fsPath dpath, path;
1697     uint16_t nwnames;
1698     struct stat stbuf;
1699     size_t offset = 7;
1700     int32_t fid, newfid;
1701     V9fsString *wnames = NULL;
1702     V9fsFidState *fidp;
1703     V9fsFidState *newfidp = NULL;
1704     V9fsPDU *pdu = opaque;
1705     V9fsState *s = pdu->s;
1706     V9fsQID qid;
1707 
1708     err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
1709     if (err < 0) {
1710         pdu_complete(pdu, err);
1711         return ;
1712     }
1713     offset += err;
1714 
1715     trace_v9fs_walk(pdu->tag, pdu->id, fid, newfid, nwnames);
1716 
1717     if (nwnames && nwnames <= P9_MAXWELEM) {
1718         wnames = g_new0(V9fsString, nwnames);
1719         qids   = g_new0(V9fsQID, nwnames);
1720         for (i = 0; i < nwnames; i++) {
1721             err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
1722             if (err < 0) {
1723                 goto out_nofid;
1724             }
1725             if (name_is_illegal(wnames[i].data)) {
1726                 err = -ENOENT;
1727                 goto out_nofid;
1728             }
1729             offset += err;
1730         }
1731     } else if (nwnames > P9_MAXWELEM) {
1732         err = -EINVAL;
1733         goto out_nofid;
1734     }
1735     fidp = get_fid(pdu, fid);
1736     if (fidp == NULL) {
1737         err = -ENOENT;
1738         goto out_nofid;
1739     }
1740 
1741     v9fs_path_init(&dpath);
1742     v9fs_path_init(&path);
1743 
1744     err = fid_to_qid(pdu, fidp, &qid);
1745     if (err < 0) {
1746         goto out;
1747     }
1748 
1749     /*
1750      * Both dpath and path initially poin to fidp.
1751      * Needed to handle request with nwnames == 0
1752      */
1753     v9fs_path_copy(&dpath, &fidp->path);
1754     v9fs_path_copy(&path, &fidp->path);
1755     for (name_idx = 0; name_idx < nwnames; name_idx++) {
1756         if (not_same_qid(&pdu->s->root_qid, &qid) ||
1757             strcmp("..", wnames[name_idx].data)) {
1758             err = v9fs_co_name_to_path(pdu, &dpath, wnames[name_idx].data,
1759                                        &path);
1760             if (err < 0) {
1761                 goto out;
1762             }
1763 
1764             err = v9fs_co_lstat(pdu, &path, &stbuf);
1765             if (err < 0) {
1766                 goto out;
1767             }
1768             err = stat_to_qid(pdu, &stbuf, &qid);
1769             if (err < 0) {
1770                 goto out;
1771             }
1772             v9fs_path_copy(&dpath, &path);
1773         }
1774         memcpy(&qids[name_idx], &qid, sizeof(qid));
1775     }
1776     if (fid == newfid) {
1777         if (fidp->fid_type != P9_FID_NONE) {
1778             err = -EINVAL;
1779             goto out;
1780         }
1781         v9fs_path_write_lock(s);
1782         v9fs_path_copy(&fidp->path, &path);
1783         v9fs_path_unlock(s);
1784     } else {
1785         newfidp = alloc_fid(s, newfid);
1786         if (newfidp == NULL) {
1787             err = -EINVAL;
1788             goto out;
1789         }
1790         newfidp->uid = fidp->uid;
1791         v9fs_path_copy(&newfidp->path, &path);
1792     }
1793     err = v9fs_walk_marshal(pdu, nwnames, qids);
1794     trace_v9fs_walk_return(pdu->tag, pdu->id, nwnames, qids);
1795 out:
1796     put_fid(pdu, fidp);
1797     if (newfidp) {
1798         put_fid(pdu, newfidp);
1799     }
1800     v9fs_path_free(&dpath);
1801     v9fs_path_free(&path);
1802 out_nofid:
1803     pdu_complete(pdu, err);
1804     if (nwnames && nwnames <= P9_MAXWELEM) {
1805         for (name_idx = 0; name_idx < nwnames; name_idx++) {
1806             v9fs_string_free(&wnames[name_idx]);
1807         }
1808         g_free(wnames);
1809         g_free(qids);
1810     }
1811 }
1812 
1813 static int32_t coroutine_fn get_iounit(V9fsPDU *pdu, V9fsPath *path)
1814 {
1815     struct statfs stbuf;
1816     int32_t iounit = 0;
1817     V9fsState *s = pdu->s;
1818 
1819     /*
1820      * iounit should be multiples of f_bsize (host filesystem block size
1821      * and as well as less than (client msize - P9_IOHDRSZ))
1822      */
1823     if (!v9fs_co_statfs(pdu, path, &stbuf)) {
1824         if (stbuf.f_bsize) {
1825             iounit = stbuf.f_bsize;
1826             iounit *= (s->msize - P9_IOHDRSZ) / stbuf.f_bsize;
1827         }
1828     }
1829     if (!iounit) {
1830         iounit = s->msize - P9_IOHDRSZ;
1831     }
1832     return iounit;
1833 }
1834 
1835 static void coroutine_fn v9fs_open(void *opaque)
1836 {
1837     int flags;
1838     int32_t fid;
1839     int32_t mode;
1840     V9fsQID qid;
1841     int iounit = 0;
1842     ssize_t err = 0;
1843     size_t offset = 7;
1844     struct stat stbuf;
1845     V9fsFidState *fidp;
1846     V9fsPDU *pdu = opaque;
1847     V9fsState *s = pdu->s;
1848 
1849     if (s->proto_version == V9FS_PROTO_2000L) {
1850         err = pdu_unmarshal(pdu, offset, "dd", &fid, &mode);
1851     } else {
1852         uint8_t modebyte;
1853         err = pdu_unmarshal(pdu, offset, "db", &fid, &modebyte);
1854         mode = modebyte;
1855     }
1856     if (err < 0) {
1857         goto out_nofid;
1858     }
1859     trace_v9fs_open(pdu->tag, pdu->id, fid, mode);
1860 
1861     fidp = get_fid(pdu, fid);
1862     if (fidp == NULL) {
1863         err = -ENOENT;
1864         goto out_nofid;
1865     }
1866     if (fidp->fid_type != P9_FID_NONE) {
1867         err = -EINVAL;
1868         goto out;
1869     }
1870 
1871     err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
1872     if (err < 0) {
1873         goto out;
1874     }
1875     err = stat_to_qid(pdu, &stbuf, &qid);
1876     if (err < 0) {
1877         goto out;
1878     }
1879     if (S_ISDIR(stbuf.st_mode)) {
1880         err = v9fs_co_opendir(pdu, fidp);
1881         if (err < 0) {
1882             goto out;
1883         }
1884         fidp->fid_type = P9_FID_DIR;
1885         err = pdu_marshal(pdu, offset, "Qd", &qid, 0);
1886         if (err < 0) {
1887             goto out;
1888         }
1889         err += offset;
1890     } else {
1891         if (s->proto_version == V9FS_PROTO_2000L) {
1892             flags = get_dotl_openflags(s, mode);
1893         } else {
1894             flags = omode_to_uflags(mode);
1895         }
1896         if (is_ro_export(&s->ctx)) {
1897             if (mode & O_WRONLY || mode & O_RDWR ||
1898                 mode & O_APPEND || mode & O_TRUNC) {
1899                 err = -EROFS;
1900                 goto out;
1901             }
1902         }
1903         err = v9fs_co_open(pdu, fidp, flags);
1904         if (err < 0) {
1905             goto out;
1906         }
1907         fidp->fid_type = P9_FID_FILE;
1908         fidp->open_flags = flags;
1909         if (flags & O_EXCL) {
1910             /*
1911              * We let the host file system do O_EXCL check
1912              * We should not reclaim such fd
1913              */
1914             fidp->flags |= FID_NON_RECLAIMABLE;
1915         }
1916         iounit = get_iounit(pdu, &fidp->path);
1917         err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
1918         if (err < 0) {
1919             goto out;
1920         }
1921         err += offset;
1922     }
1923     trace_v9fs_open_return(pdu->tag, pdu->id,
1924                            qid.type, qid.version, qid.path, iounit);
1925 out:
1926     put_fid(pdu, fidp);
1927 out_nofid:
1928     pdu_complete(pdu, err);
1929 }
1930 
1931 static void coroutine_fn v9fs_lcreate(void *opaque)
1932 {
1933     int32_t dfid, flags, mode;
1934     gid_t gid;
1935     ssize_t err = 0;
1936     ssize_t offset = 7;
1937     V9fsString name;
1938     V9fsFidState *fidp;
1939     struct stat stbuf;
1940     V9fsQID qid;
1941     int32_t iounit;
1942     V9fsPDU *pdu = opaque;
1943 
1944     v9fs_string_init(&name);
1945     err = pdu_unmarshal(pdu, offset, "dsddd", &dfid,
1946                         &name, &flags, &mode, &gid);
1947     if (err < 0) {
1948         goto out_nofid;
1949     }
1950     trace_v9fs_lcreate(pdu->tag, pdu->id, dfid, flags, mode, gid);
1951 
1952     if (name_is_illegal(name.data)) {
1953         err = -ENOENT;
1954         goto out_nofid;
1955     }
1956 
1957     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
1958         err = -EEXIST;
1959         goto out_nofid;
1960     }
1961 
1962     fidp = get_fid(pdu, dfid);
1963     if (fidp == NULL) {
1964         err = -ENOENT;
1965         goto out_nofid;
1966     }
1967     if (fidp->fid_type != P9_FID_NONE) {
1968         err = -EINVAL;
1969         goto out;
1970     }
1971 
1972     flags = get_dotl_openflags(pdu->s, flags);
1973     err = v9fs_co_open2(pdu, fidp, &name, gid,
1974                         flags | O_CREAT, mode, &stbuf);
1975     if (err < 0) {
1976         goto out;
1977     }
1978     fidp->fid_type = P9_FID_FILE;
1979     fidp->open_flags = flags;
1980     if (flags & O_EXCL) {
1981         /*
1982          * We let the host file system do O_EXCL check
1983          * We should not reclaim such fd
1984          */
1985         fidp->flags |= FID_NON_RECLAIMABLE;
1986     }
1987     iounit =  get_iounit(pdu, &fidp->path);
1988     err = stat_to_qid(pdu, &stbuf, &qid);
1989     if (err < 0) {
1990         goto out;
1991     }
1992     err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
1993     if (err < 0) {
1994         goto out;
1995     }
1996     err += offset;
1997     trace_v9fs_lcreate_return(pdu->tag, pdu->id,
1998                               qid.type, qid.version, qid.path, iounit);
1999 out:
2000     put_fid(pdu, fidp);
2001 out_nofid:
2002     pdu_complete(pdu, err);
2003     v9fs_string_free(&name);
2004 }
2005 
2006 static void coroutine_fn v9fs_fsync(void *opaque)
2007 {
2008     int err;
2009     int32_t fid;
2010     int datasync;
2011     size_t offset = 7;
2012     V9fsFidState *fidp;
2013     V9fsPDU *pdu = opaque;
2014 
2015     err = pdu_unmarshal(pdu, offset, "dd", &fid, &datasync);
2016     if (err < 0) {
2017         goto out_nofid;
2018     }
2019     trace_v9fs_fsync(pdu->tag, pdu->id, fid, datasync);
2020 
2021     fidp = get_fid(pdu, fid);
2022     if (fidp == NULL) {
2023         err = -ENOENT;
2024         goto out_nofid;
2025     }
2026     err = v9fs_co_fsync(pdu, fidp, datasync);
2027     if (!err) {
2028         err = offset;
2029     }
2030     put_fid(pdu, fidp);
2031 out_nofid:
2032     pdu_complete(pdu, err);
2033 }
2034 
2035 static void coroutine_fn v9fs_clunk(void *opaque)
2036 {
2037     int err;
2038     int32_t fid;
2039     size_t offset = 7;
2040     V9fsFidState *fidp;
2041     V9fsPDU *pdu = opaque;
2042     V9fsState *s = pdu->s;
2043 
2044     err = pdu_unmarshal(pdu, offset, "d", &fid);
2045     if (err < 0) {
2046         goto out_nofid;
2047     }
2048     trace_v9fs_clunk(pdu->tag, pdu->id, fid);
2049 
2050     fidp = clunk_fid(s, fid);
2051     if (fidp == NULL) {
2052         err = -ENOENT;
2053         goto out_nofid;
2054     }
2055     /*
2056      * Bump the ref so that put_fid will
2057      * free the fid.
2058      */
2059     fidp->ref++;
2060     err = put_fid(pdu, fidp);
2061     if (!err) {
2062         err = offset;
2063     }
2064 out_nofid:
2065     pdu_complete(pdu, err);
2066 }
2067 
2068 /*
2069  * Create a QEMUIOVector for a sub-region of PDU iovecs
2070  *
2071  * @qiov:       uninitialized QEMUIOVector
2072  * @skip:       number of bytes to skip from beginning of PDU
2073  * @size:       number of bytes to include
2074  * @is_write:   true - write, false - read
2075  *
2076  * The resulting QEMUIOVector has heap-allocated iovecs and must be cleaned up
2077  * with qemu_iovec_destroy().
2078  */
2079 static void v9fs_init_qiov_from_pdu(QEMUIOVector *qiov, V9fsPDU *pdu,
2080                                     size_t skip, size_t size,
2081                                     bool is_write)
2082 {
2083     QEMUIOVector elem;
2084     struct iovec *iov;
2085     unsigned int niov;
2086 
2087     if (is_write) {
2088         pdu->s->transport->init_out_iov_from_pdu(pdu, &iov, &niov, size + skip);
2089     } else {
2090         pdu->s->transport->init_in_iov_from_pdu(pdu, &iov, &niov, size + skip);
2091     }
2092 
2093     qemu_iovec_init_external(&elem, iov, niov);
2094     qemu_iovec_init(qiov, niov);
2095     qemu_iovec_concat(qiov, &elem, skip, size);
2096 }
2097 
2098 static int v9fs_xattr_read(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp,
2099                            uint64_t off, uint32_t max_count)
2100 {
2101     ssize_t err;
2102     size_t offset = 7;
2103     uint64_t read_count;
2104     QEMUIOVector qiov_full;
2105 
2106     if (fidp->fs.xattr.len < off) {
2107         read_count = 0;
2108     } else {
2109         read_count = fidp->fs.xattr.len - off;
2110     }
2111     if (read_count > max_count) {
2112         read_count = max_count;
2113     }
2114     err = pdu_marshal(pdu, offset, "d", read_count);
2115     if (err < 0) {
2116         return err;
2117     }
2118     offset += err;
2119 
2120     v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, read_count, false);
2121     err = v9fs_pack(qiov_full.iov, qiov_full.niov, 0,
2122                     ((char *)fidp->fs.xattr.value) + off,
2123                     read_count);
2124     qemu_iovec_destroy(&qiov_full);
2125     if (err < 0) {
2126         return err;
2127     }
2128     offset += err;
2129     return offset;
2130 }
2131 
2132 static int coroutine_fn v9fs_do_readdir_with_stat(V9fsPDU *pdu,
2133                                                   V9fsFidState *fidp,
2134                                                   uint32_t max_count)
2135 {
2136     V9fsPath path;
2137     V9fsStat v9stat;
2138     int len, err = 0;
2139     int32_t count = 0;
2140     struct stat stbuf;
2141     off_t saved_dir_pos;
2142     struct dirent *dent;
2143 
2144     /* save the directory position */
2145     saved_dir_pos = v9fs_co_telldir(pdu, fidp);
2146     if (saved_dir_pos < 0) {
2147         return saved_dir_pos;
2148     }
2149 
2150     while (1) {
2151         v9fs_path_init(&path);
2152 
2153         v9fs_readdir_lock(&fidp->fs.dir);
2154 
2155         err = v9fs_co_readdir(pdu, fidp, &dent);
2156         if (err || !dent) {
2157             break;
2158         }
2159         err = v9fs_co_name_to_path(pdu, &fidp->path, dent->d_name, &path);
2160         if (err < 0) {
2161             break;
2162         }
2163         err = v9fs_co_lstat(pdu, &path, &stbuf);
2164         if (err < 0) {
2165             break;
2166         }
2167         err = stat_to_v9stat(pdu, &path, dent->d_name, &stbuf, &v9stat);
2168         if (err < 0) {
2169             break;
2170         }
2171         if ((count + v9stat.size + 2) > max_count) {
2172             v9fs_readdir_unlock(&fidp->fs.dir);
2173 
2174             /* Ran out of buffer. Set dir back to old position and return */
2175             v9fs_co_seekdir(pdu, fidp, saved_dir_pos);
2176             v9fs_stat_free(&v9stat);
2177             v9fs_path_free(&path);
2178             return count;
2179         }
2180 
2181         /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */
2182         len = pdu_marshal(pdu, 11 + count, "S", &v9stat);
2183 
2184         v9fs_readdir_unlock(&fidp->fs.dir);
2185 
2186         if (len < 0) {
2187             v9fs_co_seekdir(pdu, fidp, saved_dir_pos);
2188             v9fs_stat_free(&v9stat);
2189             v9fs_path_free(&path);
2190             return len;
2191         }
2192         count += len;
2193         v9fs_stat_free(&v9stat);
2194         v9fs_path_free(&path);
2195         saved_dir_pos = dent->d_off;
2196     }
2197 
2198     v9fs_readdir_unlock(&fidp->fs.dir);
2199 
2200     v9fs_path_free(&path);
2201     if (err < 0) {
2202         return err;
2203     }
2204     return count;
2205 }
2206 
2207 static void coroutine_fn v9fs_read(void *opaque)
2208 {
2209     int32_t fid;
2210     uint64_t off;
2211     ssize_t err = 0;
2212     int32_t count = 0;
2213     size_t offset = 7;
2214     uint32_t max_count;
2215     V9fsFidState *fidp;
2216     V9fsPDU *pdu = opaque;
2217     V9fsState *s = pdu->s;
2218 
2219     err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);
2220     if (err < 0) {
2221         goto out_nofid;
2222     }
2223     trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);
2224 
2225     fidp = get_fid(pdu, fid);
2226     if (fidp == NULL) {
2227         err = -EINVAL;
2228         goto out_nofid;
2229     }
2230     if (fidp->fid_type == P9_FID_DIR) {
2231         if (s->proto_version != V9FS_PROTO_2000U) {
2232             warn_report_once(
2233                 "9p: bad client: T_read request on directory only expected "
2234                 "with 9P2000.u protocol version"
2235             );
2236             err = -EOPNOTSUPP;
2237             goto out;
2238         }
2239         if (off == 0) {
2240             v9fs_co_rewinddir(pdu, fidp);
2241         }
2242         count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);
2243         if (count < 0) {
2244             err = count;
2245             goto out;
2246         }
2247         err = pdu_marshal(pdu, offset, "d", count);
2248         if (err < 0) {
2249             goto out;
2250         }
2251         err += offset + count;
2252     } else if (fidp->fid_type == P9_FID_FILE) {
2253         QEMUIOVector qiov_full;
2254         QEMUIOVector qiov;
2255         int32_t len;
2256 
2257         v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);
2258         qemu_iovec_init(&qiov, qiov_full.niov);
2259         do {
2260             qemu_iovec_reset(&qiov);
2261             qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
2262             if (0) {
2263                 print_sg(qiov.iov, qiov.niov);
2264             }
2265             /* Loop in case of EINTR */
2266             do {
2267                 len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);
2268                 if (len >= 0) {
2269                     off   += len;
2270                     count += len;
2271                 }
2272             } while (len == -EINTR && !pdu->cancelled);
2273             if (len < 0) {
2274                 /* IO error return the error */
2275                 err = len;
2276                 goto out_free_iovec;
2277             }
2278         } while (count < max_count && len > 0);
2279         err = pdu_marshal(pdu, offset, "d", count);
2280         if (err < 0) {
2281             goto out_free_iovec;
2282         }
2283         err += offset + count;
2284 out_free_iovec:
2285         qemu_iovec_destroy(&qiov);
2286         qemu_iovec_destroy(&qiov_full);
2287     } else if (fidp->fid_type == P9_FID_XATTR) {
2288         err = v9fs_xattr_read(s, pdu, fidp, off, max_count);
2289     } else {
2290         err = -EINVAL;
2291     }
2292     trace_v9fs_read_return(pdu->tag, pdu->id, count, err);
2293 out:
2294     put_fid(pdu, fidp);
2295 out_nofid:
2296     pdu_complete(pdu, err);
2297 }
2298 
2299 /**
2300  * Returns size required in Rreaddir response for the passed dirent @p name.
2301  *
2302  * @param name - directory entry's name (i.e. file name, directory name)
2303  * @returns required size in bytes
2304  */
2305 size_t v9fs_readdir_response_size(V9fsString *name)
2306 {
2307     /*
2308      * Size of each dirent on the wire: size of qid (13) + size of offset (8)
2309      * size of type (1) + size of name.size (2) + strlen(name.data)
2310      */
2311     return 24 + v9fs_string_size(name);
2312 }
2313 
2314 static void v9fs_free_dirents(struct V9fsDirEnt *e)
2315 {
2316     struct V9fsDirEnt *next = NULL;
2317 
2318     for (; e; e = next) {
2319         next = e->next;
2320         g_free(e->dent);
2321         g_free(e->st);
2322         g_free(e);
2323     }
2324 }
2325 
2326 static int coroutine_fn v9fs_do_readdir(V9fsPDU *pdu, V9fsFidState *fidp,
2327                                         off_t offset, int32_t max_count)
2328 {
2329     size_t size;
2330     V9fsQID qid;
2331     V9fsString name;
2332     int len, err = 0;
2333     int32_t count = 0;
2334     struct dirent *dent;
2335     struct stat *st;
2336     struct V9fsDirEnt *entries = NULL;
2337 
2338     /*
2339      * inode remapping requires the device id, which in turn might be
2340      * different for different directory entries, so if inode remapping is
2341      * enabled we have to make a full stat for each directory entry
2342      */
2343     const bool dostat = pdu->s->ctx.export_flags & V9FS_REMAP_INODES;
2344 
2345     /*
2346      * Fetch all required directory entries altogether on a background IO
2347      * thread from fs driver. We don't want to do that for each entry
2348      * individually, because hopping between threads (this main IO thread
2349      * and background IO driver thread) would sum up to huge latencies.
2350      */
2351     count = v9fs_co_readdir_many(pdu, fidp, &entries, offset, max_count,
2352                                  dostat);
2353     if (count < 0) {
2354         err = count;
2355         count = 0;
2356         goto out;
2357     }
2358     count = 0;
2359 
2360     for (struct V9fsDirEnt *e = entries; e; e = e->next) {
2361         dent = e->dent;
2362 
2363         if (pdu->s->ctx.export_flags & V9FS_REMAP_INODES) {
2364             st = e->st;
2365             /* e->st should never be NULL, but just to be sure */
2366             if (!st) {
2367                 err = -1;
2368                 break;
2369             }
2370 
2371             /* remap inode */
2372             err = stat_to_qid(pdu, st, &qid);
2373             if (err < 0) {
2374                 break;
2375             }
2376         } else {
2377             /*
2378              * Fill up just the path field of qid because the client uses
2379              * only that. To fill the entire qid structure we will have
2380              * to stat each dirent found, which is expensive. For the
2381              * latter reason we don't call stat_to_qid() here. Only drawback
2382              * is that no multi-device export detection of stat_to_qid()
2383              * would be done and provided as error to the user here. But
2384              * user would get that error anyway when accessing those
2385              * files/dirs through other ways.
2386              */
2387             size = MIN(sizeof(dent->d_ino), sizeof(qid.path));
2388             memcpy(&qid.path, &dent->d_ino, size);
2389             /* Fill the other fields with dummy values */
2390             qid.type = 0;
2391             qid.version = 0;
2392         }
2393 
2394         v9fs_string_init(&name);
2395         v9fs_string_sprintf(&name, "%s", dent->d_name);
2396 
2397         /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */
2398         len = pdu_marshal(pdu, 11 + count, "Qqbs",
2399                           &qid, dent->d_off,
2400                           dent->d_type, &name);
2401 
2402         v9fs_string_free(&name);
2403 
2404         if (len < 0) {
2405             err = len;
2406             break;
2407         }
2408 
2409         count += len;
2410     }
2411 
2412 out:
2413     v9fs_free_dirents(entries);
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 (s->proto_version != V9FS_PROTO_2000L) {
2457         warn_report_once(
2458             "9p: bad client: T_readdir request only expected with 9P2000.L "
2459             "protocol version"
2460         );
2461         retval = -EOPNOTSUPP;
2462         goto out;
2463     }
2464     count = v9fs_do_readdir(pdu, fidp, (off_t) initial_offset, max_count);
2465     if (count < 0) {
2466         retval = count;
2467         goto out;
2468     }
2469     retval = pdu_marshal(pdu, offset, "d", count);
2470     if (retval < 0) {
2471         goto out;
2472     }
2473     retval += count + offset;
2474     trace_v9fs_readdir_return(pdu->tag, pdu->id, count, retval);
2475 out:
2476     put_fid(pdu, fidp);
2477 out_nofid:
2478     pdu_complete(pdu, retval);
2479 }
2480 
2481 static int v9fs_xattr_write(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp,
2482                             uint64_t off, uint32_t count,
2483                             struct iovec *sg, int cnt)
2484 {
2485     int i, to_copy;
2486     ssize_t err = 0;
2487     uint64_t write_count;
2488     size_t offset = 7;
2489 
2490 
2491     if (fidp->fs.xattr.len < off) {
2492         return -ENOSPC;
2493     }
2494     write_count = fidp->fs.xattr.len - off;
2495     if (write_count > count) {
2496         write_count = count;
2497     }
2498     err = pdu_marshal(pdu, offset, "d", write_count);
2499     if (err < 0) {
2500         return err;
2501     }
2502     err += offset;
2503     fidp->fs.xattr.copied_len += write_count;
2504     /*
2505      * Now copy the content from sg list
2506      */
2507     for (i = 0; i < cnt; i++) {
2508         if (write_count > sg[i].iov_len) {
2509             to_copy = sg[i].iov_len;
2510         } else {
2511             to_copy = write_count;
2512         }
2513         memcpy((char *)fidp->fs.xattr.value + off, sg[i].iov_base, to_copy);
2514         /* updating vs->off since we are not using below */
2515         off += to_copy;
2516         write_count -= to_copy;
2517     }
2518 
2519     return err;
2520 }
2521 
2522 static void coroutine_fn v9fs_write(void *opaque)
2523 {
2524     ssize_t err;
2525     int32_t fid;
2526     uint64_t off;
2527     uint32_t count;
2528     int32_t len = 0;
2529     int32_t total = 0;
2530     size_t offset = 7;
2531     V9fsFidState *fidp;
2532     V9fsPDU *pdu = opaque;
2533     V9fsState *s = pdu->s;
2534     QEMUIOVector qiov_full;
2535     QEMUIOVector qiov;
2536 
2537     err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);
2538     if (err < 0) {
2539         pdu_complete(pdu, err);
2540         return;
2541     }
2542     offset += err;
2543     v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);
2544     trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);
2545 
2546     fidp = get_fid(pdu, fid);
2547     if (fidp == NULL) {
2548         err = -EINVAL;
2549         goto out_nofid;
2550     }
2551     if (fidp->fid_type == P9_FID_FILE) {
2552         if (fidp->fs.fd == -1) {
2553             err = -EINVAL;
2554             goto out;
2555         }
2556     } else if (fidp->fid_type == P9_FID_XATTR) {
2557         /*
2558          * setxattr operation
2559          */
2560         err = v9fs_xattr_write(s, pdu, fidp, off, count,
2561                                qiov_full.iov, qiov_full.niov);
2562         goto out;
2563     } else {
2564         err = -EINVAL;
2565         goto out;
2566     }
2567     qemu_iovec_init(&qiov, qiov_full.niov);
2568     do {
2569         qemu_iovec_reset(&qiov);
2570         qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
2571         if (0) {
2572             print_sg(qiov.iov, qiov.niov);
2573         }
2574         /* Loop in case of EINTR */
2575         do {
2576             len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);
2577             if (len >= 0) {
2578                 off   += len;
2579                 total += len;
2580             }
2581         } while (len == -EINTR && !pdu->cancelled);
2582         if (len < 0) {
2583             /* IO error return the error */
2584             err = len;
2585             goto out_qiov;
2586         }
2587     } while (total < count && len > 0);
2588 
2589     offset = 7;
2590     err = pdu_marshal(pdu, offset, "d", total);
2591     if (err < 0) {
2592         goto out_qiov;
2593     }
2594     err += offset;
2595     trace_v9fs_write_return(pdu->tag, pdu->id, total, err);
2596 out_qiov:
2597     qemu_iovec_destroy(&qiov);
2598 out:
2599     put_fid(pdu, fidp);
2600 out_nofid:
2601     qemu_iovec_destroy(&qiov_full);
2602     pdu_complete(pdu, err);
2603 }
2604 
2605 static void coroutine_fn v9fs_create(void *opaque)
2606 {
2607     int32_t fid;
2608     int err = 0;
2609     size_t offset = 7;
2610     V9fsFidState *fidp;
2611     V9fsQID qid;
2612     int32_t perm;
2613     int8_t mode;
2614     V9fsPath path;
2615     struct stat stbuf;
2616     V9fsString name;
2617     V9fsString extension;
2618     int iounit;
2619     V9fsPDU *pdu = opaque;
2620     V9fsState *s = pdu->s;
2621 
2622     v9fs_path_init(&path);
2623     v9fs_string_init(&name);
2624     v9fs_string_init(&extension);
2625     err = pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name,
2626                         &perm, &mode, &extension);
2627     if (err < 0) {
2628         goto out_nofid;
2629     }
2630     trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode);
2631 
2632     if (name_is_illegal(name.data)) {
2633         err = -ENOENT;
2634         goto out_nofid;
2635     }
2636 
2637     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2638         err = -EEXIST;
2639         goto out_nofid;
2640     }
2641 
2642     fidp = get_fid(pdu, fid);
2643     if (fidp == NULL) {
2644         err = -EINVAL;
2645         goto out_nofid;
2646     }
2647     if (fidp->fid_type != P9_FID_NONE) {
2648         err = -EINVAL;
2649         goto out;
2650     }
2651     if (perm & P9_STAT_MODE_DIR) {
2652         err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777,
2653                             fidp->uid, -1, &stbuf);
2654         if (err < 0) {
2655             goto out;
2656         }
2657         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2658         if (err < 0) {
2659             goto out;
2660         }
2661         v9fs_path_write_lock(s);
2662         v9fs_path_copy(&fidp->path, &path);
2663         v9fs_path_unlock(s);
2664         err = v9fs_co_opendir(pdu, fidp);
2665         if (err < 0) {
2666             goto out;
2667         }
2668         fidp->fid_type = P9_FID_DIR;
2669     } else if (perm & P9_STAT_MODE_SYMLINK) {
2670         err = v9fs_co_symlink(pdu, fidp, &name,
2671                               extension.data, -1 , &stbuf);
2672         if (err < 0) {
2673             goto out;
2674         }
2675         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2676         if (err < 0) {
2677             goto out;
2678         }
2679         v9fs_path_write_lock(s);
2680         v9fs_path_copy(&fidp->path, &path);
2681         v9fs_path_unlock(s);
2682     } else if (perm & P9_STAT_MODE_LINK) {
2683         int32_t ofid = atoi(extension.data);
2684         V9fsFidState *ofidp = get_fid(pdu, ofid);
2685         if (ofidp == NULL) {
2686             err = -EINVAL;
2687             goto out;
2688         }
2689         err = v9fs_co_link(pdu, ofidp, fidp, &name);
2690         put_fid(pdu, ofidp);
2691         if (err < 0) {
2692             goto out;
2693         }
2694         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2695         if (err < 0) {
2696             fidp->fid_type = P9_FID_NONE;
2697             goto out;
2698         }
2699         v9fs_path_write_lock(s);
2700         v9fs_path_copy(&fidp->path, &path);
2701         v9fs_path_unlock(s);
2702         err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
2703         if (err < 0) {
2704             fidp->fid_type = P9_FID_NONE;
2705             goto out;
2706         }
2707     } else if (perm & P9_STAT_MODE_DEVICE) {
2708         char ctype;
2709         uint32_t major, minor;
2710         mode_t nmode = 0;
2711 
2712         if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) {
2713             err = -errno;
2714             goto out;
2715         }
2716 
2717         switch (ctype) {
2718         case 'c':
2719             nmode = S_IFCHR;
2720             break;
2721         case 'b':
2722             nmode = S_IFBLK;
2723             break;
2724         default:
2725             err = -EIO;
2726             goto out;
2727         }
2728 
2729         nmode |= perm & 0777;
2730         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2731                             makedev(major, minor), nmode, &stbuf);
2732         if (err < 0) {
2733             goto out;
2734         }
2735         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2736         if (err < 0) {
2737             goto out;
2738         }
2739         v9fs_path_write_lock(s);
2740         v9fs_path_copy(&fidp->path, &path);
2741         v9fs_path_unlock(s);
2742     } else if (perm & P9_STAT_MODE_NAMED_PIPE) {
2743         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2744                             0, S_IFIFO | (perm & 0777), &stbuf);
2745         if (err < 0) {
2746             goto out;
2747         }
2748         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2749         if (err < 0) {
2750             goto out;
2751         }
2752         v9fs_path_write_lock(s);
2753         v9fs_path_copy(&fidp->path, &path);
2754         v9fs_path_unlock(s);
2755     } else if (perm & P9_STAT_MODE_SOCKET) {
2756         err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
2757                             0, S_IFSOCK | (perm & 0777), &stbuf);
2758         if (err < 0) {
2759             goto out;
2760         }
2761         err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
2762         if (err < 0) {
2763             goto out;
2764         }
2765         v9fs_path_write_lock(s);
2766         v9fs_path_copy(&fidp->path, &path);
2767         v9fs_path_unlock(s);
2768     } else {
2769         err = v9fs_co_open2(pdu, fidp, &name, -1,
2770                             omode_to_uflags(mode)|O_CREAT, perm, &stbuf);
2771         if (err < 0) {
2772             goto out;
2773         }
2774         fidp->fid_type = P9_FID_FILE;
2775         fidp->open_flags = omode_to_uflags(mode);
2776         if (fidp->open_flags & O_EXCL) {
2777             /*
2778              * We let the host file system do O_EXCL check
2779              * We should not reclaim such fd
2780              */
2781             fidp->flags |= FID_NON_RECLAIMABLE;
2782         }
2783     }
2784     iounit = get_iounit(pdu, &fidp->path);
2785     err = stat_to_qid(pdu, &stbuf, &qid);
2786     if (err < 0) {
2787         goto out;
2788     }
2789     err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
2790     if (err < 0) {
2791         goto out;
2792     }
2793     err += offset;
2794     trace_v9fs_create_return(pdu->tag, pdu->id,
2795                              qid.type, qid.version, qid.path, iounit);
2796 out:
2797     put_fid(pdu, fidp);
2798 out_nofid:
2799    pdu_complete(pdu, err);
2800    v9fs_string_free(&name);
2801    v9fs_string_free(&extension);
2802    v9fs_path_free(&path);
2803 }
2804 
2805 static void coroutine_fn v9fs_symlink(void *opaque)
2806 {
2807     V9fsPDU *pdu = opaque;
2808     V9fsString name;
2809     V9fsString symname;
2810     V9fsFidState *dfidp;
2811     V9fsQID qid;
2812     struct stat stbuf;
2813     int32_t dfid;
2814     int err = 0;
2815     gid_t gid;
2816     size_t offset = 7;
2817 
2818     v9fs_string_init(&name);
2819     v9fs_string_init(&symname);
2820     err = pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid);
2821     if (err < 0) {
2822         goto out_nofid;
2823     }
2824     trace_v9fs_symlink(pdu->tag, pdu->id, dfid, name.data, symname.data, gid);
2825 
2826     if (name_is_illegal(name.data)) {
2827         err = -ENOENT;
2828         goto out_nofid;
2829     }
2830 
2831     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2832         err = -EEXIST;
2833         goto out_nofid;
2834     }
2835 
2836     dfidp = get_fid(pdu, dfid);
2837     if (dfidp == NULL) {
2838         err = -EINVAL;
2839         goto out_nofid;
2840     }
2841     err = v9fs_co_symlink(pdu, dfidp, &name, symname.data, gid, &stbuf);
2842     if (err < 0) {
2843         goto out;
2844     }
2845     err = stat_to_qid(pdu, &stbuf, &qid);
2846     if (err < 0) {
2847         goto out;
2848     }
2849     err =  pdu_marshal(pdu, offset, "Q", &qid);
2850     if (err < 0) {
2851         goto out;
2852     }
2853     err += offset;
2854     trace_v9fs_symlink_return(pdu->tag, pdu->id,
2855                               qid.type, qid.version, qid.path);
2856 out:
2857     put_fid(pdu, dfidp);
2858 out_nofid:
2859     pdu_complete(pdu, err);
2860     v9fs_string_free(&name);
2861     v9fs_string_free(&symname);
2862 }
2863 
2864 static void coroutine_fn v9fs_flush(void *opaque)
2865 {
2866     ssize_t err;
2867     int16_t tag;
2868     size_t offset = 7;
2869     V9fsPDU *cancel_pdu = NULL;
2870     V9fsPDU *pdu = opaque;
2871     V9fsState *s = pdu->s;
2872 
2873     err = pdu_unmarshal(pdu, offset, "w", &tag);
2874     if (err < 0) {
2875         pdu_complete(pdu, err);
2876         return;
2877     }
2878     trace_v9fs_flush(pdu->tag, pdu->id, tag);
2879 
2880     if (pdu->tag == tag) {
2881         warn_report("the guest sent a self-referencing 9P flush request");
2882     } else {
2883         QLIST_FOREACH(cancel_pdu, &s->active_list, next) {
2884             if (cancel_pdu->tag == tag) {
2885                 break;
2886             }
2887         }
2888     }
2889     if (cancel_pdu) {
2890         cancel_pdu->cancelled = 1;
2891         /*
2892          * Wait for pdu to complete.
2893          */
2894         qemu_co_queue_wait(&cancel_pdu->complete, NULL);
2895         if (!qemu_co_queue_next(&cancel_pdu->complete)) {
2896             cancel_pdu->cancelled = 0;
2897             pdu_free(cancel_pdu);
2898         }
2899     }
2900     pdu_complete(pdu, 7);
2901 }
2902 
2903 static void coroutine_fn v9fs_link(void *opaque)
2904 {
2905     V9fsPDU *pdu = opaque;
2906     int32_t dfid, oldfid;
2907     V9fsFidState *dfidp, *oldfidp;
2908     V9fsString name;
2909     size_t offset = 7;
2910     int err = 0;
2911 
2912     v9fs_string_init(&name);
2913     err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
2914     if (err < 0) {
2915         goto out_nofid;
2916     }
2917     trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
2918 
2919     if (name_is_illegal(name.data)) {
2920         err = -ENOENT;
2921         goto out_nofid;
2922     }
2923 
2924     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
2925         err = -EEXIST;
2926         goto out_nofid;
2927     }
2928 
2929     dfidp = get_fid(pdu, dfid);
2930     if (dfidp == NULL) {
2931         err = -ENOENT;
2932         goto out_nofid;
2933     }
2934 
2935     oldfidp = get_fid(pdu, oldfid);
2936     if (oldfidp == NULL) {
2937         err = -ENOENT;
2938         goto out;
2939     }
2940     err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
2941     if (!err) {
2942         err = offset;
2943     }
2944     put_fid(pdu, oldfidp);
2945 out:
2946     put_fid(pdu, dfidp);
2947 out_nofid:
2948     v9fs_string_free(&name);
2949     pdu_complete(pdu, err);
2950 }
2951 
2952 /* Only works with path name based fid */
2953 static void coroutine_fn v9fs_remove(void *opaque)
2954 {
2955     int32_t fid;
2956     int err = 0;
2957     size_t offset = 7;
2958     V9fsFidState *fidp;
2959     V9fsPDU *pdu = opaque;
2960 
2961     err = pdu_unmarshal(pdu, offset, "d", &fid);
2962     if (err < 0) {
2963         goto out_nofid;
2964     }
2965     trace_v9fs_remove(pdu->tag, pdu->id, fid);
2966 
2967     fidp = get_fid(pdu, fid);
2968     if (fidp == NULL) {
2969         err = -EINVAL;
2970         goto out_nofid;
2971     }
2972     /* if fs driver is not path based, return EOPNOTSUPP */
2973     if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {
2974         err = -EOPNOTSUPP;
2975         goto out_err;
2976     }
2977     /*
2978      * IF the file is unlinked, we cannot reopen
2979      * the file later. So don't reclaim fd
2980      */
2981     err = v9fs_mark_fids_unreclaim(pdu, &fidp->path);
2982     if (err < 0) {
2983         goto out_err;
2984     }
2985     err = v9fs_co_remove(pdu, &fidp->path);
2986     if (!err) {
2987         err = offset;
2988     }
2989 out_err:
2990     /* For TREMOVE we need to clunk the fid even on failed remove */
2991     clunk_fid(pdu->s, fidp->fid);
2992     put_fid(pdu, fidp);
2993 out_nofid:
2994     pdu_complete(pdu, err);
2995 }
2996 
2997 static void coroutine_fn v9fs_unlinkat(void *opaque)
2998 {
2999     int err = 0;
3000     V9fsString name;
3001     int32_t dfid, flags, rflags = 0;
3002     size_t offset = 7;
3003     V9fsPath path;
3004     V9fsFidState *dfidp;
3005     V9fsPDU *pdu = opaque;
3006 
3007     v9fs_string_init(&name);
3008     err = pdu_unmarshal(pdu, offset, "dsd", &dfid, &name, &flags);
3009     if (err < 0) {
3010         goto out_nofid;
3011     }
3012 
3013     if (name_is_illegal(name.data)) {
3014         err = -ENOENT;
3015         goto out_nofid;
3016     }
3017 
3018     if (!strcmp(".", name.data)) {
3019         err = -EINVAL;
3020         goto out_nofid;
3021     }
3022 
3023     if (!strcmp("..", name.data)) {
3024         err = -ENOTEMPTY;
3025         goto out_nofid;
3026     }
3027 
3028     if (flags & ~P9_DOTL_AT_REMOVEDIR) {
3029         err = -EINVAL;
3030         goto out_nofid;
3031     }
3032 
3033     if (flags & P9_DOTL_AT_REMOVEDIR) {
3034         rflags |= AT_REMOVEDIR;
3035     }
3036 
3037     dfidp = get_fid(pdu, dfid);
3038     if (dfidp == NULL) {
3039         err = -EINVAL;
3040         goto out_nofid;
3041     }
3042     /*
3043      * IF the file is unlinked, we cannot reopen
3044      * the file later. So don't reclaim fd
3045      */
3046     v9fs_path_init(&path);
3047     err = v9fs_co_name_to_path(pdu, &dfidp->path, name.data, &path);
3048     if (err < 0) {
3049         goto out_err;
3050     }
3051     err = v9fs_mark_fids_unreclaim(pdu, &path);
3052     if (err < 0) {
3053         goto out_err;
3054     }
3055     err = v9fs_co_unlinkat(pdu, &dfidp->path, &name, rflags);
3056     if (!err) {
3057         err = offset;
3058     }
3059 out_err:
3060     put_fid(pdu, dfidp);
3061     v9fs_path_free(&path);
3062 out_nofid:
3063     pdu_complete(pdu, err);
3064     v9fs_string_free(&name);
3065 }
3066 
3067 
3068 /* Only works with path name based fid */
3069 static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp,
3070                                              int32_t newdirfid,
3071                                              V9fsString *name)
3072 {
3073     int err = 0;
3074     V9fsPath new_path;
3075     V9fsFidState *tfidp;
3076     V9fsState *s = pdu->s;
3077     V9fsFidState *dirfidp = NULL;
3078 
3079     v9fs_path_init(&new_path);
3080     if (newdirfid != -1) {
3081         dirfidp = get_fid(pdu, newdirfid);
3082         if (dirfidp == NULL) {
3083             return -ENOENT;
3084         }
3085         if (fidp->fid_type != P9_FID_NONE) {
3086             err = -EINVAL;
3087             goto out;
3088         }
3089         err = v9fs_co_name_to_path(pdu, &dirfidp->path, name->data, &new_path);
3090         if (err < 0) {
3091             goto out;
3092         }
3093     } else {
3094         char *dir_name = g_path_get_dirname(fidp->path.data);
3095         V9fsPath dir_path;
3096 
3097         v9fs_path_init(&dir_path);
3098         v9fs_path_sprintf(&dir_path, "%s", dir_name);
3099         g_free(dir_name);
3100 
3101         err = v9fs_co_name_to_path(pdu, &dir_path, name->data, &new_path);
3102         v9fs_path_free(&dir_path);
3103         if (err < 0) {
3104             goto out;
3105         }
3106     }
3107     err = v9fs_co_rename(pdu, &fidp->path, &new_path);
3108     if (err < 0) {
3109         goto out;
3110     }
3111     /*
3112      * Fixup fid's pointing to the old name to
3113      * start pointing to the new name
3114      */
3115     for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {
3116         if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) {
3117             /* replace the name */
3118             v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data));
3119         }
3120     }
3121 out:
3122     if (dirfidp) {
3123         put_fid(pdu, dirfidp);
3124     }
3125     v9fs_path_free(&new_path);
3126     return err;
3127 }
3128 
3129 /* Only works with path name based fid */
3130 static void coroutine_fn v9fs_rename(void *opaque)
3131 {
3132     int32_t fid;
3133     ssize_t err = 0;
3134     size_t offset = 7;
3135     V9fsString name;
3136     int32_t newdirfid;
3137     V9fsFidState *fidp;
3138     V9fsPDU *pdu = opaque;
3139     V9fsState *s = pdu->s;
3140 
3141     v9fs_string_init(&name);
3142     err = pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name);
3143     if (err < 0) {
3144         goto out_nofid;
3145     }
3146 
3147     if (name_is_illegal(name.data)) {
3148         err = -ENOENT;
3149         goto out_nofid;
3150     }
3151 
3152     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
3153         err = -EISDIR;
3154         goto out_nofid;
3155     }
3156 
3157     fidp = get_fid(pdu, fid);
3158     if (fidp == NULL) {
3159         err = -ENOENT;
3160         goto out_nofid;
3161     }
3162     if (fidp->fid_type != P9_FID_NONE) {
3163         err = -EINVAL;
3164         goto out;
3165     }
3166     /* if fs driver is not path based, return EOPNOTSUPP */
3167     if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {
3168         err = -EOPNOTSUPP;
3169         goto out;
3170     }
3171     v9fs_path_write_lock(s);
3172     err = v9fs_complete_rename(pdu, fidp, newdirfid, &name);
3173     v9fs_path_unlock(s);
3174     if (!err) {
3175         err = offset;
3176     }
3177 out:
3178     put_fid(pdu, fidp);
3179 out_nofid:
3180     pdu_complete(pdu, err);
3181     v9fs_string_free(&name);
3182 }
3183 
3184 static int coroutine_fn v9fs_fix_fid_paths(V9fsPDU *pdu, V9fsPath *olddir,
3185                                            V9fsString *old_name,
3186                                            V9fsPath *newdir,
3187                                            V9fsString *new_name)
3188 {
3189     V9fsFidState *tfidp;
3190     V9fsPath oldpath, newpath;
3191     V9fsState *s = pdu->s;
3192     int err;
3193 
3194     v9fs_path_init(&oldpath);
3195     v9fs_path_init(&newpath);
3196     err = v9fs_co_name_to_path(pdu, olddir, old_name->data, &oldpath);
3197     if (err < 0) {
3198         goto out;
3199     }
3200     err = v9fs_co_name_to_path(pdu, newdir, new_name->data, &newpath);
3201     if (err < 0) {
3202         goto out;
3203     }
3204 
3205     /*
3206      * Fixup fid's pointing to the old name to
3207      * start pointing to the new name
3208      */
3209     for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {
3210         if (v9fs_path_is_ancestor(&oldpath, &tfidp->path)) {
3211             /* replace the name */
3212             v9fs_fix_path(&tfidp->path, &newpath, strlen(oldpath.data));
3213         }
3214     }
3215 out:
3216     v9fs_path_free(&oldpath);
3217     v9fs_path_free(&newpath);
3218     return err;
3219 }
3220 
3221 static int coroutine_fn v9fs_complete_renameat(V9fsPDU *pdu, int32_t olddirfid,
3222                                                V9fsString *old_name,
3223                                                int32_t newdirfid,
3224                                                V9fsString *new_name)
3225 {
3226     int err = 0;
3227     V9fsState *s = pdu->s;
3228     V9fsFidState *newdirfidp = NULL, *olddirfidp = NULL;
3229 
3230     olddirfidp = get_fid(pdu, olddirfid);
3231     if (olddirfidp == NULL) {
3232         err = -ENOENT;
3233         goto out;
3234     }
3235     if (newdirfid != -1) {
3236         newdirfidp = get_fid(pdu, newdirfid);
3237         if (newdirfidp == NULL) {
3238             err = -ENOENT;
3239             goto out;
3240         }
3241     } else {
3242         newdirfidp = get_fid(pdu, olddirfid);
3243     }
3244 
3245     err = v9fs_co_renameat(pdu, &olddirfidp->path, old_name,
3246                            &newdirfidp->path, new_name);
3247     if (err < 0) {
3248         goto out;
3249     }
3250     if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) {
3251         /* Only for path based fid  we need to do the below fixup */
3252         err = v9fs_fix_fid_paths(pdu, &olddirfidp->path, old_name,
3253                                  &newdirfidp->path, new_name);
3254     }
3255 out:
3256     if (olddirfidp) {
3257         put_fid(pdu, olddirfidp);
3258     }
3259     if (newdirfidp) {
3260         put_fid(pdu, newdirfidp);
3261     }
3262     return err;
3263 }
3264 
3265 static void coroutine_fn v9fs_renameat(void *opaque)
3266 {
3267     ssize_t err = 0;
3268     size_t offset = 7;
3269     V9fsPDU *pdu = opaque;
3270     V9fsState *s = pdu->s;
3271     int32_t olddirfid, newdirfid;
3272     V9fsString old_name, new_name;
3273 
3274     v9fs_string_init(&old_name);
3275     v9fs_string_init(&new_name);
3276     err = pdu_unmarshal(pdu, offset, "dsds", &olddirfid,
3277                         &old_name, &newdirfid, &new_name);
3278     if (err < 0) {
3279         goto out_err;
3280     }
3281 
3282     if (name_is_illegal(old_name.data) || name_is_illegal(new_name.data)) {
3283         err = -ENOENT;
3284         goto out_err;
3285     }
3286 
3287     if (!strcmp(".", old_name.data) || !strcmp("..", old_name.data) ||
3288         !strcmp(".", new_name.data) || !strcmp("..", new_name.data)) {
3289         err = -EISDIR;
3290         goto out_err;
3291     }
3292 
3293     v9fs_path_write_lock(s);
3294     err = v9fs_complete_renameat(pdu, olddirfid,
3295                                  &old_name, newdirfid, &new_name);
3296     v9fs_path_unlock(s);
3297     if (!err) {
3298         err = offset;
3299     }
3300 
3301 out_err:
3302     pdu_complete(pdu, err);
3303     v9fs_string_free(&old_name);
3304     v9fs_string_free(&new_name);
3305 }
3306 
3307 static void coroutine_fn v9fs_wstat(void *opaque)
3308 {
3309     int32_t fid;
3310     int err = 0;
3311     int16_t unused;
3312     V9fsStat v9stat;
3313     size_t offset = 7;
3314     struct stat stbuf;
3315     V9fsFidState *fidp;
3316     V9fsPDU *pdu = opaque;
3317     V9fsState *s = pdu->s;
3318 
3319     v9fs_stat_init(&v9stat);
3320     err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat);
3321     if (err < 0) {
3322         goto out_nofid;
3323     }
3324     trace_v9fs_wstat(pdu->tag, pdu->id, fid,
3325                      v9stat.mode, v9stat.atime, v9stat.mtime);
3326 
3327     fidp = get_fid(pdu, fid);
3328     if (fidp == NULL) {
3329         err = -EINVAL;
3330         goto out_nofid;
3331     }
3332     /* do we need to sync the file? */
3333     if (donttouch_stat(&v9stat)) {
3334         err = v9fs_co_fsync(pdu, fidp, 0);
3335         goto out;
3336     }
3337     if (v9stat.mode != -1) {
3338         uint32_t v9_mode;
3339         err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
3340         if (err < 0) {
3341             goto out;
3342         }
3343         v9_mode = stat_to_v9mode(&stbuf);
3344         if ((v9stat.mode & P9_STAT_MODE_TYPE_BITS) !=
3345             (v9_mode & P9_STAT_MODE_TYPE_BITS)) {
3346             /* Attempting to change the type */
3347             err = -EIO;
3348             goto out;
3349         }
3350         err = v9fs_co_chmod(pdu, &fidp->path,
3351                             v9mode_to_mode(v9stat.mode,
3352                                            &v9stat.extension));
3353         if (err < 0) {
3354             goto out;
3355         }
3356     }
3357     if (v9stat.mtime != -1 || v9stat.atime != -1) {
3358         struct timespec times[2];
3359         if (v9stat.atime != -1) {
3360             times[0].tv_sec = v9stat.atime;
3361             times[0].tv_nsec = 0;
3362         } else {
3363             times[0].tv_nsec = UTIME_OMIT;
3364         }
3365         if (v9stat.mtime != -1) {
3366             times[1].tv_sec = v9stat.mtime;
3367             times[1].tv_nsec = 0;
3368         } else {
3369             times[1].tv_nsec = UTIME_OMIT;
3370         }
3371         err = v9fs_co_utimensat(pdu, &fidp->path, times);
3372         if (err < 0) {
3373             goto out;
3374         }
3375     }
3376     if (v9stat.n_gid != -1 || v9stat.n_uid != -1) {
3377         err = v9fs_co_chown(pdu, &fidp->path, v9stat.n_uid, v9stat.n_gid);
3378         if (err < 0) {
3379             goto out;
3380         }
3381     }
3382     if (v9stat.name.size != 0) {
3383         v9fs_path_write_lock(s);
3384         err = v9fs_complete_rename(pdu, fidp, -1, &v9stat.name);
3385         v9fs_path_unlock(s);
3386         if (err < 0) {
3387             goto out;
3388         }
3389     }
3390     if (v9stat.length != -1) {
3391         err = v9fs_co_truncate(pdu, &fidp->path, v9stat.length);
3392         if (err < 0) {
3393             goto out;
3394         }
3395     }
3396     err = offset;
3397 out:
3398     put_fid(pdu, fidp);
3399 out_nofid:
3400     v9fs_stat_free(&v9stat);
3401     pdu_complete(pdu, err);
3402 }
3403 
3404 static int v9fs_fill_statfs(V9fsState *s, V9fsPDU *pdu, struct statfs *stbuf)
3405 {
3406     uint32_t f_type;
3407     uint32_t f_bsize;
3408     uint64_t f_blocks;
3409     uint64_t f_bfree;
3410     uint64_t f_bavail;
3411     uint64_t f_files;
3412     uint64_t f_ffree;
3413     uint64_t fsid_val;
3414     uint32_t f_namelen;
3415     size_t offset = 7;
3416     int32_t bsize_factor;
3417 
3418     /*
3419      * compute bsize factor based on host file system block size
3420      * and client msize
3421      */
3422     bsize_factor = (s->msize - P9_IOHDRSZ)/stbuf->f_bsize;
3423     if (!bsize_factor) {
3424         bsize_factor = 1;
3425     }
3426     f_type  = stbuf->f_type;
3427     f_bsize = stbuf->f_bsize;
3428     f_bsize *= bsize_factor;
3429     /*
3430      * f_bsize is adjusted(multiplied) by bsize factor, so we need to
3431      * adjust(divide) the number of blocks, free blocks and available
3432      * blocks by bsize factor
3433      */
3434     f_blocks = stbuf->f_blocks/bsize_factor;
3435     f_bfree  = stbuf->f_bfree/bsize_factor;
3436     f_bavail = stbuf->f_bavail/bsize_factor;
3437     f_files  = stbuf->f_files;
3438     f_ffree  = stbuf->f_ffree;
3439     fsid_val = (unsigned int) stbuf->f_fsid.__val[0] |
3440                (unsigned long long)stbuf->f_fsid.__val[1] << 32;
3441     f_namelen = stbuf->f_namelen;
3442 
3443     return pdu_marshal(pdu, offset, "ddqqqqqqd",
3444                        f_type, f_bsize, f_blocks, f_bfree,
3445                        f_bavail, f_files, f_ffree,
3446                        fsid_val, f_namelen);
3447 }
3448 
3449 static void coroutine_fn v9fs_statfs(void *opaque)
3450 {
3451     int32_t fid;
3452     ssize_t retval = 0;
3453     size_t offset = 7;
3454     V9fsFidState *fidp;
3455     struct statfs stbuf;
3456     V9fsPDU *pdu = opaque;
3457     V9fsState *s = pdu->s;
3458 
3459     retval = pdu_unmarshal(pdu, offset, "d", &fid);
3460     if (retval < 0) {
3461         goto out_nofid;
3462     }
3463     fidp = get_fid(pdu, fid);
3464     if (fidp == NULL) {
3465         retval = -ENOENT;
3466         goto out_nofid;
3467     }
3468     retval = v9fs_co_statfs(pdu, &fidp->path, &stbuf);
3469     if (retval < 0) {
3470         goto out;
3471     }
3472     retval = v9fs_fill_statfs(s, pdu, &stbuf);
3473     if (retval < 0) {
3474         goto out;
3475     }
3476     retval += offset;
3477 out:
3478     put_fid(pdu, fidp);
3479 out_nofid:
3480     pdu_complete(pdu, retval);
3481 }
3482 
3483 static void coroutine_fn v9fs_mknod(void *opaque)
3484 {
3485 
3486     int mode;
3487     gid_t gid;
3488     int32_t fid;
3489     V9fsQID qid;
3490     int err = 0;
3491     int major, minor;
3492     size_t offset = 7;
3493     V9fsString name;
3494     struct stat stbuf;
3495     V9fsFidState *fidp;
3496     V9fsPDU *pdu = opaque;
3497 
3498     v9fs_string_init(&name);
3499     err = pdu_unmarshal(pdu, offset, "dsdddd", &fid, &name, &mode,
3500                         &major, &minor, &gid);
3501     if (err < 0) {
3502         goto out_nofid;
3503     }
3504     trace_v9fs_mknod(pdu->tag, pdu->id, fid, mode, major, minor);
3505 
3506     if (name_is_illegal(name.data)) {
3507         err = -ENOENT;
3508         goto out_nofid;
3509     }
3510 
3511     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
3512         err = -EEXIST;
3513         goto out_nofid;
3514     }
3515 
3516     fidp = get_fid(pdu, fid);
3517     if (fidp == NULL) {
3518         err = -ENOENT;
3519         goto out_nofid;
3520     }
3521     err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, gid,
3522                         makedev(major, minor), mode, &stbuf);
3523     if (err < 0) {
3524         goto out;
3525     }
3526     err = stat_to_qid(pdu, &stbuf, &qid);
3527     if (err < 0) {
3528         goto out;
3529     }
3530     err = pdu_marshal(pdu, offset, "Q", &qid);
3531     if (err < 0) {
3532         goto out;
3533     }
3534     err += offset;
3535     trace_v9fs_mknod_return(pdu->tag, pdu->id,
3536                             qid.type, qid.version, qid.path);
3537 out:
3538     put_fid(pdu, fidp);
3539 out_nofid:
3540     pdu_complete(pdu, err);
3541     v9fs_string_free(&name);
3542 }
3543 
3544 /*
3545  * Implement posix byte range locking code
3546  * Server side handling of locking code is very simple, because 9p server in
3547  * QEMU can handle only one client. And most of the lock handling
3548  * (like conflict, merging) etc is done by the VFS layer itself, so no need to
3549  * do any thing in * qemu 9p server side lock code path.
3550  * So when a TLOCK request comes, always return success
3551  */
3552 static void coroutine_fn v9fs_lock(void *opaque)
3553 {
3554     V9fsFlock flock;
3555     size_t offset = 7;
3556     struct stat stbuf;
3557     V9fsFidState *fidp;
3558     int32_t fid, err = 0;
3559     V9fsPDU *pdu = opaque;
3560 
3561     v9fs_string_init(&flock.client_id);
3562     err = pdu_unmarshal(pdu, offset, "dbdqqds", &fid, &flock.type,
3563                         &flock.flags, &flock.start, &flock.length,
3564                         &flock.proc_id, &flock.client_id);
3565     if (err < 0) {
3566         goto out_nofid;
3567     }
3568     trace_v9fs_lock(pdu->tag, pdu->id, fid,
3569                     flock.type, flock.start, flock.length);
3570 
3571 
3572     /* We support only block flag now (that too ignored currently) */
3573     if (flock.flags & ~P9_LOCK_FLAGS_BLOCK) {
3574         err = -EINVAL;
3575         goto out_nofid;
3576     }
3577     fidp = get_fid(pdu, fid);
3578     if (fidp == NULL) {
3579         err = -ENOENT;
3580         goto out_nofid;
3581     }
3582     err = v9fs_co_fstat(pdu, fidp, &stbuf);
3583     if (err < 0) {
3584         goto out;
3585     }
3586     err = pdu_marshal(pdu, offset, "b", P9_LOCK_SUCCESS);
3587     if (err < 0) {
3588         goto out;
3589     }
3590     err += offset;
3591     trace_v9fs_lock_return(pdu->tag, pdu->id, P9_LOCK_SUCCESS);
3592 out:
3593     put_fid(pdu, fidp);
3594 out_nofid:
3595     pdu_complete(pdu, err);
3596     v9fs_string_free(&flock.client_id);
3597 }
3598 
3599 /*
3600  * When a TGETLOCK request comes, always return success because all lock
3601  * handling is done by client's VFS layer.
3602  */
3603 static void coroutine_fn v9fs_getlock(void *opaque)
3604 {
3605     size_t offset = 7;
3606     struct stat stbuf;
3607     V9fsFidState *fidp;
3608     V9fsGetlock glock;
3609     int32_t fid, err = 0;
3610     V9fsPDU *pdu = opaque;
3611 
3612     v9fs_string_init(&glock.client_id);
3613     err = pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock.type,
3614                         &glock.start, &glock.length, &glock.proc_id,
3615                         &glock.client_id);
3616     if (err < 0) {
3617         goto out_nofid;
3618     }
3619     trace_v9fs_getlock(pdu->tag, pdu->id, fid,
3620                        glock.type, glock.start, glock.length);
3621 
3622     fidp = get_fid(pdu, fid);
3623     if (fidp == NULL) {
3624         err = -ENOENT;
3625         goto out_nofid;
3626     }
3627     err = v9fs_co_fstat(pdu, fidp, &stbuf);
3628     if (err < 0) {
3629         goto out;
3630     }
3631     glock.type = P9_LOCK_TYPE_UNLCK;
3632     err = pdu_marshal(pdu, offset, "bqqds", glock.type,
3633                           glock.start, glock.length, glock.proc_id,
3634                           &glock.client_id);
3635     if (err < 0) {
3636         goto out;
3637     }
3638     err += offset;
3639     trace_v9fs_getlock_return(pdu->tag, pdu->id, glock.type, glock.start,
3640                               glock.length, glock.proc_id);
3641 out:
3642     put_fid(pdu, fidp);
3643 out_nofid:
3644     pdu_complete(pdu, err);
3645     v9fs_string_free(&glock.client_id);
3646 }
3647 
3648 static void coroutine_fn v9fs_mkdir(void *opaque)
3649 {
3650     V9fsPDU *pdu = opaque;
3651     size_t offset = 7;
3652     int32_t fid;
3653     struct stat stbuf;
3654     V9fsQID qid;
3655     V9fsString name;
3656     V9fsFidState *fidp;
3657     gid_t gid;
3658     int mode;
3659     int err = 0;
3660 
3661     v9fs_string_init(&name);
3662     err = pdu_unmarshal(pdu, offset, "dsdd", &fid, &name, &mode, &gid);
3663     if (err < 0) {
3664         goto out_nofid;
3665     }
3666     trace_v9fs_mkdir(pdu->tag, pdu->id, fid, name.data, mode, gid);
3667 
3668     if (name_is_illegal(name.data)) {
3669         err = -ENOENT;
3670         goto out_nofid;
3671     }
3672 
3673     if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
3674         err = -EEXIST;
3675         goto out_nofid;
3676     }
3677 
3678     fidp = get_fid(pdu, fid);
3679     if (fidp == NULL) {
3680         err = -ENOENT;
3681         goto out_nofid;
3682     }
3683     err = v9fs_co_mkdir(pdu, fidp, &name, mode, fidp->uid, gid, &stbuf);
3684     if (err < 0) {
3685         goto out;
3686     }
3687     err = stat_to_qid(pdu, &stbuf, &qid);
3688     if (err < 0) {
3689         goto out;
3690     }
3691     err = pdu_marshal(pdu, offset, "Q", &qid);
3692     if (err < 0) {
3693         goto out;
3694     }
3695     err += offset;
3696     trace_v9fs_mkdir_return(pdu->tag, pdu->id,
3697                             qid.type, qid.version, qid.path, err);
3698 out:
3699     put_fid(pdu, fidp);
3700 out_nofid:
3701     pdu_complete(pdu, err);
3702     v9fs_string_free(&name);
3703 }
3704 
3705 static void coroutine_fn v9fs_xattrwalk(void *opaque)
3706 {
3707     int64_t size;
3708     V9fsString name;
3709     ssize_t err = 0;
3710     size_t offset = 7;
3711     int32_t fid, newfid;
3712     V9fsFidState *file_fidp;
3713     V9fsFidState *xattr_fidp = NULL;
3714     V9fsPDU *pdu = opaque;
3715     V9fsState *s = pdu->s;
3716 
3717     v9fs_string_init(&name);
3718     err = pdu_unmarshal(pdu, offset, "dds", &fid, &newfid, &name);
3719     if (err < 0) {
3720         goto out_nofid;
3721     }
3722     trace_v9fs_xattrwalk(pdu->tag, pdu->id, fid, newfid, name.data);
3723 
3724     file_fidp = get_fid(pdu, fid);
3725     if (file_fidp == NULL) {
3726         err = -ENOENT;
3727         goto out_nofid;
3728     }
3729     xattr_fidp = alloc_fid(s, newfid);
3730     if (xattr_fidp == NULL) {
3731         err = -EINVAL;
3732         goto out;
3733     }
3734     v9fs_path_copy(&xattr_fidp->path, &file_fidp->path);
3735     if (!v9fs_string_size(&name)) {
3736         /*
3737          * listxattr request. Get the size first
3738          */
3739         size = v9fs_co_llistxattr(pdu, &xattr_fidp->path, NULL, 0);
3740         if (size < 0) {
3741             err = size;
3742             clunk_fid(s, xattr_fidp->fid);
3743             goto out;
3744         }
3745         /*
3746          * Read the xattr value
3747          */
3748         xattr_fidp->fs.xattr.len = size;
3749         xattr_fidp->fid_type = P9_FID_XATTR;
3750         xattr_fidp->fs.xattr.xattrwalk_fid = true;
3751         xattr_fidp->fs.xattr.value = g_malloc0(size);
3752         if (size) {
3753             err = v9fs_co_llistxattr(pdu, &xattr_fidp->path,
3754                                      xattr_fidp->fs.xattr.value,
3755                                      xattr_fidp->fs.xattr.len);
3756             if (err < 0) {
3757                 clunk_fid(s, xattr_fidp->fid);
3758                 goto out;
3759             }
3760         }
3761         err = pdu_marshal(pdu, offset, "q", size);
3762         if (err < 0) {
3763             goto out;
3764         }
3765         err += offset;
3766     } else {
3767         /*
3768          * specific xattr fid. We check for xattr
3769          * presence also collect the xattr size
3770          */
3771         size = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
3772                                  &name, NULL, 0);
3773         if (size < 0) {
3774             err = size;
3775             clunk_fid(s, xattr_fidp->fid);
3776             goto out;
3777         }
3778         /*
3779          * Read the xattr value
3780          */
3781         xattr_fidp->fs.xattr.len = size;
3782         xattr_fidp->fid_type = P9_FID_XATTR;
3783         xattr_fidp->fs.xattr.xattrwalk_fid = true;
3784         xattr_fidp->fs.xattr.value = g_malloc0(size);
3785         if (size) {
3786             err = v9fs_co_lgetxattr(pdu, &xattr_fidp->path,
3787                                     &name, xattr_fidp->fs.xattr.value,
3788                                     xattr_fidp->fs.xattr.len);
3789             if (err < 0) {
3790                 clunk_fid(s, xattr_fidp->fid);
3791                 goto out;
3792             }
3793         }
3794         err = pdu_marshal(pdu, offset, "q", size);
3795         if (err < 0) {
3796             goto out;
3797         }
3798         err += offset;
3799     }
3800     trace_v9fs_xattrwalk_return(pdu->tag, pdu->id, size);
3801 out:
3802     put_fid(pdu, file_fidp);
3803     if (xattr_fidp) {
3804         put_fid(pdu, xattr_fidp);
3805     }
3806 out_nofid:
3807     pdu_complete(pdu, err);
3808     v9fs_string_free(&name);
3809 }
3810 
3811 static void coroutine_fn v9fs_xattrcreate(void *opaque)
3812 {
3813     int flags, rflags = 0;
3814     int32_t fid;
3815     uint64_t size;
3816     ssize_t err = 0;
3817     V9fsString name;
3818     size_t offset = 7;
3819     V9fsFidState *file_fidp;
3820     V9fsFidState *xattr_fidp;
3821     V9fsPDU *pdu = opaque;
3822 
3823     v9fs_string_init(&name);
3824     err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
3825     if (err < 0) {
3826         goto out_nofid;
3827     }
3828     trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
3829 
3830     if (flags & ~(P9_XATTR_CREATE | P9_XATTR_REPLACE)) {
3831         err = -EINVAL;
3832         goto out_nofid;
3833     }
3834 
3835     if (flags & P9_XATTR_CREATE) {
3836         rflags |= XATTR_CREATE;
3837     }
3838 
3839     if (flags & P9_XATTR_REPLACE) {
3840         rflags |= XATTR_REPLACE;
3841     }
3842 
3843     if (size > XATTR_SIZE_MAX) {
3844         err = -E2BIG;
3845         goto out_nofid;
3846     }
3847 
3848     file_fidp = get_fid(pdu, fid);
3849     if (file_fidp == NULL) {
3850         err = -EINVAL;
3851         goto out_nofid;
3852     }
3853     if (file_fidp->fid_type != P9_FID_NONE) {
3854         err = -EINVAL;
3855         goto out_put_fid;
3856     }
3857 
3858     /* Make the file fid point to xattr */
3859     xattr_fidp = file_fidp;
3860     xattr_fidp->fid_type = P9_FID_XATTR;
3861     xattr_fidp->fs.xattr.copied_len = 0;
3862     xattr_fidp->fs.xattr.xattrwalk_fid = false;
3863     xattr_fidp->fs.xattr.len = size;
3864     xattr_fidp->fs.xattr.flags = rflags;
3865     v9fs_string_init(&xattr_fidp->fs.xattr.name);
3866     v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
3867     xattr_fidp->fs.xattr.value = g_malloc0(size);
3868     err = offset;
3869 out_put_fid:
3870     put_fid(pdu, file_fidp);
3871 out_nofid:
3872     pdu_complete(pdu, err);
3873     v9fs_string_free(&name);
3874 }
3875 
3876 static void coroutine_fn v9fs_readlink(void *opaque)
3877 {
3878     V9fsPDU *pdu = opaque;
3879     size_t offset = 7;
3880     V9fsString target;
3881     int32_t fid;
3882     int err = 0;
3883     V9fsFidState *fidp;
3884 
3885     err = pdu_unmarshal(pdu, offset, "d", &fid);
3886     if (err < 0) {
3887         goto out_nofid;
3888     }
3889     trace_v9fs_readlink(pdu->tag, pdu->id, fid);
3890     fidp = get_fid(pdu, fid);
3891     if (fidp == NULL) {
3892         err = -ENOENT;
3893         goto out_nofid;
3894     }
3895 
3896     v9fs_string_init(&target);
3897     err = v9fs_co_readlink(pdu, &fidp->path, &target);
3898     if (err < 0) {
3899         goto out;
3900     }
3901     err = pdu_marshal(pdu, offset, "s", &target);
3902     if (err < 0) {
3903         v9fs_string_free(&target);
3904         goto out;
3905     }
3906     err += offset;
3907     trace_v9fs_readlink_return(pdu->tag, pdu->id, target.data);
3908     v9fs_string_free(&target);
3909 out:
3910     put_fid(pdu, fidp);
3911 out_nofid:
3912     pdu_complete(pdu, err);
3913 }
3914 
3915 static CoroutineEntry *pdu_co_handlers[] = {
3916     [P9_TREADDIR] = v9fs_readdir,
3917     [P9_TSTATFS] = v9fs_statfs,
3918     [P9_TGETATTR] = v9fs_getattr,
3919     [P9_TSETATTR] = v9fs_setattr,
3920     [P9_TXATTRWALK] = v9fs_xattrwalk,
3921     [P9_TXATTRCREATE] = v9fs_xattrcreate,
3922     [P9_TMKNOD] = v9fs_mknod,
3923     [P9_TRENAME] = v9fs_rename,
3924     [P9_TLOCK] = v9fs_lock,
3925     [P9_TGETLOCK] = v9fs_getlock,
3926     [P9_TRENAMEAT] = v9fs_renameat,
3927     [P9_TREADLINK] = v9fs_readlink,
3928     [P9_TUNLINKAT] = v9fs_unlinkat,
3929     [P9_TMKDIR] = v9fs_mkdir,
3930     [P9_TVERSION] = v9fs_version,
3931     [P9_TLOPEN] = v9fs_open,
3932     [P9_TATTACH] = v9fs_attach,
3933     [P9_TSTAT] = v9fs_stat,
3934     [P9_TWALK] = v9fs_walk,
3935     [P9_TCLUNK] = v9fs_clunk,
3936     [P9_TFSYNC] = v9fs_fsync,
3937     [P9_TOPEN] = v9fs_open,
3938     [P9_TREAD] = v9fs_read,
3939 #if 0
3940     [P9_TAUTH] = v9fs_auth,
3941 #endif
3942     [P9_TFLUSH] = v9fs_flush,
3943     [P9_TLINK] = v9fs_link,
3944     [P9_TSYMLINK] = v9fs_symlink,
3945     [P9_TCREATE] = v9fs_create,
3946     [P9_TLCREATE] = v9fs_lcreate,
3947     [P9_TWRITE] = v9fs_write,
3948     [P9_TWSTAT] = v9fs_wstat,
3949     [P9_TREMOVE] = v9fs_remove,
3950 };
3951 
3952 static void coroutine_fn v9fs_op_not_supp(void *opaque)
3953 {
3954     V9fsPDU *pdu = opaque;
3955     pdu_complete(pdu, -EOPNOTSUPP);
3956 }
3957 
3958 static void coroutine_fn v9fs_fs_ro(void *opaque)
3959 {
3960     V9fsPDU *pdu = opaque;
3961     pdu_complete(pdu, -EROFS);
3962 }
3963 
3964 static inline bool is_read_only_op(V9fsPDU *pdu)
3965 {
3966     switch (pdu->id) {
3967     case P9_TREADDIR:
3968     case P9_TSTATFS:
3969     case P9_TGETATTR:
3970     case P9_TXATTRWALK:
3971     case P9_TLOCK:
3972     case P9_TGETLOCK:
3973     case P9_TREADLINK:
3974     case P9_TVERSION:
3975     case P9_TLOPEN:
3976     case P9_TATTACH:
3977     case P9_TSTAT:
3978     case P9_TWALK:
3979     case P9_TCLUNK:
3980     case P9_TFSYNC:
3981     case P9_TOPEN:
3982     case P9_TREAD:
3983     case P9_TAUTH:
3984     case P9_TFLUSH:
3985         return 1;
3986     default:
3987         return 0;
3988     }
3989 }
3990 
3991 void pdu_submit(V9fsPDU *pdu, P9MsgHeader *hdr)
3992 {
3993     Coroutine *co;
3994     CoroutineEntry *handler;
3995     V9fsState *s = pdu->s;
3996 
3997     pdu->size = le32_to_cpu(hdr->size_le);
3998     pdu->id = hdr->id;
3999     pdu->tag = le16_to_cpu(hdr->tag_le);
4000 
4001     if (pdu->id >= ARRAY_SIZE(pdu_co_handlers) ||
4002         (pdu_co_handlers[pdu->id] == NULL)) {
4003         handler = v9fs_op_not_supp;
4004     } else if (is_ro_export(&s->ctx) && !is_read_only_op(pdu)) {
4005         handler = v9fs_fs_ro;
4006     } else {
4007         handler = pdu_co_handlers[pdu->id];
4008     }
4009 
4010     qemu_co_queue_init(&pdu->complete);
4011     co = qemu_coroutine_create(handler, pdu);
4012     qemu_coroutine_enter(co);
4013 }
4014 
4015 /* Returns 0 on success, 1 on failure. */
4016 int v9fs_device_realize_common(V9fsState *s, const V9fsTransport *t,
4017                                Error **errp)
4018 {
4019     ERRP_GUARD();
4020     int i, len;
4021     struct stat stat;
4022     FsDriverEntry *fse;
4023     V9fsPath path;
4024     int rc = 1;
4025 
4026     assert(!s->transport);
4027     s->transport = t;
4028 
4029     /* initialize pdu allocator */
4030     QLIST_INIT(&s->free_list);
4031     QLIST_INIT(&s->active_list);
4032     for (i = 0; i < MAX_REQ; i++) {
4033         QLIST_INSERT_HEAD(&s->free_list, &s->pdus[i], next);
4034         s->pdus[i].s = s;
4035         s->pdus[i].idx = i;
4036     }
4037 
4038     v9fs_path_init(&path);
4039 
4040     fse = get_fsdev_fsentry(s->fsconf.fsdev_id);
4041 
4042     if (!fse) {
4043         /* We don't have a fsdev identified by fsdev_id */
4044         error_setg(errp, "9pfs device couldn't find fsdev with the "
4045                    "id = %s",
4046                    s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL");
4047         goto out;
4048     }
4049 
4050     if (!s->fsconf.tag) {
4051         /* we haven't specified a mount_tag */
4052         error_setg(errp, "fsdev with id %s needs mount_tag arguments",
4053                    s->fsconf.fsdev_id);
4054         goto out;
4055     }
4056 
4057     s->ctx.export_flags = fse->export_flags;
4058     s->ctx.fs_root = g_strdup(fse->path);
4059     s->ctx.exops.get_st_gen = NULL;
4060     len = strlen(s->fsconf.tag);
4061     if (len > MAX_TAG_LEN - 1) {
4062         error_setg(errp, "mount tag '%s' (%d bytes) is longer than "
4063                    "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1);
4064         goto out;
4065     }
4066 
4067     s->tag = g_strdup(s->fsconf.tag);
4068     s->ctx.uid = -1;
4069 
4070     s->ops = fse->ops;
4071 
4072     s->ctx.fmode = fse->fmode;
4073     s->ctx.dmode = fse->dmode;
4074 
4075     s->fid_list = NULL;
4076     qemu_co_rwlock_init(&s->rename_lock);
4077 
4078     if (s->ops->init(&s->ctx, errp) < 0) {
4079         error_prepend(errp, "cannot initialize fsdev '%s': ",
4080                       s->fsconf.fsdev_id);
4081         goto out;
4082     }
4083 
4084     /*
4085      * Check details of export path, We need to use fs driver
4086      * call back to do that. Since we are in the init path, we don't
4087      * use co-routines here.
4088      */
4089     if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) {
4090         error_setg(errp,
4091                    "error in converting name to path %s", strerror(errno));
4092         goto out;
4093     }
4094     if (s->ops->lstat(&s->ctx, &path, &stat)) {
4095         error_setg(errp, "share path %s does not exist", fse->path);
4096         goto out;
4097     } else if (!S_ISDIR(stat.st_mode)) {
4098         error_setg(errp, "share path %s is not a directory", fse->path);
4099         goto out;
4100     }
4101 
4102     s->dev_id = stat.st_dev;
4103 
4104     /* init inode remapping : */
4105     /* hash table for variable length inode suffixes */
4106     qpd_table_init(&s->qpd_table);
4107     /* hash table for slow/full inode remapping (most users won't need it) */
4108     qpf_table_init(&s->qpf_table);
4109     /* hash table for quick inode remapping */
4110     qpp_table_init(&s->qpp_table);
4111     s->qp_ndevices = 0;
4112     s->qp_affix_next = 1; /* reserve 0 to detect overflow */
4113     s->qp_fullpath_next = 1;
4114 
4115     s->ctx.fst = &fse->fst;
4116     fsdev_throttle_init(s->ctx.fst);
4117 
4118     rc = 0;
4119 out:
4120     if (rc) {
4121         v9fs_device_unrealize_common(s);
4122     }
4123     v9fs_path_free(&path);
4124     return rc;
4125 }
4126 
4127 void v9fs_device_unrealize_common(V9fsState *s)
4128 {
4129     if (s->ops && s->ops->cleanup) {
4130         s->ops->cleanup(&s->ctx);
4131     }
4132     if (s->ctx.fst) {
4133         fsdev_throttle_cleanup(s->ctx.fst);
4134     }
4135     g_free(s->tag);
4136     qp_table_destroy(&s->qpd_table);
4137     qp_table_destroy(&s->qpp_table);
4138     qp_table_destroy(&s->qpf_table);
4139     g_free(s->ctx.fs_root);
4140 }
4141 
4142 typedef struct VirtfsCoResetData {
4143     V9fsPDU pdu;
4144     bool done;
4145 } VirtfsCoResetData;
4146 
4147 static void coroutine_fn virtfs_co_reset(void *opaque)
4148 {
4149     VirtfsCoResetData *data = opaque;
4150 
4151     virtfs_reset(&data->pdu);
4152     data->done = true;
4153 }
4154 
4155 void v9fs_reset(V9fsState *s)
4156 {
4157     VirtfsCoResetData data = { .pdu = { .s = s }, .done = false };
4158     Coroutine *co;
4159 
4160     while (!QLIST_EMPTY(&s->active_list)) {
4161         aio_poll(qemu_get_aio_context(), true);
4162     }
4163 
4164     co = qemu_coroutine_create(virtfs_co_reset, &data);
4165     qemu_coroutine_enter(co);
4166 
4167     while (!data.done) {
4168         aio_poll(qemu_get_aio_context(), true);
4169     }
4170 }
4171 
4172 static void __attribute__((__constructor__)) v9fs_set_fd_limit(void)
4173 {
4174     struct rlimit rlim;
4175     if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
4176         error_report("Failed to get the resource limit");
4177         exit(1);
4178     }
4179     open_fd_hw = rlim.rlim_cur - MIN(400, rlim.rlim_cur/3);
4180     open_fd_rc = rlim.rlim_cur/2;
4181 }
4182