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