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