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