long do_syscall(void *cpu_env, int num, long arg1, long arg2, long arg3,

                long arg4, long arg5, long arg6)

{

    long ret;

    struct stat st;

    struct kernel_statfs *stfs;

#ifdef DEBUG

    gemu_log("syscall %d\n", num);

#endif

    switch(num) {

    case TARGET_NR_exit:

#ifdef HAVE_GPROF

        _mcleanup();

#endif

        _exit(arg1);

        ret = 0; /* avoid warning */

        break;

    case TARGET_NR_read:

        ret = get_errno(read(arg1, (void *)arg2, arg3));

        break;

    case TARGET_NR_write:

        ret = get_errno(write(arg1, (void *)arg2, arg3));

        break;

    case TARGET_NR_open:

        ret = get_errno(open((const char *)arg1, arg2, arg3));

        break;

    case TARGET_NR_close:

        ret = get_errno(close(arg1));

        break;

    case TARGET_NR_brk:

        ret = do_brk((char *)arg1);

        break;

    case TARGET_NR_fork:

        ret = get_errno(fork());

        break;

    case TARGET_NR_waitpid:

        {

            int *status = (int *)arg2;

            ret = get_errno(waitpid(arg1, status, arg3));

            if (!is_error(ret) && status)

                tswapls((long *)&status);

        }

        break;

    case TARGET_NR_creat:

        ret = get_errno(creat((const char *)arg1, arg2));

        break;

    case TARGET_NR_link:

        ret = get_errno(link((const char *)arg1, (const char *)arg2));

        break;

    case TARGET_NR_unlink:

        ret = get_errno(unlink((const char *)arg1));

        break;

    case TARGET_NR_execve:

        ret = get_errno(execve((const char *)arg1, (void *)arg2, (void *)arg3));

        break;

    case TARGET_NR_chdir:

        ret = get_errno(chdir((const char *)arg1));

        break;

    case TARGET_NR_time:

        {

            int *time_ptr = (int *)arg1;

            ret = get_errno(time((time_t *)time_ptr));

            if (!is_error(ret) && time_ptr)

                tswap32s(time_ptr);

        }

        break;

    case TARGET_NR_mknod:

        ret = get_errno(mknod((const char *)arg1, arg2, arg3));

        break;

    case TARGET_NR_chmod:

        ret = get_errno(chmod((const char *)arg1, arg2));

        break;

    case TARGET_NR_lchown:

        ret = get_errno(chown((const char *)arg1, arg2, arg3));

        break;

    case TARGET_NR_break:

        goto unimplemented;

    case TARGET_NR_oldstat:

        goto unimplemented;

    case TARGET_NR_lseek:

        ret = get_errno(lseek(arg1, arg2, arg3));

        break;

    case TARGET_NR_getpid:

        ret = get_errno(getpid());

        break;

    case TARGET_NR_mount:

        /* need to look at the data field */

        goto unimplemented;

    case TARGET_NR_umount:

        ret = get_errno(umount((const char *)arg1));

        break;

    case TARGET_NR_setuid:

        ret = get_errno(setuid(arg1));

        break;

    case TARGET_NR_getuid:

        ret = get_errno(getuid());

        break;

    case TARGET_NR_stime:

        {

            int *time_ptr = (int *)arg1;

            if (time_ptr)

                tswap32s(time_ptr);

            ret = get_errno(stime((time_t *)time_ptr));

        }

        break;

    case TARGET_NR_ptrace:

        goto unimplemented;

    case TARGET_NR_alarm:

        ret = alarm(arg1);

        break;

    case TARGET_NR_oldfstat:

        goto unimplemented;

    case TARGET_NR_pause:

        ret = get_errno(pause());

        break;

    case TARGET_NR_utime:

        goto unimplemented;

    case TARGET_NR_stty:

        goto unimplemented;

    case TARGET_NR_gtty:

        goto unimplemented;

    case TARGET_NR_access:

        ret = get_errno(access((const char *)arg1, arg2));

        break;

    case TARGET_NR_nice:

        ret = get_errno(nice(arg1));

        break;

    case TARGET_NR_ftime:

        goto unimplemented;

    case TARGET_NR_sync:

        ret = get_errno(sync());

        break;

    case TARGET_NR_kill:

        ret = get_errno(kill(arg1, arg2));

        break;

    case TARGET_NR_rename:

        ret = get_errno(rename((const char *)arg1, (const char *)arg2));

        break;

    case TARGET_NR_mkdir:

        ret = get_errno(mkdir((const char *)arg1, arg2));

        break;

    case TARGET_NR_rmdir:

        ret = get_errno(rmdir((const char *)arg1));

        break;

    case TARGET_NR_dup:

        ret = get_errno(dup(arg1));

        break;

    case TARGET_NR_pipe:

        {

            int *pipe_ptr = (int *)arg1;

            ret = get_errno(pipe(pipe_ptr));

            if (!is_error(ret)) {

                tswap32s(&pipe_ptr[0]);

                tswap32s(&pipe_ptr[1]);

            }

        }

        break;

    case TARGET_NR_times:

        goto unimplemented;

    case TARGET_NR_prof:

        goto unimplemented;

    case TARGET_NR_setgid:

        ret = get_errno(setgid(arg1));

        break;

    case TARGET_NR_getgid:

        ret = get_errno(getgid());

        break;

    case TARGET_NR_signal:

        goto unimplemented;

    case TARGET_NR_geteuid:

        ret = get_errno(geteuid());

        break;

    case TARGET_NR_getegid:

        ret = get_errno(getegid());

        break;

    case TARGET_NR_acct:

        goto unimplemented;

    case TARGET_NR_umount2:

        ret = get_errno(umount2((const char *)arg1, arg2));

        break;

    case TARGET_NR_lock:

        goto unimplemented;

    case TARGET_NR_ioctl:

        ret = do_ioctl(arg1, arg2, arg3);

        break;

    case TARGET_NR_fcntl:

        switch(arg2) {

        case F_GETLK:

        case F_SETLK:

        case F_SETLKW:

            goto unimplemented;

        default:

            ret = get_errno(fcntl(arg1, arg2, arg3));

            break;

        }

        break;

    case TARGET_NR_mpx:

        goto unimplemented;

    case TARGET_NR_setpgid:

        ret = get_errno(setpgid(arg1, arg2));

        break;

    case TARGET_NR_ulimit:

        goto unimplemented;

    case TARGET_NR_oldolduname:

        goto unimplemented;

    case TARGET_NR_umask:

        ret = get_errno(umask(arg1));

        break;

    case TARGET_NR_chroot:

        ret = get_errno(chroot((const char *)arg1));

        break;

    case TARGET_NR_ustat:

        goto unimplemented;

    case TARGET_NR_dup2:

        ret = get_errno(dup2(arg1, arg2));

        break;

    case TARGET_NR_getppid:

        ret = get_errno(getppid());

        break;

    case TARGET_NR_getpgrp:

        ret = get_errno(getpgrp());

        break;

    case TARGET_NR_setsid:

        ret = get_errno(setsid());

        break;

    case TARGET_NR_sigaction:

#if 0

        {

            int signum = arg1;

            struct target_old_sigaction *tact = arg2, *toldact = arg3;

            ret = get_errno(setsid());

        }

        break;

#else

        goto unimplemented;

#endif

    case TARGET_NR_sgetmask:

        goto unimplemented;

    case TARGET_NR_ssetmask:

        goto unimplemented;

    case TARGET_NR_setreuid:

        ret = get_errno(setreuid(arg1, arg2));

        break;

    case TARGET_NR_setregid:

        ret = get_errno(setregid(arg1, arg2));

        break;

    case TARGET_NR_sigsuspend:

        goto unimplemented;

    case TARGET_NR_sigpending:

        goto unimplemented;

    case TARGET_NR_sethostname:

        ret = get_errno(sethostname((const char *)arg1, arg2));

        break;

    case TARGET_NR_setrlimit:

        goto unimplemented;

    case TARGET_NR_getrlimit:

        goto unimplemented;

    case TARGET_NR_getrusage:

        goto unimplemented;

    case TARGET_NR_gettimeofday:

        {

            struct target_timeval *target_tv = (void *)arg1;

            struct timeval tv;

            ret = get_errno(gettimeofday(&tv, NULL));

            if (!is_error(ret)) {

                target_tv->tv_sec = tswapl(tv.tv_sec);

                target_tv->tv_usec = tswapl(tv.tv_usec);

            }

        }

        break;

    case TARGET_NR_settimeofday:

        {

            struct target_timeval *target_tv = (void *)arg1;

            struct timeval tv;

            tv.tv_sec = tswapl(target_tv->tv_sec);

            tv.tv_usec = tswapl(target_tv->tv_usec);

            ret = get_errno(settimeofday(&tv, NULL));

        }

        break;

    case TARGET_NR_getgroups:

        goto unimplemented;

    case TARGET_NR_setgroups:

        goto unimplemented;

    case TARGET_NR_select:

        goto unimplemented;

    case TARGET_NR_symlink:

        ret = get_errno(symlink((const char *)arg1, (const char *)arg2));

        break;

    case TARGET_NR_oldlstat:

        goto unimplemented;

    case TARGET_NR_readlink:

        ret = get_errno(readlink((const char *)arg1, (char *)arg2, arg3));

        break;

    case TARGET_NR_uselib:

        goto unimplemented;

    case TARGET_NR_swapon:

        ret = get_errno(swapon((const char *)arg1, arg2));

        break;

    case TARGET_NR_reboot:

        goto unimplemented;

    case TARGET_NR_readdir:

        goto unimplemented;

#ifdef TARGET_I386

    case TARGET_NR_mmap:

        {

            uint32_t v1, v2, v3, v4, v5, v6, *vptr;

            vptr = (uint32_t *)arg1;

            v1 = tswap32(vptr[0]);

            v2 = tswap32(vptr[1]);

            v3 = tswap32(vptr[2]);

            v4 = tswap32(vptr[3]);

            v5 = tswap32(vptr[4]);

            v6 = tswap32(vptr[5]);

            ret = get_errno((long)mmap((void *)v1, v2, v3, v4, v5, v6));

        }

        break;

#endif

#ifdef TARGET_I386

    case TARGET_NR_mmap2:

#else

    case TARGET_NR_mmap:

#endif

        ret = get_errno((long)mmap((void *)arg1, arg2, arg3, arg4, arg5, arg6));

        break;

    case TARGET_NR_munmap:

        ret = get_errno(munmap((void *)arg1, arg2));

        break;

    case TARGET_NR_truncate:

        ret = get_errno(truncate((const char *)arg1, arg2));

        break;

    case TARGET_NR_ftruncate:

        ret = get_errno(ftruncate(arg1, arg2));

        break;

    case TARGET_NR_fchmod:

        ret = get_errno(fchmod(arg1, arg2));

        break;

    case TARGET_NR_fchown:

        ret = get_errno(fchown(arg1, arg2, arg3));

        break;

    case TARGET_NR_getpriority:

        ret = get_errno(getpriority(arg1, arg2));

        break;

    case TARGET_NR_setpriority:

        ret = get_errno(setpriority(arg1, arg2, arg3));

        break;

    case TARGET_NR_profil:

        goto unimplemented;

    case TARGET_NR_statfs:

        stfs = (void *)arg2;

        ret = get_errno(sys_statfs((const char *)arg1, stfs));

    convert_statfs:

        if (!is_error(ret)) {

            tswap32s(&stfs->f_type);

            tswap32s(&stfs->f_bsize);

            tswap32s(&stfs->f_blocks);

            tswap32s(&stfs->f_bfree);

            tswap32s(&stfs->f_bavail);

            tswap32s(&stfs->f_files);

            tswap32s(&stfs->f_ffree);

            tswap32s(&stfs->f_fsid.val[0]);

            tswap32s(&stfs->f_fsid.val[1]);

            tswap32s(&stfs->f_namelen);

        }

        break;

    case TARGET_NR_fstatfs:

        stfs = (void *)arg2;

        ret = get_errno(sys_fstatfs(arg1, stfs));

        goto convert_statfs;

    case TARGET_NR_ioperm:

        goto unimplemented;

    case TARGET_NR_socketcall:

        ret = do_socketcall(arg1, (long *)arg2);

        break;

    case TARGET_NR_syslog:

        goto unimplemented;

    case TARGET_NR_setitimer:

        goto unimplemented;

    case TARGET_NR_getitimer:

        goto unimplemented;

    case TARGET_NR_stat:

        ret = get_errno(stat((const char *)arg1, &st));

        goto do_stat;

    case TARGET_NR_lstat:

        ret = get_errno(lstat((const char *)arg1, &st));

        goto do_stat;

    case TARGET_NR_fstat:

        {

            ret = get_errno(fstat(arg1, &st));

        do_stat:

            if (!is_error(ret)) {

                struct target_stat *target_st = (void *)arg2;

                target_st->st_dev = tswap16(st.st_dev);

                target_st->st_ino = tswapl(st.st_ino);

                target_st->st_mode = tswap16(st.st_mode);

                target_st->st_nlink = tswap16(st.st_nlink);

                target_st->st_uid = tswap16(st.st_uid);

                target_st->st_gid = tswap16(st.st_gid);

                target_st->st_rdev = tswap16(st.st_rdev);

                target_st->st_size = tswapl(st.st_size);

                target_st->st_blksize = tswapl(st.st_blksize);

                target_st->st_blocks = tswapl(st.st_blocks);

                target_st->st_atime = tswapl(st.st_atime);

                target_st->st_mtime = tswapl(st.st_mtime);

                target_st->st_ctime = tswapl(st.st_ctime);

            }

        }

        break;

    case TARGET_NR_olduname:

        goto unimplemented;

    case TARGET_NR_iopl:

        goto unimplemented;

    case TARGET_NR_vhangup:

        ret = get_errno(vhangup());

        break;

    case TARGET_NR_idle:

        goto unimplemented;

    case TARGET_NR_vm86old:

        goto unimplemented;

    case TARGET_NR_wait4:

        {

            int status;

            target_long *status_ptr = (void *)arg2;

            struct rusage rusage, *rusage_ptr;

            struct target_rusage *target_rusage = (void *)arg4;

            if (target_rusage)

                rusage_ptr = &rusage;

            else

                rusage_ptr = NULL;

            ret = get_errno(wait4(arg1, &status, arg3, rusage_ptr));

            if (!is_error(ret)) {

                if (status_ptr)

                    *status_ptr = tswap32(status);

                if (target_rusage) {

                    target_rusage->ru_utime.tv_sec = tswapl(rusage.ru_utime.tv_sec);

                    target_rusage->ru_utime.tv_usec = tswapl(rusage.ru_utime.tv_usec);

                    target_rusage->ru_stime.tv_sec = tswapl(rusage.ru_stime.tv_sec);

                    target_rusage->ru_stime.tv_usec = tswapl(rusage.ru_stime.tv_usec);

                    target_rusage->ru_maxrss = tswapl(rusage.ru_maxrss);

                    target_rusage->ru_ixrss = tswapl(rusage.ru_ixrss);

                    target_rusage->ru_idrss = tswapl(rusage.ru_idrss);

                    target_rusage->ru_isrss = tswapl(rusage.ru_isrss);

                    target_rusage->ru_minflt = tswapl(rusage.ru_minflt);

                    target_rusage->ru_majflt = tswapl(rusage.ru_majflt);

                    target_rusage->ru_nswap = tswapl(rusage.ru_nswap);

                    target_rusage->ru_inblock = tswapl(rusage.ru_inblock);

                    target_rusage->ru_oublock = tswapl(rusage.ru_oublock);

                    target_rusage->ru_msgsnd = tswapl(rusage.ru_msgsnd);

                    target_rusage->ru_msgrcv = tswapl(rusage.ru_msgrcv);

                    target_rusage->ru_nsignals = tswapl(rusage.ru_nsignals);

                    target_rusage->ru_nvcsw = tswapl(rusage.ru_nvcsw);

                    target_rusage->ru_nivcsw = tswapl(rusage.ru_nivcsw);

                }

            }

        }

        break;

    case TARGET_NR_swapoff:

        ret = get_errno(swapoff((const char *)arg1));

        break;

    case TARGET_NR_sysinfo:

        goto unimplemented;

    case TARGET_NR_ipc:

        goto unimplemented;

    case TARGET_NR_fsync:

        ret = get_errno(fsync(arg1));

        break;

    case TARGET_NR_sigreturn:

        goto unimplemented;

    case TARGET_NR_clone:

        goto unimplemented;

    case TARGET_NR_setdomainname:

        ret = get_errno(setdomainname((const char *)arg1, arg2));

        break;

    case TARGET_NR_uname:

        /* no need to transcode because we use the linux syscall */

        ret = get_errno(sys_uname((struct new_utsname *)arg1));

        break;

#ifdef TARGET_I386

    case TARGET_NR_modify_ldt:

        ret = get_errno(gemu_modify_ldt(cpu_env, arg1, (void *)arg2, arg3));

        break;

#endif

    case TARGET_NR_adjtimex:

        goto unimplemented;

    case TARGET_NR_mprotect:

        ret = get_errno(mprotect((void *)arg1, arg2, arg3));

        break;

    case TARGET_NR_sigprocmask:

        {

            int how = arg1;

            sigset_t set, oldset, *set_ptr;

            target_ulong *pset = (void *)arg2, *poldset = (void *)arg3;

            switch(how) {

            case TARGET_SIG_BLOCK:

                how = SIG_BLOCK;

                break;

            case TARGET_SIG_UNBLOCK:

                how = SIG_UNBLOCK;

                break;

            case TARGET_SIG_SETMASK:

                how = SIG_SETMASK;

                break;

            default:

                ret = -EINVAL;

                goto fail;

            }

            if (pset) {

                target_to_host_old_sigset(&set, pset);

                set_ptr = &set;

            } else {

                set_ptr = NULL;

            }

            ret = get_errno(sigprocmask(arg1, set_ptr, &oldset));

            if (!is_error(ret) && poldset) {

                host_to_target_old_sigset(poldset, &oldset);

            }

        }

        break;

    case TARGET_NR_create_module:

    case TARGET_NR_init_module:

    case TARGET_NR_delete_module:

    case TARGET_NR_get_kernel_syms:

        goto unimplemented;

    case TARGET_NR_quotactl:

        goto unimplemented;

    case TARGET_NR_getpgid:

        ret = get_errno(getpgid(arg1));

        break;

    case TARGET_NR_fchdir:

        ret = get_errno(fchdir(arg1));

        break;

    case TARGET_NR_bdflush:

        goto unimplemented;

    case TARGET_NR_sysfs:

        goto unimplemented;

    case TARGET_NR_personality:

        ret = get_errno(mprotect((void *)arg1, arg2, arg3));

        break;

    case TARGET_NR_afs_syscall:

        goto unimplemented;

    case TARGET_NR_setfsuid:

        goto unimplemented;

    case TARGET_NR_setfsgid:

        goto unimplemented;

    case TARGET_NR__llseek:

        {

            int64_t res;

            ret = get_errno(_llseek(arg1, arg2, arg3, &res, arg5));

            *(int64_t *)arg4 = tswap64(res);

        }

        break;

    case TARGET_NR_getdents:

#if TARGET_LONG_SIZE != 4

#error not supported

#endif

        {

            struct dirent *dirp = (void *)arg2;

            long count = arg3;

            ret = get_errno(sys_getdents(arg1, dirp, count));

            if (!is_error(ret)) {

                struct dirent *de;

                int len = ret;

                int reclen;

                de = dirp;

                while (len > 0) {

                    reclen = tswap16(de->d_reclen);

                    if (reclen > len)

                        break;

                    de->d_reclen = reclen;

                    tswapls(&de->d_ino);

                    tswapls(&de->d_off);

                    de = (struct dirent *)((char *)de + reclen);

                    len -= reclen;

                }

            }

        }

        break;

    case TARGET_NR__newselect:

        ret = do_select(arg1, (void *)arg2, (void *)arg3, (void *)arg4,

                        (void *)arg5);

        break;

    case TARGET_NR_flock:

        goto unimplemented;

    case TARGET_NR_msync:

        ret = get_errno(msync((void *)arg1, arg2, arg3));

        break;

    case TARGET_NR_readv:

        {

            int count = arg3;

            int i;

            struct iovec *vec;

            struct target_iovec *target_vec = (void *)arg2;

            vec = alloca(count * sizeof(struct iovec));

            for(i = 0;i < count; i++) {

                vec[i].iov_base = (void *)tswapl(target_vec[i].iov_base);

                vec[i].iov_len = tswapl(target_vec[i].iov_len);

            }

            ret = get_errno(readv(arg1, vec, count));

        }

        break;

    case TARGET_NR_writev:

        {

            int count = arg3;

            int i;

            struct iovec *vec;

            struct target_iovec *target_vec = (void *)arg2;

            vec = alloca(count * sizeof(struct iovec));

            for(i = 0;i < count; i++) {

                vec[i].iov_base = (void *)tswapl(target_vec[i].iov_base);

                vec[i].iov_len = tswapl(target_vec[i].iov_len);

            }

            ret = get_errno(writev(arg1, vec, count));

        }

        break;

    case TARGET_NR_getsid:

        ret = get_errno(getsid(arg1));

        break;

    case TARGET_NR_fdatasync:

        goto unimplemented;

    case TARGET_NR__sysctl:

        goto unimplemented;

    case TARGET_NR_mlock:

        ret = get_errno(mlock((void *)arg1, arg2));

        break;

    case TARGET_NR_munlock:

        ret = get_errno(munlock((void *)arg1, arg2));

        break;

    case TARGET_NR_mlockall:

        ret = get_errno(mlockall(arg1));

        break;

    case TARGET_NR_munlockall:

        ret = get_errno(munlockall());

        break;

    case TARGET_NR_sched_setparam:

        goto unimplemented;

    case TARGET_NR_sched_getparam:

        goto unimplemented;

    case TARGET_NR_sched_setscheduler:

        goto unimplemented;

    case TARGET_NR_sched_getscheduler:

        goto unimplemented;

    case TARGET_NR_sched_yield:

        ret = get_errno(sched_yield());

        break;

    case TARGET_NR_sched_get_priority_max:

    case TARGET_NR_sched_get_priority_min:

    case TARGET_NR_sched_rr_get_interval:

    case TARGET_NR_nanosleep:

    case TARGET_NR_mremap:

    case TARGET_NR_setresuid:

    case TARGET_NR_getresuid:

    case TARGET_NR_vm86:

    case TARGET_NR_query_module:

    case TARGET_NR_poll:

    case TARGET_NR_nfsservctl:

    case TARGET_NR_setresgid:

    case TARGET_NR_getresgid:

    case TARGET_NR_prctl:

    case TARGET_NR_rt_sigreturn:

    case TARGET_NR_rt_sigaction:

    case TARGET_NR_rt_sigprocmask:

    case TARGET_NR_rt_sigpending:

    case TARGET_NR_rt_sigtimedwait:

    case TARGET_NR_rt_sigqueueinfo:

    case TARGET_NR_rt_sigsuspend:

    case TARGET_NR_pread:

    case TARGET_NR_pwrite:

        goto unimplemented;

    case TARGET_NR_chown:

        ret = get_errno(chown((const char *)arg1, arg2, arg3));

        break;

    case TARGET_NR_getcwd:

        ret = get_errno(sys_getcwd1((char *)arg1, arg2));

        break;

    case TARGET_NR_capget:

    case TARGET_NR_capset:

    case TARGET_NR_sigaltstack:

    case TARGET_NR_sendfile:

    case TARGET_NR_getpmsg:

    case TARGET_NR_putpmsg:

    case TARGET_NR_vfork:

        ret = get_errno(vfork());

        break;

    case TARGET_NR_ugetrlimit:

    case TARGET_NR_truncate64:

    case TARGET_NR_ftruncate64:

    case TARGET_NR_stat64:

    case TARGET_NR_lstat64:

    case TARGET_NR_fstat64:

    case TARGET_NR_lchown32:

    case TARGET_NR_getuid32:

    case TARGET_NR_getgid32:

    case TARGET_NR_geteuid32:

    case TARGET_NR_getegid32:

    case TARGET_NR_setreuid32:

    case TARGET_NR_setregid32:

    case TARGET_NR_getgroups32:

    case TARGET_NR_setgroups32:

    case TARGET_NR_fchown32:

    case TARGET_NR_setresuid32:

    case TARGET_NR_getresuid32:

    case TARGET_NR_setresgid32:

    case TARGET_NR_getresgid32:

    case TARGET_NR_chown32:

    case TARGET_NR_setuid32:

    case TARGET_NR_setgid32:

    case TARGET_NR_setfsuid32:

    case TARGET_NR_setfsgid32:

    case TARGET_NR_pivot_root:

    case TARGET_NR_mincore:

    case TARGET_NR_madvise:

    case TARGET_NR_getdents64:

    case TARGET_NR_fcntl64:

    case TARGET_NR_security:

        goto unimplemented;

    case TARGET_NR_gettid:

        ret = get_errno(gettid());

        break;

    case TARGET_NR_readahead:

    case TARGET_NR_setxattr:

    case TARGET_NR_lsetxattr:

    case TARGET_NR_fsetxattr:

    case TARGET_NR_getxattr:

    case TARGET_NR_lgetxattr:

    case TARGET_NR_fgetxattr:

    case TARGET_NR_listxattr:

    case TARGET_NR_llistxattr:

    case TARGET_NR_flistxattr:

    case TARGET_NR_removexattr:

    case TARGET_NR_lremovexattr:

    case TARGET_NR_fremovexattr:

        goto unimplemented;

    default:

    unimplemented:

        gemu_log("Unsupported syscall: %d\n", num);

        ret = -ENOSYS;

        break;

    }

 fail:

    return ret;

}


static int rebuild_refcount_structure(BlockDriverState *bs,

                                      BdrvCheckResult *res,

                                      void **refcount_table,

                                      int64_t *nb_clusters)

{

    BDRVQcow2State *s = bs->opaque;

    int64_t first_free_cluster = 0, reftable_offset = -1, cluster = 0;

    int64_t refblock_offset, refblock_start, refblock_index;

    uint32_t reftable_size = 0;

    uint64_t *on_disk_reftable = NULL;

    void *on_disk_refblock;

    int ret = 0;

    struct {

        uint64_t reftable_offset;

        uint32_t reftable_clusters;

    } QEMU_PACKED reftable_offset_and_clusters;

    qcow2_cache_empty(bs, s->refcount_block_cache);

write_refblocks:

    for (; cluster < *nb_clusters; cluster++) {

        if (!s->get_refcount(*refcount_table, cluster)) {

            continue;

        }

        refblock_index = cluster >> s->refcount_block_bits;

        refblock_start = refblock_index << s->refcount_block_bits;

        /* Don't allocate a cluster in a refblock already written to disk */

        if (first_free_cluster < refblock_start) {

            first_free_cluster = refblock_start;

        }

        refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,

                                              nb_clusters, &first_free_cluster);

        if (refblock_offset < 0) {

            fprintf(stderr, "ERROR allocating refblock: %s\n",

                    strerror(-refblock_offset));

            res->check_errors++;

            ret = refblock_offset;

            goto fail;

        }

        if (reftable_size <= refblock_index) {

            uint32_t old_reftable_size = reftable_size;

            uint64_t *new_on_disk_reftable;

            reftable_size = ROUND_UP((refblock_index + 1) * sizeof(uint64_t),

                                     s->cluster_size) / sizeof(uint64_t);

            new_on_disk_reftable = g_try_realloc(on_disk_reftable,

                                                 reftable_size *

                                                 sizeof(uint64_t));

            if (!new_on_disk_reftable) {

                res->check_errors++;

                ret = -ENOMEM;

                goto fail;

            }

            on_disk_reftable = new_on_disk_reftable;

            memset(on_disk_reftable + old_reftable_size, 0,

                   (reftable_size - old_reftable_size) * sizeof(uint64_t));

            /* The offset we have for the reftable is now no longer valid;

             * this will leak that range, but we can easily fix that by running

             * a leak-fixing check after this rebuild operation */

            reftable_offset = -1;

        }

        on_disk_reftable[refblock_index] = refblock_offset;

        /* If this is apparently the last refblock (for now), try to squeeze the

         * reftable in */

        if (refblock_index == (*nb_clusters - 1) >> s->refcount_block_bits &&

            reftable_offset < 0)

        {

            uint64_t reftable_clusters = size_to_clusters(s, reftable_size *

                                                          sizeof(uint64_t));

            reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,

                                                  refcount_table, nb_clusters,

                                                  &first_free_cluster);

            if (reftable_offset < 0) {

                fprintf(stderr, "ERROR allocating reftable: %s\n",

                        strerror(-reftable_offset));

                res->check_errors++;

                ret = reftable_offset;

                goto fail;

            }

        }

        ret = qcow2_pre_write_overlap_check(bs, 0, refblock_offset,

                                            s->cluster_size);

        if (ret < 0) {

            fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));

            goto fail;

        }

        /* The size of *refcount_table is always cluster-aligned, therefore the

         * write operation will not overflow */

        on_disk_refblock = (void *)((char *) *refcount_table +

                                    refblock_index * s->cluster_size);

        ret = bdrv_write(bs->file, refblock_offset / BDRV_SECTOR_SIZE,

                         on_disk_refblock, s->cluster_sectors);

        if (ret < 0) {

            fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));

            goto fail;

        }

        /* Go to the end of this refblock */

        cluster = refblock_start + s->refcount_block_size - 1;

    }

    if (reftable_offset < 0) {

        uint64_t post_refblock_start, reftable_clusters;

        post_refblock_start = ROUND_UP(*nb_clusters, s->refcount_block_size);

        reftable_clusters = size_to_clusters(s,

                                             reftable_size * sizeof(uint64_t));

        /* Not pretty but simple */

        if (first_free_cluster < post_refblock_start) {

            first_free_cluster = post_refblock_start;

        }

        reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,

                                              refcount_table, nb_clusters,

                                              &first_free_cluster);

        if (reftable_offset < 0) {

            fprintf(stderr, "ERROR allocating reftable: %s\n",

                    strerror(-reftable_offset));

            res->check_errors++;

            ret = reftable_offset;

            goto fail;

        }

        goto write_refblocks;

    }

    assert(on_disk_reftable);

    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {

        cpu_to_be64s(&on_disk_reftable[refblock_index]);

    }

    ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset,

                                        reftable_size * sizeof(uint64_t));

    if (ret < 0) {

        fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));

        goto fail;

    }

    assert(reftable_size < INT_MAX / sizeof(uint64_t));

    ret = bdrv_pwrite(bs->file, reftable_offset, on_disk_reftable,

                      reftable_size * sizeof(uint64_t));

    if (ret < 0) {

        fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));

        goto fail;

    }

    /* Enter new reftable into the image header */

    reftable_offset_and_clusters.reftable_offset = cpu_to_be64(reftable_offset);

    reftable_offset_and_clusters.reftable_clusters =

        cpu_to_be32(size_to_clusters(s, reftable_size * sizeof(uint64_t)));

    ret = bdrv_pwrite_sync(bs->file,

                           offsetof(QCowHeader, refcount_table_offset),

                           &reftable_offset_and_clusters,

                           sizeof(reftable_offset_and_clusters));

    if (ret < 0) {

        fprintf(stderr, "ERROR setting reftable: %s\n", strerror(-ret));

        goto fail;

    }

    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {

        be64_to_cpus(&on_disk_reftable[refblock_index]);

    }

    s->refcount_table = on_disk_reftable;

    s->refcount_table_offset = reftable_offset;

    s->refcount_table_size = reftable_size;

    update_max_refcount_table_index(s);

    return 0;

fail:

    g_free(on_disk_reftable);

    return ret;

}


static int synchronize_audio(VideoState *is, short *samples,

                             int samples_size1, double pts)

{

    int n, samples_size;

    double ref_clock;

    n = 2 * is->audio_st->codec->channels;

    samples_size = samples_size1;

    /* if not master, then we try to remove or add samples to correct the clock */

    if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||

         is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {

        double diff, avg_diff;

        int wanted_size, min_size, max_size, nb_samples;

        ref_clock = get_master_clock(is);

        diff = get_audio_clock(is) - ref_clock;

        if (diff < AV_NOSYNC_THRESHOLD) {

            is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;

            if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {

                /* not enough measures to have a correct estimate */

                is->audio_diff_avg_count++;

            } else {

                /* estimate the A-V difference */

                avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);

                if (fabs(avg_diff) >= is->audio_diff_threshold) {

                    wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n);

                    nb_samples = samples_size / n;

                    min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;

                    max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;

                    if (wanted_size < min_size)

                        wanted_size = min_size;

                    else if (wanted_size > max_size)

                        wanted_size = max_size;

                    /* add or remove samples to correction the synchro */

                    if (wanted_size < samples_size) {

                        /* remove samples */

                        samples_size = wanted_size;

                    } else if (wanted_size > samples_size) {

                        uint8_t *samples_end, *q;

                        int nb;

                        /* add samples */

                        nb = (samples_size - wanted_size);

                        samples_end = (uint8_t *)samples + samples_size - n;

                        q = samples_end + n;

                        while (nb > 0) {

                            memcpy(q, samples_end, n);

                            q += n;

                            nb -= n;

                        }

                        samples_size = wanted_size;

                    }

                }

                av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",

                        diff, avg_diff, samples_size - samples_size1,

                        is->audio_clock, is->video_clock, is->audio_diff_threshold);

            }

        } else {

            /* too big difference : may be initial PTS errors, so

               reset A-V filter */

            is->audio_diff_avg_count = 0;

            is->audio_diff_cum       = 0;

        }

    }

    return samples_size;

}


av_cold int ff_ivi_init_planes(IVIPlaneDesc *planes, const IVIPicConfig *cfg,

                               int is_indeo4)

{

    int p, b;

    uint32_t b_width, b_height, align_fac, width_aligned,

             height_aligned, buf_size;

    IVIBandDesc *band;

    ivi_free_buffers(planes);

    if (av_image_check_size(cfg->pic_width, cfg->pic_height, 0, NULL) < 0 ||

        cfg->luma_bands < 1 || cfg->chroma_bands < 1)

        return AVERROR_INVALIDDATA;

    /* fill in the descriptor of the luminance plane */

    planes[0].width     = cfg->pic_width;

    planes[0].height    = cfg->pic_height;

    planes[0].num_bands = cfg->luma_bands;

    /* fill in the descriptors of the chrominance planes */

    planes[1].width     = planes[2].width     = (cfg->pic_width  + 3) >> 2;

    planes[1].height    = planes[2].height    = (cfg->pic_height + 3) >> 2;

    planes[1].num_bands = planes[2].num_bands = cfg->chroma_bands;

    for (p = 0; p < 3; p++) {

        planes[p].bands = av_mallocz_array(planes[p].num_bands, sizeof(IVIBandDesc));

        if (!planes[p].bands)

            return AVERROR(ENOMEM);

        /* select band dimensions: if there is only one band then it

         *  has the full size, if there are several bands each of them

         *  has only half size */

        b_width  = planes[p].num_bands == 1 ? planes[p].width

                                            : (planes[p].width  + 1) >> 1;

        b_height = planes[p].num_bands == 1 ? planes[p].height

                                            : (planes[p].height + 1) >> 1;

        /* luma   band buffers will be aligned on 16x16 (max macroblock size) */

        /* chroma band buffers will be aligned on   8x8 (max macroblock size) */

        align_fac       = p ? 8 : 16;

        width_aligned   = FFALIGN(b_width , align_fac);

        height_aligned  = FFALIGN(b_height, align_fac);

        buf_size        = width_aligned * height_aligned * sizeof(int16_t);

        for (b = 0; b < planes[p].num_bands; b++) {

            band = &planes[p].bands[b]; /* select appropriate plane/band */

            band->plane    = p;

            band->band_num = b;

            band->width    = b_width;

            band->height   = b_height;

            band->pitch    = width_aligned;

            band->aheight  = height_aligned;

            band->bufs[0]  = av_mallocz(buf_size);

            band->bufs[1]  = av_mallocz(buf_size);

            band->bufsize  = buf_size/2;

            if (!band->bufs[0] || !band->bufs[1])

                return AVERROR(ENOMEM);

            /* allocate the 3rd band buffer for scalability mode */

            if (cfg->luma_bands > 1) {

                band->bufs[2] = av_mallocz(buf_size);

                if (!band->bufs[2])

                    return AVERROR(ENOMEM);

            }

            if (is_indeo4) {

                band->bufs[3]  = av_mallocz(buf_size);

                if (!band->bufs[3])

                    return AVERROR(ENOMEM);

            }

            /* reset custom vlc */

            planes[p].bands[0].blk_vlc.cust_desc.num_rows = 0;

        }

    }

    return 0;

}


static av_cold int seqvideo_decode_init(AVCodecContext *avctx)
{
    SeqVideoContext *seq = avctx->priv_data;
    seq->avctx = avctx;
    avctx->pix_fmt = AV_PIX_FMT_PAL8;
    seq->frame = av_frame_alloc();
    if (!seq->frame)
        return AVERROR(ENOMEM);
    return 0;
}


static BlockAIOCB *bdrv_co_aio_rw_vector(BdrvChild *child,

                                         int64_t sector_num,

                                         QEMUIOVector *qiov,

                                         int nb_sectors,

                                         BdrvRequestFlags flags,

                                         BlockCompletionFunc *cb,

                                         void *opaque,

                                         bool is_write)

{

    Coroutine *co;

    BlockAIOCBCoroutine *acb;

    acb = qemu_aio_get(&bdrv_em_co_aiocb_info, child->bs, cb, opaque);

    acb->child = child;

    acb->need_bh = true;

    acb->req.error = -EINPROGRESS;

    acb->req.sector = sector_num;

    acb->req.nb_sectors = nb_sectors;

    acb->req.qiov = qiov;

    acb->req.flags = flags;

    acb->is_write = is_write;

    co = qemu_coroutine_create(bdrv_co_do_rw);

    qemu_coroutine_enter(co, acb);

    bdrv_co_maybe_schedule_bh(acb);

    return &acb->common;

}


static int standard_decode_picture_secondary_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    int status = 0, index;

    switch (v->s.pict_type)

    {

    case P_TYPE: status = decode_p_picture_secondary_header(v); break;

    case B_TYPE: status = decode_b_picture_secondary_header(v); break;

    case BI_TYPE:

    case I_TYPE: break; //Nothing needed as it's done in the epilog

    }

    if (status < 0) return FRAME_SKIPED;

    /* AC Syntax */

    v->ac_table_level = decode012(gb);

    if (v->s.pict_type == I_TYPE || v->s.pict_type == BI_TYPE)

    {

        v->ac2_table_level = decode012(gb);

    }

    /* DC Syntax */

    index = decode012(gb);

    v->luma_dc_vlc = &ff_msmp4_dc_luma_vlc[index];

    v->chroma_dc_vlc = &ff_msmp4_dc_chroma_vlc[index];

    return 0;

}


static void ccw_machine_class_init(ObjectClass *oc, void *data)

{

    MachineClass *mc = MACHINE_CLASS(oc);

    NMIClass *nc = NMI_CLASS(oc);

    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);

    S390CcwMachineClass *s390mc = S390_MACHINE_CLASS(mc);

    s390mc->ri_allowed = true;

    s390mc->cpu_model_allowed = true;

    s390mc->css_migration_enabled = true;

    s390mc->gs_allowed = true;

    mc->init = ccw_init;

    mc->reset = s390_machine_reset;

    mc->hot_add_cpu = s390_hot_add_cpu;

    mc->block_default_type = IF_VIRTIO;

    mc->no_cdrom = 1;

    mc->no_floppy = 1;

    mc->no_serial = 1;

    mc->no_parallel = 1;

    mc->no_sdcard = 1;

    mc->use_sclp = 1;

    mc->max_cpus = S390_MAX_CPUS;

    mc->has_hotpluggable_cpus = true;

    mc->get_hotplug_handler = s390_get_hotplug_handler;

    mc->cpu_index_to_instance_props = s390_cpu_index_to_props;

    mc->possible_cpu_arch_ids = s390_possible_cpu_arch_ids;

    /* it is overridden with 'host' cpu *in kvm_arch_init* */

    mc->default_cpu_type = S390_CPU_TYPE_NAME("qemu");

    hc->plug = s390_machine_device_plug;

    hc->unplug_request = s390_machine_device_unplug_request;

    nc->nmi_monitor_handler = s390_nmi;

}


static int write_cvid_header(CinepakEncContext *s, unsigned char *buf, int num_strips, int data_size)

{

    buf[0] = 0;

    AV_WB24(&buf[1], data_size + CVID_HEADER_SIZE);

    AV_WB16(&buf[4], s->w);

    AV_WB16(&buf[6], s->h);

    AV_WB16(&buf[8], num_strips);

    return CVID_HEADER_SIZE;

}


static av_cold int mpeg4video_parse_init(AVCodecParserContext *s)

{

    ParseContext1 *pc = s->priv_data;

    pc->enc = av_mallocz(sizeof(MpegEncContext));

    if (!pc->enc)

        return -1;

    pc->first_picture = 1;

    return 0;

}


const AVOption *av_opt_next(void *obj, const AVOption *last)

{

    AVClass *class = *(AVClass**)obj;

    if (!last && class->option[0].name) return class->option;

    if (last && last[1].name)           return ++last;

    return NULL;

}


static void do_audio_out(AVFormatContext *s, OutputStream *ost,

                         InputStream *ist, AVFrame *decoded_frame)

{

    uint8_t *buftmp;

    int size_out, frame_bytes, resample_changed, ret;

    AVCodecContext *enc = ost->st->codec;

    AVCodecContext *dec = ist->st->codec;

    int osize = av_get_bytes_per_sample(enc->sample_fmt);

    int isize = av_get_bytes_per_sample(dec->sample_fmt);

    uint8_t *buf = decoded_frame->data[0];

    int size     = decoded_frame->nb_samples * dec->channels * isize;

    int out_linesize = 0;

    int buf_linesize = decoded_frame->linesize[0];

    get_default_channel_layouts(ost, ist);

    if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples, &out_linesize) < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");

        exit_program(1);

    }

    if (audio_sync_method > 1                      ||

        enc->channels       != dec->channels       ||

        enc->channel_layout != dec->channel_layout ||

        enc->sample_rate    != dec->sample_rate    ||

        dec->sample_fmt     != enc->sample_fmt)

        ost->audio_resample = 1;

    resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||

                       ost->resample_channels    != dec->channels   ||

                       ost->resample_channel_layout != dec->channel_layout ||

                       ost->resample_sample_rate != dec->sample_rate;

    if ((ost->audio_resample && !ost->avr) || resample_changed) {

        if (resample_changed) {

            av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:0x%"PRIx64" to rate:%d fmt:%s ch:%d chl:0x%"PRIx64"\n",

                   ist->file_index, ist->st->index,

                   ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt),

                   ost->resample_channels, ost->resample_channel_layout,

                   dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt),

                   dec->channels, dec->channel_layout);

            ost->resample_sample_fmt  = dec->sample_fmt;

            ost->resample_channels    = dec->channels;

            ost->resample_channel_layout = dec->channel_layout;

            ost->resample_sample_rate = dec->sample_rate;

            if (ost->avr)

                avresample_close(ost->avr);

        }

        /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */

        if (audio_sync_method <= 1 &&

            ost->resample_sample_fmt  == enc->sample_fmt &&

            ost->resample_channels    == enc->channels   &&

            ost->resample_channel_layout == enc->channel_layout &&

            ost->resample_sample_rate == enc->sample_rate) {

            ost->audio_resample = 0;

        } else if (ost->audio_resample) {

            if (!ost->avr) {

                ost->avr = avresample_alloc_context();

                if (!ost->avr) {

                    av_log(NULL, AV_LOG_FATAL, "Error allocating context for libavresample\n");

                    exit_program(1);

                }

            }

            av_opt_set_int(ost->avr, "in_channel_layout",  dec->channel_layout, 0);

            av_opt_set_int(ost->avr, "in_sample_fmt",      dec->sample_fmt,     0);

            av_opt_set_int(ost->avr, "in_sample_rate",     dec->sample_rate,    0);

            av_opt_set_int(ost->avr, "out_channel_layout", enc->channel_layout, 0);

            av_opt_set_int(ost->avr, "out_sample_fmt",     enc->sample_fmt,     0);

            av_opt_set_int(ost->avr, "out_sample_rate",    enc->sample_rate,    0);

            if (audio_sync_method > 1)

                av_opt_set_int(ost->avr, "force_resampling", 1, 0);

            /* if both the input and output formats are s16 or u8, use s16 as

               the internal sample format */

            if (av_get_bytes_per_sample(dec->sample_fmt) <= 2 &&

                av_get_bytes_per_sample(enc->sample_fmt) <= 2) {

                av_opt_set_int(ost->avr, "internal_sample_fmt", AV_SAMPLE_FMT_S16P, 0);

            }

            ret = avresample_open(ost->avr);

            if (ret < 0) {

                av_log(NULL, AV_LOG_FATAL, "Error opening libavresample\n");

                exit_program(1);

            }

        }

    }

    if (audio_sync_method > 0) {

        double delta = get_sync_ipts(ost, ist->last_dts) * enc->sample_rate - ost->sync_opts -

                       av_fifo_size(ost->fifo) / (enc->channels * osize);

        int idelta = delta * dec->sample_rate / enc->sample_rate;

        int byte_delta = idelta * isize * dec->channels;

        // FIXME resample delay

        if (fabs(delta) > 50) {

            if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {

                if (byte_delta < 0) {

                    byte_delta = FFMAX(byte_delta, -size);

                    size += byte_delta;

                    buf  -= byte_delta;

                    av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",

                           -byte_delta / (isize * dec->channels));

                    if (!size)

                        return;

                    ist->is_start = 0;

                } else {

                    av_fast_malloc(&async_buf, &allocated_async_buf_size,

                                   byte_delta + size);

                    if (!async_buf) {

                        av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");

                        exit_program(1);

                    }

                    if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta, &out_linesize) < 0) {

                        av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");

                        exit_program(1);

                    }

                    ist->is_start = 0;

                    generate_silence(async_buf, dec->sample_fmt, byte_delta);

                    memcpy(async_buf + byte_delta, buf, size);

                    buf = async_buf;

                    size += byte_delta;

                    buf_linesize = allocated_async_buf_size;

                    av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);

                }

            } else if (audio_sync_method > 1) {

                int comp = av_clip(delta, -audio_sync_method, audio_sync_method);

                av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",

                       delta, comp, enc->sample_rate);

//                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2));

                avresample_set_compensation(ost->avr, comp, enc->sample_rate);

            }

        }

    } else if (audio_sync_method == 0)

        ost->sync_opts = lrintf(get_sync_ipts(ost, ist->last_dts) * enc->sample_rate) -

                                av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong

    if (ost->audio_resample) {

        buftmp = audio_buf;

        size_out = avresample_convert(ost->avr, (void **)&buftmp,

                                      allocated_audio_buf_size, out_linesize,

                                      (void **)&buf, buf_linesize,

                                      size / (dec->channels * isize));

        size_out = size_out * enc->channels * osize;

    } else {

        buftmp = buf;

        size_out = size;

    }

    /* now encode as many frames as possible */

    if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {

        /* output resampled raw samples */

        if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {

            av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");

            exit_program(1);

        }

        av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);

        frame_bytes = enc->frame_size * osize * enc->channels;

        while (av_fifo_size(ost->fifo) >= frame_bytes) {

            av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);

            encode_audio_frame(s, ost, audio_buf, frame_bytes);

        }

    } else {

        encode_audio_frame(s, ost, buftmp, size_out);

    }

}


static inline void gen_arm_shift_im(TCGv var, int shiftop, int shift, int flags)

{

    switch (shiftop) {

    case 0: /* LSL */

        if (shift != 0) {

            if (flags)

                shifter_out_im(var, 32 - shift);

            tcg_gen_shli_i32(var, var, shift);

        }

        break;

    case 1: /* LSR */

        if (shift == 0) {

            if (flags) {

                tcg_gen_shri_i32(var, var, 31);

                gen_set_CF(var);

            }

            tcg_gen_movi_i32(var, 0);

        } else {

            if (flags)

                shifter_out_im(var, shift - 1);

            tcg_gen_shri_i32(var, var, shift);

        }

        break;

    case 2: /* ASR */

        if (shift == 0)

            shift = 32;

        if (flags)

            shifter_out_im(var, shift - 1);

        if (shift == 32)

          shift = 31;

        tcg_gen_sari_i32(var, var, shift);

        break;

    case 3: /* ROR/RRX */

        if (shift != 0) {

            if (flags)

                shifter_out_im(var, shift - 1);

            tcg_gen_rotri_i32(var, var, shift); break;

        } else {

            TCGv tmp = load_cpu_field(CF);

            if (flags)

                shifter_out_im(var, 0);

            tcg_gen_shri_i32(var, var, 1);

            tcg_gen_shli_i32(tmp, tmp, 31);

            tcg_gen_or_i32(var, var, tmp);

            dead_tmp(tmp);

        }

    }

};


static void vmxnet3_update_vlan_filters(VMXNET3State *s)

{

    int i;

    /* Copy configuration from shared memory */

    VMXNET3_READ_DRV_SHARED(s->drv_shmem,

                            devRead.rxFilterConf.vfTable,

                            s->vlan_table,

                            sizeof(s->vlan_table));

    /* Invert byte order when needed */

    for (i = 0; i < ARRAY_SIZE(s->vlan_table); i++) {

        s->vlan_table[i] = le32_to_cpu(s->vlan_table[i]);

    }

    /* Dump configuration for debugging purposes */

    VMW_CFPRN("Configured VLANs:");

    for (i = 0; i < sizeof(s->vlan_table) * 8; i++) {

        if (VMXNET3_VFTABLE_ENTRY_IS_SET(s->vlan_table, i)) {

            VMW_CFPRN("\tVLAN %d is present", i);

        }

    }

}


static void arm_timer_recalibrate(arm_timer_state *s, int reload)

{

    uint32_t limit;

    if ((s->control & TIMER_CTRL_PERIODIC) == 0) {

        /* Free running.  */

        if (s->control & TIMER_CTRL_32BIT)

            limit = 0xffffffff;

        else

            limit = 0xffff;

    } else {

          /* Periodic.  */

          limit = s->limit;

    }

    ptimer_set_limit(s->timer, limit, reload);

}


static void term_down_char(void)

{

    if (term_hist_entry == TERM_MAX_CMDS - 1 || term_hist_entry == -1)

	return;

    if (term_history[++term_hist_entry] != NULL) {

	pstrcpy(term_cmd_buf, sizeof(term_cmd_buf),

                term_history[term_hist_entry]);

    } else {

	term_hist_entry = -1;

    }

    term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf);

}


int kvm_log_start(target_phys_addr_t phys_addr, ram_addr_t size)

{

        return kvm_dirty_pages_log_change(phys_addr, size,

                                          KVM_MEM_LOG_DIRTY_PAGES,

                                          KVM_MEM_LOG_DIRTY_PAGES);

}


static void do_log(int argc, const char **argv)

{

    int mask;

    if (argc != 2)

        goto help;

    if (!strcmp(argv[1], "none")) {

        mask = 0;

    } else {

        mask = cpu_str_to_log_mask(argv[1]);

        if (!mask) {

        help:

            help_cmd(argv[0]);

            return;

        }

    }

    cpu_set_log(mask);

}


static int hls_decode_entry(AVCodecContext *avctxt, void *isFilterThread)

{

    HEVCContext *s  = avctxt->priv_data;

    int ctb_size    = 1 << s->sps->log2_ctb_size;

    int more_data   = 1;

    int x_ctb       = 0;

    int y_ctb       = 0;

    int ctb_addr_ts = s->pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs];

    if (!ctb_addr_ts && s->sh.dependent_slice_segment_flag) {

        av_log(s->avctx, AV_LOG_ERROR, "Impossible initial tile.\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->sh.dependent_slice_segment_flag) {

        int prev_rs = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts - 1];

        if (s->tab_slice_address[prev_rs] == -1) {

            av_log(s->avctx, AV_LOG_ERROR, "Previous slice segment missing\n");

            return AVERROR_INVALIDDATA;

        }

    }

    while (more_data && ctb_addr_ts < s->sps->ctb_size) {

        int ctb_addr_rs = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];

        x_ctb = (ctb_addr_rs % ((s->sps->width + ctb_size - 1) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;

        y_ctb = (ctb_addr_rs / ((s->sps->width + ctb_size - 1) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;

        hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);

        ff_hevc_cabac_init(s, ctb_addr_ts);

        hls_sao_param(s, x_ctb >> s->sps->log2_ctb_size, y_ctb >> s->sps->log2_ctb_size);

        s->deblock[ctb_addr_rs].beta_offset = s->sh.beta_offset;

        s->deblock[ctb_addr_rs].tc_offset   = s->sh.tc_offset;

        s->filter_slice_edges[ctb_addr_rs]  = s->sh.slice_loop_filter_across_slices_enabled_flag;

        more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->sps->log2_ctb_size, 0);

        if (more_data < 0) {

            s->tab_slice_address[ctb_addr_rs] = -1;

            return more_data;

        }

        ctb_addr_ts++;

        ff_hevc_save_states(s, ctb_addr_ts);

        ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);

    }

    if (x_ctb + ctb_size >= s->sps->width &&

        y_ctb + ctb_size >= s->sps->height)

        ff_hevc_hls_filter(s, x_ctb, y_ctb);

    return ctb_addr_ts;

}


static int decode_header(MPADecodeContext *s, UINT32 header)

{

    int sample_rate, frame_size, mpeg25, padding;

    int sample_rate_index, bitrate_index;

    if (header & (1<<20)) {

        s->lsf = (header & (1<<19)) ? 0 : 1;

        mpeg25 = 0;

    } else {

        s->lsf = 1;

        mpeg25 = 1;

    }

    s->layer = 4 - ((header >> 17) & 3);

    /* extract frequency */

    sample_rate_index = (header >> 10) & 3;

    sample_rate = mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);

    if (sample_rate == 0)

        return 1;

    sample_rate_index += 3 * (s->lsf + mpeg25);

    s->sample_rate_index = sample_rate_index;

    s->error_protection = ((header >> 16) & 1) ^ 1;

    bitrate_index = (header >> 12) & 0xf;

    padding = (header >> 9) & 1;

    //extension = (header >> 8) & 1;

    s->mode = (header >> 6) & 3;

    s->mode_ext = (header >> 4) & 3;

    //copyright = (header >> 3) & 1;

    //original = (header >> 2) & 1;

    //emphasis = header & 3;

    if (s->mode == MPA_MONO)

        s->nb_channels = 1;

    else

        s->nb_channels = 2;

    if (bitrate_index != 0) {

        frame_size = mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];

        s->bit_rate = frame_size * 1000;

        switch(s->layer) {

        case 1:

            frame_size = (frame_size * 12000) / sample_rate;

            frame_size = (frame_size + padding) * 4;

            break;

        case 2:

            frame_size = (frame_size * 144000) / sample_rate;

            frame_size += padding;

            break;

        default:

        case 3:

            frame_size = (frame_size * 144000) / (sample_rate << s->lsf);

            frame_size += padding;

            break;

        }

        s->frame_size = frame_size;

    } else {

        /* if no frame size computed, signal it */

        if (!s->free_format_frame_size)

            return 1;

        /* free format: compute bitrate and real frame size from the

           frame size we extracted by reading the bitstream */

        s->frame_size = s->free_format_frame_size;

        switch(s->layer) {

        case 1:

            s->frame_size += padding  * 4;

            s->bit_rate = (s->frame_size * sample_rate) / 48000;

            break;

        case 2:

            s->frame_size += padding;

            s->bit_rate = (s->frame_size * sample_rate) / 144000;

            break;

        default:

        case 3:

            s->frame_size += padding;

            s->bit_rate = (s->frame_size * (sample_rate << s->lsf)) / 144000;

            break;

        }

    }

    s->sample_rate = sample_rate;

#if defined(DEBUG)

    printf("layer%d, %d Hz, %d kbits/s, ",

           s->layer, s->sample_rate, s->bit_rate);

    if (s->nb_channels == 2) {

        if (s->layer == 3) {

            if (s->mode_ext & MODE_EXT_MS_STEREO)

                printf("ms-");

            if (s->mode_ext & MODE_EXT_I_STEREO)

                printf("i-");

        }

        printf("stereo");

    } else {

        printf("mono");

    }

    printf("\n");

#endif

    return 0;

}


static av_cold int init(AVFilterContext *ctx, const char *args)

{

    GradFunContext *gf = ctx->priv;

    float thresh = 1.2;

    int radius = 16;

    if (args)

        sscanf(args, "%f:%d", &thresh, &radius);

    thresh = av_clipf(thresh, 0.51, 255);

    gf->thresh = (1 << 15) / thresh;

    gf->radius = av_clip((radius + 1) & ~1, 4, 32);

    gf->blur_line = ff_gradfun_blur_line_c;

    gf->filter_line = ff_gradfun_filter_line_c;

    if (ARCH_X86)

        ff_gradfun_init_x86(gf);

    av_log(ctx, AV_LOG_VERBOSE, "threshold:%.2f radius:%d\n", thresh, gf->radius);

    return 0;

}


static int kvm_client_migration_log(struct CPUPhysMemoryClient *client,

				    int enable)

{

	return kvm_set_migration_log(enable);

}


static int64_t rtmp_read_seek(URLContext *s, int stream_index,

                              int64_t timestamp, int flags)

{

    RTMP *r = s->priv_data;

    if (flags & AVSEEK_FLAG_BYTE)

        return AVERROR(ENOSYS);

    /* seeks are in milliseconds */

    timestamp = av_rescale(timestamp, AV_TIME_BASE, 1000);

    if (!RTMP_SendSeek(r, timestamp))

        return -1;

    return timestamp;

}


static av_cold int mace_decode_init(AVCodecContext * avctx)

{

    MACEContext *ctx = avctx->priv_data;

    if (avctx->channels > 2)

        return -1;

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    avcodec_get_frame_defaults(&ctx->frame);

    avctx->coded_frame = &ctx->frame;

    return 0;

}


float16 float32_to_float16(float32 a, flag ieee STATUS_PARAM)

{

    flag aSign;

    int_fast16_t aExp;

    uint32_t aSig;

    uint32_t mask;

    uint32_t increment;

    int8 roundingMode;

    a = float32_squash_input_denormal(a STATUS_VAR);

    aSig = extractFloat32Frac( a );

    aExp = extractFloat32Exp( a );

    aSign = extractFloat32Sign( a );

    if ( aExp == 0xFF ) {

        if (aSig) {

            /* Input is a NaN */

            float16 r = commonNaNToFloat16( float32ToCommonNaN( a STATUS_VAR ) STATUS_VAR );

            if (!ieee) {

                return packFloat16(aSign, 0, 0);

            }

            return r;

        }

        /* Infinity */

        if (!ieee) {

            float_raise(float_flag_invalid STATUS_VAR);

            return packFloat16(aSign, 0x1f, 0x3ff);

        }

        return packFloat16(aSign, 0x1f, 0);

    }

    if (aExp == 0 && aSig == 0) {

        return packFloat16(aSign, 0, 0);

    }

    /* Decimal point between bits 22 and 23.  */

    aSig |= 0x00800000;

    aExp -= 0x7f;

    if (aExp < -14) {

        mask = 0x00ffffff;

        if (aExp >= -24) {

            mask >>= 25 + aExp;

        }

    } else {

        mask = 0x00001fff;

    }

    if (aSig & mask) {

        float_raise( float_flag_underflow STATUS_VAR );

        roundingMode = STATUS(float_rounding_mode);

        switch (roundingMode) {

        case float_round_nearest_even:

            increment = (mask + 1) >> 1;

            if ((aSig & mask) == increment) {

                increment = aSig & (increment << 1);

            }

            break;

        case float_round_up:

            increment = aSign ? 0 : mask;

            break;

        case float_round_down:

            increment = aSign ? mask : 0;

            break;

        default: /* round_to_zero */

            increment = 0;

            break;

        }

        aSig += increment;

        if (aSig >= 0x01000000) {

            aSig >>= 1;

            aExp++;

        }

    } else if (aExp < -14

          && STATUS(float_detect_tininess) == float_tininess_before_rounding) {

        float_raise( float_flag_underflow STATUS_VAR);

    }

    if (ieee) {

        if (aExp > 15) {

            float_raise( float_flag_overflow | float_flag_inexact STATUS_VAR);

            return packFloat16(aSign, 0x1f, 0);

        }

    } else {

        if (aExp > 16) {

            float_raise(float_flag_invalid | float_flag_inexact STATUS_VAR);

            return packFloat16(aSign, 0x1f, 0x3ff);

        }

    }

    if (aExp < -24) {

        return packFloat16(aSign, 0, 0);

    }

    if (aExp < -14) {

        aSig >>= -14 - aExp;

        aExp = -14;

    }

    return packFloat16(aSign, aExp + 14, aSig >> 13);

}


int virtqueue_avail_bytes(VirtQueue *vq, int in_bytes, int out_bytes)

{

    unsigned int idx;

    unsigned int total_bufs, in_total, out_total;

    idx = vq->last_avail_idx;

    total_bufs = in_total = out_total = 0;

    while (virtqueue_num_heads(vq, idx)) {

        unsigned int max, num_bufs, indirect = 0;

        target_phys_addr_t desc_pa;

        int i;

        max = vq->vring.num;

        num_bufs = total_bufs;

        i = virtqueue_get_head(vq, idx++);

        desc_pa = vq->vring.desc;

        if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {

            if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {

                error_report("Invalid size for indirect buffer table");

                exit(1);

            }

            /* If we've got too many, that implies a descriptor loop. */

            if (num_bufs >= max) {

                error_report("Looped descriptor");

                exit(1);

            }

            /* loop over the indirect descriptor table */

            indirect = 1;

            max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);

            num_bufs = i = 0;

            desc_pa = vring_desc_addr(desc_pa, i);

        }

        do {

            /* If we've got too many, that implies a descriptor loop. */

            if (++num_bufs > max) {

                error_report("Looped descriptor");

                exit(1);

            }

            if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {

                if (in_bytes > 0 &&

                    (in_total += vring_desc_len(desc_pa, i)) >= in_bytes)

                    return 1;

            } else {

                if (out_bytes > 0 &&

                    (out_total += vring_desc_len(desc_pa, i)) >= out_bytes)

                    return 1;

            }

        } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);

        if (!indirect)

            total_bufs = num_bufs;

        else

            total_bufs++;

    }

    return 0;

}


static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)

{

    CharDriverState *chr;

    FDCharDriver *s;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(FDCharDriver));

    s->fd_in = io_channel_from_fd(fd_in);

    s->fd_out = io_channel_from_fd(fd_out);

    fcntl(fd_out, F_SETFL, O_NONBLOCK);

    s->chr = chr;

    chr->opaque = s;

    chr->chr_add_watch = fd_chr_add_watch;

    chr->chr_write = fd_chr_write;

    chr->chr_update_read_handler = fd_chr_update_read_handler;

    chr->chr_close = fd_chr_close;

    qemu_chr_be_generic_open(chr);

    return chr;

}


static int g722_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                             const AVFrame *frame, int *got_packet_ptr)

{

    G722Context *c = avctx->priv_data;

    const int16_t *samples = (const int16_t *)frame->data[0];

    int nb_samples, out_size, ret;

    out_size = (frame->nb_samples + 1) / 2;

    if ((ret = ff_alloc_packet2(avctx, avpkt, out_size)))

        return ret;

    nb_samples = frame->nb_samples - (frame->nb_samples & 1);

    if (avctx->trellis)

        g722_encode_trellis(c, avctx->trellis, avpkt->data, nb_samples, samples);

    else

        g722_encode_no_trellis(c, avpkt->data, nb_samples, samples);

    /* handle last frame with odd frame_size */

    if (nb_samples < frame->nb_samples) {

        int16_t last_samples[2] = { samples[nb_samples], samples[nb_samples] };

        encode_byte(c, &avpkt->data[nb_samples >> 1], last_samples);

    }

    if (frame->pts != AV_NOPTS_VALUE)

        avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);

    *got_packet_ptr = 1;

    return 0;

}


static int gif_image_write_image(AVCodecContext *avctx,

                                 uint8_t **bytestream, uint8_t *end,

                                 const uint32_t *palette,

                                 const uint8_t *buf, const int linesize,

                                 AVPacket *pkt)

{

    GIFContext *s = avctx->priv_data;

    int len = 0, height = avctx->height, width = avctx->width, x, y;

    int x_start = 0, y_start = 0, trans = s->transparent_index;

    int honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame;

    const uint8_t *ptr;

    /* Crop image */

    if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {

        const uint8_t *ref = s->last_frame->data[0];

        const int ref_linesize = s->last_frame->linesize[0];

        int x_end = avctx->width  - 1,

            y_end = avctx->height - 1;

        /* skip common lines */

        while (y_start < y_end) {

            if (memcmp(ref + y_start*ref_linesize, buf + y_start*linesize, width))

                break;

            y_start++;

        }

        while (y_end > y_start) {

            if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, width))

                break;

            y_end--;

        }

        height = y_end + 1 - y_start;

        /* skip common columns */

        while (x_start < x_end) {

            int same_column = 1;

            for (y = y_start; y <= y_end; y++) {

                if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {

                    same_column = 0;

                    break;

                }

            }

            if (!same_column)

                break;

            x_start++;

        }

        while (x_end > x_start) {

            int same_column = 1;

            for (y = y_start; y <= y_end; y++) {

                if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {

                    same_column = 0;

                    break;

                }

            }

            if (!same_column)

                break;

            x_end--;

        }

        width = x_end + 1 - x_start;

        av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",

               width, height, x_start, y_start, avctx->width, avctx->height);

    }

    /* image block */

    bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);

    bytestream_put_le16(bytestream, x_start);

    bytestream_put_le16(bytestream, y_start);

    bytestream_put_le16(bytestream, width);

    bytestream_put_le16(bytestream, height);

    if (!palette) {

        bytestream_put_byte(bytestream, 0x00); /* flags */

    } else {

        unsigned i;

        bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */

        for (i = 0; i < AVPALETTE_COUNT; i++) {

            const uint32_t v = palette[i];

            bytestream_put_be24(bytestream, v);

        }

    }

    if (honor_transparency && trans < 0) {

        trans = pick_palette_entry(buf + y_start*linesize + x_start,

                                   linesize, width, height);

        if (trans < 0) { // TODO, patch welcome

            av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");

        } else {

            uint8_t *pal_exdata = s->pal_exdata;

            if (!pal_exdata)

                pal_exdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);

            if (!pal_exdata)

                return AVERROR(ENOMEM);

            memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);

            pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;

        }

    }

    if (trans < 0)

        honor_transparency = 0;

    bytestream_put_byte(bytestream, 0x08);

    ff_lzw_encode_init(s->lzw, s->buf, 2 * width * height,

                       12, FF_LZW_GIF, put_bits);

    ptr = buf + y_start*linesize + x_start;

    if (honor_transparency) {

        const int ref_linesize = s->last_frame->linesize[0];

        const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;

        for (y = 0; y < height; y++) {

            memcpy(s->tmpl, ptr, width);

            for (x = 0; x < width; x++)

                if (ref[x] == ptr[x])

                    s->tmpl[x] = trans;

            len += ff_lzw_encode(s->lzw, s->tmpl, width);

            ptr += linesize;

            ref += ref_linesize;

        }

    } else {

        for (y = 0; y < height; y++) {

            len += ff_lzw_encode(s->lzw, ptr, width);

            ptr += linesize;

        }

    }

    len += ff_lzw_encode_flush(s->lzw, flush_put_bits);

    ptr = s->buf;

    while (len > 0) {

        int size = FFMIN(255, len);

        bytestream_put_byte(bytestream, size);

        if (end - *bytestream < size)

            return -1;

        bytestream_put_buffer(bytestream, ptr, size);

        ptr += size;

        len -= size;

    }

    bytestream_put_byte(bytestream, 0x00); /* end of image block */

    return 0;

}


static int openfile(char *name, int flags)

{

	if (bs) {

		fprintf(stderr, "file open already, try 'help close'\n");

		return 1;

	}

	bs = bdrv_new("hda");

	if (!bs)

		return 1;

	if (bdrv_open(bs, name, flags) == -1) {

		fprintf(stderr, "%s: can't open device %s\n", progname, name);

		bs = NULL;

		return 1;

	}

	return 0;

}


static void e500_pcihost_bridge_realize(PCIDevice *d, Error **errp)

{

    PPCE500PCIBridgeState *b = PPC_E500_PCI_BRIDGE(d);

    PPCE500CCSRState *ccsr = CCSR(container_get(qdev_get_machine(),

                                  "/e500-ccsr"));

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_PCI);

    d->config[PCI_HEADER_TYPE] =

        (d->config[PCI_HEADER_TYPE] & PCI_HEADER_TYPE_MULTI_FUNCTION) |

        PCI_HEADER_TYPE_BRIDGE;

    memory_region_init_alias(&b->bar0, OBJECT(ccsr), "e500-pci-bar0", &ccsr->ccsr_space,

                             0, int128_get64(ccsr->ccsr_space.size));

    pci_register_bar(d, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &b->bar0);

}


void ff_clear_fixed_vector(float *out, const AMRFixed *in, int size)

{

    int i;

    for (i=0; i < in->n; i++) {

        int x  = in->x[i], repeats = !((in->no_repeat_mask >> i) & 1);

        do {

            out[x] = 0.0;

            x += in->pitch_lag;

        } while (x < size && repeats);

    }

}


static int film_read_header(AVFormatContext *s,

                            AVFormatParameters *ap)

{

    FilmDemuxContext *film = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st;

    unsigned char scratch[256];

    int i;

    unsigned int data_offset;

    unsigned int audio_frame_counter;

    film->sample_table = NULL;

    film->stereo_buffer = NULL;

    film->stereo_buffer_size = 0;

    /* load the main FILM header */

    if (avio_read(pb, scratch, 16) != 16)

        return AVERROR(EIO);

    data_offset = AV_RB32(&scratch[4]);

    film->version = AV_RB32(&scratch[8]);

    /* load the FDSC chunk */

    if (film->version == 0) {

        /* special case for Lemmings .film files; 20-byte header */

        if (avio_read(pb, scratch, 20) != 20)

            return AVERROR(EIO);

        /* make some assumptions about the audio parameters */

        film->audio_type = CODEC_ID_PCM_S8;

        film->audio_samplerate = 22050;

        film->audio_channels = 1;

        film->audio_bits = 8;

    } else {

        /* normal Saturn .cpk files; 32-byte header */

        if (avio_read(pb, scratch, 32) != 32)

            return AVERROR(EIO);

        film->audio_samplerate = AV_RB16(&scratch[24]);

        film->audio_channels = scratch[21];

        film->audio_bits = scratch[22];

        if (scratch[23] == 2)

            film->audio_type = CODEC_ID_ADPCM_ADX;

        else if (film->audio_bits == 8)

            film->audio_type = CODEC_ID_PCM_S8;

        else if (film->audio_bits == 16)

            film->audio_type = CODEC_ID_PCM_S16BE;

        else

            film->audio_type = CODEC_ID_NONE;

    }

    if (AV_RB32(&scratch[0]) != FDSC_TAG)

        return AVERROR_INVALIDDATA;

    if (AV_RB32(&scratch[8]) == CVID_TAG) {

        film->video_type = CODEC_ID_CINEPAK;

    } else

        film->video_type = CODEC_ID_NONE;

    /* initialize the decoder streams */

    if (film->video_type) {

        st = av_new_stream(s, 0);

        if (!st)

            return AVERROR(ENOMEM);

        film->video_stream_index = st->index;

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id = film->video_type;

        st->codec->codec_tag = 0;  /* no fourcc */

        st->codec->width = AV_RB32(&scratch[16]);

        st->codec->height = AV_RB32(&scratch[12]);

    }

    if (film->audio_type) {

        st = av_new_stream(s, 0);

        if (!st)

            return AVERROR(ENOMEM);

        film->audio_stream_index = st->index;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = film->audio_type;

        st->codec->codec_tag = 1;

        st->codec->channels = film->audio_channels;

        st->codec->sample_rate = film->audio_samplerate;

        if (film->audio_type == CODEC_ID_ADPCM_ADX) {

            st->codec->bits_per_coded_sample = 18 * 8 / 32;

            st->codec->block_align = st->codec->channels * 18;

        } else {

            st->codec->bits_per_coded_sample = film->audio_bits;

            st->codec->block_align = st->codec->channels *

                st->codec->bits_per_coded_sample / 8;

        }

        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *

            st->codec->bits_per_coded_sample;

    }

    /* load the sample table */

    if (avio_read(pb, scratch, 16) != 16)

        return AVERROR(EIO);

    if (AV_RB32(&scratch[0]) != STAB_TAG)

        return AVERROR_INVALIDDATA;

    film->base_clock = AV_RB32(&scratch[8]);

    film->sample_count = AV_RB32(&scratch[12]);

    if(film->sample_count >= UINT_MAX / sizeof(film_sample))

        return -1;

    film->sample_table = av_malloc(film->sample_count * sizeof(film_sample));

    if (!film->sample_table)

        return AVERROR(ENOMEM);

    for(i=0; i<s->nb_streams; i++)

        av_set_pts_info(s->streams[i], 33, 1, film->base_clock);

    audio_frame_counter = 0;

    for (i = 0; i < film->sample_count; i++) {

        /* load the next sample record and transfer it to an internal struct */

        if (avio_read(pb, scratch, 16) != 16) {

            av_free(film->sample_table);

            return AVERROR(EIO);

        }

        film->sample_table[i].sample_offset =

            data_offset + AV_RB32(&scratch[0]);

        film->sample_table[i].sample_size = AV_RB32(&scratch[4]);

        if (AV_RB32(&scratch[8]) == 0xFFFFFFFF) {

            film->sample_table[i].stream = film->audio_stream_index;

            film->sample_table[i].pts = audio_frame_counter;

            film->sample_table[i].pts *= film->base_clock;

            film->sample_table[i].pts /= film->audio_samplerate;

            if (film->audio_type == CODEC_ID_ADPCM_ADX)

                audio_frame_counter += (film->sample_table[i].sample_size * 32 /

                    (18 * film->audio_channels));

            else

                audio_frame_counter += (film->sample_table[i].sample_size /

                    (film->audio_channels * film->audio_bits / 8));

        } else {

            film->sample_table[i].stream = film->video_stream_index;

            film->sample_table[i].pts = AV_RB32(&scratch[8]) & 0x7FFFFFFF;

            film->sample_table[i].keyframe = (scratch[8] & 0x80) ? 0 : 1;

        }

    }

    film->current_sample = 0;

    return 0;

}


static int vlc_decode_block(MimicContext *ctx, int num_coeffs, int qscale)

{

    int16_t *block = ctx->dct_block;

    unsigned int pos;

    ctx->bdsp.clear_block(block);

    block[0] = get_bits(&ctx->gb, 8) << 3;

    for (pos = 1; pos < num_coeffs; pos++) {

        uint32_t vlc, num_bits;

        int value;

        int coeff;

        vlc = get_vlc2(&ctx->gb, ctx->vlc.table, ctx->vlc.bits, 3);

        if (!vlc) /* end-of-block code */

            return 0;

        if (vlc == -1)

            return AVERROR_INVALIDDATA;

        /* pos_add and num_bits are coded in the vlc code */

        pos     += vlc & 15; // pos_add

        num_bits = vlc >> 4; // num_bits

        if (pos >= 64)

            return AVERROR_INVALIDDATA;

        value = get_bits(&ctx->gb, num_bits);

        /* FFmpeg's IDCT behaves somewhat different from the original code, so

         * a factor of 4 was added to the input */

        coeff = vlcdec_lookup[num_bits][value];

        if (pos < 3)

            coeff *= 16;

        else /* TODO Use >> 10 instead of / 1001 */

            coeff = (coeff * qscale) / 1001;

        block[ctx->scantable.permutated[pos]] = coeff;

    }

    return 0;

}


static int svq3_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MpegEncContext *const s = avctx->priv_data;

    H264Context *const h = avctx->priv_data;

    int m, mb_type;

    /* special case for last picture */

    if (buf_size == 0) {

        if (s->next_picture_ptr && !s->low_delay) {

            *(AVFrame *) data = *(AVFrame *) &s->next_picture;

            s->next_picture_ptr = NULL;

            *data_size = sizeof(AVFrame);

        }

        return 0;

    }

    init_get_bits (&s->gb, buf, 8*buf_size);

    s->mb_x = s->mb_y = h->mb_xy = 0;

    if (svq3_decode_slice_header(h))

        return -1;

    s->pict_type = h->slice_type;

    s->picture_number = h->slice_num;

    if (avctx->debug&FF_DEBUG_PICT_INFO){

        av_log(h->s.avctx, AV_LOG_DEBUG, "%c hpel:%d, tpel:%d aqp:%d qp:%d, slice_num:%02X\n",

               av_get_pict_type_char(s->pict_type), h->halfpel_flag, h->thirdpel_flag,

               s->adaptive_quant, s->qscale, h->slice_num);

    }

    /* for hurry_up == 5 */

    s->current_picture.pict_type = s->pict_type;

    s->current_picture.key_frame = (s->pict_type == FF_I_TYPE);

    /* Skip B-frames if we do not have reference frames. */

    if (s->last_picture_ptr == NULL && s->pict_type == FF_B_TYPE)

        return 0;

    /* Skip B-frames if we are in a hurry. */

    if (avctx->hurry_up && s->pict_type == FF_B_TYPE)

        return 0;

    /* Skip everything if we are in a hurry >= 5. */

    if (avctx->hurry_up >= 5)

        return 0;

    if (  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)

        ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)

        || avctx->skip_frame >= AVDISCARD_ALL)

        return 0;

    if (s->next_p_frame_damaged) {

        if (s->pict_type == FF_B_TYPE)

            return 0;

        else

            s->next_p_frame_damaged = 0;

    }

    if (frame_start(h) < 0)

        return -1;

    if (s->pict_type == FF_B_TYPE) {

        h->frame_num_offset = (h->slice_num - h->prev_frame_num);

        if (h->frame_num_offset < 0) {

            h->frame_num_offset += 256;

        }

        if (h->frame_num_offset == 0 || h->frame_num_offset >= h->prev_frame_num_offset) {

            av_log(h->s.avctx, AV_LOG_ERROR, "error in B-frame picture id\n");

            return -1;

        }

    } else {

        h->prev_frame_num = h->frame_num;

        h->frame_num = h->slice_num;

        h->prev_frame_num_offset = (h->frame_num - h->prev_frame_num);

        if (h->prev_frame_num_offset < 0) {

            h->prev_frame_num_offset += 256;

        }

    }

    for (m = 0; m < 2; m++){

        int i;

        for (i = 0; i < 4; i++){

            int j;

            for (j = -1; j < 4; j++)

                h->ref_cache[m][scan8[0] + 8*i + j]= 1;

            if (i < 3)

                h->ref_cache[m][scan8[0] + 8*i + j]= PART_NOT_AVAILABLE;

        }

    }

    for (s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {

        for (s->mb_x = 0; s->mb_x < s->mb_width; s->mb_x++) {

            h->mb_xy = s->mb_x + s->mb_y*s->mb_stride;

            if ( (get_bits_count(&s->gb) + 7) >= s->gb.size_in_bits &&

                ((get_bits_count(&s->gb) & 7) == 0 || show_bits(&s->gb, (-get_bits_count(&s->gb) & 7)) == 0)) {

                skip_bits(&s->gb, h->next_slice_index - get_bits_count(&s->gb));

                s->gb.size_in_bits = 8*buf_size;

                if (svq3_decode_slice_header(h))

                    return -1;

                /* TODO: support s->mb_skip_run */

            }

            mb_type = svq3_get_ue_golomb(&s->gb);

            if (s->pict_type == FF_I_TYPE) {

                mb_type += 8;

            } else if (s->pict_type == FF_B_TYPE && mb_type >= 4) {

                mb_type += 4;

            }

            if (mb_type > 33 || svq3_decode_mb(h, mb_type)) {

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            if (mb_type != 0) {

                hl_decode_mb (h);

            }

            if (s->pict_type != FF_B_TYPE && !s->low_delay) {

                s->current_picture.mb_type[s->mb_x + s->mb_y*s->mb_stride] =

                    (s->pict_type == FF_P_TYPE && mb_type < 8) ? (mb_type - 1) : -1;

            }

        }

        ff_draw_horiz_band(s, 16*s->mb_y, 16);

    }

    MPV_frame_end(s);

    if (s->pict_type == FF_B_TYPE || s->low_delay) {

        *(AVFrame *) data = *(AVFrame *) &s->current_picture;

    } else {

        *(AVFrame *) data = *(AVFrame *) &s->last_picture;

    }

    avctx->frame_number = s->picture_number - 1;

    /* Do not output the last pic after seeking. */

    if (s->last_picture_ptr || s->low_delay) {

        *data_size = sizeof(AVFrame);

    }

    return buf_size;

}


static av_cold int rl2_decode_init(AVCodecContext *avctx)

{

    Rl2Context *s = avctx->priv_data;

    int back_size;

    int i;

    s->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    avcodec_get_frame_defaults(&s->frame);

    /** parse extra data */

    if(!avctx->extradata || avctx->extradata_size < EXTRADATA1_SIZE){

        av_log(avctx, AV_LOG_ERROR, "invalid extradata size\n");

        return -1;

    }

    /** get frame_offset */

    s->video_base = AV_RL16(&avctx->extradata[0]);

    s->clr_count = AV_RL32(&avctx->extradata[2]);

    if(s->video_base >= avctx->width * avctx->height){

        av_log(avctx, AV_LOG_ERROR, "invalid video_base\n");

        return -1;

    }

    /** initialize palette */

    for(i=0;i<AVPALETTE_COUNT;i++)

        s->palette[i] = 0xFF << 24 | AV_RB24(&avctx->extradata[6 + i * 3]);

    /** decode background frame if present */

    back_size = avctx->extradata_size - EXTRADATA1_SIZE;

    if(back_size > 0){

        unsigned char* back_frame = av_mallocz(avctx->width*avctx->height);

        if(!back_frame)

            return -1;

        rl2_rle_decode(s,avctx->extradata + EXTRADATA1_SIZE,back_size,

                           back_frame,avctx->width,0);

        s->back_frame = back_frame;

    }

    return 0;

}


static void picmemset(PicContext *s, AVFrame *frame, int value, int run,

                      int *x, int *y, int *plane, int bits_per_plane)

{

    uint8_t *d;

    int shift = *plane * bits_per_plane;

    int mask  = ((1 << bits_per_plane) - 1) << shift;

    value   <<= shift;

    while (run > 0) {

        int j;

        for (j = 8-bits_per_plane; j >= 0; j -= bits_per_plane) {

            d = frame->data[0] + *y * frame->linesize[0];

            d[*x] |= (value >> j) & mask;

            *x += 1;

            if (*x == s->width) {

                *y -= 1;

                *x = 0;

                if (*y < 0) {

                   *y = s->height - 1;

                   *plane += 1;

                   if (*plane >= s->nb_planes)

                       return;

                   value <<= bits_per_plane;

                   mask  <<= bits_per_plane;

                }

            }

        }

        run--;

    }

}


static inline void silk_stabilize_lsf(int16_t nlsf[16], int order, const uint16_t min_delta[17])

{

    int pass, i;

    for (pass = 0; pass < 20; pass++) {

        int k, min_diff = 0;

        for (i = 0; i < order+1; i++) {

            int low  = i != 0     ? nlsf[i-1] : 0;

            int high = i != order ? nlsf[i]   : 32768;

            int diff = (high - low) - (min_delta[i]);

            if (diff < min_diff) {

                min_diff = diff;

                k = i;

                if (pass == 20)

                    break;

            }

        }

        if (min_diff == 0) /* no issues; stabilized */

            return;

        /* wiggle one or two LSFs */

        if (k == 0) {

            /* repel away from lower bound */

            nlsf[0] = min_delta[0];

        } else if (k == order) {

            /* repel away from higher bound */

            nlsf[order-1] = 32768 - min_delta[order];

        } else {

            /* repel away from current position */

            int min_center = 0, max_center = 32768, center_val;

            /* lower extent */

            for (i = 0; i < k; i++)

                min_center += min_delta[i];

            min_center += min_delta[k] >> 1;

            /* upper extent */

            for (i = order; i > k; i--)

                max_center -= min_delta[k];

            max_center -= min_delta[k] >> 1;

            /* move apart */

            center_val = nlsf[k - 1] + nlsf[k];

            center_val = (center_val >> 1) + (center_val & 1); // rounded divide by 2

            center_val = FFMIN(max_center, FFMAX(min_center, center_val));

            nlsf[k - 1] = center_val - (min_delta[k] >> 1);

            nlsf[k]     = nlsf[k - 1] + min_delta[k];

        }

    }

    /* resort to the fall-back method, the standard method for LSF stabilization */

    /* sort; as the LSFs should be nearly sorted, use insertion sort */

    for (i = 1; i < order; i++) {

        int j, value = nlsf[i];

        for (j = i - 1; j >= 0 && nlsf[j] > value; j--)

            nlsf[j + 1] = nlsf[j];

        nlsf[j + 1] = value;

    }

    /* push forwards to increase distance */

    if (nlsf[0] < min_delta[0])

        nlsf[0] = min_delta[0];

    for (i = 1; i < order; i++)

        if (nlsf[i] < nlsf[i - 1] + min_delta[i])

            nlsf[i] = nlsf[i - 1] + min_delta[i];

    /* push backwards to increase distance */

    if (nlsf[order-1] > 32768 - min_delta[order])

        nlsf[order-1] = 32768 - min_delta[order];

    for (i = order-2; i >= 0; i--)

        if (nlsf[i] > nlsf[i + 1] - min_delta[i+1])

            nlsf[i] = nlsf[i + 1] - min_delta[i+1];

    return;

}


static void pci_unin_main_config_writel (void *opaque, target_phys_addr_t addr,

                                         uint32_t val)

{

    UNINState *s = opaque;

    UNIN_DPRINTF("config_writel addr " TARGET_FMT_plx " val %x\n", addr, val);

#ifdef TARGET_WORDS_BIGENDIAN

    val = bswap32(val);

#endif

    s->config_reg = val;

}


vubr_set_vring_addr_exec(VubrDev *dev, VhostUserMsg *vmsg)
{
    struct vhost_vring_addr *vra = &vmsg->payload.addr;
    unsigned int index = vra->index;
    VubrVirtq *vq = &dev->vq[index];
    DPRINT("vhost_vring_addr:\n");
    DPRINT("    index:  %d\n", vra->index);
    DPRINT("    flags:  %d\n", vra->flags);
    DPRINT("    desc_user_addr:   0x%016llx\n", vra->desc_user_addr);
    DPRINT("    used_user_addr:   0x%016llx\n", vra->used_user_addr);
    DPRINT("    avail_user_addr:  0x%016llx\n", vra->avail_user_addr);
    DPRINT("    log_guest_addr:   0x%016llx\n", vra->log_guest_addr);
    vq->desc = (struct vring_desc *)(uintptr_t)qva_to_va(dev, vra->desc_user_addr);
    vq->used = (struct vring_used *)(uintptr_t)qva_to_va(dev, vra->used_user_addr);
    vq->avail = (struct vring_avail *)(uintptr_t)qva_to_va(dev, vra->avail_user_addr);
    vq->log_guest_addr = vra->log_guest_addr;
    DPRINT("Setting virtq addresses:\n");
    DPRINT("    vring_desc  at %p\n", vq->desc);
    DPRINT("    vring_used  at %p\n", vq->used);
    DPRINT("    vring_avail at %p\n", vq->avail);
    vq->last_used_index = vq->used->idx;
    return 0;


void ff_get_unscaled_swscale(SwsContext *c)

{

    const enum PixelFormat srcFormat = c->srcFormat;

    const enum PixelFormat dstFormat = c->dstFormat;

    const int flags = c->flags;

    const int dstH = c->dstH;

    int needsDither;

    needsDither = isAnyRGB(dstFormat) &&

            c->dstFormatBpp < 24 &&

           (c->dstFormatBpp < c->srcFormatBpp || (!isAnyRGB(srcFormat)));

    /* yv12_to_nv12 */

    if ((srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUVA420P) &&

        (dstFormat == PIX_FMT_NV12 || dstFormat == PIX_FMT_NV21)) {

        c->swScale = planarToNv12Wrapper;

    }

    /* yuv2bgr */

    if ((srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUV422P ||

         srcFormat == PIX_FMT_YUVA420P) && isAnyRGB(dstFormat) &&

        !(flags & SWS_ACCURATE_RND) && !(dstH & 1)) {

        c->swScale = ff_yuv2rgb_get_func_ptr(c);

    }

    if (srcFormat == PIX_FMT_YUV410P &&

        (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P) &&

        !(flags & SWS_BITEXACT)) {

        c->swScale = yvu9ToYv12Wrapper;

    }

    /* bgr24toYV12 */

    if (srcFormat == PIX_FMT_BGR24 &&

        (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P) &&

        !(flags & SWS_ACCURATE_RND))

        c->swScale = bgr24ToYv12Wrapper;

    /* RGB/BGR -> RGB/BGR (no dither needed forms) */

    if (   isAnyRGB(srcFormat)

        && isAnyRGB(dstFormat)

        && srcFormat != PIX_FMT_BGR8      && dstFormat != PIX_FMT_BGR8

        && srcFormat != PIX_FMT_RGB8      && dstFormat != PIX_FMT_RGB8

        && srcFormat != PIX_FMT_BGR4      && dstFormat != PIX_FMT_BGR4

        && srcFormat != PIX_FMT_RGB4      && dstFormat != PIX_FMT_RGB4

        && srcFormat != PIX_FMT_BGR4_BYTE && dstFormat != PIX_FMT_BGR4_BYTE

        && srcFormat != PIX_FMT_RGB4_BYTE && dstFormat != PIX_FMT_RGB4_BYTE

        && srcFormat != PIX_FMT_MONOBLACK && dstFormat != PIX_FMT_MONOBLACK

        && srcFormat != PIX_FMT_MONOWHITE && dstFormat != PIX_FMT_MONOWHITE

        && srcFormat != PIX_FMT_RGB48LE   && dstFormat != PIX_FMT_RGB48LE

        && srcFormat != PIX_FMT_RGB48BE   && dstFormat != PIX_FMT_RGB48BE

        && srcFormat != PIX_FMT_BGR48LE   && dstFormat != PIX_FMT_BGR48LE

        && srcFormat != PIX_FMT_BGR48BE   && dstFormat != PIX_FMT_BGR48BE

        && (!needsDither || (c->flags&(SWS_FAST_BILINEAR|SWS_POINT))))

        c->swScale= rgbToRgbWrapper;

    /* bswap 16 bits per pixel/component packed formats */

    if (IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR444) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR48)  ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR555) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_BGR565) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_GRAY16) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB444) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB48)  ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB555) ||

        IS_DIFFERENT_ENDIANESS(srcFormat, dstFormat, PIX_FMT_RGB565))

        c->swScale = packed_16bpc_bswap;

    if ((usePal(srcFormat) && (

        dstFormat == PIX_FMT_RGB32   ||

        dstFormat == PIX_FMT_RGB32_1 ||

        dstFormat == PIX_FMT_RGB24   ||

        dstFormat == PIX_FMT_BGR32   ||

        dstFormat == PIX_FMT_BGR32_1 ||

        dstFormat == PIX_FMT_BGR24)))

        c->swScale = palToRgbWrapper;

    if (srcFormat == PIX_FMT_YUV422P) {

        if (dstFormat == PIX_FMT_YUYV422)

            c->swScale = yuv422pToYuy2Wrapper;

        else if (dstFormat == PIX_FMT_UYVY422)

            c->swScale = yuv422pToUyvyWrapper;

    }

    /* LQ converters if -sws 0 or -sws 4*/

    if (c->flags&(SWS_FAST_BILINEAR|SWS_POINT)) {

        /* yv12_to_yuy2 */

        if (srcFormat == PIX_FMT_YUV420P || srcFormat == PIX_FMT_YUVA420P) {

            if (dstFormat == PIX_FMT_YUYV422)

                c->swScale = planarToYuy2Wrapper;

            else if (dstFormat == PIX_FMT_UYVY422)

                c->swScale = planarToUyvyWrapper;

        }

    }

    if (srcFormat == PIX_FMT_YUYV422 &&

       (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P))

        c->swScale = yuyvToYuv420Wrapper;

    if (srcFormat == PIX_FMT_UYVY422 &&

       (dstFormat == PIX_FMT_YUV420P || dstFormat == PIX_FMT_YUVA420P))

        c->swScale = uyvyToYuv420Wrapper;

    if (srcFormat == PIX_FMT_YUYV422 && dstFormat == PIX_FMT_YUV422P)

        c->swScale = yuyvToYuv422Wrapper;

    if (srcFormat == PIX_FMT_UYVY422 && dstFormat == PIX_FMT_YUV422P)

        c->swScale = uyvyToYuv422Wrapper;

    /* simple copy */

    if ( srcFormat == dstFormat ||

        (srcFormat == PIX_FMT_YUVA420P && dstFormat == PIX_FMT_YUV420P) ||

        (srcFormat == PIX_FMT_YUV420P && dstFormat == PIX_FMT_YUVA420P) ||

        (isPlanarYUV(srcFormat) && isGray(dstFormat)) ||

        (isPlanarYUV(dstFormat) && isGray(srcFormat)) ||

        (isGray(dstFormat) && isGray(srcFormat)) ||

        (isPlanarYUV(srcFormat) && isPlanarYUV(dstFormat) &&

         c->chrDstHSubSample == c->chrSrcHSubSample &&

         c->chrDstVSubSample == c->chrSrcVSubSample &&

         dstFormat != PIX_FMT_NV12 && dstFormat != PIX_FMT_NV21 &&

         srcFormat != PIX_FMT_NV12 && srcFormat != PIX_FMT_NV21))

    {

        if (isPacked(c->srcFormat))

            c->swScale = packedCopyWrapper;

        else /* Planar YUV or gray */

            c->swScale = planarCopyWrapper;

    }

    if (ARCH_BFIN)

        ff_bfin_get_unscaled_swscale(c);

    if (HAVE_ALTIVEC)

        ff_swscale_get_unscaled_altivec(c);

}


static PCIBridgeWindows *pci_bridge_region_init(PCIBridge *br)

{

    PCIDevice *pd = PCI_DEVICE(br);

    PCIBus *parent = pd->bus;

    PCIBridgeWindows *w = g_new(PCIBridgeWindows, 1);

    uint16_t cmd = pci_get_word(pd->config + PCI_COMMAND);

    pci_bridge_init_alias(br, &w->alias_pref_mem,

                          PCI_BASE_ADDRESS_MEM_PREFETCH,

                          "pci_bridge_pref_mem",

                          &br->address_space_mem,

                          parent->address_space_mem,

                          cmd & PCI_COMMAND_MEMORY);

    pci_bridge_init_alias(br, &w->alias_mem,

                          PCI_BASE_ADDRESS_SPACE_MEMORY,

                          "pci_bridge_mem",

                          &br->address_space_mem,

                          parent->address_space_mem,

                          cmd & PCI_COMMAND_MEMORY);

    pci_bridge_init_alias(br, &w->alias_io,

                          PCI_BASE_ADDRESS_SPACE_IO,

                          "pci_bridge_io",

                          &br->address_space_io,

                          parent->address_space_io,

                          cmd & PCI_COMMAND_IO);

    pci_bridge_init_vga_aliases(br, parent, w->alias_vga);

    return w;

}