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