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