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