static int bink_decode_plane(BinkContext *c, AVFrame *frame, BitstreamContext *bc,

                             int plane_idx, int is_chroma)

{

    int blk, ret;

    int i, j, bx, by;

    uint8_t *dst, *prev, *ref_start, *ref_end;

    int v, col[2];

    const uint8_t *scan;

    LOCAL_ALIGNED_16(int16_t, block, [64]);

    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);

    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);

    int coordmap[64];

    const int stride = frame->linesize[plane_idx];

    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;

    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;

    int width = c->avctx->width >> is_chroma;

    init_lengths(c, FFMAX(width, 8), bw);

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

        read_bundle(bc, c, i);

    ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx]

                                         : frame->data[plane_idx];

    ref_end   = ref_start

                + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8;

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

        coordmap[i] = (i & 7) + (i >> 3) * stride;

    for (by = 0; by < bh; by++) {

        if ((ret = read_block_types(c->avctx, bc, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0)

            return ret;

        if ((ret = read_block_types(c->avctx, bc, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0)

            return ret;

        if ((ret = read_colors(bc, &c->bundle[BINK_SRC_COLORS], c)) < 0)

            return ret;

        if ((ret = read_patterns(c->avctx, bc, &c->bundle[BINK_SRC_PATTERN])) < 0)

            return ret;

        if ((ret = read_motion_values(c->avctx, bc, &c->bundle[BINK_SRC_X_OFF])) < 0)

            return ret;

        if ((ret = read_motion_values(c->avctx, bc, &c->bundle[BINK_SRC_Y_OFF])) < 0)

            return ret;

        if ((ret = read_dcs(c->avctx, bc, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0)

            return ret;

        if ((ret = read_dcs(c->avctx, bc, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0)

            return ret;

        if ((ret = read_runs(c->avctx, bc, &c->bundle[BINK_SRC_RUN])) < 0)

            return ret;

        if (by == bh)

            break;

        dst  = frame->data[plane_idx]  + 8*by*stride;

        prev = (c->last->data[plane_idx] ? c->last->data[plane_idx]

                                         : frame->data[plane_idx]) + 8*by*stride;

        for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {

            blk = get_value(c, BINK_SRC_BLOCK_TYPES);

            // 16x16 block type on odd line means part of the already decoded block, so skip it

            if ((by & 1) && blk == SCALED_BLOCK) {

                bx++;

                dst  += 8;

                prev += 8;

                continue;

            }

            switch (blk) {

            case SKIP_BLOCK:

                c->hdsp.put_pixels_tab[1][0](dst, prev, stride, 8);

                break;

            case SCALED_BLOCK:

                blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);

                switch (blk) {

                case RUN_BLOCK:

                    scan = bink_patterns[bitstream_read(bc, 4)];

                    i = 0;

                    do {

                        int run = get_value(c, BINK_SRC_RUN) + 1;

                        i += run;

                        if (i > 64) {

                            av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                            return AVERROR_INVALIDDATA;

                        }

                        if (bitstream_read_bit(bc)) {

                            v = get_value(c, BINK_SRC_COLORS);

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

                                ublock[*scan++] = v;

                        } else {

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

                                ublock[*scan++] = get_value(c, BINK_SRC_COLORS);

                        }

                    } while (i < 63);

                    if (i == 63)

                        ublock[*scan++] = get_value(c, BINK_SRC_COLORS);

                    break;

                case INTRA_BLOCK:

                    memset(dctblock, 0, sizeof(*dctblock) * 64);

                    dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);

                    read_dct_coeffs(bc, dctblock, bink_scan, bink_intra_quant, -1);

                    c->binkdsp.idct_put(ublock, 8, dctblock);

                    break;

                case FILL_BLOCK:

                    v = get_value(c, BINK_SRC_COLORS);

                    c->bdsp.fill_block_tab[0](dst, v, stride, 16);

                    break;

                case PATTERN_BLOCK:

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

                        col[i] = get_value(c, BINK_SRC_COLORS);

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

                        v = get_value(c, BINK_SRC_PATTERN);

                        for (i = 0; i < 8; i++, v >>= 1)

                            ublock[i + j*8] = col[v & 1];

                    }

                    break;

                case RAW_BLOCK:

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

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

                            ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);

                    break;

                default:

                    av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);

                    return AVERROR_INVALIDDATA;

                }

                if (blk != FILL_BLOCK)

                c->binkdsp.scale_block(ublock, dst, stride);

                bx++;

                dst  += 8;

                prev += 8;

                break;

            case MOTION_BLOCK:

                ret = bink_put_pixels(c, dst, prev, stride,

                                      ref_start, ref_end);

                if (ret < 0)

                    return ret;

                break;

            case RUN_BLOCK:

                scan = bink_patterns[bitstream_read(bc, 4)];

                i = 0;

                do {

                    int run = get_value(c, BINK_SRC_RUN) + 1;

                    i += run;

                    if (i > 64) {

                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                        return AVERROR_INVALIDDATA;

                    }

                    if (bitstream_read_bit(bc)) {

                        v = get_value(c, BINK_SRC_COLORS);

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

                            dst[coordmap[*scan++]] = v;

                    } else {

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

                            dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);

                    }

                } while (i < 63);

                if (i == 63)

                    dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);

                break;

            case RESIDUE_BLOCK:

                ret = bink_put_pixels(c, dst, prev, stride,

                                      ref_start, ref_end);

                if (ret < 0)

                    return ret;

                c->bdsp.clear_block(block);

                v = bitstream_read(bc, 7);

                read_residue(bc, block, v);

                c->binkdsp.add_pixels8(dst, block, stride);

                break;

            case INTRA_BLOCK:

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);

                read_dct_coeffs(bc, dctblock, bink_scan, bink_intra_quant, -1);

                c->binkdsp.idct_put(dst, stride, dctblock);

                break;

            case FILL_BLOCK:

                v = get_value(c, BINK_SRC_COLORS);

                c->bdsp.fill_block_tab[1](dst, v, stride, 8);

                break;

            case INTER_BLOCK:

                ret = bink_put_pixels(c, dst, prev, stride,

                                      ref_start, ref_end);

                if (ret < 0)

                    return ret;

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = get_value(c, BINK_SRC_INTER_DC);

                read_dct_coeffs(bc, dctblock, bink_scan, bink_inter_quant, -1);

                c->binkdsp.idct_add(dst, stride, dctblock);

                break;

            case PATTERN_BLOCK:

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

                    col[i] = get_value(c, BINK_SRC_COLORS);

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

                    v = get_value(c, BINK_SRC_PATTERN);

                    for (j = 0; j < 8; j++, v >>= 1)

                        dst[i*stride + j] = col[v & 1];

                }

                break;

            case RAW_BLOCK:

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

                    memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);

                c->bundle[BINK_SRC_COLORS].cur_ptr += 64;

                break;

            default:

                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (bitstream_tell(bc) & 0x1F) // next plane data starts at 32-bit boundary

        bitstream_skip(bc, 32 - (bitstream_tell(bc) & 0x1F));

    return 0;

}


static void opt_frame_pad_right(const char *arg)

{

    frame_padright = atoi(arg);

    if (frame_padright < 0) {

        fprintf(stderr, "Incorrect right pad size\n");

        av_exit(1);

    }

}


static int dcadec_decode_frame(AVCodecContext *avctx, void *data,

                               int *got_frame_ptr, AVPacket *avpkt)

{

    DCAContext *s = avctx->priv_data;

    AVFrame *frame = data;

    uint8_t *input = avpkt->data;

    int input_size = avpkt->size;

    int i, ret, prev_packet = s->packet;

    if (input_size < MIN_PACKET_SIZE || input_size > MAX_PACKET_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "Invalid packet size\n");

        return AVERROR_INVALIDDATA;

    }

    av_fast_malloc(&s->buffer, &s->buffer_size,

                   FFALIGN(input_size, 4096) + DCA_BUFFER_PADDING_SIZE);

    if (!s->buffer)

        return AVERROR(ENOMEM);

    for (i = 0, ret = AVERROR_INVALIDDATA; i < input_size - MIN_PACKET_SIZE + 1 && ret < 0; i++)

        ret = convert_bitstream(input + i, input_size - i, s->buffer, s->buffer_size);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");

        return ret;

    }

    input      = s->buffer;

    input_size = ret;

    s->packet = 0;

    // Parse backward compatible core sub-stream

    if (AV_RB32(input) == DCA_SYNCWORD_CORE_BE) {

        int frame_size;

        if ((ret = ff_dca_core_parse(&s->core, input, input_size)) < 0)

            return ret;

        s->packet |= DCA_PACKET_CORE;

        // EXXS data must be aligned on 4-byte boundary

        frame_size = FFALIGN(s->core.frame_size, 4);

        if (input_size - 4 > frame_size) {

            input      += frame_size;

            input_size -= frame_size;

        }

    }

    if (!s->core_only) {

        DCAExssAsset *asset = NULL;

        // Parse extension sub-stream (EXSS)

        if (AV_RB32(input) == DCA_SYNCWORD_SUBSTREAM) {

            if ((ret = ff_dca_exss_parse(&s->exss, input, input_size)) < 0) {

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return ret;

            } else {

                s->packet |= DCA_PACKET_EXSS;

                asset = &s->exss.assets[0];

            }

        }

        // Parse XLL component in EXSS

        if (asset && (asset->extension_mask & DCA_EXSS_XLL)) {

            if ((ret = ff_dca_xll_parse(&s->xll, input, asset)) < 0) {

                // Conceal XLL synchronization error

                if (ret == AVERROR(EAGAIN)

                    && (prev_packet & DCA_PACKET_XLL)

                    && (s->packet & DCA_PACKET_CORE))

                    s->packet |= DCA_PACKET_XLL | DCA_PACKET_RECOVERY;

                else if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))

                    return ret;

            } else {

                s->packet |= DCA_PACKET_XLL;

            }

        }

        // Parse LBR component in EXSS

        if (asset && (asset->extension_mask & DCA_EXSS_LBR)) {

            if ((ret = ff_dca_lbr_parse(&s->lbr, input, asset)) < 0) {

                if (ret == AVERROR(ENOMEM) || (avctx->err_recognition & AV_EF_EXPLODE))

                    return ret;

            } else {

                s->packet |= DCA_PACKET_LBR;

            }

        }

        // Parse core extensions in EXSS or backward compatible core sub-stream

        if ((s->packet & DCA_PACKET_CORE)

            && (ret = ff_dca_core_parse_exss(&s->core, input, asset)) < 0)

            return ret;

    }

    // Filter the frame

    if (s->packet & DCA_PACKET_LBR) {

        if ((ret = ff_dca_lbr_filter_frame(&s->lbr, frame)) < 0)

            return ret;

    } else if (s->packet & DCA_PACKET_XLL) {

        if (s->packet & DCA_PACKET_CORE) {

            int x96_synth = -1;

            // Enable X96 synthesis if needed

            if (s->xll.chset[0].freq == 96000 && s->core.sample_rate == 48000)

                x96_synth = 1;

            if ((ret = ff_dca_core_filter_fixed(&s->core, x96_synth)) < 0)

                return ret;

            // Force lossy downmixed output on the first core frame filtered.

            // This prevents audible clicks when seeking and is consistent with

            // what reference decoder does when there are multiple channel sets.

            if (!(prev_packet & DCA_PACKET_RESIDUAL) && s->xll.nreschsets > 0

                && s->xll.nchsets > 1) {

                av_log(avctx, AV_LOG_VERBOSE, "Forcing XLL recovery mode\n");

                s->packet |= DCA_PACKET_RECOVERY;

            }

            // Set 'residual ok' flag for the next frame

            s->packet |= DCA_PACKET_RESIDUAL;

        }

        if ((ret = ff_dca_xll_filter_frame(&s->xll, frame)) < 0) {

            // Fall back to core unless hard error

            if (!(s->packet & DCA_PACKET_CORE))

                return ret;

            if (ret != AVERROR_INVALIDDATA || (avctx->err_recognition & AV_EF_EXPLODE))

                return ret;

            if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0)

                return ret;

        }

    } else if (s->packet & DCA_PACKET_CORE) {

        if ((ret = ff_dca_core_filter_frame(&s->core, frame)) < 0)

            return ret;

        if (s->core.filter_mode & DCA_FILTER_MODE_FIXED)

            s->packet |= DCA_PACKET_RESIDUAL;

    } else {

        av_log(avctx, AV_LOG_ERROR, "No valid DCA sub-stream found\n");

        if (s->core_only)

            av_log(avctx, AV_LOG_WARNING, "Consider disabling 'core_only' option\n");

        return AVERROR_INVALIDDATA;

    }

    *got_frame_ptr = 1;

    return avpkt->size;

}


static int iszero(const int16_t *c, int sz)

{

    int n;

    for (n = 0; n < sz; n += 4)

        if (AV_RN32A(&c[n]))

            return 0;

    return 1;

}


void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,

                         unsigned int pts_num, unsigned int pts_den)

{

    AVRational new_tb;

    if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){

        if(new_tb.num != pts_num)

            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);

    }else

        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);

    if(new_tb.num <= 0 || new_tb.den <= 0) {

        av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);

        return;

    }

    s->time_base = new_tb;

    s->pts_wrap_bits = pts_wrap_bits;

}


static void pci_bridge_region_init(PCIBridge *br)

{

    PCIBus *parent = br->dev.bus;

    uint16_t cmd = pci_get_word(br->dev.config + PCI_COMMAND);

    pci_bridge_init_alias(br, &br->alias_pref_mem,

                          PCI_BASE_ADDRESS_MEM_PREFETCH,

                          "pci_bridge_pref_mem",

                          &br->address_space_mem,

                          parent->address_space_mem,

                          cmd & PCI_COMMAND_MEMORY);

    pci_bridge_init_alias(br, &br->alias_mem,

                          PCI_BASE_ADDRESS_SPACE_MEMORY,

                          "pci_bridge_mem",

                          &br->address_space_mem,

                          parent->address_space_mem,

                          cmd & PCI_COMMAND_MEMORY);

    pci_bridge_init_alias(br, &br->alias_io,

                          PCI_BASE_ADDRESS_SPACE_IO,

                          "pci_bridge_io",

                          &br->address_space_io,

                          parent->address_space_io,

                          cmd & PCI_COMMAND_IO);

   /* TODO: optinal VGA and VGA palette snooping support. */

}


static void ecc_reset(void *opaque)

{

    ECCState *s = opaque;

    int i;

    s->regs[ECC_MER] &= (ECC_MER_VER | ECC_MER_IMPL);

    s->regs[ECC_MER] |= ECC_MER_MRR;

    s->regs[ECC_MDR] = 0x20;

    s->regs[ECC_MFSR] = 0;

    s->regs[ECC_VCR] = 0;

    s->regs[ECC_MFAR0] = 0x07c00000;

    s->regs[ECC_MFAR1] = 0;

    s->regs[ECC_DR] = 0;

    s->regs[ECC_ECR0] = 0;

    s->regs[ECC_ECR1] = 0;

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

        s->regs[i] = 0;

}


static inline int16_t mipsdsp_add_i16(int16_t a, int16_t b, CPUMIPSState *env)

{

    int16_t tempI;

    tempI = a + b;

    if (MIPSDSP_OVERFLOW(a, b, tempI, 0x8000)) {

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return tempI;

}


void cpu_loop(CPUMBState *env)

{

    int trapnr, ret;

    target_siginfo_t info;

    while (1) {

        trapnr = cpu_mb_exec (env);

        switch (trapnr) {

        case 0xaa:

            {

                info.si_signo = SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = 0;

                queue_signal(env, info.si_signo, &info);

            }

            break;

	case EXCP_INTERRUPT:

	  /* just indicate that signals should be handled asap */

	  break;

        case EXCP_BREAK:

            /* Return address is 4 bytes after the call.  */

            env->regs[14] += 4;

            ret = do_syscall(env,

                             env->regs[12],

                             env->regs[5],

                             env->regs[6],

                             env->regs[7],

                             env->regs[8],

                             env->regs[9],

                             env->regs[10],

                             0, 0);

            env->regs[3] = ret;

            env->sregs[SR_PC] = env->regs[14];

            break;

        case EXCP_HW_EXCP:

            env->regs[17] = env->sregs[SR_PC] + 4;

            if (env->iflags & D_FLAG) {

                env->sregs[SR_ESR] |= 1 << 12;

                env->sregs[SR_PC] -= 4;

                /* FIXME: if branch was immed, replay the imm as well.  */

            }

            env->iflags &= ~(IMM_FLAG | D_FLAG);

            switch (env->sregs[SR_ESR] & 31) {

                case ESR_EC_DIVZERO:

                    info.si_signo = SIGFPE;

                    info.si_errno = 0;

                    info.si_code = TARGET_FPE_FLTDIV;

                    info._sifields._sigfault._addr = 0;

                    queue_signal(env, info.si_signo, &info);

                    break;

                case ESR_EC_FPU:

                    info.si_signo = SIGFPE;

                    info.si_errno = 0;

                    if (env->sregs[SR_FSR] & FSR_IO) {

                        info.si_code = TARGET_FPE_FLTINV;

                    }

                    if (env->sregs[SR_FSR] & FSR_DZ) {

                        info.si_code = TARGET_FPE_FLTDIV;

                    }

                    info._sifields._sigfault._addr = 0;

                    queue_signal(env, info.si_signo, &info);

                    break;

                default:

                    printf ("Unhandled hw-exception: 0x%x\n",

                            env->sregs[SR_ESR] & ESR_EC_MASK);

                    cpu_dump_state(env, stderr, fprintf, 0);

                    exit (1);

                    break;

            }

            break;

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig (env, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

                    queue_signal(env, info.si_signo, &info);

                  }

            }

            break;

        default:

            printf ("Unhandled trap: 0x%x\n", trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            exit (1);

        }

        process_pending_signals (env);

    }

}


static void RENAME(interleaveBytes)(const uint8_t *src1, const uint8_t *src2, uint8_t *dest,

                                    int width, int height, int src1Stride,

                                    int src2Stride, int dstStride)

{

    int h;

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

        int w;

        if (width >= 16)

#if COMPILE_TEMPLATE_SSE2

        __asm__(

            "xor              %%"REG_a", %%"REG_a"  \n\t"

            "1:                                     \n\t"

            PREFETCH" 64(%1, %%"REG_a")             \n\t"

            PREFETCH" 64(%2, %%"REG_a")             \n\t"

            "movdqa     (%1, %%"REG_a"), %%xmm0     \n\t"

            "movdqa     (%1, %%"REG_a"), %%xmm1     \n\t"

            "movdqa     (%2, %%"REG_a"), %%xmm2     \n\t"

            "punpcklbw           %%xmm2, %%xmm0     \n\t"

            "punpckhbw           %%xmm2, %%xmm1     \n\t"

            "movntdq             %%xmm0,   (%0, %%"REG_a", 2)   \n\t"

            "movntdq             %%xmm1, 16(%0, %%"REG_a", 2)   \n\t"

            "add                    $16, %%"REG_a"  \n\t"

            "cmp                     %3, %%"REG_a"  \n\t"

            " jb                     1b             \n\t"

            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)

            : "memory", XMM_CLOBBERS("xmm0", "xmm1", "xmm2",) "%"REG_a

        );

#else

        __asm__(

            "xor %%"REG_a", %%"REG_a"               \n\t"

            "1:                                     \n\t"

            PREFETCH" 64(%1, %%"REG_a")             \n\t"

            PREFETCH" 64(%2, %%"REG_a")             \n\t"

            "movq       (%1, %%"REG_a"), %%mm0      \n\t"

            "movq      8(%1, %%"REG_a"), %%mm2      \n\t"

            "movq                 %%mm0, %%mm1      \n\t"

            "movq                 %%mm2, %%mm3      \n\t"

            "movq       (%2, %%"REG_a"), %%mm4      \n\t"

            "movq      8(%2, %%"REG_a"), %%mm5      \n\t"

            "punpcklbw            %%mm4, %%mm0      \n\t"

            "punpckhbw            %%mm4, %%mm1      \n\t"

            "punpcklbw            %%mm5, %%mm2      \n\t"

            "punpckhbw            %%mm5, %%mm3      \n\t"

            MOVNTQ"               %%mm0,   (%0, %%"REG_a", 2)   \n\t"

            MOVNTQ"               %%mm1,  8(%0, %%"REG_a", 2)   \n\t"

            MOVNTQ"               %%mm2, 16(%0, %%"REG_a", 2)   \n\t"

            MOVNTQ"               %%mm3, 24(%0, %%"REG_a", 2)   \n\t"

            "add                    $16, %%"REG_a"  \n\t"

            "cmp                     %3, %%"REG_a"  \n\t"

            " jb                     1b             \n\t"

            ::"r"(dest), "r"(src1), "r"(src2), "r" ((x86_reg)width-15)

            : "memory", "%"REG_a

        );

#endif

        for (w= (width&(~15)); w < width; w++) {

            dest[2*w+0] = src1[w];

            dest[2*w+1] = src2[w];

        }

        dest += dstStride;

        src1 += src1Stride;

        src2 += src2Stride;

    }

    __asm__(

#if !COMPILE_TEMPLATE_SSE2

            EMMS"       \n\t"

#endif

            SFENCE"     \n\t"

            ::: "memory"

            );

}


static int dvbsub_parse_page_segment(AVCodecContext *avctx,
                                     const uint8_t *buf, int buf_size, AVSubtitle *sub, int *got_output)
{
    DVBSubContext *ctx = avctx->priv_data;
    DVBSubRegionDisplay *display;
    DVBSubRegionDisplay *tmp_display_list, **tmp_ptr;
    const uint8_t *buf_end = buf + buf_size;
    int region_id;
    int page_state;
    int timeout;
    int version;
    if (buf_size < 1)
        return AVERROR_INVALIDDATA;
    timeout = *buf++;
    version = ((*buf)>>4) & 15;
    page_state = ((*buf++) >> 2) & 3;
    if (ctx->version == version) {
        return 0;
    ctx->time_out = timeout;
    ctx->version = version;
    ff_dlog(avctx, "Page time out %ds, state %d\n", ctx->time_out, page_state);
    if(ctx->compute_edt == 1)
        save_subtitle_set(avctx, sub, got_output);
    if (page_state == 1 || page_state == 2) {
        delete_regions(ctx);
        delete_objects(ctx);
        delete_cluts(ctx);
    tmp_display_list = ctx->display_list;
    ctx->display_list = NULL;
    while (buf + 5 < buf_end) {
        region_id = *buf++;
        buf += 1;
        display = tmp_display_list;
        tmp_ptr = &tmp_display_list;
            tmp_ptr = &display->next;
        if (!display) {
            display = av_mallocz(sizeof(DVBSubRegionDisplay));
            if (!display)
                return AVERROR(ENOMEM);
        display->region_id = region_id;
        display->x_pos = AV_RB16(buf);
        buf += 2;
        display->y_pos = AV_RB16(buf);
        buf += 2;
        *tmp_ptr = display->next;
        display->next = ctx->display_list;
        ctx->display_list = display;
        ff_dlog(avctx, "Region %d, (%d,%d)\n", region_id, display->x_pos, display->y_pos);
    while (tmp_display_list) {
        display = tmp_display_list;
        tmp_display_list = display->next;
        av_freep(&display);
    return 0;


static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s,
                                  void *last, void *dst, int last2, int w,
                                  int stride, int comp, int bits)
{
    int i, x = 0;
    int Ra, Rb, Rc, Rd;
    int D0, D1, D2;
    while (x < w) {
        int err, pred;
        /* compute gradients */
        Ra = x ? R(dst, x - stride) : R(last, x);
        Rb = R(last, x);
        Rc = x ? R(last, x - stride) : last2;
        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
        D0 = Rd - Rb;
        D1 = Rb - Rc;
        D2 = Rc - Ra;
        /* run mode */
        if ((FFABS(D0) <= state->near) &&
            (FFABS(D1) <= state->near) &&
            (FFABS(D2) <= state->near)) {
            int r;
            int RItype;
            /* decode full runs while available */
            while (get_bits1(&s->gb)) {
                int r;
                r = 1 << ff_log2_run[state->run_index[comp]];
                if (x + r * stride > w)
                    r = (w - x) / stride;
                for (i = 0; i < r; i++) {
                    W(dst, x, Ra);
                    x += stride;
                }
                /* if EOL reached, we stop decoding */
                if (r != 1 << ff_log2_run[state->run_index[comp]])
                if (state->run_index[comp] < 31)
                    state->run_index[comp]++;
                if (x + stride > w)
            }
            /* decode aborted run */
            r = ff_log2_run[state->run_index[comp]];
            if (r)
                r = get_bits_long(&s->gb, r);
            if (x + r * stride > w) {
                r = (w - x) / stride;
            }
            for (i = 0; i < r; i++) {
                W(dst, x, Ra);
                x += stride;
            }
            if (x >= w) {
                av_log(NULL, AV_LOG_ERROR, "run overflow\n");
                av_assert0(x <= w);
            }
            /* decode run termination value */
            Rb     = R(last, x);
            RItype = (FFABS(Ra - Rb) <= state->near) ? 1 : 0;
            err    = ls_get_code_runterm(&s->gb, state, RItype,
                                         ff_log2_run[state->run_index[comp]]);
            if (state->run_index[comp])
                state->run_index[comp]--;
            if (state->near && RItype) {
                pred = Ra + err;
            } else {
                if (Rb < Ra)
                    pred = Rb - err;
                else
                    pred = Rb + err;
            }
        } else { /* regular mode */
            int context, sign;
            context = ff_jpegls_quantize(state, D0) * 81 +
                      ff_jpegls_quantize(state, D1) *  9 +
                      ff_jpegls_quantize(state, D2);
            pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
            if (context < 0) {
                context = -context;
                sign    = 1;
            } else {
                sign = 0;
            }
            if (sign) {
                pred = av_clip(pred - state->C[context], 0, state->maxval);
                err  = -ls_get_code_regular(&s->gb, state, context);
            } else {
                pred = av_clip(pred + state->C[context], 0, state->maxval);
                err  = ls_get_code_regular(&s->gb, state, context);
            }
            /* we have to do something more for near-lossless coding */
            pred += err;
        }
        if (state->near) {
            if (pred < -state->near)
                pred += state->range * state->twonear;
            else if (pred > state->maxval + state->near)
                pred -= state->range * state->twonear;
            pred = av_clip(pred, 0, state->maxval);
        }
        pred &= state->maxval;
        W(dst, x, pred);
        x += stride;
    }
}


static int finish_frame(AVCodecContext *avctx, AVFrame *pict)

{

    RV34DecContext *r = avctx->priv_data;

    MpegEncContext *s = &r->s;

    int got_picture = 0;

    ff_er_frame_end(s);

    ff_MPV_frame_end(s);

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

        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);

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

        *pict = s->current_picture_ptr->f;

        got_picture = 1;

    } else if (s->last_picture_ptr != NULL) {

        *pict = s->last_picture_ptr->f;

        got_picture = 1;

    }

    if (got_picture)

        ff_print_debug_info(s, pict);

    return got_picture;

}


static int s337m_probe(AVProbeData *p)

{

    uint64_t state = 0;

    int markers[3] = { 0 };

    int i, sum, max, data_type, data_size, offset;

    uint8_t *buf;

    for (buf = p->buf; buf < p->buf + p->buf_size; buf++) {

        state = (state << 8) | *buf;

        if (!IS_LE_MARKER(state))

            continue;

        if (IS_16LE_MARKER(state)) {

            data_type = AV_RL16(buf + 1);

            data_size = AV_RL16(buf + 3);

            buf += 4;

        } else {

            data_type = AV_RL24(buf + 1);

            data_size = AV_RL24(buf + 4);

            buf += 6;

        }

        if (s337m_get_offset_and_codec(NULL, state, data_type, data_size, &offset, NULL))

            continue;

        i = IS_16LE_MARKER(state) ? 0 : IS_20LE_MARKER(state) ? 1 : 2;

        markers[i]++;

        buf  += offset;

        state = 0;

    }

    sum = max = 0;

    for (i = 0; i < FF_ARRAY_ELEMS(markers); i++) {

        sum += markers[i];

        if (markers[max] < markers[i])

            max = i;

    }

    if (markers[max] > 3 && markers[max] * 4 > sum * 3)

        return AVPROBE_SCORE_EXTENSION + 1;

    return 0;

}


static inline void RENAME(yuv2nv12X)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,

                                     const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,

                                     uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, enum PixelFormat dstFormat)

{

    yuv2nv12XinC(lumFilter, lumSrc, lumFilterSize,

                 chrFilter, chrSrc, chrFilterSize,

                 dest, uDest, dstW, chrDstW, dstFormat);

}


static int usb_bt_handle_control(USBDevice *dev, USBPacket *p,

               int request, int value, int index, int length, uint8_t *data)

{

    struct USBBtState *s = (struct USBBtState *) dev->opaque;

    int ret;

    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);

    if (ret >= 0) {

        switch (request) {

        case DeviceRequest | USB_REQ_GET_CONFIGURATION:

            s->config = 0;

            break;

        case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

            s->config = 1;

            usb_bt_fifo_reset(&s->evt);

            usb_bt_fifo_reset(&s->acl);

            usb_bt_fifo_reset(&s->sco);

            break;

        }

        return ret;

    }

    ret = 0;

    switch (request) {

    case InterfaceRequest | USB_REQ_GET_STATUS:

    case EndpointRequest | USB_REQ_GET_STATUS:

        data[0] = 0x00;

        data[1] = 0x00;

        ret = 2;

        break;

    case InterfaceOutRequest | USB_REQ_CLEAR_FEATURE:

    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:

        goto fail;

    case InterfaceOutRequest | USB_REQ_SET_FEATURE:

    case EndpointOutRequest | USB_REQ_SET_FEATURE:

        goto fail;

        break;

    case InterfaceRequest | USB_REQ_GET_INTERFACE:

        if (value != 0 || (index & ~1) || length != 1)

            goto fail;

        if (index == 1)

            data[0] = s->altsetting;

        else

            data[0] = 0;

        ret = 1;

        break;

    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:

        if ((index & ~1) || length != 0 ||

                        (index == 1 && (value < 0 || value > 4)) ||

                        (index == 0 && value != 0)) {

            printf("%s: Wrong SET_INTERFACE request (%i, %i)\n",

                            __FUNCTION__, index, value);

            goto fail;

        }

        s->altsetting = value;

        ret = 0;

        break;

    case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE) << 8):

        if (s->config)

            usb_bt_fifo_out_enqueue(s, &s->outcmd, s->hci->cmd_send,

                            usb_bt_hci_cmd_complete, data, length);

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


int get_filtered_video_frame(AVFilterContext *ctx, AVFrame *frame,

                             AVFilterBufferRef **picref_ptr, AVRational *tb)

{

    int ret;

    AVFilterBufferRef *picref;

    if ((ret = avfilter_request_frame(ctx->inputs[0])) < 0)

        return ret;

    if (!(picref = ctx->inputs[0]->cur_buf))

        return AVERROR(ENOENT);

    *picref_ptr = picref;

    ctx->inputs[0]->cur_buf = NULL;

    *tb = ctx->inputs[0]->time_base;

    memcpy(frame->data,     picref->data,     sizeof(frame->data));

    memcpy(frame->linesize, picref->linesize, sizeof(frame->linesize));

    frame->pkt_pos          = picref->pos;

    frame->interlaced_frame = picref->video->interlaced;

    frame->top_field_first  = picref->video->top_field_first;

    frame->key_frame        = picref->video->key_frame;

    frame->pict_type        = picref->video->pict_type;

    frame->sample_aspect_ratio = picref->video->sample_aspect_ratio;

    return 1;

}


static int vmxnet3_post_load(void *opaque, int version_id)
{
    VMXNET3State *s = opaque;
    PCIDevice *d = PCI_DEVICE(s);
    vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
    vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
    if (s->msix_used) {
        if  (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
            VMW_WRPRN("Failed to re-use MSI-X vectors");
            msix_uninit(d, &s->msix_bar, &s->msix_bar);
            s->msix_used = false;
            return -1;
        }
    }
    return 0;
}


static int hq_decode_block(HQContext *c, GetBitContext *gb, int16_t block[64],

                           int qsel, int is_chroma, int is_hqa)

{

    const int32_t *q;

    int val, pos = 1;

    memset(block, 0, 64 * sizeof(*block));

    if (!is_hqa) {

        block[0] = get_sbits(gb, 9) * 64;

        q = ff_hq_quants[qsel][is_chroma][get_bits(gb, 2)];

    } else {

        q = ff_hq_quants[qsel][is_chroma][get_bits(gb, 2)];

        block[0] = get_sbits(gb, 9) * 64;

    }

    for (;;) {

        val = get_vlc2(gb, c->hq_ac_vlc.table, 9, 2);

        if (val < 0)

            return AVERROR_INVALIDDATA;

        pos += ff_hq_ac_skips[val];

        if (pos >= 64)

            break;

        block[ff_zigzag_direct[pos]] = (ff_hq_ac_syms[val] * q[pos]) >> 12;

        pos++;

    }

    return 0;

}


void dsputil_init_alpha(void)

{

    put_pixels_tab[0][0] = put_pixels16_axp_asm;

    put_pixels_tab[0][1] = put_pixels16_x2_axp;

    put_pixels_tab[0][2] = put_pixels16_y2_axp;

    put_pixels_tab[0][3] = put_pixels16_xy2_axp;

    put_no_rnd_pixels_tab[0][0] = put_pixels16_axp_asm;

    put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_axp;

    put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_axp;

    put_no_rnd_pixels_tab[0][3] = put_no_rnd_pixels16_xy2_axp;

    avg_pixels_tab[0][0] = avg_pixels16_axp;

    avg_pixels_tab[0][1] = avg_pixels16_x2_axp;

    avg_pixels_tab[0][2] = avg_pixels16_y2_axp;

    avg_pixels_tab[0][3] = avg_pixels16_xy2_axp;

    avg_no_rnd_pixels_tab[0][0] = avg_no_rnd_pixels16_axp;

    avg_no_rnd_pixels_tab[0][1] = avg_no_rnd_pixels16_x2_axp;

    avg_no_rnd_pixels_tab[0][2] = avg_no_rnd_pixels16_y2_axp;

    avg_no_rnd_pixels_tab[0][3] = avg_no_rnd_pixels16_xy2_axp;

    put_pixels_tab[1][0] = put_pixels_axp_asm;

    put_pixels_tab[1][1] = put_pixels_x2_axp;

    put_pixels_tab[1][2] = put_pixels_y2_axp;

    put_pixels_tab[1][3] = put_pixels_xy2_axp;

    put_no_rnd_pixels_tab[1][0] = put_pixels_axp_asm;

    put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels_x2_axp;

    put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels_y2_axp;

    put_no_rnd_pixels_tab[1][3] = put_no_rnd_pixels_xy2_axp;

    avg_pixels_tab[1][0] = avg_pixels_axp;

    avg_pixels_tab[1][1] = avg_pixels_x2_axp;

    avg_pixels_tab[1][2] = avg_pixels_y2_axp;

    avg_pixels_tab[1][3] = avg_pixels_xy2_axp;

    avg_no_rnd_pixels_tab[1][0] = avg_no_rnd_pixels_axp;

    avg_no_rnd_pixels_tab[1][1] = avg_no_rnd_pixels_x2_axp;

    avg_no_rnd_pixels_tab[1][2] = avg_no_rnd_pixels_y2_axp;

    avg_no_rnd_pixels_tab[1][3] = avg_no_rnd_pixels_xy2_axp;

    clear_blocks = clear_blocks_axp;

    /* amask clears all bits that correspond to present features.  */

    if (amask(AMASK_MVI) == 0) {

        put_pixels_clamped = put_pixels_clamped_mvi_asm;

        add_pixels_clamped = add_pixels_clamped_mvi_asm;

        get_pixels       = get_pixels_mvi;

        diff_pixels      = diff_pixels_mvi;

        pix_abs8x8       = pix_abs8x8_mvi;

        pix_abs16x16     = pix_abs16x16_mvi_asm;

        pix_abs16x16_x2  = pix_abs16x16_x2_mvi;

        pix_abs16x16_y2  = pix_abs16x16_y2_mvi;

        pix_abs16x16_xy2 = pix_abs16x16_xy2_mvi;

    }

}


address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,

                                  hwaddr *xlat, hwaddr *plen)

{

    MemoryRegionSection *section;

    AddressSpaceDispatch *d = cpu->cpu_ases[asidx].memory_dispatch;

    section = address_space_translate_internal(d, addr, xlat, plen, false);

    assert(!section->mr->iommu_ops);

    return section;

}


static struct pxa2xx_fir_s *pxa2xx_fir_init(target_phys_addr_t base,

                qemu_irq irq, struct pxa2xx_dma_state_s *dma,

                CharDriverState *chr)

{

    int iomemtype;

    struct pxa2xx_fir_s *s = (struct pxa2xx_fir_s *)

            qemu_mallocz(sizeof(struct pxa2xx_fir_s));

    s->base = base;

    s->irq = irq;

    s->dma = dma;

    s->chr = chr;

    pxa2xx_fir_reset(s);

    iomemtype = cpu_register_io_memory(0, pxa2xx_fir_readfn,

                    pxa2xx_fir_writefn, s);

    cpu_register_physical_memory(s->base, 0xfff, iomemtype);

    if (chr)

        qemu_chr_add_handlers(chr, pxa2xx_fir_is_empty,

                        pxa2xx_fir_rx, pxa2xx_fir_event, s);

    register_savevm("pxa2xx_fir", 0, 0, pxa2xx_fir_save, pxa2xx_fir_load, s);

    return s;

}


static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)

{

    NBDClient *client = req->client;

    int csock = client->sock;

    ssize_t rc;

    client->recv_coroutine = qemu_coroutine_self();

    if (nbd_receive_request(csock, request) < 0) {

        rc = -EIO;

        goto out;

    }

    if (request->len > NBD_BUFFER_SIZE) {

        LOG("len (%u) is larger than max len (%u)",

            request->len, NBD_BUFFER_SIZE);

        rc = -EINVAL;

        goto out;

    }

    if ((request->from + request->len) < request->from) {

        LOG("integer overflow detected! "

            "you're probably being attacked");

        rc = -EINVAL;

        goto out;

    }

    TRACE("Decoding type");

    if ((request->type & NBD_CMD_MASK_COMMAND) == NBD_CMD_WRITE) {

        TRACE("Reading %u byte(s)", request->len);

        if (qemu_co_recv(csock, req->data, request->len) != request->len) {

            LOG("reading from socket failed");

            rc = -EIO;

            goto out;

        }

    }

    rc = 0;

out:

    client->recv_coroutine = NULL;

    return rc;

}


ram_addr_t migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,

                                       ram_addr_t start,

                                       ram_addr_t *ram_addr_abs)

{

    unsigned long base = rb->offset >> TARGET_PAGE_BITS;

    unsigned long nr = base + (start >> TARGET_PAGE_BITS);

    uint64_t rb_size = rb->used_length;

    unsigned long size = base + (rb_size >> TARGET_PAGE_BITS);

    unsigned long *bitmap;

    unsigned long next;

    bitmap = atomic_rcu_read(&rs->ram_bitmap)->bmap;

    if (rs->ram_bulk_stage && nr > base) {

        next = nr + 1;

    } else {

        next = find_next_bit(bitmap, size, nr);

    }

    *ram_addr_abs = next << TARGET_PAGE_BITS;

    return (next - base) << TARGET_PAGE_BITS;

}


AVFrame *ff_framequeue_take(FFFrameQueue *fq)

{

    FFFrameBucket *b;

    check_consistency(fq);

    av_assert1(fq->queued);

    b = bucket(fq, 0);

    fq->queued--;

    fq->tail++;

    fq->tail &= fq->allocated - 1;

    fq->total_frames_tail++;

    fq->total_samples_tail += b->frame->nb_samples;

    check_consistency(fq);

    return b->frame;

}


static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,

                                   int sector_size)

{

    s->lba = lba;

    s->packet_transfer_size = nb_sectors * sector_size;

    s->io_buffer_index = 0;

    s->io_buffer_size = 0;

    s->cd_sector_size = sector_size;

    block_acct_start(bdrv_get_stats(s->bs), &s->acct, s->packet_transfer_size,

                     BLOCK_ACCT_READ);

    /* XXX: check if BUSY_STAT should be set */

    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;

    ide_start_dma(s, ide_atapi_cmd_read_dma_cb);

}


void qed_acquire(BDRVQEDState *s)

{

    aio_context_acquire(bdrv_get_aio_context(s->bs));

}


static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,

                                       RDMAControlHeader *head)

{

    int ret = 0;

    RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];

    struct ibv_send_wr *bad_wr;

    struct ibv_sge sge = {

                           .addr = (uint64_t)(wr->control),

                           .length = head->len + sizeof(RDMAControlHeader),

                           .lkey = wr->control_mr->lkey,

                         };

    struct ibv_send_wr send_wr = {

                                   .wr_id = RDMA_WRID_SEND_CONTROL,

                                   .opcode = IBV_WR_SEND,

                                   .send_flags = IBV_SEND_SIGNALED,

                                   .sg_list = &sge,

                                   .num_sge = 1,

                                };

    DDDPRINTF("CONTROL: sending %s..\n", control_desc[head->type]);

    /*

     * We don't actually need to do a memcpy() in here if we used

     * the "sge" properly, but since we're only sending control messages

     * (not RAM in a performance-critical path), then its OK for now.

     *

     * The copy makes the RDMAControlHeader simpler to manipulate

     * for the time being.

     */

    assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));

    memcpy(wr->control, head, sizeof(RDMAControlHeader));

    control_to_network((void *) wr->control);

    if (buf) {

        memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);

    }

    if (ibv_post_send(rdma->qp, &send_wr, &bad_wr)) {

        return -1;

    }

    if (ret < 0) {

        fprintf(stderr, "Failed to use post IB SEND for control!\n");

        return ret;

    }

    ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL);

    if (ret < 0) {

        fprintf(stderr, "rdma migration: send polling control error!\n");

    }

    return ret;

}


static int hdev_open(BlockDriverState *bs, QDict *options, int flags,

                     Error **errp)

{

    BDRVRawState *s = bs->opaque;

    Error *local_err = NULL;

    int ret;

#if defined(__APPLE__) && defined(__MACH__)

    const char *filename = qdict_get_str(options, "filename");

    if (strstart(filename, "/dev/cdrom", NULL)) {

        kern_return_t kernResult;

        io_iterator_t mediaIterator;

        char bsdPath[ MAXPATHLEN ];

        int fd;

        kernResult = FindEjectableCDMedia( &mediaIterator );

        kernResult = GetBSDPath(mediaIterator, bsdPath, sizeof(bsdPath),

                                flags);

        if ( bsdPath[ 0 ] != '\0' ) {

            strcat(bsdPath,"s0");

            /* some CDs don't have a partition 0 */

            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);

            if (fd < 0) {

                bsdPath[strlen(bsdPath)-1] = '1';

            } else {

                qemu_close(fd);

            }

            filename = bsdPath;

            qdict_put(options, "filename", qstring_from_str(filename));

        }

        if ( mediaIterator )

            IOObjectRelease( mediaIterator );

    }

#endif

    s->type = FTYPE_FILE;

    ret = raw_open_common(bs, options, flags, 0, &local_err);

    if (ret < 0) {

        if (local_err) {

            error_propagate(errp, local_err);

        }

        return ret;

    }

    /* Since this does ioctl the device must be already opened */

    bs->sg = hdev_is_sg(bs);

    if (flags & BDRV_O_RDWR) {

        ret = check_hdev_writable(s);

        if (ret < 0) {

            raw_close(bs);

            error_setg_errno(errp, -ret, "The device is not writable");

            return ret;

        }

    }

    return ret;

}


static void pc_init1(MachineState *machine,

                     int pci_enabled,

                     int kvmclock_enabled)

{

    PCMachineState *pc_machine = PC_MACHINE(machine);

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq *smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    ISADevice *floppy;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    DeviceState *icc_bridge;

    FWCfgState *fw_cfg = NULL;

    PcGuestInfo *guest_info;

    /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory).

     * If it doesn't, we need to split it in chunks below and above 4G.

     * In any case, try to make sure that guest addresses aligned at

     * 1G boundaries get mapped to host addresses aligned at 1G boundaries.

     * For old machine types, use whatever split we used historically to avoid

     * breaking migration.

     */

    if (machine->ram_size >= 0xe0000000) {

        ram_addr_t lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000;

        above_4g_mem_size = machine->ram_size - lowmem;

        below_4g_mem_size = lowmem;

    } else {

        above_4g_mem_size = 0;

        below_4g_mem_size = machine->ram_size;

    }

    if (xen_enabled() && xen_hvm_init(&below_4g_mem_size, &above_4g_mem_size,

                                      &ram_memory) != 0) {

        fprintf(stderr, "xen hardware virtual machine initialisation failed\n");

        exit(1);

    }

    icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE);

    object_property_add_child(qdev_get_machine(), "icc-bridge",

                              OBJECT(icc_bridge), NULL);

    pc_cpus_init(machine->cpu_model, icc_bridge);

    if (kvm_enabled() && kvmclock_enabled) {

        kvmclock_create();

    }

    if (pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size);

    guest_info->has_acpi_build = has_acpi_build;

    guest_info->has_pci_info = has_pci_info;

    guest_info->isapc_ram_fw = !pci_enabled;

    guest_info->has_reserved_memory = has_reserved_memory;

    if (smbios_defaults) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            mc->name, smbios_legacy_mode);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        fw_cfg = pc_memory_init(machine, system_memory,

                                below_4g_mem_size, above_4g_mem_size,

                                rom_memory, &ram_memory, guest_info);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_irqchip_in_kernel()) {

        kvm_pc_setup_irq_routing(pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, machine->ram_size,

                              below_4g_mem_size,

                              above_4g_mem_size,

                              pci_memory, ram_memory);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, system_io);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_irqchip_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        cpu_irq = pc_allocate_cpu_irq();

        i8259 = i8259_init(isa_bus, cpu_irq[0]);

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    if (pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    qdev_init_nofail(icc_bridge);

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL);

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, xen_enabled(),

        0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, MAX_IDE_BUS);

    if (pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, machine->boot_order,

                 floppy, idebus[0], idebus[1], rtc_state);

    if (pci_enabled && usb_enabled(false)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pci_enabled && acpi_enabled) {

        DeviceState *piix4_pm;

        I2CBus *smbus;

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], *smi_irq,

                              kvm_enabled(), fw_cfg, &piix4_pm);

        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,

                                 TYPE_HOTPLUG_HANDLER,

                                 (Object **)&pc_machine->acpi_dev,

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),

                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

}


static void qpci_spapr_io_writel(QPCIBus *bus, void *addr, uint32_t value)

{

    QPCIBusSPAPR *s = container_of(bus, QPCIBusSPAPR, bus);

    uint64_t port = (uintptr_t)addr;

    value = bswap32(value);

    if (port < s->pio.size) {

        writel(s->pio_cpu_base + port, value);

    } else {

        writel(s->mmio_cpu_base + port, value);

    }

}


static int get_char(GDBState *s)

{

    uint8_t ch;

    int ret;

    for(;;) {

        ret = qemu_recv(s->fd, &ch, 1, 0);

        if (ret < 0) {

            if (errno == ECONNRESET)

                s->fd = -1;

            if (errno != EINTR && errno != EAGAIN)

                return -1;

        } else if (ret == 0) {

            close(s->fd);

            s->fd = -1;

            return -1;

        } else {

            break;

        }

    }

    return ch;

}


static void gen_ldda_asi(DisasContext *dc, TCGv hi, TCGv addr,

                         int insn, int rd)

{

    TCGv_i32 r_asi, r_rd;

    r_asi = gen_get_asi(dc, insn);

    r_rd = tcg_const_i32(rd);

    gen_helper_ldda_asi(cpu_env, addr, r_asi, r_rd);

    tcg_temp_free_i32(r_rd);

    tcg_temp_free_i32(r_asi);

}


static int kvm_sclp_service_call(CPUS390XState *env, struct kvm_run *run,

                                 uint16_t ipbh0)

{

    uint32_t sccb;

    uint64_t code;

    int r = 0;

    cpu_synchronize_state(env);

    sccb = env->regs[ipbh0 & 0xf];

    code = env->regs[(ipbh0 & 0xf0) >> 4];

    r = sclp_service_call(env, sccb, code);

    if (r) {

        setcc(env, 3);

    }

    return 0;

}


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

                        char *line, int line_size, int *print_prefix)

{

    AVBPrint part[4];

    format_line(ptr, level, fmt, vl, part, print_prefix, NULL);

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

    av_bprint_finalize(part+3, NULL);

}


void do_raise_exception_err (uint32_t exception, int error_code)

{

#if 0

    printf("Raise exception %3x code : %d\n", exception, error_code);

#endif

    switch (exception) {

    case EXCP_PROGRAM:

        if (error_code == EXCP_FP && msr_fe0 == 0 && msr_fe1 == 0)

            return;

        break;

    default:

        break;

    }

    env->exception_index = exception;

    env->error_code = error_code;

    cpu_loop_exit();

}


static AddressSpace *virtio_pci_get_dma_as(DeviceState *d)

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    PCIDevice *dev = &proxy->pci_dev;

    return pci_get_address_space(dev);

}


static int pte32_check (mmu_ctx_t *ctx,

                        target_ulong pte0, target_ulong pte1, int h, int rw)

{

    return _pte_check(ctx, 0, pte0, pte1, h, rw);

}


static void x86_cpu_class_check_missing_features(X86CPUClass *xcc,

                                                 strList **missing_feats)

{

    X86CPU *xc;

    FeatureWord w;

    Error *err = NULL;

    strList **next = missing_feats;

    if (xcc->kvm_required && !kvm_enabled()) {

        strList *new = g_new0(strList, 1);

        new->value = g_strdup("kvm");;

        *missing_feats = new;

        return;

    }

    xc = X86_CPU(object_new(object_class_get_name(OBJECT_CLASS(xcc))));

    x86_cpu_load_features(xc, &err);

    if (err) {

        /* Errors at x86_cpu_load_features should never happen,

         * but in case it does, just report the model as not

         * runnable at all using the "type" property.

         */

        strList *new = g_new0(strList, 1);

        new->value = g_strdup("type");

        *next = new;

        next = &new->next;

    }

    x86_cpu_filter_features(xc);

    for (w = 0; w < FEATURE_WORDS; w++) {

        uint32_t filtered = xc->filtered_features[w];

        int i;

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

            if (filtered & (1UL << i)) {

                strList *new = g_new0(strList, 1);

                new->value = g_strdup(x86_cpu_feature_name(w, i));

                *next = new;

                next = &new->next;

            }

        }

    }

    object_unref(OBJECT(xc));

}


int bdrv_flush(BlockDriverState *bs)

{

    Coroutine *co;

    RwCo rwco = {

        .bs = bs,

        .ret = NOT_DONE,

    };

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_flush_co_entry(&rwco);

    } else {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        co = qemu_coroutine_create(bdrv_flush_co_entry);

        qemu_coroutine_enter(co, &rwco);

        while (rwco.ret == NOT_DONE) {

            aio_poll(aio_context, true);

        }

    }

    return rwco.ret;

}


void qmp_nbd_server_start(SocketAddressLegacy *addr,

                          bool has_tls_creds, const char *tls_creds,

                          Error **errp)

{

    if (nbd_server) {

        error_setg(errp, "NBD server already running");

        return;

    }

    nbd_server = g_new0(NBDServerData, 1);

    nbd_server->watch = -1;

    nbd_server->listen_ioc = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL(nbd_server->listen_ioc),

                         "nbd-listener");

    if (qio_channel_socket_listen_sync(

            nbd_server->listen_ioc, addr, errp) < 0) {

        goto error;

    }

    if (has_tls_creds) {

        nbd_server->tlscreds = nbd_get_tls_creds(tls_creds, errp);

        if (!nbd_server->tlscreds) {

            goto error;

        }

        /* TODO SOCKET_ADDRESS_LEGACY_KIND_FD where fd has AF_INET or AF_INET6 */

        if (addr->type != SOCKET_ADDRESS_LEGACY_KIND_INET) {

            error_setg(errp, "TLS is only supported with IPv4/IPv6");

            goto error;

        }

    }

    nbd_server->watch = qio_channel_add_watch(

        QIO_CHANNEL(nbd_server->listen_ioc),

        G_IO_IN,

        nbd_accept,

        NULL,

        NULL);

    return;

 error:

    nbd_server_free(nbd_server);

    nbd_server = NULL;

}


vubr_backend_recv_cb(int sock, void *ctx)

{

    VubrDev *vubr = (VubrDev *) ctx;

    VuDev *dev = &vubr->vudev;

    VuVirtq *vq = vu_get_queue(dev, 0);

    VuVirtqElement *elem = NULL;

    struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];

    struct virtio_net_hdr_mrg_rxbuf mhdr;

    unsigned mhdr_cnt = 0;

    int hdrlen = vubr->hdrlen;

    int i = 0;

    struct virtio_net_hdr hdr = {

        .flags = 0,

        .gso_type = VIRTIO_NET_HDR_GSO_NONE

    };

    DPRINT("\n\n   ***   IN UDP RECEIVE CALLBACK    ***\n\n");

    DPRINT("    hdrlen = %d\n", hdrlen);

    if (!vu_queue_enabled(dev, vq) ||

        !vu_queue_started(dev, vq) ||

        !vu_queue_avail_bytes(dev, vq, hdrlen, 0)) {

        DPRINT("Got UDP packet, but no available descriptors on RX virtq.\n");

        return;

    }

    do {

        struct iovec *sg;

        ssize_t ret, total = 0;

        unsigned int num;

        elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));

        if (!elem) {

            break;

        }

        if (elem->in_num < 1) {

            fprintf(stderr, "virtio-net contains no in buffers\n");

            break;

        }

        sg = elem->in_sg;

        num = elem->in_num;

        if (i == 0) {

            if (hdrlen == 12) {

                mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),

                                    sg, elem->in_num,

                                    offsetof(typeof(mhdr), num_buffers),

                                    sizeof(mhdr.num_buffers));

            }

            iov_from_buf(sg, elem->in_num, 0, &hdr, sizeof hdr);

            total += hdrlen;

            ret = iov_discard_front(&sg, &num, hdrlen);

            assert(ret == hdrlen);

        }

        struct msghdr msg = {

            .msg_name = (struct sockaddr *) &vubr->backend_udp_dest,

            .msg_namelen = sizeof(struct sockaddr_in),

            .msg_iov = sg,

            .msg_iovlen = elem->in_num,

            .msg_flags = MSG_DONTWAIT,

        };

        do {

            ret = recvmsg(vubr->backend_udp_sock, &msg, 0);

        } while (ret == -1 && (errno == EINTR));

        if (i == 0) {

            iov_restore_front(elem->in_sg, sg, hdrlen);

        }

        if (ret == -1) {

            if (errno == EWOULDBLOCK) {

                vu_queue_rewind(dev, vq, 1);

                break;

            }

            vubr_die("recvmsg()");

        }

        total += ret;

        iov_truncate(elem->in_sg, elem->in_num, total);

        vu_queue_fill(dev, vq, elem, total, i++);

        free(elem);

        elem = NULL;

    } while (false); /* could loop if DONTWAIT worked? */

    if (mhdr_cnt) {

        mhdr.num_buffers = i;

        iov_from_buf(mhdr_sg, mhdr_cnt,

                     0,

                     &mhdr.num_buffers, sizeof mhdr.num_buffers);

    }

    vu_queue_flush(dev, vq, i);

    vu_queue_notify(dev, vq);

    free(elem);

}


int ff_j2k_init_component(Jpeg2000Component *comp,

                          Jpeg2000CodingStyle *codsty,

                          Jpeg2000QuantStyle *qntsty,

                          int cbps, int dx, int dy,

                          AVCodecContext *avctx)

{

    uint8_t log2_band_prec_width, log2_band_prec_height;

    int reslevelno, bandno, gbandno = 0, ret, i, j, csize = 1;

    if (ret=ff_jpeg2000_dwt_init(&comp->dwt, comp->coord, codsty->nreslevels2decode-1, codsty->transform == FF_DWT53 ? FF_DWT53 : FF_DWT97_INT))

        return ret;

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

        csize *= comp->coord[i][1] - comp->coord[i][0];

    comp->data = av_malloc_array(csize, sizeof(*comp->data));

    if (!comp->data)

        return AVERROR(ENOMEM);

    comp->reslevel = av_malloc_array(codsty->nreslevels, sizeof(*comp->reslevel));

    if (!comp->reslevel)

        return AVERROR(ENOMEM);

    /* LOOP on resolution levels */

    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {

        int declvl = codsty->nreslevels - reslevelno;    // N_L -r see  ISO/IEC 15444-1:2002 B.5

        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

        /* Compute borders for each resolution level.

         * Computation of trx_0, trx_1, try_0 and try_1.

         * see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */

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

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

                reslevel->coord[i][j] =

                    ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1);

        // update precincts size: 2^n value

        reslevel->log2_prec_width  = codsty->log2_prec_widths[reslevelno];

        reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno];

        /* Number of bands for each resolution level */

        if (reslevelno == 0)

            reslevel->nbands = 1;

        else

            reslevel->nbands = 3;

        /* Number of precincts wich span the tile for resolution level reslevelno

         * see B.6 in ISO/IEC 15444-1:2002 eq. B-16

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width)

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width)

         * for Dcinema profiles in JPEG 2000

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -|

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */

        if (reslevel->coord[0][1] == reslevel->coord[0][0])

            reslevel->num_precincts_x = 0;

        else

            reslevel->num_precincts_x =

                ff_jpeg2000_ceildivpow2(reslevel->coord[0][1],

                                        reslevel->log2_prec_width) -

                (reslevel->coord[0][0] >> reslevel->log2_prec_width);

        if (reslevel->coord[1][1] == reslevel->coord[1][0])

            reslevel->num_precincts_y = 0;

        else

            reslevel->num_precincts_y =

                ff_jpeg2000_ceildivpow2(reslevel->coord[1][1],

                                        reslevel->log2_prec_height) -

                (reslevel->coord[1][0] >> reslevel->log2_prec_height);

        reslevel->band = av_malloc_array(reslevel->nbands, sizeof(*reslevel->band));

        if (!reslevel->band)

            return AVERROR(ENOMEM);

        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {

            Jpeg2000Band *band = reslevel->band + bandno;

            int cblkno, precno;

            int nb_precincts;

            /* TODO: Implementation of quantization step not finished,

             * see ISO/IEC 15444-1:2002 E.1 and A.6.4. */

            switch (qntsty->quantsty) {

                uint8_t gain;

                int numbps;

            case JPEG2000_QSTY_NONE:

                /* TODO: to verify. No quantization in this case */

                band->f_stepsize = 1;

                break;

            case JPEG2000_QSTY_SI:

                /*TODO: Compute formula to implement. */

                numbps = cbps +

                         lut_gain[codsty->transform][bandno + (reslevelno > 0)];

                band->f_stepsize = SHL(2048 + qntsty->mant[gbandno],

                                            2 + numbps - qntsty->expn[gbandno]);

                break;

            case JPEG2000_QSTY_SE:

                /* Exponent quantization step.

                 * Formula:

                 * delta_b = 2 ^ (R_b - expn_b) * (1 + (mant_b / 2 ^ 11))

                 * R_b = R_I + log2 (gain_b )

                 * see ISO/IEC 15444-1:2002 E.1.1 eqn. E-3 and E-4 */

                /* TODO/WARN: value of log2 (gain_b ) not taken into account

                 * but it works (compared to OpenJPEG). Why?

                 * Further investigation needed. */

                gain      = cbps;

                band->f_stepsize  = pow(2.0, gain - qntsty->expn[gbandno]);

                band->f_stepsize *= (qntsty->mant[gbandno] / 2048.0 + 1.0);

                break;

            default:

                band->f_stepsize = 0;

                av_log(avctx, AV_LOG_ERROR, "Unknown quantization format\n");

                break;

            }

            /* FIXME: In openjepg code stespize = stepsize * 0.5. Why?

             * If not set output of entropic decoder is not correct. */

            if (!av_codec_is_encoder(avctx->codec))

                band->f_stepsize *= 0.5;

            band->i_stepsize = band->f_stepsize * (1 << 16);

            /* computation of tbx_0, tbx_1, tby_0, tby_1

             * see ISO/IEC 15444-1:2002 B.5 eq. B-15 and tbl B.1

             * codeblock width and height is computed for

             * DCI JPEG 2000 codeblock_width = codeblock_width = 32 = 2 ^ 5 */

            if (reslevelno == 0) {

                /* for reslevelno = 0, only one band, x0_b = y0_b = 0 */

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

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

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0],

                                                    declvl - 1);

                log2_band_prec_width  = reslevel->log2_prec_width;

                log2_band_prec_height = reslevel->log2_prec_height;

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height);

            } else {

                /* 3 bands x0_b = 1 y0_b = 0; x0_b = 0 y0_b = 1; x0_b = y0_b = 1 */

                /* x0_b and y0_b are computed with ((bandno + 1 >> i) & 1) */

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

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

                        /* Formula example for tbx_0 = ceildiv((tcx_0 - 2 ^ (declvl - 1) * x0_b) / declvl) */

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0] -

                                                    (((bandno + 1 >> i) & 1) << declvl - 1),

                                                    declvl);

                /* TODO: Manage case of 3 band offsets here or

                 * in coding/decoding function? */

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width - 1);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height - 1);

                log2_band_prec_width  = reslevel->log2_prec_width  - 1;

                log2_band_prec_height = reslevel->log2_prec_height - 1;

            }

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

                band->coord[0][j] = ff_jpeg2000_ceildiv(band->coord[0][j], dx);

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

                band->coord[1][j] = ff_jpeg2000_ceildiv(band->coord[1][j], dy);

            band->prec = av_malloc_array(reslevel->num_precincts_x *

                                         reslevel->num_precincts_y,

                                         sizeof(*band->prec));

            if (!band->prec)

                return AVERROR(ENOMEM);

            nb_precincts = reslevel->num_precincts_x * reslevel->num_precincts_y;

            for (precno = 0; precno < nb_precincts; precno++) {

                Jpeg2000Prec *prec = band->prec + precno;

                /* TODO: Explain formula for JPEG200 DCINEMA. */

                /* TODO: Verify with previous count of codeblocks per band */

                /* Compute P_x0 */

                prec->coord[0][0] = (precno % reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_width);

                prec->coord[0][0] = FFMAX(prec->coord[0][0], band->coord[0][0]);

                /* Compute P_y0 */

                prec->coord[1][0] = (precno / reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_height);

                prec->coord[1][0] = FFMAX(prec->coord[1][0], band->coord[1][0]);

                /* Compute P_x1 */

                prec->coord[0][1] = prec->coord[0][0] +

                                    (1 << log2_band_prec_width);

                prec->coord[0][1] = FFMIN(prec->coord[0][1], band->coord[0][1]);

                /* Compute P_y1 */

                prec->coord[1][1] = prec->coord[1][0] +

                                    (1 << log2_band_prec_height);

                prec->coord[1][1] = FFMIN(prec->coord[1][1], band->coord[1][1]);

                prec->nb_codeblocks_width =

                    ff_jpeg2000_ceildivpow2(prec->coord[0][1] -

                                            prec->coord[0][0],

                                            band->log2_cblk_width);

                prec->nb_codeblocks_height =

                    ff_jpeg2000_ceildivpow2(prec->coord[1][1] -

                                            prec->coord[1][0],

                                            band->log2_cblk_height);

                /* Tag trees initialization */

                prec->cblkincl =

                    ff_j2k_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->cblkincl)

                    return AVERROR(ENOMEM);

                prec->zerobits =

                    ff_j2k_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->zerobits)

                    return AVERROR(ENOMEM);

                prec->cblk = av_malloc_array(prec->nb_codeblocks_width *

                                             prec->nb_codeblocks_height,

                                             sizeof(*prec->cblk));

                if (!prec->cblk)

                    return AVERROR(ENOMEM);

                for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                    Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                    uint16_t Cx0, Cy0;

                    /* Compute coordinates of codeblocks */

                    /* Compute Cx0*/

                    Cx0 = (prec->coord[0][0] >> band->log2_cblk_width) << band->log2_cblk_width;

                    Cx0 = Cx0 + ((cblkno % prec->nb_codeblocks_width)  << band->log2_cblk_width);

                    cblk->coord[0][0] = FFMAX(Cx0, prec->coord[0][0]);

                    /* Compute Cy0*/

                    Cy0 = (prec->coord[1][0] >> band->log2_cblk_height) << band->log2_cblk_height;

                    Cy0 = Cy0 + ((cblkno / prec->nb_codeblocks_width)   << band->log2_cblk_height);

                    cblk->coord[1][0] = FFMAX(Cy0, prec->coord[1][0]);

                    /* Compute Cx1 */

                    cblk->coord[0][1] = FFMIN(Cx0 + (1 << band->log2_cblk_width),

                                              prec->coord[0][1]);

                    /* Compute Cy1 */

                    cblk->coord[1][1] = FFMIN(Cy0 + (1 << band->log2_cblk_height),

                                              prec->coord[1][1]);

                    if((bandno + !!reslevelno) & 1) {

                        cblk->coord[0][0] += comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];

                        cblk->coord[0][1] += comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];

                    }

                    if((bandno + !!reslevelno) & 2) {

                        cblk->coord[1][0] += comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];

                        cblk->coord[1][1] += comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];

                    }

                    cblk->zero      = 0;

                    cblk->lblock    = 3;

                    cblk->length    = 0;

                    cblk->lengthinc = 0;

                    cblk->npasses   = 0;

                }

            }

        }

    }

    return 0;

}


static av_always_inline void blend_image_packed_rgb(AVFilterContext *ctx,

                                   AVFrame *dst, const AVFrame *src,

                                   int main_has_alpha, int x, int y,

                                   int is_straight)

{

    OverlayContext *s = ctx->priv;

    int i, imax, j, jmax;

    const int src_w = src->width;

    const int src_h = src->height;

    const int dst_w = dst->width;

    const int dst_h = dst->height;

    uint8_t alpha;          ///< the amount of overlay to blend on to main

    const int dr = s->main_rgba_map[R];

    const int dg = s->main_rgba_map[G];

    const int db = s->main_rgba_map[B];

    const int da = s->main_rgba_map[A];

    const int dstep = s->main_pix_step[0];

    const int sr = s->overlay_rgba_map[R];

    const int sg = s->overlay_rgba_map[G];

    const int sb = s->overlay_rgba_map[B];

    const int sa = s->overlay_rgba_map[A];

    const int sstep = s->overlay_pix_step[0];

    uint8_t *S, *sp, *d, *dp;

    i = FFMAX(-y, 0);

    sp = src->data[0] + i     * src->linesize[0];

    dp = dst->data[0] + (y+i) * dst->linesize[0];

    for (imax = FFMIN(-y + dst_h, src_h); i < imax; i++) {

        j = FFMAX(-x, 0);

        S = sp + j     * sstep;

        d = dp + (x+j) * dstep;

        for (jmax = FFMIN(-x + dst_w, src_w); j < jmax; j++) {

            alpha = S[sa];

            // if the main channel has an alpha channel, alpha has to be calculated

            // to create an un-premultiplied (straight) alpha value

            if (main_has_alpha && alpha != 0 && alpha != 255) {

                uint8_t alpha_d = d[da];

                alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);

            }

            switch (alpha) {

            case 0:

                break;

            case 255:

                d[dr] = S[sr];

                d[dg] = S[sg];

                d[db] = S[sb];

                break;

            default:

                // main_value = main_value * (1 - alpha) + overlay_value * alpha

                // since alpha is in the range 0-255, the result must divided by 255

                d[dr] = is_straight ? FAST_DIV255(d[dr] * (255 - alpha) + S[sr] * alpha) : FAST_DIV255(d[dr] * (255 - alpha) + S[sr]);

                d[dg] = is_straight ? FAST_DIV255(d[dg] * (255 - alpha) + S[sg] * alpha) : FAST_DIV255(d[dr] * (255 - alpha) + S[sr]);

                d[db] = is_straight ? FAST_DIV255(d[db] * (255 - alpha) + S[sb] * alpha) : FAST_DIV255(d[dr] * (255 - alpha) + S[sr]);

            }

            if (main_has_alpha) {

                switch (alpha) {

                case 0:

                    break;

                case 255:

                    d[da] = S[sa];

                    break;

                default:

                    // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha

                    d[da] += FAST_DIV255((255 - d[da]) * S[sa]);

                }

            }

            d += dstep;

            S += sstep;

        }

        dp += dst->linesize[0];

        sp += src->linesize[0];

    }

}


static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,

                                   uint8_t *data, RDMAControlHeader *resp,

                                   int *resp_idx,

                                   int (*callback)(RDMAContext *rdma))

{

    int ret = 0;

    /*

     * Wait until the dest is ready before attempting to deliver the message

     * by waiting for a READY message.

     */

    if (rdma->control_ready_expected) {

        RDMAControlHeader resp;

        ret = qemu_rdma_exchange_get_response(rdma,

                                    &resp, RDMA_CONTROL_READY, RDMA_WRID_READY);

        if (ret < 0) {

            return ret;

        }

    }

    /*

     * If the user is expecting a response, post a WR in anticipation of it.

     */

    if (resp) {

        ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);

        if (ret) {

            fprintf(stderr, "rdma migration: error posting"

                    " extra control recv for anticipated result!");

            return ret;

        }

    }

    /*

     * Post a WR to replace the one we just consumed for the READY message.

     */

    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);

    if (ret) {

        fprintf(stderr, "rdma migration: error posting first control recv!");

        return ret;

    }

    /*

     * Deliver the control message that was requested.

     */

    ret = qemu_rdma_post_send_control(rdma, data, head);

    if (ret < 0) {

        fprintf(stderr, "Failed to send control buffer!\n");

        return ret;

    }

    /*

     * If we're expecting a response, block and wait for it.

     */

    if (resp) {

        if (callback) {

            DDPRINTF("Issuing callback before receiving response...\n");

            ret = callback(rdma);

            if (ret < 0) {

                return ret;

            }

        }

        DDPRINTF("Waiting for response %s\n", control_desc[resp->type]);

        ret = qemu_rdma_exchange_get_response(rdma, resp,

                                              resp->type, RDMA_WRID_DATA);

        if (ret < 0) {

            return ret;

        }

        qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);

        if (resp_idx) {

            *resp_idx = RDMA_WRID_DATA;

        }

        DDPRINTF("Response %s received.\n", control_desc[resp->type]);

    }

    rdma->control_ready_expected = 1;

    return 0;

}


static int configure_accelerator(void)

{

    const char *p = NULL;

    char buf[10];

    int i, ret;

    bool accel_initialised = false;

    bool init_failed = false;

    QemuOptsList *list = qemu_find_opts("machine");

    if (!QTAILQ_EMPTY(&list->head)) {

        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");

    }

    if (p == NULL) {

        /* Use the default "accelerator", tcg */

        p = "tcg";

    }

    while (!accel_initialised && *p != '\0') {

        if (*p == ':') {

            p++;

        }

        p = get_opt_name(buf, sizeof (buf), p, ':');

        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {

            if (strcmp(accel_list[i].opt_name, buf) == 0) {

                if (!accel_list[i].available()) {

                    printf("%s not supported for this target\n",

                           accel_list[i].name);

                    continue;

                }

                *(accel_list[i].allowed) = true;

                ret = accel_list[i].init();

                if (ret < 0) {

                    init_failed = true;

                    fprintf(stderr, "failed to initialize %s: %s\n",

                            accel_list[i].name,

                            strerror(-ret));

                    *(accel_list[i].allowed) = false;

                } else {

                    accel_initialised = true;

                }

                break;

            }

        }

        if (i == ARRAY_SIZE(accel_list)) {

            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);

        }

    }

    if (!accel_initialised) {

        if (!init_failed) {

            fprintf(stderr, "No accelerator found!\n");

        }

        exit(1);

    }

    if (init_failed) {

        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);

    }

    return !accel_initialised;

}


void qemu_chr_add_handlers(CharDriverState *s,

                           IOCanReadHandler *fd_can_read,

                           IOReadHandler *fd_read,

                           IOEventHandler *fd_event,

                           void *opaque)

{

    if (!opaque) {

        /* chr driver being released. */

        s->assigned = 0;

    }

    s->chr_can_read = fd_can_read;

    s->chr_read = fd_read;

    s->chr_event = fd_event;

    s->handler_opaque = opaque;

    if (s->chr_update_read_handler)

        s->chr_update_read_handler(s);

    /* We're connecting to an already opened device, so let's make sure we

       also get the open event */

    if (s->opened) {

        qemu_chr_generic_open(s);

    }

}


static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,

                                   uint8_t *last_nnz,

                                   int ac_index, int16_t *quant_matrix,

                                   int ss, int se, int Al, int *EOBRUN)

{

    int code, i = ss, j, sign, val, run;

    int last    = FFMIN(se, *last_nnz);

    OPEN_READER(re, &s->gb);

    if (*EOBRUN) {

        (*EOBRUN)--;

    } else {

        for (; ; i++) {

            UPDATE_CACHE(re, &s->gb);

            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);

            if (code & 0xF) {

                run = ((unsigned) code) >> 4;

                UPDATE_CACHE(re, &s->gb);

                val = SHOW_UBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

                ZERO_RUN;

                j = s->scantable.permutated[i];

                val--;

                block[j] = ((quant_matrix[j]^val) - val) << Al;

                if (i == se) {

                    if (i > *last_nnz)

                        *last_nnz = i;

                    CLOSE_READER(re, &s->gb);

                    return 0;

                }

            } else {

                run = ((unsigned) code) >> 4;

                if (run == 0xF) {

                    ZERO_RUN;

                } else {

                    val = run;

                    run = (1 << run);

                    if (val) {

                        UPDATE_CACHE(re, &s->gb);

                        run += SHOW_UBITS(re, &s->gb, val);

                        LAST_SKIP_BITS(re, &s->gb, val);

                    }

                    *EOBRUN = run - 1;

                    break;

                }

            }

        }

        if (i > *last_nnz)

            *last_nnz = i;

    }

    for (; i <= last; i++) {

        j = s->scantable.permutated[i];

        if (block[j])

            REFINE_BIT(j)

    }

    CLOSE_READER(re, &s->gb);

    return 0;

}


int ff_mov_lang_to_iso639(int code, char *to)

{

    int i;

    /* is it the mangled iso code? */

    /* see http://www.geocities.com/xhelmboyx/quicktime/formats/mp4-layout.txt */

    if (code > 138) {

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

            to[i] = 0x60 + (code & 0x1f);

            code >>= 5;

        }

        return 1;

    }

    /* old fashion apple lang code */

    if (code >= FF_ARRAY_ELEMS(mov_mdhd_language_map))

        return 0;

    if (!mov_mdhd_language_map[code])

        return 0;

    strncpy(to, mov_mdhd_language_map[code], 4);

    return 1;

}


static void ohci_sysbus_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = ohci_realize_pxa;

    set_bit(DEVICE_CATEGORY_USB, dc->categories);

    dc->desc = "OHCI USB Controller";

    dc->props = ohci_sysbus_properties;

    dc->reset = usb_ohci_reset_sysbus;

}


av_cold void ff_vp3dsp_init_x86(VP3DSPContext *c, int flags)

{

#if HAVE_YASM

    int cpuflags = av_get_cpu_flags();

#if ARCH_X86_32

    if (HAVE_MMX && cpuflags & AV_CPU_FLAG_MMX) {

        c->idct_put  = ff_vp3_idct_put_mmx;

        c->idct_add  = ff_vp3_idct_add_mmx;

        c->idct_perm = FF_PARTTRANS_IDCT_PERM;

    }

#endif

    if (HAVE_MMXEXT && cpuflags & AV_CPU_FLAG_MMXEXT) {

        c->idct_dc_add = ff_vp3_idct_dc_add_mmx2;

        if (!(flags & CODEC_FLAG_BITEXACT)) {

            c->v_loop_filter = ff_vp3_v_loop_filter_mmx2;

            c->h_loop_filter = ff_vp3_h_loop_filter_mmx2;

        }

    }

    if (cpuflags & AV_CPU_FLAG_SSE2) {

        c->idct_put  = ff_vp3_idct_put_sse2;

        c->idct_add  = ff_vp3_idct_add_sse2;

        c->idct_perm = FF_TRANSPOSE_IDCT_PERM;

    }

#endif

}


void memory_region_init(MemoryRegion *mr,

                        const char *name,

                        uint64_t size)

{

    mr->ops = NULL;

    mr->parent = NULL;

    mr->size = int128_make64(size);

    if (size == UINT64_MAX) {

        mr->size = int128_2_64();

    }

    mr->addr = 0;

    mr->subpage = false;

    mr->enabled = true;

    mr->terminates = false;

    mr->ram = false;

    mr->romd_mode = true;

    mr->readonly = false;

    mr->rom_device = false;

    mr->destructor = memory_region_destructor_none;

    mr->priority = 0;

    mr->may_overlap = false;

    mr->alias = NULL;

    QTAILQ_INIT(&mr->subregions);

    memset(&mr->subregions_link, 0, sizeof mr->subregions_link);

    QTAILQ_INIT(&mr->coalesced);

    mr->name = g_strdup(name);

    mr->dirty_log_mask = 0;

    mr->ioeventfd_nb = 0;

    mr->ioeventfds = NULL;

    mr->flush_coalesced_mmio = false;

}


float64 helper_sub_cmpf64(CPUM68KState *env, float64 src0, float64 src1)

{

    /* ??? This may incorrectly raise exceptions.  */

    /* ??? Should flush denormals to zero.  */

    float64 res;

    res = float64_sub(src0, src1, &env->fp_status);

    if (float64_is_nan(res)) {

        /* +/-inf compares equal against itself, but sub returns nan.  */

        if (!float64_is_nan(src0)

            && !float64_is_nan(src1)) {

            res = 0;

            if (float64_lt_quiet(src0, res, &env->fp_status))

                res = float64_chs(res);

        }

    }

    return res;

}


bool write_list_to_kvmstate(ARMCPU *cpu)

{

    CPUState *cs = CPU(cpu);

    int i;

    bool ok = true;

    for (i = 0; i < cpu->cpreg_array_len; i++) {

        struct kvm_one_reg r;

        uint64_t regidx = cpu->cpreg_indexes[i];

        uint32_t v32;

        int ret;

        r.id = regidx;

        switch (regidx & KVM_REG_SIZE_MASK) {

        case KVM_REG_SIZE_U32:

            v32 = cpu->cpreg_values[i];

            r.addr = (uintptr_t)&v32;

            break;

        case KVM_REG_SIZE_U64:

            r.addr = (uintptr_t)(cpu->cpreg_values + i);

            break;

        default:

            abort();

        }

        ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &r);

        if (ret) {

            /* We might fail for "unknown register" and also for

             * "you tried to set a register which is constant with

             * a different value from what it actually contains".

             */

            ok = false;

        }

    }

    return ok;

}


static void do_mchk_interrupt(CPUS390XState *env)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    uint64_t mask, addr;

    LowCore *lowcore;

    MchkQueue *q;

    int i;

    if (!(env->psw.mask & PSW_MASK_MCHECK)) {

        cpu_abort(CPU(cpu), "Machine check w/o mchk mask\n");

    }

    if (env->mchk_index < 0 || env->mchk_index >= MAX_MCHK_QUEUE) {

        cpu_abort(CPU(cpu), "Mchk queue overrun: %d\n", env->mchk_index);

    }

    q = &env->mchk_queue[env->mchk_index];

    if (q->type != 1) {

        /* Don't know how to handle this... */

        cpu_abort(CPU(cpu), "Unknown machine check type %d\n", q->type);

    }

    if (!(env->cregs[14] & (1 << 28))) {

        /* CRW machine checks disabled */

        return;

    }

    lowcore = cpu_map_lowcore(env);

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

        lowcore->floating_pt_save_area[i] = cpu_to_be64(get_freg(env, i)->ll);

        lowcore->gpregs_save_area[i] = cpu_to_be64(env->regs[i]);

        lowcore->access_regs_save_area[i] = cpu_to_be32(env->aregs[i]);

        lowcore->cregs_save_area[i] = cpu_to_be64(env->cregs[i]);

    }

    lowcore->prefixreg_save_area = cpu_to_be32(env->psa);

    lowcore->fpt_creg_save_area = cpu_to_be32(env->fpc);

    lowcore->tod_progreg_save_area = cpu_to_be32(env->todpr);

    lowcore->cpu_timer_save_area[0] = cpu_to_be32(env->cputm >> 32);

    lowcore->cpu_timer_save_area[1] = cpu_to_be32((uint32_t)env->cputm);

    lowcore->clock_comp_save_area[0] = cpu_to_be32(env->ckc >> 32);

    lowcore->clock_comp_save_area[1] = cpu_to_be32((uint32_t)env->ckc);

    lowcore->mcck_interruption_code[0] = cpu_to_be32(0x00400f1d);

    lowcore->mcck_interruption_code[1] = cpu_to_be32(0x40330000);

    lowcore->mcck_old_psw.mask = cpu_to_be64(get_psw_mask(env));

    lowcore->mcck_old_psw.addr = cpu_to_be64(env->psw.addr);

    mask = be64_to_cpu(lowcore->mcck_new_psw.mask);

    addr = be64_to_cpu(lowcore->mcck_new_psw.addr);

    cpu_unmap_lowcore(lowcore);

    env->mchk_index--;

    if (env->mchk_index == -1) {

        env->pending_int &= ~INTERRUPT_MCHK;

    }

    DPRINTF("%s: %" PRIx64 " %" PRIx64 "\n", __func__,

            env->psw.mask, env->psw.addr);

    load_psw(env, mask, addr);

}


static void bochs_bios_init(void)

{

    void *fw_cfg;

    uint8_t *smbios_table;

    size_t smbios_len;

    uint64_t *numa_fw_cfg;

    int i, j;

    register_ioport_write(0x400, 1, 2, bochs_bios_write, NULL);

    register_ioport_write(0x401, 1, 2, bochs_bios_write, NULL);

    register_ioport_write(0x402, 1, 1, bochs_bios_write, NULL);

    register_ioport_write(0x403, 1, 1, bochs_bios_write, NULL);

    register_ioport_write(0x8900, 1, 1, bochs_bios_write, NULL);

    register_ioport_write(0x501, 1, 2, bochs_bios_write, NULL);

    register_ioport_write(0x502, 1, 2, bochs_bios_write, NULL);

    register_ioport_write(0x500, 1, 1, bochs_bios_write, NULL);

    register_ioport_write(0x503, 1, 1, bochs_bios_write, NULL);

    fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_ACPI_TABLES, (uint8_t *)acpi_tables,

                     acpi_tables_len);

    smbios_table = smbios_get_table(&smbios_len);

    if (smbios_table)

        fw_cfg_add_bytes(fw_cfg, FW_CFG_SMBIOS_ENTRIES,

                         smbios_table, smbios_len);

    /* allocate memory for the NUMA channel: one (64bit) word for the number

     * of nodes, one word for each VCPU->node and one word for each node to

     * hold the amount of memory.

     */

    numa_fw_cfg = qemu_mallocz((1 + smp_cpus + nb_numa_nodes) * 8);

    numa_fw_cfg[0] = cpu_to_le64(nb_numa_nodes);

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

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

            if (node_cpumask[j] & (1 << i)) {

                numa_fw_cfg[i + 1] = cpu_to_le64(j);

                break;

            }

        }

    }

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

        numa_fw_cfg[smp_cpus + 1 + i] = cpu_to_le64(node_mem[i]);

    }

    fw_cfg_add_bytes(fw_cfg, FW_CFG_NUMA, (uint8_t *)numa_fw_cfg,

                     (1 + smp_cpus + nb_numa_nodes) * 8);

}


check_host_key_hash(BDRVSSHState *s, const char *hash,

                    int hash_type, size_t fingerprint_len)

{

    const char *fingerprint;

    fingerprint = libssh2_hostkey_hash(s->session, hash_type);

    if (!fingerprint) {

        session_error_report(s, "failed to read remote host key");

        return -EINVAL;

    }

    if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,

                           hash) != 0) {

        error_report("remote host key does not match host_key_check '%s'",

                     hash);

        return -EPERM;

    }

    return 0;

}