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