void register_cp_regs_for_features(ARMCPU *cpu)

{

    /* Register all the coprocessor registers based on feature bits */

    CPUARMState *env = &cpu->env;

    if (arm_feature(env, ARM_FEATURE_M)) {

        /* M profile has no coprocessor registers */

        return;

    }

    define_arm_cp_regs(cpu, cp_reginfo);

    if (!arm_feature(env, ARM_FEATURE_V8)) {

        /* Must go early as it is full of wildcards that may be

         * overridden by later definitions.

         */

        define_arm_cp_regs(cpu, not_v8_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_V6)) {

        /* The ID registers all have impdef reset values */

        ARMCPRegInfo v6_idregs[] = {

            { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_pfr0 },

            { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_pfr1 },

            { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_dfr0 },

            { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_afr0 },

            { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_mmfr0 },

            { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_mmfr1 },

            { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_mmfr2 },

            { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_mmfr3 },

            { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar0 },

            { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar1 },

            { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar2 },

            { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar3 },

            { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar4 },

            { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_isar5 },

            /* 6..7 are as yet unallocated and must RAZ */

            { .name = "ID_ISAR6", .cp = 15, .crn = 0, .crm = 2,

              .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = 0 },

            { .name = "ID_ISAR7", .cp = 15, .crn = 0, .crm = 2,

              .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = 0 },

            REGINFO_SENTINEL

        };

        define_arm_cp_regs(cpu, v6_idregs);

        define_arm_cp_regs(cpu, v6_cp_reginfo);

    } else {

        define_arm_cp_regs(cpu, not_v6_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_V6K)) {

        define_arm_cp_regs(cpu, v6k_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_V7)) {

        /* v7 performance monitor control register: same implementor

         * field as main ID register, and we implement only the cycle

         * count register.

         */

#ifndef CONFIG_USER_ONLY

        ARMCPRegInfo pmcr = {

            .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,

            .access = PL0_RW, .resetvalue = cpu->midr & 0xff000000,

            .type = ARM_CP_IO,

            .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),

            .accessfn = pmreg_access, .writefn = pmcr_write,

            .raw_writefn = raw_write,

        };

        define_one_arm_cp_reg(cpu, &pmcr);

#endif

        ARMCPRegInfo clidr = {

            .name = "CLIDR", .state = ARM_CP_STATE_BOTH,

            .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,

            .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr

        };

        define_one_arm_cp_reg(cpu, &clidr);

        define_arm_cp_regs(cpu, v7_cp_reginfo);

    } else {

        define_arm_cp_regs(cpu, not_v7_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_V8)) {

        /* AArch64 ID registers, which all have impdef reset values */

        ARMCPRegInfo v8_idregs[] = {

            { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64pfr0 },

            { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64pfr1},

            { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              /* We mask out the PMUVer field, because we don't currently

               * implement the PMU. Not advertising it prevents the guest

               * from trying to use it and getting UNDEFs on registers we

               * don't implement.

               */

              .resetvalue = cpu->id_aa64dfr0 & ~0xf00 },

            { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64dfr1 },

            { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64afr0 },

            { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64afr1 },

            { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64isar0 },

            { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64isar1 },

            { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64mmfr0 },

            { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->id_aa64mmfr1 },

            { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->mvfr0 },

            { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->mvfr1 },

            { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,

              .access = PL1_R, .type = ARM_CP_CONST,

              .resetvalue = cpu->mvfr2 },

            REGINFO_SENTINEL

        };

        ARMCPRegInfo rvbar = {

            .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,

            .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 2,

            .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar

        };

        define_one_arm_cp_reg(cpu, &rvbar);

        define_arm_cp_regs(cpu, v8_idregs);

        define_arm_cp_regs(cpu, v8_cp_reginfo);

        define_aarch64_debug_regs(cpu);

    }

    if (arm_feature(env, ARM_FEATURE_EL2)) {

        define_arm_cp_regs(cpu, v8_el2_cp_reginfo);

    } else {

        /* If EL2 is missing but higher ELs are enabled, we need to

         * register the no_el2 reginfos.

         */

        if (arm_feature(env, ARM_FEATURE_EL3)) {

            define_arm_cp_regs(cpu, v8_el3_no_el2_cp_reginfo);

        }

    }

    if (arm_feature(env, ARM_FEATURE_EL3)) {

        define_arm_cp_regs(cpu, v8_el3_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_MPU)) {

        /* These are the MPU registers prior to PMSAv6. Any new

         * PMSA core later than the ARM946 will require that we

         * implement the PMSAv6 or PMSAv7 registers, which are

         * completely different.

         */

        assert(!arm_feature(env, ARM_FEATURE_V6));

        define_arm_cp_regs(cpu, pmsav5_cp_reginfo);

    } else {

        define_arm_cp_regs(cpu, vmsa_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {

        define_arm_cp_regs(cpu, t2ee_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {

        define_arm_cp_regs(cpu, generic_timer_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_VAPA)) {

        define_arm_cp_regs(cpu, vapa_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {

        define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {

        define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {

        define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_OMAPCP)) {

        define_arm_cp_regs(cpu, omap_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_STRONGARM)) {

        define_arm_cp_regs(cpu, strongarm_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_XSCALE)) {

        define_arm_cp_regs(cpu, xscale_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {

        define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_LPAE)) {

        define_arm_cp_regs(cpu, lpae_cp_reginfo);

    }

    /* Slightly awkwardly, the OMAP and StrongARM cores need all of

     * cp15 crn=0 to be writes-ignored, whereas for other cores they should

     * be read-only (ie write causes UNDEF exception).

     */

    {

        ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {

            /* Pre-v8 MIDR space.

             * Note that the MIDR isn't a simple constant register because

             * of the TI925 behaviour where writes to another register can

             * cause the MIDR value to change.

             *

             * Unimplemented registers in the c15 0 0 0 space default to

             * MIDR. Define MIDR first as this entire space, then CTR, TCMTR

             * and friends override accordingly.

             */

            { .name = "MIDR",

              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .resetvalue = cpu->midr,

              .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,

              .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),

              .type = ARM_CP_OVERRIDE },

            /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */

            { .name = "DUMMY",

              .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            { .name = "DUMMY",

              .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            { .name = "DUMMY",

              .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            { .name = "DUMMY",

              .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            { .name = "DUMMY",

              .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            REGINFO_SENTINEL

        };

        ARMCPRegInfo id_v8_midr_cp_reginfo[] = {

            /* v8 MIDR -- the wildcard isn't necessary, and nor is the

             * variable-MIDR TI925 behaviour. Instead we have a single

             * (strictly speaking IMPDEF) alias of the MIDR, REVIDR.

             */

            { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->midr },

            { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,

              .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->midr },

            REGINFO_SENTINEL

        };

        ARMCPRegInfo id_cp_reginfo[] = {

            /* These are common to v8 and pre-v8 */

            { .name = "CTR",

              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },

            { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,

              .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,

              .access = PL0_R, .accessfn = ctr_el0_access,

              .type = ARM_CP_CONST, .resetvalue = cpu->ctr },

            /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */

            { .name = "TCMTR",

              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            { .name = "TLBTR",

              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,

              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },

            REGINFO_SENTINEL

        };

        ARMCPRegInfo crn0_wi_reginfo = {

            .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,

            .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,

            .type = ARM_CP_NOP | ARM_CP_OVERRIDE

        };

        if (arm_feature(env, ARM_FEATURE_OMAPCP) ||

            arm_feature(env, ARM_FEATURE_STRONGARM)) {

            ARMCPRegInfo *r;

            /* Register the blanket "writes ignored" value first to cover the

             * whole space. Then update the specific ID registers to allow write

             * access, so that they ignore writes rather than causing them to

             * UNDEF.

             */

            define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);

            for (r = id_pre_v8_midr_cp_reginfo;

                 r->type != ARM_CP_SENTINEL; r++) {

                r->access = PL1_RW;

            }

            for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {

                r->access = PL1_RW;

            }

        }

        if (arm_feature(env, ARM_FEATURE_V8)) {

            define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);

        } else {

            define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);

        }

        define_arm_cp_regs(cpu, id_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_MPIDR)) {

        define_arm_cp_regs(cpu, mpidr_cp_reginfo);

    }

    if (arm_feature(env, ARM_FEATURE_AUXCR)) {

        ARMCPRegInfo auxcr = {

            .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,

            .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,

            .access = PL1_RW, .type = ARM_CP_CONST,

            .resetvalue = cpu->reset_auxcr

        };

        define_one_arm_cp_reg(cpu, &auxcr);

    }

    if (arm_feature(env, ARM_FEATURE_CBAR)) {

        if (arm_feature(env, ARM_FEATURE_AARCH64)) {

            /* 32 bit view is [31:18] 0...0 [43:32]. */

            uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)

                | extract64(cpu->reset_cbar, 32, 12);

            ARMCPRegInfo cbar_reginfo[] = {

                { .name = "CBAR",

                  .type = ARM_CP_CONST,

                  .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,

                  .access = PL1_R, .resetvalue = cpu->reset_cbar },

                { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,

                  .type = ARM_CP_CONST,

                  .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,

                  .access = PL1_R, .resetvalue = cbar32 },

                REGINFO_SENTINEL

            };

            /* We don't implement a r/w 64 bit CBAR currently */

            assert(arm_feature(env, ARM_FEATURE_CBAR_RO));

            define_arm_cp_regs(cpu, cbar_reginfo);

        } else {

            ARMCPRegInfo cbar = {

                .name = "CBAR",

                .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,

                .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,

                .fieldoffset = offsetof(CPUARMState,

                                        cp15.c15_config_base_address)

            };

            if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {

                cbar.access = PL1_R;

                cbar.fieldoffset = 0;

                cbar.type = ARM_CP_CONST;

            }

            define_one_arm_cp_reg(cpu, &cbar);

        }

    }

    /* Generic registers whose values depend on the implementation */

    {

        ARMCPRegInfo sctlr = {

            .name = "SCTLR", .state = ARM_CP_STATE_BOTH,

            .opc0 = 3, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,

            .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_sys),

            .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,

            .raw_writefn = raw_write,

        };

        if (arm_feature(env, ARM_FEATURE_XSCALE)) {

            /* Normally we would always end the TB on an SCTLR write, but Linux

             * arch/arm/mach-pxa/sleep.S expects two instructions following

             * an MMU enable to execute from cache.  Imitate this behaviour.

             */

            sctlr.type |= ARM_CP_SUPPRESS_TB_END;

        }

        define_one_arm_cp_reg(cpu, &sctlr);

    }

}


static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun,

                                      MegasasCmd *cmd)

{

    struct mfi_pd_info *info = cmd->iov_buf;

    size_t dcmd_size = sizeof(struct mfi_pd_info);

    BlockConf *conf = &sdev->conf;

    uint64_t pd_size;

    uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (lun & 0xFF);

    uint8_t cmdbuf[6];

    SCSIRequest *req;

    size_t len, resid;

    if (!cmd->iov_buf) {

        cmd->iov_buf = g_malloc(dcmd_size);

        memset(cmd->iov_buf, 0, dcmd_size);

        info = cmd->iov_buf;

        info->inquiry_data[0] = 0x7f; /* Force PQual 0x3, PType 0x1f */

        info->vpd_page83[0] = 0x7f;

        megasas_setup_inquiry(cmdbuf, 0, sizeof(info->inquiry_data));

        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);

        if (!req) {

            trace_megasas_dcmd_req_alloc_failed(cmd->index,

                                                "PD get info std inquiry");

            g_free(cmd->iov_buf);

            cmd->iov_buf = NULL;

            return MFI_STAT_FLASH_ALLOC_FAIL;

        }

        trace_megasas_dcmd_internal_submit(cmd->index,

                                           "PD get info std inquiry", lun);

        len = scsi_req_enqueue(req);

        if (len > 0) {

            cmd->iov_size = len;

            scsi_req_continue(req);

        }

        return MFI_STAT_INVALID_STATUS;

    } else if (info->inquiry_data[0] != 0x7f && info->vpd_page83[0] == 0x7f) {

        megasas_setup_inquiry(cmdbuf, 0x83, sizeof(info->vpd_page83));

        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);

        if (!req) {

            trace_megasas_dcmd_req_alloc_failed(cmd->index,

                                                "PD get info vpd inquiry");

            return MFI_STAT_FLASH_ALLOC_FAIL;

        }

        trace_megasas_dcmd_internal_submit(cmd->index,

                                           "PD get info vpd inquiry", lun);

        len = scsi_req_enqueue(req);

        if (len > 0) {

            cmd->iov_size = len;

            scsi_req_continue(req);

        }

        return MFI_STAT_INVALID_STATUS;

    }

    /* Finished, set FW state */

    if ((info->inquiry_data[0] >> 5) == 0) {

        if (megasas_is_jbod(cmd->state)) {

            info->fw_state = cpu_to_le16(MFI_PD_STATE_SYSTEM);

        } else {

            info->fw_state = cpu_to_le16(MFI_PD_STATE_ONLINE);

        }

    } else {

        info->fw_state = cpu_to_le16(MFI_PD_STATE_OFFLINE);

    }

    info->ref.v.device_id = cpu_to_le16(sdev_id);

    info->state.ddf.pd_type = cpu_to_le16(MFI_PD_DDF_TYPE_IN_VD|

                                          MFI_PD_DDF_TYPE_INTF_SAS);

    bdrv_get_geometry(conf->bs, &pd_size);

    info->raw_size = cpu_to_le64(pd_size);

    info->non_coerced_size = cpu_to_le64(pd_size);

    info->coerced_size = cpu_to_le64(pd_size);

    info->encl_device_id = 0xFFFF;

    info->slot_number = (sdev->id & 0xFF);

    info->path_info.count = 1;

    info->path_info.sas_addr[0] =

        cpu_to_le64(megasas_get_sata_addr(sdev_id));

    info->connected_port_bitmap = 0x1;

    info->device_speed = 1;

    info->link_speed = 1;

    resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);

    g_free(cmd->iov_buf);

    cmd->iov_size = dcmd_size - resid;

    cmd->iov_buf = NULL;

    return MFI_STAT_OK;

}


static void yuv_from_cqt(ColorFloat *c, const FFTComplex *v, float gamma, int len)

{

    int x;

    for (x = 0; x < len; x++) {

        float r, g, b;

        r = calculate_gamma(FFMIN(1.0f, v[x].re), gamma);

        g = calculate_gamma(FFMIN(1.0f, 0.5f * (v[x].re + v[x].im)), gamma);

        b = calculate_gamma(FFMIN(1.0f, v[x].im), gamma);

        c[x].yuv.y = 16.0f + 65.481f * r + 128.553f * g + 24.966f * b;

        c[x].yuv.u = 128.0f - 37.797f * r - 74.203f * g + 112.0f * b;

        c[x].yuv.v = 128.0f + 112.0f * r - 93.786f * g - 18.214 * b;

    }

}


static void tcp_chr_close(CharDriverState *chr)

{

    TCPCharDriver *s = chr->opaque;

    if (s->fd >= 0) {

        if (s->tag) {

            g_source_remove(s->tag);

            s->tag = 0;

        }

        if (s->chan) {

            g_io_channel_unref(s->chan);

        }

        closesocket(s->fd);

    }

    if (s->listen_fd >= 0) {

        if (s->listen_tag) {

            g_source_remove(s->listen_tag);

            s->listen_tag = 0;

        }

        if (s->listen_chan) {

            g_io_channel_unref(s->listen_chan);

        }

        closesocket(s->listen_fd);

    }

    g_free(s);

    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

}


static int kvm_put_vcpu_events(CPUState *env, int level)

{

    struct kvm_vcpu_events events;

    if (!kvm_has_vcpu_events()) {

        return 0;

    }

    events.exception.injected = (env->exception_injected >= 0);

    events.exception.nr = env->exception_injected;

    events.exception.has_error_code = env->has_error_code;

    events.exception.error_code = env->error_code;

    events.interrupt.injected = (env->interrupt_injected >= 0);

    events.interrupt.nr = env->interrupt_injected;

    events.interrupt.soft = env->soft_interrupt;

    events.nmi.injected = env->nmi_injected;

    events.nmi.pending = env->nmi_pending;

    events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);

    events.nmi.pad = 0;

    events.sipi_vector = env->sipi_vector;

    events.flags = 0;

    if (level >= KVM_PUT_RESET_STATE) {

        events.flags |=

            KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;

    }

    return kvm_vcpu_ioctl(env, KVM_SET_VCPU_EVENTS, &events);

}


static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    RTSPState *rt = s->priv_data;

    int ret;

    RTSPMessageHeader reply1, *reply = &reply1;

    char cmd[1024];

    if (rt->server_type == RTSP_SERVER_REAL) {

        int i;

        enum AVDiscard cache[MAX_STREAMS];

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

            cache[i] = s->streams[i]->discard;

        if (!rt->need_subscription) {

            if (memcmp (cache, rt->real_setup_cache,

                        sizeof(enum AVDiscard) * s->nb_streams)) {

                av_strlcatf(cmd, sizeof(cmd),

                            "SET_PARAMETER %s RTSP/1.0\r\n"

                            "Unsubscribe: %s\r\n",

                            s->filename, rt->last_subscription);

                rtsp_send_cmd(s, cmd, reply, NULL);

                if (reply->status_code != RTSP_STATUS_OK)

                    return AVERROR_INVALIDDATA;

                rt->need_subscription = 1;

            }

        }

        if (rt->need_subscription) {

            int r, rule_nr, first = 1;

            memcpy(rt->real_setup_cache, cache,

                   sizeof(enum AVDiscard) * s->nb_streams);

            rt->last_subscription[0] = 0;

            snprintf(cmd, sizeof(cmd),

                     "SET_PARAMETER %s RTSP/1.0\r\n"

                     "Subscribe: ",

                     s->filename);

            for (i = 0; i < rt->nb_rtsp_streams; i++) {

                rule_nr = 0;

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

                    if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {

                        if (s->streams[r]->discard != AVDISCARD_ALL) {

                            if (!first)

                                av_strlcat(rt->last_subscription, ",",

                                           sizeof(rt->last_subscription));

                            ff_rdt_subscribe_rule(

                                rt->last_subscription,

                                sizeof(rt->last_subscription), i, rule_nr);

                            first = 0;

                        }

                        rule_nr++;

                    }

                }

            }

            av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);

            rtsp_send_cmd(s, cmd, reply, NULL);

            if (reply->status_code != RTSP_STATUS_OK)

                return AVERROR_INVALIDDATA;

            rt->need_subscription = 0;

            if (rt->state == RTSP_STATE_PLAYING)

                rtsp_read_play (s);

        }

    }

    ret = rtsp_fetch_packet(s, pkt);

    if (ret < 0)

        return ret;

    /* send dummy request to keep TCP connection alive */

    if ((rt->server_type == RTSP_SERVER_WMS ||

         rt->server_type == RTSP_SERVER_REAL) &&

        (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {

        if (rt->server_type == RTSP_SERVER_WMS) {

            snprintf(cmd, sizeof(cmd) - 1,

                     "GET_PARAMETER %s RTSP/1.0\r\n",

                     s->filename);

            rtsp_send_cmd_async(s, cmd, reply, NULL);

        } else {

            rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n",

                                reply, NULL);

        }

    }

    return 0;

}


static target_ulong h_resize_hpt_prepare(PowerPCCPU *cpu,

                                         sPAPRMachineState *spapr,

                                         target_ulong opcode,

                                         target_ulong *args)

{

    target_ulong flags = args[0];

    int shift = args[1];

    sPAPRPendingHPT *pending = spapr->pending_hpt;

    uint64_t current_ram_size = MACHINE(spapr)->ram_size;

    int rc;

    if (spapr->resize_hpt == SPAPR_RESIZE_HPT_DISABLED) {

        return H_AUTHORITY;

    }

    if (!spapr->htab_shift) {

        /* Radix guest, no HPT */

        return H_NOT_AVAILABLE;

    }

    trace_spapr_h_resize_hpt_prepare(flags, shift);

    if (flags != 0) {

        return H_PARAMETER;

    }

    if (shift && ((shift < 18) || (shift > 46))) {

        return H_PARAMETER;

    }

    current_ram_size = pc_existing_dimms_capacity(&error_fatal);

    /* We only allow the guest to allocate an HPT one order above what

     * we'd normally give them (to stop a small guest claiming a huge

     * chunk of resources in the HPT */

    if (shift > (spapr_hpt_shift_for_ramsize(current_ram_size) + 1)) {

        return H_RESOURCE;

    }

    rc = kvmppc_resize_hpt_prepare(cpu, flags, shift);

    if (rc != -ENOSYS) {

        return resize_hpt_convert_rc(rc);

    }

    if (pending) {

        /* something already in progress */

        if (pending->shift == shift) {

            /* and it's suitable */

            if (pending->complete) {

                return pending->ret;

            } else {

                return H_LONG_BUSY_ORDER_100_MSEC;

            }

        }

        /* not suitable, cancel and replace */

        cancel_hpt_prepare(spapr);

    }

    if (!shift) {

        /* nothing to do */

        return H_SUCCESS;

    }

    /* start new prepare */

    pending = g_new0(sPAPRPendingHPT, 1);

    pending->shift = shift;

    pending->ret = H_HARDWARE;

    qemu_thread_create(&pending->thread, "sPAPR HPT prepare",

                       hpt_prepare_thread, pending, QEMU_THREAD_DETACHED);

    spapr->pending_hpt = pending;

    /* In theory we could estimate the time more accurately based on

     * the new size, but there's not much point */

    return H_LONG_BUSY_ORDER_100_MSEC;

}


void qemu_cond_signal(QemuCond *cond)

{

    DWORD result;

    /*

     * Signal only when there are waiters.  cond->waiters is

     * incremented by pthread_cond_wait under the external lock,

     * so we are safe about that.

     */

    if (cond->waiters == 0) {

        return;

    }

    /*

     * Waiting threads decrement it outside the external lock, but

     * only if another thread is executing pthread_cond_broadcast and

     * has the mutex.  So, it also cannot be decremented concurrently

     * with this particular access.

     */

    cond->target = cond->waiters - 1;

    result = SignalObjectAndWait(cond->sema, cond->continue_event,

                                 INFINITE, FALSE);

    if (result == WAIT_ABANDONED || result == WAIT_FAILED) {

        error_exit(GetLastError(), __func__);

    }

}


static int split_field_half_ref_list(Picture *dest, int dest_len,

                                     Picture *src,  int src_len,  int parity){

    int same_parity   = 1;

    int same_i        = 0;

    int opp_i         = 0;

    int out_i;

    int field_output;

    for (out_i = 0; out_i < dest_len; out_i += field_output) {

        if (same_parity && same_i < src_len) {

            field_output = split_field_copy(dest + out_i, src + same_i,

                                            parity, 1);

            same_parity = !field_output;

            same_i++;

        } else if (opp_i < src_len) {

            field_output = split_field_copy(dest + out_i, src + opp_i,

                                            PICT_FRAME - parity, 0);

            same_parity = field_output;

            opp_i++;

        } else {

            break;

        }

    }

    return out_i;

}


int64_t xbzrle_cache_resize(int64_t new_size)

{

    if (new_size < TARGET_PAGE_SIZE) {

        return -1;

    }

    if (XBZRLE.cache != NULL) {

        return cache_resize(XBZRLE.cache, new_size / TARGET_PAGE_SIZE) *

            TARGET_PAGE_SIZE;

    }

    return pow2floor(new_size);

}


static void count_usage(uint8_t *src, int width,

                        int height, uint32_t *counts)

{

    int i, j;

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

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

            counts[src[i]]++;

        }

        src += width;

    }

}


void ff_rtp_send_hevc(AVFormatContext *ctx, const uint8_t *frame_buf, int frame_size)

{

    const uint8_t *next_NAL_unit;

    const uint8_t *buf_ptr, *buf_end = frame_buf + frame_size;

    RTPMuxContext *rtp_ctx = ctx->priv_data;

    /* use the default 90 KHz time stamp */

    rtp_ctx->timestamp = rtp_ctx->cur_timestamp;

    rtp_ctx->buf_ptr   = rtp_ctx->buf;

    if (rtp_ctx->nal_length_size)

        buf_ptr = ff_avc_mp4_find_startcode(frame_buf, buf_end, rtp_ctx->nal_length_size) ? frame_buf : buf_end;

    else

        buf_ptr = ff_avc_find_startcode(frame_buf, buf_end);

    /* find all NAL units and send them as separate packets */

    while (buf_ptr < buf_end) {

        if (rtp_ctx->nal_length_size) {

            next_NAL_unit = ff_avc_mp4_find_startcode(buf_ptr, buf_end, rtp_ctx->nal_length_size);

            if (!next_NAL_unit)

                next_NAL_unit = buf_end;

            buf_ptr += rtp_ctx->nal_length_size;

        } else {

            while (!*(buf_ptr++))

                ;

            next_NAL_unit = ff_avc_find_startcode(buf_ptr, buf_end);

        }

        /* send the next NAL unit */

        nal_send(ctx, buf_ptr, next_NAL_unit - buf_ptr, next_NAL_unit == buf_end);

        /* jump to the next NAL unit */

        buf_ptr = next_NAL_unit;

    }

    flush_buffered(ctx, 1);

}


static inline int dc1394_read_common(AVFormatContext *c, AVFormatParameters *ap,

                                     struct dc1394_frame_format **select_fmt, struct dc1394_frame_rate **select_fps)

{

    dc1394_data* dc1394 = c->priv_data;

    AVStream* vst;

    struct dc1394_frame_format *fmt;

    struct dc1394_frame_rate *fps;

    enum PixelFormat pix_fmt;

    int width, height;

    AVRational framerate;

    int ret = 0;

    if ((pix_fmt = av_get_pix_fmt(dc1394->pixel_format)) == PIX_FMT_NONE) {

        av_log(c, AV_LOG_ERROR, "No such pixel format: %s.\n", dc1394->pixel_format);

        ret = AVERROR(EINVAL);

        goto out;

    }

    if ((ret = av_parse_video_size(&width, &height, dc1394->video_size)) < 0) {

        av_log(c, AV_LOG_ERROR, "Couldn't parse video size.\n");

        goto out;

    }

    if ((ret = av_parse_video_rate(&framerate, dc1394->framerate)) < 0) {

        av_log(c, AV_LOG_ERROR, "Couldn't parse framerate.\n");

        goto out;

    }

#if FF_API_FORMAT_PARAMETERS

    if (ap->width > 0)

        width = ap->width;

    if (ap->height > 0)

        height = ap->height;

    if (ap->pix_fmt)

        pix_fmt = ap->pix_fmt;

    if (ap->time_base.num)

        framerate = (AVRational){ap->time_base.den, ap->time_base.num};

#endif

    dc1394->frame_rate = av_rescale(1000, framerate.num, framerate.den);

    for (fmt = dc1394_frame_formats; fmt->width; fmt++)

         if (fmt->pix_fmt == pix_fmt && fmt->width == width && fmt->height == height)

             break;

    for (fps = dc1394_frame_rates; fps->frame_rate; fps++)

         if (fps->frame_rate == dc1394->frame_rate)

             break;

    if (!fps->frame_rate || !fmt->width) {

        av_log(c, AV_LOG_ERROR, "Can't find matching camera format for %s, %dx%d@%d:1000fps\n", av_get_pix_fmt_name(pix_fmt),

                                                                                width, height, dc1394->frame_rate);

        ret = AVERROR(EINVAL);

        goto out;

    }

    /* create a video stream */

    vst = av_new_stream(c, 0);

    if (!vst) {

        ret = AVERROR(ENOMEM);

        goto out;

    }

    av_set_pts_info(vst, 64, 1, 1000);

    vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    vst->codec->codec_id = CODEC_ID_RAWVIDEO;

    vst->codec->time_base.den = framerate.num;

    vst->codec->time_base.num = framerate.den;

    vst->codec->width = fmt->width;

    vst->codec->height = fmt->height;

    vst->codec->pix_fmt = fmt->pix_fmt;

    /* packet init */

    av_init_packet(&dc1394->packet);

    dc1394->packet.size = avpicture_get_size(fmt->pix_fmt, fmt->width, fmt->height);

    dc1394->packet.stream_index = vst->index;

    dc1394->packet.flags |= AV_PKT_FLAG_KEY;

    dc1394->current_frame = 0;

    vst->codec->bit_rate = av_rescale(dc1394->packet.size * 8, fps->frame_rate, 1000);

    *select_fps = fps;

    *select_fmt = fmt;

out:

    return ret;

}


int av_tempfile(const char *prefix, char **filename, int log_offset, void *log_ctx) {

    FileLogContext file_log_ctx = { &file_log_ctx_class, log_offset, log_ctx };

    int fd=-1;

#if !HAVE_MKSTEMP

    void *ptr= tempnam(NULL, prefix);

    if(!ptr)

        ptr= tempnam(".", prefix);

    *filename = av_strdup(ptr);

#undef free

    free(ptr);

#else

    size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */

    *filename = av_malloc(len);

#endif

    /* -----common section-----*/

    if (*filename == NULL) {

        av_log(&file_log_ctx, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");

        return AVERROR(ENOMEM);

    }

#if !HAVE_MKSTEMP

#   ifndef O_BINARY

#       define O_BINARY 0

#   endif

#   ifndef O_EXCL

#       define O_EXCL 0

#   endif

    fd = open(*filename, O_RDWR | O_BINARY | O_CREAT | O_EXCL, 0600);

#else

    snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);

    fd = mkstemp(*filename);

#ifdef _WIN32

    if (fd < 0) {

        snprintf(*filename, len, "./%sXXXXXX", prefix);

        fd = mkstemp(*filename);

    }

#endif

#endif

    /* -----common section-----*/

    if (fd < 0) {

        int err = AVERROR(errno);

        av_log(&file_log_ctx, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);

        return err;

    }

    return fd; /* success */

}


static void i82374_isa_realize(DeviceState *dev, Error **errp)

{

    ISAi82374State *isa = I82374(dev);

    I82374State *s = &isa->state;

    PortioList *port_list = g_new(PortioList, 1);

    portio_list_init(port_list, OBJECT(isa), i82374_portio_list, s, "i82374");

    portio_list_add(port_list, isa_address_space_io(&isa->parent_obj),

                    isa->iobase);

    i82374_realize(s, errp);

    qdev_init_gpio_out(dev, &s->out, 1);

}


uint64_t pc_dimm_get_free_addr(uint64_t address_space_start,

                               uint64_t address_space_size,

                               uint64_t *hint, uint64_t align, uint64_t size,

                               Error **errp)

{

    GSList *list = NULL, *item;

    uint64_t new_addr, ret = 0;

    uint64_t address_space_end = address_space_start + address_space_size;

    g_assert(QEMU_ALIGN_UP(address_space_start, align) == address_space_start);

    g_assert(QEMU_ALIGN_UP(address_space_size, align) == address_space_size);

    if (!address_space_size) {

        error_setg(errp, "memory hotplug is not enabled, "

                         "please add maxmem option");

        goto out;

    }

    if (hint && QEMU_ALIGN_UP(*hint, align) != *hint) {

        error_setg(errp, "address must be aligned to 0x%" PRIx64 " bytes",

                   align);

        goto out;

    }

    if (QEMU_ALIGN_UP(size, align) != size) {

        error_setg(errp, "backend memory size must be multiple of 0x%"

                   PRIx64, align);

        goto out;

    }

    assert(address_space_end > address_space_start);

    object_child_foreach(qdev_get_machine(), pc_dimm_built_list, &list);

    if (hint) {

        new_addr = *hint;

    } else {

        new_addr = address_space_start;

    }

    /* find address range that will fit new DIMM */

    for (item = list; item; item = g_slist_next(item)) {

        PCDIMMDevice *dimm = item->data;

        uint64_t dimm_size = object_property_get_int(OBJECT(dimm),

                                                     PC_DIMM_SIZE_PROP,

                                                     errp);

        if (errp && *errp) {

            goto out;

        }

        if (ranges_overlap(dimm->addr, dimm_size, new_addr, size)) {

            if (hint) {

                DeviceState *d = DEVICE(dimm);

                error_setg(errp, "address range conflicts with '%s'", d->id);

                goto out;

            }

            new_addr = QEMU_ALIGN_UP(dimm->addr + dimm_size, align);

        }

    }

    ret = new_addr;

    if (new_addr < address_space_start) {

        error_setg(errp, "can't add memory [0x%" PRIx64 ":0x%" PRIx64

                   "] at 0x%" PRIx64, new_addr, size, address_space_start);

    } else if ((new_addr + size) > address_space_end) {

        error_setg(errp, "can't add memory [0x%" PRIx64 ":0x%" PRIx64

                   "] beyond 0x%" PRIx64, new_addr, size, address_space_end);

    }

out:

    g_slist_free(list);

    return ret;

}


floatx80 floatx80_scalbn( floatx80 a, int n STATUS_PARAM )

{

    flag aSign;

    int16 aExp;

    uint64_t aSig;

    aSig = extractFloatx80Frac( a );

    aExp = extractFloatx80Exp( a );

    aSign = extractFloatx80Sign( a );

    if ( aExp == 0x7FF ) {

        return a;

    }

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

        return a;

    aExp += n;

    return normalizeRoundAndPackFloatx80( STATUS(floatx80_rounding_precision),

                                          aSign, aExp, aSig, 0 STATUS_VAR );

}


static int decode_frame_header(NUTContext *nut, int *flags_ret, int64_t *pts, int *stream_id, int frame_code){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    StreamContext *stc;

    int size, flags, size_mul, pts_delta, i, reserved_count;

    uint64_t tmp;

    if(url_ftell(bc) > nut->last_syncpoint_pos + nut->max_distance){

        av_log(s, AV_LOG_ERROR, "last frame must have been damaged %Ld > %Ld + %d\n", url_ftell(bc), nut->last_syncpoint_pos, nut->max_distance);

        return -1;

    }

    flags          = nut->frame_code[frame_code].flags;

    size_mul       = nut->frame_code[frame_code].size_mul;

    size           = nut->frame_code[frame_code].size_lsb;

    *stream_id     = nut->frame_code[frame_code].stream_id;

    pts_delta      = nut->frame_code[frame_code].pts_delta;

    reserved_count = nut->frame_code[frame_code].reserved_count;

    if(flags & FLAG_INVALID)

        return -1;

    if(flags & FLAG_CODED)

        flags ^= get_v(bc);

    if(flags & FLAG_STREAM_ID){

        GET_V(*stream_id, tmp < s->nb_streams)

    }

    stc= &nut->stream[*stream_id];

    if(flags&FLAG_CODED_PTS){

        int coded_pts= get_v(bc);

//FIXME check last_pts validity?

        if(coded_pts < (1<<stc->msb_pts_shift)){

            *pts=lsb2full(stc, coded_pts);

        }else

            *pts=coded_pts - (1<<stc->msb_pts_shift);

    }else

        *pts= stc->last_pts + pts_delta;

    if(flags&FLAG_SIZE_MSB){

        size += size_mul*get_v(bc);

    }

    if(flags&FLAG_RESERVED)

        reserved_count= get_v(bc);

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

        get_v(bc);

    if(flags&FLAG_CHECKSUM){

        get_be32(bc); //FIXME check this

    }else if(size > 2*nut->max_distance){

        av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");

        return -1;

    }

    *flags_ret= flags;

    stc->last_pts= *pts;

    stc->last_key_frame= flags&FLAG_KEY; //FIXME change to last flags

    return size;

}


static av_cold int alac_encode_init(AVCodecContext *avctx)

{

    AlacEncodeContext *s = avctx->priv_data;

    int ret;

    uint8_t *alac_extradata;

    avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;

    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {

        av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");

        return -1;

    }

    /* TODO: Correctly implement multi-channel ALAC.

             It is similar to multi-channel AAC, in that it has a series of

             single-channel (SCE), channel-pair (CPE), and LFE elements. */

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");

        return AVERROR_PATCHWELCOME;

    }

    // Set default compression level

    if (avctx->compression_level == FF_COMPRESSION_DEFAULT)

        s->compression_level = 2;

    else

        s->compression_level = av_clip(avctx->compression_level, 0, 2);

    // Initialize default Rice parameters

    s->rc.history_mult    = 40;

    s->rc.initial_history = 10;

    s->rc.k_modifier      = 14;

    s->rc.rice_modifier   = 4;

    s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,

                                                 avctx->channels,

                                                 DEFAULT_SAMPLE_SIZE);

    // FIXME: consider wasted_bytes

    s->write_sample_size  = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;

    avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!avctx->extradata) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    avctx->extradata_size = ALAC_EXTRADATA_SIZE;

    alac_extradata = avctx->extradata;

    AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);

    AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));

    AV_WB32(alac_extradata+12, avctx->frame_size);

    AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);

    AV_WB8 (alac_extradata+21, avctx->channels);

    AV_WB32(alac_extradata+24, s->max_coded_frame_size);

    AV_WB32(alac_extradata+28,

            avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); // average bitrate

    AV_WB32(alac_extradata+32, avctx->sample_rate);

    // Set relevant extradata fields

    if (s->compression_level > 0) {

        AV_WB8(alac_extradata+18, s->rc.history_mult);

        AV_WB8(alac_extradata+19, s->rc.initial_history);

        AV_WB8(alac_extradata+20, s->rc.k_modifier);

    }

    s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;

    if (avctx->min_prediction_order >= 0) {

        if (avctx->min_prediction_order < MIN_LPC_ORDER ||

           avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {

            av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",

                   avctx->min_prediction_order);

            ret = AVERROR(EINVAL);

            goto error;

        }

        s->min_prediction_order = avctx->min_prediction_order;

    }

    s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;

    if (avctx->max_prediction_order >= 0) {

        if (avctx->max_prediction_order < MIN_LPC_ORDER ||

            avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {

            av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",

                   avctx->max_prediction_order);

            ret = AVERROR(EINVAL);

            goto error;

        }

        s->max_prediction_order = avctx->max_prediction_order;

    }

    if (s->max_prediction_order < s->min_prediction_order) {

        av_log(avctx, AV_LOG_ERROR,

               "invalid prediction orders: min=%d max=%d\n",

               s->min_prediction_order, s->max_prediction_order);

        ret = AVERROR(EINVAL);

        goto error;

    }

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    s->avctx = avctx;

    if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,

                           s->max_prediction_order,

                           FF_LPC_TYPE_LEVINSON)) < 0) {

        goto error;

    }

    return 0;

error:

    alac_encode_close(avctx);

    return ret;

}


static int rv34_decode_mv(RV34DecContext *r, int block_type)

{

    MpegEncContext *s = &r->s;

    GetBitContext *gb = &s->gb;

    int i, j, k, l;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride;

    int next_bt;

    memset(r->dmv, 0, sizeof(r->dmv));

    for(i = 0; i < num_mvs[block_type]; i++){

        r->dmv[i][0] = get_interleaved_se_golomb(gb);

        r->dmv[i][1] = get_interleaved_se_golomb(gb);

    switch(block_type){

    case RV34_MB_TYPE_INTRA:

    case RV34_MB_TYPE_INTRA16x16:

        ZERO8x2(s->current_picture_ptr->motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        return 0;

    case RV34_MB_SKIP:

        if(s->pict_type == AV_PICTURE_TYPE_P){

            ZERO8x2(s->current_picture_ptr->motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

            rv34_mc_1mv (r, block_type, 0, 0, 0, 2, 2, 0);

            break;

    case RV34_MB_B_DIRECT:

        //surprisingly, it uses motion scheme from next reference frame

        /* wait for the current mb row to be finished */

        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))

            ff_thread_await_progress(&s->next_picture_ptr->tf, FFMAX(0, s->mb_y-1), 0);

        next_bt = s->next_picture_ptr->mb_type[s->mb_x + s->mb_y * s->mb_stride];

        if(IS_INTRA(next_bt) || IS_SKIP(next_bt)){

            ZERO8x2(s->current_picture_ptr->motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

            ZERO8x2(s->current_picture_ptr->motion_val[1][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        }else

            for(j = 0; j < 2; j++)

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

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

                        for(l = 0; l < 2; l++)

                            s->current_picture_ptr->motion_val[l][mv_pos + i + j*s->b8_stride][k] = calc_add_mv(r, l, s->next_picture_ptr->motion_val[0][mv_pos + i + j*s->b8_stride][k]);

        if(!(IS_16X8(next_bt) || IS_8X16(next_bt) || IS_8X8(next_bt))) //we can use whole macroblock MC

            rv34_mc_2mv(r, block_type);

        else

            rv34_mc_2mv_skip(r);

        ZERO8x2(s->current_picture_ptr->motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        break;

    case RV34_MB_P_16x16:

    case RV34_MB_P_MIX16x16:

        rv34_pred_mv(r, block_type, 0, 0);

        rv34_mc_1mv (r, block_type, 0, 0, 0, 2, 2, 0);

        break;

    case RV34_MB_B_FORWARD:

    case RV34_MB_B_BACKWARD:

        r->dmv[1][0] = r->dmv[0][0];

        r->dmv[1][1] = r->dmv[0][1];

        if(r->rv30)

            rv34_pred_mv_rv3(r, block_type, block_type == RV34_MB_B_BACKWARD);

        else

            rv34_pred_mv_b  (r, block_type, block_type == RV34_MB_B_BACKWARD);

        rv34_mc_1mv     (r, block_type, 0, 0, 0, 2, 2, block_type == RV34_MB_B_BACKWARD);

        break;

    case RV34_MB_P_16x8:

    case RV34_MB_P_8x16:

        rv34_pred_mv(r, block_type, 0, 0);

        rv34_pred_mv(r, block_type, 1 + (block_type == RV34_MB_P_16x8), 1);

        if(block_type == RV34_MB_P_16x8){

            rv34_mc_1mv(r, block_type, 0, 0, 0,            2, 1, 0);

            rv34_mc_1mv(r, block_type, 0, 8, s->b8_stride, 2, 1, 0);

        if(block_type == RV34_MB_P_8x16){

            rv34_mc_1mv(r, block_type, 0, 0, 0, 1, 2, 0);

            rv34_mc_1mv(r, block_type, 8, 0, 1, 1, 2, 0);

        break;

    case RV34_MB_B_BIDIR:

        rv34_pred_mv_b  (r, block_type, 0);

        rv34_pred_mv_b  (r, block_type, 1);

        rv34_mc_2mv     (r, block_type);

        break;

    case RV34_MB_P_8x8:

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

            rv34_pred_mv(r, block_type, i, i);

            rv34_mc_1mv (r, block_type, (i&1)<<3, (i&2)<<2, (i&1)+(i>>1)*s->b8_stride, 1, 1, 0);

        break;

    return 0;


static void pl181_send_command(pl181_state *s)

{

    SDRequest request;

    uint8_t response[16];

    int rlen;

    request.cmd = s->cmd & PL181_CMD_INDEX;

    request.arg = s->cmdarg;

    DPRINTF("Command %d %08x\n", request.cmd, request.arg);

    rlen = sd_do_command(s->card, &request, response);

    if (rlen < 0)

        goto error;

    if (s->cmd & PL181_CMD_RESPONSE) {

#define RWORD(n) ((response[n] << 24) | (response[n + 1] << 16) \

                  | (response[n + 2] << 8) | response[n + 3])

        if (rlen == 0 || (rlen == 4 && (s->cmd & PL181_CMD_LONGRESP)))

            goto error;

        if (rlen != 4 && rlen != 16)

            goto error;

        s->response[0] = RWORD(0);

        if (rlen == 4) {

            s->response[1] = s->response[2] = s->response[3] = 0;

        } else {

            s->response[1] = RWORD(4);

            s->response[2] = RWORD(8);

            s->response[3] = RWORD(12) & ~1;

        }

        DPRINTF("Response received\n");

        s->status |= PL181_STATUS_CMDRESPEND;

#undef RWORD

    } else {

        DPRINTF("Command sent\n");

        s->status |= PL181_STATUS_CMDSENT;

    }

    return;

error:

    DPRINTF("Timeout\n");

    s->status |= PL181_STATUS_CMDTIMEOUT;

}


static void print_format_entry(const char *tag,

                               const char *val)

{

    if (!fmt_entries_to_show) {

        if (tag) {

            printf("%s=%s\n", tag, val);

        } else {

            printf("%s\n", val);

        }

    } else if (tag && av_dict_get(fmt_entries_to_show, tag, NULL, 0)) {

        if (nb_fmt_entries_to_show > 1)

            printf("%s=", tag);

        printf("%s\n", val);

    }

}


static int dnxhd_decode_dct_block_8(const DNXHDContext *ctx,

                                    RowContext *row, int n)

{

    return dnxhd_decode_dct_block(ctx, row, n, 4, 32, 6);

}


void ram_control_load_hook(QEMUFile *f, uint64_t flags)

{

    int ret = -EINVAL;

    if (f->ops->hook_ram_load) {

        ret = f->ops->hook_ram_load(f, f->opaque, flags);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

        }

    } else {

        qemu_file_set_error(f, ret);

    }

}


static int ogg_packet(AVFormatContext *s, int *str, int *dstart, int *dsize,

                      int64_t *fpos)

{

    struct ogg *ogg = s->priv_data;

    int idx, i, ret;

    struct ogg_stream *os;

    int complete = 0;

    int segp = 0, psize = 0;

    av_dlog(s, "ogg_packet: curidx=%i\n", ogg->curidx);

    do{

        idx = ogg->curidx;

        while (idx < 0){

            ret = ogg_read_page(s, &idx);

            if (ret < 0)

                return ret;

        }

        os = ogg->streams + idx;

        av_dlog(s, "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n",

                idx, os->pstart, os->psize, os->segp, os->nsegs);

        if (!os->codec){

            if (os->header < 0){

                os->codec = ogg_find_codec (os->buf, os->bufpos);

                if (!os->codec){

                    av_log(s, AV_LOG_WARNING, "Codec not found\n");

                    os->header = 0;

                    return 0;

                }

            }else{

                return 0;

            }

        }

        segp = os->segp;

        psize = os->psize;

        while (os->segp < os->nsegs){

            int ss = os->segments[os->segp++];

            os->psize += ss;

            if (ss < 255){

                complete = 1;

                break;

            }

        }

        if (!complete && os->segp == os->nsegs){

            ogg->curidx = -1;

            os->incomplete = 1;

        }

    }while (!complete);

    if (os->granule == -1)

        av_log(s, AV_LOG_WARNING, "Page at %"PRId64" is missing granule\n", os->page_pos);

    ogg->curidx = idx;

    os->incomplete = 0;

    if (os->header) {

        os->header = os->codec->header (s, idx);

        if (!os->header){

            os->segp = segp;

            os->psize = psize;

            // We have reached the first non-header packet in this stream.

            // Unfortunately more header packets may still follow for others,

            // but if we continue with header parsing we may lose data packets.

            ogg->headers = 1;

            // Update the header state for all streams and

            // compute the data_offset.

            if (!s->data_offset)

                s->data_offset = os->sync_pos;

            for (i = 0; i < ogg->nstreams; i++) {

                struct ogg_stream *cur_os = ogg->streams + i;

                // if we have a partial non-header packet, its start is

                // obviously at or after the data start

                if (cur_os->incomplete)

                    s->data_offset = FFMIN(s->data_offset, cur_os->sync_pos);

            }

        }else{

            os->pstart += os->psize;

            os->psize = 0;

        }

    } else {

        os->pflags = 0;

        os->pduration = 0;

        if (os->codec && os->codec->packet)

            os->codec->packet (s, idx);

        if (str)

            *str = idx;

        if (dstart)

            *dstart = os->pstart;

        if (dsize)

            *dsize = os->psize;

        if (fpos)

            *fpos = os->sync_pos;

        os->pstart += os->psize;

        os->psize = 0;

        if(os->pstart == os->bufpos)

            os->bufpos = os->pstart = 0;

        os->sync_pos = os->page_pos;

    }

    // determine whether there are more complete packets in this page

    // if not, the page's granule will apply to this packet

    os->page_end = 1;

    for (i = os->segp; i < os->nsegs; i++)

        if (os->segments[i] < 255) {

            os->page_end = 0;

            break;

        }

    if (os->segp == os->nsegs)

        ogg->curidx = -1;

    return 0;

}


static void migration_bitmap_sync(void)

{

    RAMBlock *block;

    uint64_t num_dirty_pages_init = migration_dirty_pages;

    MigrationState *s = migrate_get_current();

    int64_t end_time;

    int64_t bytes_xfer_now;

    bitmap_sync_count++;

    if (!bytes_xfer_prev) {

        bytes_xfer_prev = ram_bytes_transferred();

    }

    if (!start_time) {

        start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);

    }

    trace_migration_bitmap_sync_start();

    address_space_sync_dirty_bitmap(&address_space_memory);

    rcu_read_lock();

    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {

        migration_bitmap_sync_range(block->mr->ram_addr, block->used_length);

    }

    rcu_read_unlock();

    trace_migration_bitmap_sync_end(migration_dirty_pages

                                    - num_dirty_pages_init);

    num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init;

    end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);

    /* more than 1 second = 1000 millisecons */

    if (end_time > start_time + 1000) {

        if (migrate_auto_converge()) {

            /* The following detection logic can be refined later. For now:

               Check to see if the dirtied bytes is 50% more than the approx.

               amount of bytes that just got transferred since the last time we

               were in this routine. If that happens >N times (for now N==4)

               we turn on the throttle down logic */

            bytes_xfer_now = ram_bytes_transferred();

            if (s->dirty_pages_rate &&

               (num_dirty_pages_period * TARGET_PAGE_SIZE >

                   (bytes_xfer_now - bytes_xfer_prev)/2) &&

               (dirty_rate_high_cnt++ > 4)) {

                    trace_migration_throttle();

                    mig_throttle_on = true;

                    dirty_rate_high_cnt = 0;

             }

             bytes_xfer_prev = bytes_xfer_now;

        } else {

             mig_throttle_on = false;

        }

        if (migrate_use_xbzrle()) {

            if (iterations_prev != acct_info.iterations) {

                acct_info.xbzrle_cache_miss_rate =

                   (double)(acct_info.xbzrle_cache_miss -

                            xbzrle_cache_miss_prev) /

                   (acct_info.iterations - iterations_prev);

            }

            iterations_prev = acct_info.iterations;

            xbzrle_cache_miss_prev = acct_info.xbzrle_cache_miss;

        }

        s->dirty_pages_rate = num_dirty_pages_period * 1000

            / (end_time - start_time);

        s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;

        start_time = end_time;

        num_dirty_pages_period = 0;

    }

    s->dirty_sync_count = bitmap_sync_count;

}


static void gen_window_check3(DisasContext *dc, unsigned r1, unsigned r2,

        unsigned r3)

{

    gen_window_check2(dc, r1, r2 > r3 ? r2 : r3);

}


void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl)

{

    static int print_prefix = 1;

    static int count;

    static char prev[LINE_SZ];

    AVBPrint part[4];

    char line[LINE_SZ];

    static int is_atty;

    int type[2];

    unsigned tint = 0;

    if (level >= 0) {

        tint = level & 0xff00;

        level &= 0xff;

    }

    if (level > av_log_level)

        return;

#if HAVE_PTHREADS

    pthread_mutex_lock(&mutex);

#endif

    format_line(ptr, level, fmt, vl, part, &print_prefix, type);

    snprintf(line, sizeof(line), "%s%s%s%s", part[0].str, part[1].str, part[2].str, part[3].str);

#if HAVE_ISATTY

    if (!is_atty)

        is_atty = isatty(2) ? 1 : -1;

#endif

    if (print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev) &&

        *line && line[strlen(line) - 1] != '\r'){

        count++;

        if (is_atty == 1)

            fprintf(stderr, "    Last message repeated %d times\r", count);

        goto end;

    }

    if (count > 0) {

        fprintf(stderr, "    Last message repeated %d times\n", count);

        count = 0;

    }

    strcpy(prev, line);

    sanitize(part[0].str);

    colored_fputs(type[0], 0, part[0].str);

    sanitize(part[1].str);

    colored_fputs(type[1], 0, part[1].str);

    sanitize(part[2].str);

    colored_fputs(av_clip(level >> 3, 0, NB_LEVELS - 1), tint >> 8, part[2].str);

    sanitize(part[3].str);

    colored_fputs(av_clip(level >> 3, 0, NB_LEVELS - 1), tint >> 8, part[3].str);

#if CONFIG_VALGRIND_BACKTRACE

    if (level <= BACKTRACE_LOGLEVEL)

        VALGRIND_PRINTF_BACKTRACE("%s", "");

#endif

end:

    av_bprint_finalize(part+3, NULL);

#if HAVE_PTHREADS

    pthread_mutex_unlock(&mutex);

#endif

}


int usb_desc_handle_control(USBDevice *dev, int request, int value,

                            int index, int length, uint8_t *data)

{

    const USBDesc *desc = dev->info->usb_desc;

    int ret = -1;

    assert(desc != NULL);

    switch(request) {

    case DeviceOutRequest | USB_REQ_SET_ADDRESS:

        dev->addr = value;

        trace_usb_set_addr(dev->addr);

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:

        ret = usb_desc_get_descriptor(dev, value, data, length);

        break;

    }

    return ret;

}


static void trigger_prot_fault(CPUS390XState *env, target_ulong vaddr,

                               uint64_t mode)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    int ilen = ILEN_LATER_INC;

    int bits = trans_bits(env, mode) | 4;

    DPRINTF("%s: vaddr=%016" PRIx64 " bits=%d\n", __func__, vaddr, bits);

    stq_phys(cs->as,

             env->psa + offsetof(LowCore, trans_exc_code), vaddr | bits);

    trigger_pgm_exception(env, PGM_PROTECTION, ilen);

}


int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,

                              const uint8_t **pp, const uint8_t *desc_list_end,

                              Mp4Descr *mp4_descr, int mp4_descr_count, int pid,

                              MpegTSContext *ts)

{

    const uint8_t *desc_end;

    int desc_len, desc_tag, desc_es_id;

    char language[252];

    int i;

    desc_tag = get8(pp, desc_list_end);

    if (desc_tag < 0)

        return AVERROR_INVALIDDATA;

    desc_len = get8(pp, desc_list_end);

    if (desc_len < 0)

        return AVERROR_INVALIDDATA;

    desc_end = *pp + desc_len;

    if (desc_end > desc_list_end)

        return AVERROR_INVALIDDATA;

    av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);

    if (st->codec->codec_id == AV_CODEC_ID_NONE &&

        stream_type == STREAM_TYPE_PRIVATE_DATA)

        mpegts_find_stream_type(st, desc_tag, DESC_types);

    switch (desc_tag) {

    case 0x1E: /* SL descriptor */

        desc_es_id = get16(pp, desc_end);

        if (ts && ts->pids[pid])

            ts->pids[pid]->es_id = desc_es_id;

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

            if (mp4_descr[i].dec_config_descr_len &&

                mp4_descr[i].es_id == desc_es_id) {

                AVIOContext pb;

                ffio_init_context(&pb, mp4_descr[i].dec_config_descr,

                                  mp4_descr[i].dec_config_descr_len, 0,

                                  NULL, NULL, NULL, NULL);

                ff_mp4_read_dec_config_descr(fc, st, &pb);

                if (st->codec->codec_id == AV_CODEC_ID_AAC &&

                    st->codec->extradata_size > 0)

                    st->need_parsing = 0;

                if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)

                    mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);

            }

        break;

    case 0x1F: /* FMC descriptor */

        get16(pp, desc_end);

        if (mp4_descr_count > 0 &&

            st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&

            mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {

            AVIOContext pb;

            ffio_init_context(&pb, mp4_descr->dec_config_descr,

                              mp4_descr->dec_config_descr_len, 0,

                              NULL, NULL, NULL, NULL);

            ff_mp4_read_dec_config_descr(fc, st, &pb);

            if (st->codec->codec_id == AV_CODEC_ID_AAC &&

                st->codec->extradata_size > 0)

                st->need_parsing = 0;

        }

        break;

    case 0x56: /* DVB teletext descriptor */

        language[0] = get8(pp, desc_end);

        language[1] = get8(pp, desc_end);

        language[2] = get8(pp, desc_end);

        language[3] = 0;

        av_dict_set(&st->metadata, "language", language, 0);

        break;

    case 0x59: /* subtitling descriptor */

        language[0] = get8(pp, desc_end);

        language[1] = get8(pp, desc_end);

        language[2] = get8(pp, desc_end);

        language[3] = 0;

        /* hearing impaired subtitles detection */

        switch (get8(pp, desc_end)) {

        case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */

        case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */

        case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */

        case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */

        case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */

        case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */

            st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;

            break;

        }

        if (st->codec->extradata) {

            if (st->codec->extradata_size == 4 &&

                memcmp(st->codec->extradata, *pp, 4))

                avpriv_request_sample(fc, "DVB sub with multiple IDs");

        } else {

            st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);

            if (st->codec->extradata) {

                st->codec->extradata_size = 4;

                memcpy(st->codec->extradata, *pp, 4);

            }

        }

        *pp += 4;

        av_dict_set(&st->metadata, "language", language, 0);

        break;

    case 0x0a: /* ISO 639 language descriptor */

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

            language[i + 0] = get8(pp, desc_end);

            language[i + 1] = get8(pp, desc_end);

            language[i + 2] = get8(pp, desc_end);

            language[i + 3] = ',';

            switch (get8(pp, desc_end)) {

            case 0x01:

                st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;

                break;

            case 0x02:

                st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;

                break;

            case 0x03:

                st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;

                break;

            }

        }

        if (i && language[0]) {

            language[i - 1] = 0;

            av_dict_set(&st->metadata, "language", language, 0);

        }

        break;

    case 0x05: /* registration descriptor */

        st->codec->codec_tag = bytestream_get_le32(pp);

        av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);

        if (st->codec->codec_id == AV_CODEC_ID_NONE)

            mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);

        break;

    default:

        break;

    }

    *pp = desc_end;

    return 0;

}


void string_output_visitor_cleanup(StringOutputVisitor *sov)

{

    if (sov->string) {

        g_string_free(sov->string, true);

    }

    g_list_foreach(sov->ranges, free_range, NULL);

    g_list_free(sov->ranges);

    g_free(sov);

}


void memory_region_allocate_system_memory(MemoryRegion *mr, Object *owner,
                                          const char *name,
                                          uint64_t ram_size)
{
    uint64_t addr = 0;
    int i;
    if (nb_numa_nodes == 0 || !have_memdevs) {
        allocate_system_memory_nonnuma(mr, owner, name, ram_size);
        return;
    memory_region_init(mr, owner, name, ram_size);
    for (i = 0; i < MAX_NODES; i++) {
        Error *local_err = NULL;
        uint64_t size = numa_info[i].node_mem;
        HostMemoryBackend *backend = numa_info[i].node_memdev;
        if (!backend) {
            continue;
        MemoryRegion *seg = host_memory_backend_get_memory(backend, &local_err);
        if (local_err) {
            qerror_report_err(local_err);
        memory_region_add_subregion(mr, addr, seg);
        vmstate_register_ram_global(seg);
        addr += size;


void av_register_output_format(AVOutputFormat *format)

{

    AVOutputFormat **p = last_oformat;

    format->next = NULL;

    while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format))

        p = &(*p)->next;

    last_oformat = &format->next;

}


static inline void gen_jcc(DisasContext *s, int b,

                           target_ulong val, target_ulong next_eip)

{

    int l1, l2;

    gen_update_cc_op(s);

    if (s->jmp_opt) {

        l1 = gen_new_label();

        gen_jcc1(s, b, l1);

        set_cc_op(s, CC_OP_DYNAMIC);

        gen_goto_tb(s, 0, next_eip);

        gen_set_label(l1);

        gen_goto_tb(s, 1, val);

        s->is_jmp = DISAS_TB_JUMP;

    } else {

        l1 = gen_new_label();

        l2 = gen_new_label();

        gen_jcc1(s, b, l1);

        set_cc_op(s, CC_OP_DYNAMIC);

        gen_jmp_im(next_eip);

        tcg_gen_br(l2);

        gen_set_label(l1);

        gen_jmp_im(val);

        gen_set_label(l2);

        gen_eob(s);

    }

}


static int check_shm_size(IVShmemState *s, int fd) {

    /* check that the guest isn't going to try and map more memory than the

     * the object has allocated return -1 to indicate error */

    struct stat buf;

    fstat(fd, &buf);

    if (s->ivshmem_size > buf.st_size) {

        fprintf(stderr,

                "IVSHMEM ERROR: Requested memory size greater"

                " than shared object size (%" PRIu64 " > %" PRIu64")\n",

                s->ivshmem_size, (uint64_t)buf.st_size);

        return -1;

    } else {

        return 0;

    }

}


e1000e_rss_get_hash_type(E1000ECore *core, struct NetRxPkt *pkt)

{

    bool isip4, isip6, isudp, istcp;

    assert(e1000e_rss_enabled(core));

    net_rx_pkt_get_protocols(pkt, &isip4, &isip6, &isudp, &istcp);

    if (isip4) {

        bool fragment = net_rx_pkt_get_ip4_info(pkt)->fragment;

        trace_e1000e_rx_rss_ip4(fragment, istcp, core->mac[MRQC],

                                E1000_MRQC_EN_TCPIPV4(core->mac[MRQC]),

                                E1000_MRQC_EN_IPV4(core->mac[MRQC]));

        if (!fragment && istcp && E1000_MRQC_EN_TCPIPV4(core->mac[MRQC])) {

            return E1000_MRQ_RSS_TYPE_IPV4TCP;

        }

        if (E1000_MRQC_EN_IPV4(core->mac[MRQC])) {

            return E1000_MRQ_RSS_TYPE_IPV4;

        }

    } else if (isip6) {

        eth_ip6_hdr_info *ip6info = net_rx_pkt_get_ip6_info(pkt);

        bool ex_dis = core->mac[RFCTL] & E1000_RFCTL_IPV6_EX_DIS;

        bool new_ex_dis = core->mac[RFCTL] & E1000_RFCTL_NEW_IPV6_EXT_DIS;

        trace_e1000e_rx_rss_ip6(core->mac[RFCTL],

                                ex_dis, new_ex_dis, istcp,

                                ip6info->has_ext_hdrs,

                                ip6info->rss_ex_dst_valid,

                                ip6info->rss_ex_src_valid,

                                core->mac[MRQC],

                                E1000_MRQC_EN_TCPIPV6(core->mac[MRQC]),

                                E1000_MRQC_EN_IPV6EX(core->mac[MRQC]),

                                E1000_MRQC_EN_IPV6(core->mac[MRQC]));

        if ((!ex_dis || !ip6info->has_ext_hdrs) &&

            (!new_ex_dis || !(ip6info->rss_ex_dst_valid ||

                              ip6info->rss_ex_src_valid))) {

            if (istcp && !ip6info->fragment &&

                E1000_MRQC_EN_TCPIPV6(core->mac[MRQC])) {

                return E1000_MRQ_RSS_TYPE_IPV6TCP;

            }

            if (E1000_MRQC_EN_IPV6EX(core->mac[MRQC])) {

                return E1000_MRQ_RSS_TYPE_IPV6EX;

            }

        }

        if (E1000_MRQC_EN_IPV6(core->mac[MRQC])) {

            return E1000_MRQ_RSS_TYPE_IPV6;

        }

    }

    return E1000_MRQ_RSS_TYPE_NONE;

}


static void select_input_picture(MpegEncContext *s){

    int i;

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

        s->reordered_input_picture[i-1]= s->reordered_input_picture[i];

    s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;

    /* set next picture type & ordering */

    if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){

        if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){

            s->reordered_input_picture[0]= s->input_picture[0];

            s->reordered_input_picture[0]->pict_type= I_TYPE;

            s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;

        }else{

            int b_frames;

            if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){

                if(skip_check(s, s->input_picture[0], s->next_picture_ptr)){

//av_log(NULL, AV_LOG_DEBUG, "skip %p %Ld\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);

                    if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){

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

                            s->input_picture[0]->data[i]= NULL;

                        s->input_picture[0]->type= 0;

                    }else{

                        assert(   s->input_picture[0]->type==FF_BUFFER_TYPE_USER

                               || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);

                        s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);

                    }

                    goto no_output_pic;

                }

            }

            if(s->flags&CODEC_FLAG_PASS2){

                for(i=0; i<s->max_b_frames+1; i++){

                    int pict_num= s->input_picture[0]->display_picture_number + i;

                    if(pict_num >= s->rc_context.num_entries)

                        break;

                    if(!s->input_picture[i]){

                        s->rc_context.entry[pict_num-1].new_pict_type = P_TYPE;

                        break;

                    }

                    s->input_picture[i]->pict_type=

                        s->rc_context.entry[pict_num].new_pict_type;

                }

            }

            if(s->avctx->b_frame_strategy==0){

                b_frames= s->max_b_frames;

                while(b_frames && !s->input_picture[b_frames]) b_frames--;

            }else if(s->avctx->b_frame_strategy==1){

                for(i=1; i<s->max_b_frames+1; i++){

                    if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){

                        s->input_picture[i]->b_frame_score=

                            get_intra_count(s, s->input_picture[i  ]->data[0],

                                               s->input_picture[i-1]->data[0], s->linesize) + 1;

                    }

                }

                for(i=0; i<s->max_b_frames+1; i++){

                    if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/40) break;

                }

                b_frames= FFMAX(0, i-1);

                /* reset scores */

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

                    s->input_picture[i]->b_frame_score=0;

                }

            }else{

                av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");

                b_frames=0;

            }

            emms_c();

//static int b_count=0;

//b_count+= b_frames;

//av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);

            for(i= b_frames - 1; i>=0; i--){

                int type= s->input_picture[i]->pict_type;

                if(type && type != B_TYPE)

                    b_frames= i;

            }

            if(s->input_picture[b_frames]->pict_type == B_TYPE && b_frames == s->max_b_frames){

                av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");

            }

            if(s->picture_in_gop_number + b_frames >= s->gop_size){

              if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){

                    b_frames= s->gop_size - s->picture_in_gop_number - 1;

              }else{

                if(s->flags & CODEC_FLAG_CLOSED_GOP)

                    b_frames=0;

                s->input_picture[b_frames]->pict_type= I_TYPE;

              }

            }

            if(   (s->flags & CODEC_FLAG_CLOSED_GOP)

               && b_frames

               && s->input_picture[b_frames]->pict_type== I_TYPE)

                b_frames--;

            s->reordered_input_picture[0]= s->input_picture[b_frames];

            if(s->reordered_input_picture[0]->pict_type != I_TYPE)

                s->reordered_input_picture[0]->pict_type= P_TYPE;

            s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;

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

                s->reordered_input_picture[i+1]= s->input_picture[i];

                s->reordered_input_picture[i+1]->pict_type= B_TYPE;

                s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;

            }

        }

    }

no_output_pic:

    if(s->reordered_input_picture[0]){

        s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=B_TYPE ? 3 : 0;

        copy_picture(&s->new_picture, s->reordered_input_picture[0]);

        if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED){

            // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable

            int i= ff_find_unused_picture(s, 0);

            Picture *pic= &s->picture[i];

            /* mark us unused / free shared pic */

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

                s->reordered_input_picture[0]->data[i]= NULL;

            s->reordered_input_picture[0]->type= 0;

            pic->reference              = s->reordered_input_picture[0]->reference;

            alloc_picture(s, pic, 0);

            copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);

            s->current_picture_ptr= pic;

        }else{

            // input is not a shared pix -> reuse buffer for current_pix

            assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER

                   || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);

            s->current_picture_ptr= s->reordered_input_picture[0];

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

                s->new_picture.data[i]+=16;

            }

        }

        copy_picture(&s->current_picture, s->current_picture_ptr);

        s->picture_number= s->new_picture.display_picture_number;

//printf("dpn:%d\n", s->picture_number);

    }else{

       memset(&s->new_picture, 0, sizeof(Picture));

    }

}


static inline uint32_t lduw_phys_internal(target_phys_addr_t addr,

                                          enum device_endian endian)

{

    uint8_t *ptr;

    uint64_t val;

    MemoryRegionSection *section;

    section = phys_page_find(addr >> TARGET_PAGE_BITS);

    if (!(memory_region_is_ram(section->mr) ||

          memory_region_is_romd(section->mr))) {

        /* I/O case */

        addr = memory_region_section_addr(section, addr);

        val = io_mem_read(section->mr, addr, 2);

#if defined(TARGET_WORDS_BIGENDIAN)

        if (endian == DEVICE_LITTLE_ENDIAN) {

            val = bswap16(val);

        }

#else

        if (endian == DEVICE_BIG_ENDIAN) {

            val = bswap16(val);

        }

#endif

    } else {

        /* RAM case */

        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr)

                                & TARGET_PAGE_MASK)

                               + memory_region_section_addr(section, addr));

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            val = lduw_le_p(ptr);

            break;

        case DEVICE_BIG_ENDIAN:

            val = lduw_be_p(ptr);

            break;

        default:

            val = lduw_p(ptr);

            break;

        }

    }

    return val;

}


static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){

    MpegEncContext * const s = &h->s;

    int temp8, i;

    uint64_t temp64;

    int deblock_left;

    int deblock_top;

    int mb_xy;

    int step    = 1;

    int offset  = 1;

    int uvoffset= 1;

    int top_idx = 1;

    if(!simple && FRAME_MBAFF){

        if(s->mb_y&1){

            offset  = MB_MBAFF ? 1 : 17;

            uvoffset= MB_MBAFF ? 1 : 9;

        }else{

            offset  =

            uvoffset=

            top_idx = MB_MBAFF ? 0 : 1;

        }

        step= MB_MBAFF ? 2 : 1;

    }

    if(h->deblocking_filter == 2) {

        mb_xy = h->mb_xy;

        deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];

        deblock_top  = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];

    } else {

        deblock_left = (s->mb_x > 0);

        deblock_top =  (s->mb_y > !!MB_FIELD);

    }

    src_y  -=   linesize + 1;

    src_cb -= uvlinesize + 1;

    src_cr -= uvlinesize + 1;

#define XCHG(a,b,t,xchg)\

t= a;\

if(xchg)\

    a= b;\

b= t;

    if(deblock_left){

        for(i = !deblock_top; i<16; i++){

            XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, xchg);

        }

        XCHG(h->left_border[offset+i*step], src_y [i*  linesize], temp8, 1);

    }

    if(deblock_top){

        XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);

        XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);

        if(s->mb_x+1 < s->mb_width){

            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);

        }

    }

    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

        if(deblock_left){

            for(i = !deblock_top; i<8; i++){

                XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, xchg);

                XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, xchg);

            }

            XCHG(h->left_border[uvoffset+34   +i*step], src_cb[i*uvlinesize], temp8, 1);

            XCHG(h->left_border[uvoffset+34+18+i*step], src_cr[i*uvlinesize], temp8, 1);

        }

        if(deblock_top){

            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);

            XCHG(*(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);

        }

    }

}


static void rv34_pred_4x4_block(RV34DecContext *r, uint8_t *dst, int stride, int itype, int up, int left, int down, int right)

{

    uint8_t *prev = dst - stride + 4;

    uint32_t topleft;

    if(!up && !left)

        itype = DC_128_PRED;

    else if(!up){

        if(itype == VERT_PRED) itype = HOR_PRED;

        if(itype == DC_PRED)   itype = LEFT_DC_PRED;

    }else if(!left){

        if(itype == HOR_PRED)  itype = VERT_PRED;

        if(itype == DC_PRED)   itype = TOP_DC_PRED;

        if(itype == DIAG_DOWN_LEFT_PRED) itype = DIAG_DOWN_LEFT_PRED_RV40_NODOWN;

    }

    if(!down){

        if(itype == DIAG_DOWN_LEFT_PRED) itype = DIAG_DOWN_LEFT_PRED_RV40_NODOWN;

        if(itype == HOR_UP_PRED) itype = HOR_UP_PRED_RV40_NODOWN;

        if(itype == VERT_LEFT_PRED) itype = VERT_LEFT_PRED_RV40_NODOWN;

    }

    if(!right && up){

        topleft = dst[-stride + 3] * 0x01010101;

        prev = (uint8_t*)&topleft;

    }

    r->h.pred4x4[itype](dst, prev, stride);

}


static av_cold int MP3lame_encode_init(AVCodecContext *avctx)

{

    Mp3AudioContext *s = avctx->priv_data;

    if (avctx->channels > 2)

        return -1;

    s->stereo = avctx->channels > 1 ? 1 : 0;

    if ((s->gfp = lame_init()) == NULL)

        goto err;

    lame_set_in_samplerate(s->gfp, avctx->sample_rate);

    lame_set_out_samplerate(s->gfp, avctx->sample_rate);

    lame_set_num_channels(s->gfp, avctx->channels);

    if(avctx->compression_level == FF_COMPRESSION_DEFAULT) {

        lame_set_quality(s->gfp, 5);

    } else {

        lame_set_quality(s->gfp, avctx->compression_level);

    }

    lame_set_mode(s->gfp, s->stereo ? JOINT_STEREO : MONO);

    lame_set_brate(s->gfp, avctx->bit_rate/1000);

    if(avctx->flags & CODEC_FLAG_QSCALE) {

        lame_set_brate(s->gfp, 0);

        lame_set_VBR(s->gfp, vbr_default);

        lame_set_VBR_quality(s->gfp, avctx->global_quality/(float)FF_QP2LAMBDA);

    }

    lame_set_bWriteVbrTag(s->gfp,0);

    lame_set_disable_reservoir(s->gfp, avctx->flags2 & CODEC_FLAG2_BIT_RESERVOIR ? 0 : 1);

    if (lame_init_params(s->gfp) < 0)

        goto err_close;

    avctx->frame_size = lame_get_framesize(s->gfp);

    avctx->coded_frame= avcodec_alloc_frame();

    avctx->coded_frame->key_frame= 1;

    return 0;

err_close:

    lame_close(s->gfp);

err:

    return -1;

}


int av_strerror(int errnum, char *errbuf, size_t errbuf_size)

{

    int ret = 0;

    const char *errstr = NULL;

    switch (errnum) {

    case AVERROR_EOF:               errstr = "End of file"; break;

    case AVERROR_INVALIDDATA:       errstr = "Invalid data found when processing input"; break;

    case AVERROR_NUMEXPECTED:       errstr = "Number syntax expected in filename"; break;

    case AVERROR_PATCHWELCOME:      errstr = "Not yet implemented in FFmpeg, patches welcome"; break;

    }

    if (errstr) {

        av_strlcpy(errbuf, errstr, errbuf_size);

    } else {

#if HAVE_STRERROR_R

        ret = strerror_r(AVUNERROR(errnum), errbuf, errbuf_size);

#endif

        if (!HAVE_STRERROR_R || ret < 0)

            snprintf(errbuf, errbuf_size, "Error number %d occurred", errnum);

    }

    return ret;

}


void *postcopy_get_tmp_page(MigrationIncomingState *mis)

{

    if (!mis->postcopy_tmp_page) {

        mis->postcopy_tmp_page = mmap(NULL, getpagesize(),

                             PROT_READ | PROT_WRITE, MAP_PRIVATE |

                             MAP_ANONYMOUS, -1, 0);

        if (!mis->postcopy_tmp_page) {

            error_report("%s: %s", __func__, strerror(errno));

            return NULL;

        }

    }

    return mis->postcopy_tmp_page;

}


static int pci_slot_get_pirq(PCIDevice *pci_dev, int irq_num)

{

    int slot_addend;

    slot_addend = (pci_dev->devfn >> 3) - 1;

    return (irq_num + slot_addend) & 3;

}


static int h263_decode_gob_header(MpegEncContext *s)

{

    unsigned int val, gob_number;

    int left;

    /* Check for GOB Start Code */

    val = show_bits(&s->gb, 16);

    if(val)

        return -1;

        /* We have a GBSC probably with GSTUFF */

    skip_bits(&s->gb, 16); /* Drop the zeros */

    left= get_bits_left(&s->gb);

    //MN: we must check the bits left or we might end in a infinite loop (or segfault)

    for(;left>13; left--){

        if(get_bits1(&s->gb)) break; /* Seek the '1' bit */

    }

    if(left<=13)

        return -1;

    if(s->h263_slice_structured){

        if(get_bits1(&s->gb)==0)

            return -1;

        ff_h263_decode_mba(s);

        if(s->mb_num > 1583)

            if(get_bits1(&s->gb)==0)

                return -1;

        s->qscale = get_bits(&s->gb, 5); /* SQUANT */

        if(get_bits1(&s->gb)==0)

            return -1;

        skip_bits(&s->gb, 2); /* GFID */

    }else{

        gob_number = get_bits(&s->gb, 5); /* GN */

        s->mb_x= 0;

        s->mb_y= s->gob_index* gob_number;

        skip_bits(&s->gb, 2); /* GFID */

        s->qscale = get_bits(&s->gb, 5); /* GQUANT */

    }

    if(s->mb_y >= s->mb_height)

        return -1;

    if(s->qscale==0)

        return -1;

    return 0;

}


DevicePropertyInfoList *qmp_device_list_properties(const char *typename,
                                                   Error **errp)
{
    ObjectClass *klass;
    Object *obj;
    ObjectProperty *prop;
    DevicePropertyInfoList *prop_list = NULL;
    klass = object_class_by_name(typename);
    if (klass == NULL) {
        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
                  "Device '%s' not found", typename);
    klass = object_class_dynamic_cast(klass, TYPE_DEVICE);
    if (klass == NULL) {
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "name", TYPE_DEVICE);
    if (object_class_is_abstract(klass)) {
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "name",
                   "non-abstract device type");
    obj = object_new(typename);
    QTAILQ_FOREACH(prop, &obj->properties, node) {
        DevicePropertyInfo *info;
        DevicePropertyInfoList *entry;
        /* Skip Object and DeviceState properties */
        if (strcmp(prop->name, "type") == 0 ||
            strcmp(prop->name, "realized") == 0 ||
            strcmp(prop->name, "hotpluggable") == 0 ||
            strcmp(prop->name, "hotplugged") == 0 ||
            strcmp(prop->name, "parent_bus") == 0) {
            continue;
        /* Skip legacy properties since they are just string versions of
         * properties that we already list.
         */
        if (strstart(prop->name, "legacy-", NULL)) {
            continue;
        info = make_device_property_info(klass, prop->name, prop->type,
                                         prop->description);
        if (!info) {
            continue;
        entry = g_malloc0(sizeof(*entry));
        entry->value = info;
        entry->next = prop_list;
        prop_list = entry;
    object_unref(obj);
    return prop_list;


static void FUNCC(pred4x4_dc)(uint8_t *_src, const uint8_t *topright, int _stride){

    pixel *src = (pixel*)_src;

    int stride = _stride/sizeof(pixel);

    const int dc= (  src[-stride] + src[1-stride] + src[2-stride] + src[3-stride]

                   + src[-1+0*stride] + src[-1+1*stride] + src[-1+2*stride] + src[-1+3*stride] + 4) >>3;

    ((pixel4*)(src+0*stride))[0]=

    ((pixel4*)(src+1*stride))[0]=

    ((pixel4*)(src+2*stride))[0]=

    ((pixel4*)(src+3*stride))[0]= PIXEL_SPLAT_X4(dc);

}


static void test_bmdma_setup(void)

{

    ide_test_start(

        "-vnc none "

        "-drive file=%s,if=ide,serial=%s,cache=writeback "

        "-global ide-hd.ver=%s",

        tmp_path, "testdisk", "version");

}


static void unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)

{

    int i;

    int dc_y_table;

    int dc_c_table;

    int ac_y_table;

    int ac_c_table;

    int residual_eob_run = 0;

    /* fetch the DC table indices */

    dc_y_table = get_bits(gb, 4);

    dc_c_table = get_bits(gb, 4);

    /* unpack the Y plane DC coefficients */

    debug_vp3("  vp3: unpacking Y plane DC coefficients using table %d\n",

        dc_y_table);

    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,

        s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);

    /* unpack the C plane DC coefficients */

    debug_vp3("  vp3: unpacking C plane DC coefficients using table %d\n",

        dc_c_table);

    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,

        s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);

    /* fetch the AC table indices */

    ac_y_table = get_bits(gb, 4);

    ac_c_table = get_bits(gb, 4);

    /* unpack the group 1 AC coefficients (coeffs 1-5) */

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

        debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",

            i, ac_y_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_y_table], i,

            s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);

        debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",

            i, ac_c_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_c_table], i,

            s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);

    }

    /* unpack the group 2 AC coefficients (coeffs 6-14) */

    for (i = 6; i <= 14; i++) {

        debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",

            i, ac_y_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_y_table], i,

            s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);

        debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",

            i, ac_c_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_c_table], i,

            s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);

    }

    /* unpack the group 3 AC coefficients (coeffs 15-27) */

    for (i = 15; i <= 27; i++) {

        debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",

            i, ac_y_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_y_table], i,

            s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);

        debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",

            i, ac_c_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_c_table], i,

            s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);

    }

    /* unpack the group 4 AC coefficients (coeffs 28-63) */

    for (i = 28; i <= 63; i++) {

        debug_vp3("  vp3: unpacking level %d Y plane AC coefficients using table %d\n",

            i, ac_y_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_y_table], i,

            s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);

        debug_vp3("  vp3: unpacking level %d C plane AC coefficients using table %d\n",

            i, ac_c_table);

        residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_c_table], i,

            s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);

    }

}


int bdrv_has_zero_init(BlockDriverState *bs)

{

    assert(bs->drv);

    if (bs->drv->no_zero_init) {

        return 0;

    } else if (bs->file) {

        return bdrv_has_zero_init(bs->file);

    }

    return 1;

}


void ff_fix_long_mvs(MpegEncContext * s, uint8_t *field_select_table, int field_select,

                     int16_t (*mv_table)[2], int f_code, int type, int truncate)

{

    MotionEstContext * const c= &s->me;

    int y, h_range, v_range;

    // RAL: 8 in MPEG-1, 16 in MPEG-4

    int range = (((s->out_format == FMT_MPEG1 || s->msmpeg4_version) ? 8 : 16) << f_code);

    if(c->avctx->me_range && range > c->avctx->me_range) range= c->avctx->me_range;

    h_range= range;

    v_range= field_select_table ? range>>1 : range;

    /* clip / convert to intra 16x16 type MVs */

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

        int x;

        int xy= y*s->mb_stride;

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

            if (s->mb_type[xy] & type){    // RAL: "type" test added...

                if(field_select_table==NULL || field_select_table[xy] == field_select){

                    if(   mv_table[xy][0] >=h_range || mv_table[xy][0] <-h_range

                       || mv_table[xy][1] >=v_range || mv_table[xy][1] <-v_range){

                        if(truncate){

                            if     (mv_table[xy][0] > h_range-1) mv_table[xy][0]=  h_range-1;

                            else if(mv_table[xy][0] < -h_range ) mv_table[xy][0]= -h_range;

                            if     (mv_table[xy][1] > v_range-1) mv_table[xy][1]=  v_range-1;

                            else if(mv_table[xy][1] < -v_range ) mv_table[xy][1]= -v_range;

                        }else{

                            s->mb_type[xy] &= ~type;

                            s->mb_type[xy] |= CANDIDATE_MB_TYPE_INTRA;

                            mv_table[xy][0]=

                            mv_table[xy][1]= 0;

                        }

                    }

                }

            }

            xy++;

        }

    }

}