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