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