sctp_disposition_t sctp_sf_do_asconf(struct net *net,
				     const struct sctp_endpoint *ep,
				     const struct sctp_association *asoc,
				     const sctp_subtype_t type, void *arg,
				     sctp_cmd_seq_t *commands)
{
	struct sctp_chunk	*chunk = arg;
	struct sctp_chunk	*asconf_ack = NULL;
	struct sctp_paramhdr	*err_param = NULL;
	sctp_addiphdr_t		*hdr;
	__u32			serial;

	if (!sctp_vtag_verify(chunk, asoc)) {
		sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
				SCTP_NULL());
		return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
	}

	/* ADD-IP: Section 4.1.1
	 * This chunk MUST be sent in an authenticated way by using
	 * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
	 * is received unauthenticated it MUST be silently discarded as
	 * described in [I-D.ietf-tsvwg-sctp-auth].
	 */
	if (!net->sctp.addip_noauth && !chunk->auth)
		return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands);

	/* Make sure that the ASCONF ADDIP chunk has a valid length.  */
	if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t)))
		return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
						  commands);

	hdr = (sctp_addiphdr_t *)chunk->skb->data;
	serial = ntohl(hdr->serial);

	/* Verify the ASCONF chunk before processing it. */
	if (!sctp_verify_asconf(asoc, chunk, true, &err_param))
		return sctp_sf_violation_paramlen(net, ep, asoc, type, arg,
						  (void *)err_param, commands);

	/* ADDIP 5.2 E1) Compare the value of the serial number to the value
	 * the endpoint stored in a new association variable
	 * 'Peer-Serial-Number'.
	 */
	if (serial == asoc->peer.addip_serial + 1) {
		/* If this is the first instance of ASCONF in the packet,
		 * we can clean our old ASCONF-ACKs.
		 */
		if (!chunk->has_asconf)
			sctp_assoc_clean_asconf_ack_cache(asoc);

		/* ADDIP 5.2 E4) When the Sequence Number matches the next one
		 * expected, process the ASCONF as described below and after
		 * processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
		 * the response packet and cache a copy of it (in the event it
		 * later needs to be retransmitted).
		 *
		 * Essentially, do V1-V5.
		 */
		asconf_ack = sctp_process_asconf((struct sctp_association *)
						 asoc, chunk);
		if (!asconf_ack)
			return SCTP_DISPOSITION_NOMEM;
	} else if (serial < asoc->peer.addip_serial + 1) {
		/* ADDIP 5.2 E2)
		 * If the value found in the Sequence Number is less than the
		 * ('Peer- Sequence-Number' + 1), simply skip to the next
		 * ASCONF, and include in the outbound response packet
		 * any previously cached ASCONF-ACK response that was
		 * sent and saved that matches the Sequence Number of the
		 * ASCONF.  Note: It is possible that no cached ASCONF-ACK
		 * Chunk exists.  This will occur when an older ASCONF
		 * arrives out of order.  In such a case, the receiver
		 * should skip the ASCONF Chunk and not include ASCONF-ACK
		 * Chunk for that chunk.
		 */
		asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial);
		if (!asconf_ack)
			return SCTP_DISPOSITION_DISCARD;

		/* Reset the transport so that we select the correct one
		 * this time around.  This is to make sure that we don't
		 * accidentally use a stale transport that's been removed.
		 */
		asconf_ack->transport = NULL;
	} else {
		/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
		 * it must be either a stale packet or from an attacker.
		 */
		return SCTP_DISPOSITION_DISCARD;
	}

	/* ADDIP 5.2 E6)  The destination address of the SCTP packet
	 * containing the ASCONF-ACK Chunks MUST be the source address of
	 * the SCTP packet that held the ASCONF Chunks.
	 *
	 * To do this properly, we'll set the destination address of the chunk
	 * and at the transmit time, will try look up the transport to use.
	 * Since ASCONFs may be bundled, the correct transport may not be
	 * created until we process the entire packet, thus this workaround.
	 */
	asconf_ack->dest = chunk->source;
	sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
	if (asoc->new_transport) {
		sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands);
		((struct sctp_association *)asoc)->new_transport = NULL;
	}

	return SCTP_DISPOSITION_CONSUME;
}


static int kvm_put_msrs(X86CPU *cpu, int level)

{

    CPUX86State *env = &cpu->env;

    int i;

    int ret;

    kvm_msr_buf_reset(cpu);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);

    kvm_msr_entry_add(cpu, MSR_PAT, env->pat);

    if (has_msr_star) {

        kvm_msr_entry_add(cpu, MSR_STAR, env->star);

    }

    if (has_msr_hsave_pa) {

        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);

    }

    if (has_msr_tsc_aux) {

        kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);

    }

    if (has_msr_tsc_adjust) {

        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);

    }

    if (has_msr_misc_enable) {

        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,

                          env->msr_ia32_misc_enable);

    }

    if (has_msr_smbase) {

        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);

    }

    if (has_msr_bndcfgs) {

        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);

    }

    if (has_msr_xss) {

        kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);

    }

#ifdef TARGET_X86_64

    if (lm_capable_kernel) {

        kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);

        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);

        kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);

        kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);

    }

#endif

    /*

     * The following MSRs have side effects on the guest or are too heavy

     * for normal writeback. Limit them to reset or full state updates.

     */

    if (level >= KVM_PUT_RESET_STATE) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);

        kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);

        kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {

            kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);

        }

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {

            kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);

        }

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {

            kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);

        }

        if (has_msr_architectural_pmu) {

            /* Stop the counter.  */

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);

            /* Set the counter values.  */

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

                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,

                                  env->msr_fixed_counters[i]);

            }

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

                kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,

                                  env->msr_gp_counters[i]);

                kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,

                                  env->msr_gp_evtsel[i]);

            }

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,

                              env->msr_global_status);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,

                              env->msr_global_ovf_ctrl);

            /* Now start the PMU.  */

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,

                              env->msr_fixed_ctr_ctrl);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,

                              env->msr_global_ctrl);

        }

        /*

         * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,

         * only sync them to KVM on the first cpu

         */

        if (current_cpu == first_cpu) {

            if (has_msr_hv_hypercall) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,

                                  env->msr_hv_guest_os_id);

                kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,

                                  env->msr_hv_hypercall);

            }

            if (cpu->hyperv_time) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,

                                  env->msr_hv_tsc);

            }

        }

        if (cpu->hyperv_vapic) {

            kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,

                              env->msr_hv_vapic);

        }

        if (has_msr_hv_crash) {

            int j;

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

                kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,

                                  env->msr_hv_crash_params[j]);

            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);

        }

        if (has_msr_hv_runtime) {

            kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);

        }

        if (cpu->hyperv_synic) {

            int j;

            kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,

                              env->msr_hv_synic_control);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,

                              env->msr_hv_synic_evt_page);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,

                              env->msr_hv_synic_msg_page);

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,

                                  env->msr_hv_synic_sint[j]);

            }

        }

        if (has_msr_hv_stimer) {

            int j;

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,

                                env->msr_hv_stimer_config[j]);

            }

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,

                                env->msr_hv_stimer_count[j]);

            }

        }

        if (env->features[FEAT_1_EDX] & CPUID_MTRR) {

            uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);

            kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);

            kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);

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

                /* The CPU GPs if we write to a bit above the physical limit of

                 * the host CPU (and KVM emulates that)

                 */

                uint64_t mask = env->mtrr_var[i].mask;

                mask &= phys_mask;

                kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),

                                  env->mtrr_var[i].base);

                kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);

            }

        }

        /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see

         *       kvm_put_msr_feature_control. */

    }

    if (env->mcg_cap) {

        int i;

        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);

        kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);

        if (has_msr_mcg_ext_ctl) {

            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);

        }

        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {

            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);

        }

    }

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);

    if (ret < 0) {

        return ret;

    }

    if (ret < cpu->kvm_msr_buf->nmsrs) {

        struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];

        error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,

                     (uint32_t)e->index, (uint64_t)e->data);

    }

    assert(ret == cpu->kvm_msr_buf->nmsrs);

    return 0;

}


getvcols(
    win_T	*wp,
    pos_T	*pos1,
    pos_T	*pos2,
    colnr_T	*left,
    colnr_T	*right)
{
    colnr_T	from1, from2, to1, to2;

    if (LT_POSP(pos1, pos2))
    {
	getvvcol(wp, pos1, &from1, NULL, &to1);
	getvvcol(wp, pos2, &from2, NULL, &to2);
    }
    else
    {
	getvvcol(wp, pos2, &from1, NULL, &to1);
	getvvcol(wp, pos1, &from2, NULL, &to2);
    }
    if (from2 < from1)
	*left = from2;
    else
	*left = from1;
    if (to2 > to1)
    {
	if (*p_sel == 'e' && from2 - 1 >= to1)
	    *right = from2 - 1;
	else
	    *right = to2;
    }
    else
	*right = to1;
}


static void tsc_bad(void *info)
{
	__this_cpu_write(cpu_tsc_khz, 0);
}


void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  char *zSql;
  char *zErrMsg = 0;
  sqlite3 *db = pParse->db;
  char saveBuf[PARSE_TAIL_SZ];

  if( pParse->nErr ) return;
  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
  va_start(ap, zFormat);
  zSql = sqlite3VMPrintf(db, zFormat, ap);
  va_end(ap);
  if( zSql==0 ){
    /* This can result either from an OOM or because the formatted string
    ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set
    ** an error */
    if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
    pParse->nErr++;
    return;
  }
  pParse->nested++;
  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  sqlite3RunParser(pParse, zSql, &zErrMsg);
  sqlite3DbFree(db, zErrMsg);
  sqlite3DbFree(db, zSql);
  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  pParse->nested--;
}


inline void FullyConnected(
    const FullyConnectedParams& params, const RuntimeShape& input_shape,
    const uint8* input_data, const RuntimeShape& filter_shape,
    const uint8* filter_data, const RuntimeShape& bias_shape,
    const int32* bias_data_int32, const RuntimeShape& output_shape,
    int16* output_data, CpuBackendContext* cpu_backend_context) {
  ruy::profiler::ScopeLabel label("FullyConnected/Uint8Int16");
  const int32 input_offset = params.input_offset;
  const int32 filter_offset = params.weights_offset;
  const int32 output_offset = params.output_offset;
  const int32 output_multiplier = params.output_multiplier;
  const int output_shift = params.output_shift;
  const int32 output_activation_min = params.quantized_activation_min;
  const int32 output_activation_max = params.quantized_activation_max;
  TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  TFLITE_DCHECK_EQ(output_offset, 0);
  TFLITE_DCHECK_GE(filter_shape.DimensionsCount(), 2);
  TFLITE_DCHECK_GE(output_shape.DimensionsCount(), 1);

  // TODO(b/62193649): This really should be:
  //     const int batches = ArraySize(output_dims, 1);
  // but the current --variable_batch hack consists in overwriting the 3rd
  // dimension with the runtime batch size, as we don't keep track for each
  // array of which dimension is the batch dimension in it.
  const int output_dim_count = output_shape.DimensionsCount();
  const int filter_dim_count = filter_shape.DimensionsCount();
  const int batches = FlatSizeSkipDim(output_shape, output_dim_count - 1);
  const int output_depth = MatchingDim(filter_shape, filter_dim_count - 2,
                                       output_shape, output_dim_count - 1);
  const int accum_depth = filter_shape.Dims(filter_dim_count - 1);

  cpu_backend_gemm::MatrixParams<uint8> lhs_params;
  lhs_params.rows = output_depth;
  lhs_params.cols = accum_depth;
  lhs_params.order = cpu_backend_gemm::Order::kRowMajor;
  lhs_params.zero_point = -filter_offset;
  lhs_params.cache_policy =
      cpu_backend_gemm::DefaultCachePolicy(params.lhs_cacheable);
  cpu_backend_gemm::MatrixParams<uint8> rhs_params;
  rhs_params.rows = accum_depth;
  rhs_params.cols = batches;
  rhs_params.order = cpu_backend_gemm::Order::kColMajor;
  rhs_params.zero_point = -input_offset;
  rhs_params.cache_policy =
      cpu_backend_gemm::DefaultCachePolicy(params.rhs_cacheable);
  cpu_backend_gemm::MatrixParams<int16> dst_params;
  dst_params.rows = output_depth;
  dst_params.cols = batches;
  dst_params.order = cpu_backend_gemm::Order::kColMajor;
  dst_params.zero_point = 0;
  cpu_backend_gemm::GemmParams<int32, int16> gemm_params;
  gemm_params.bias = bias_data_int32;
  gemm_params.clamp_min = output_activation_min;
  gemm_params.clamp_max = output_activation_max;
  gemm_params.multiplier_fixedpoint = output_multiplier;
  gemm_params.multiplier_exponent = output_shift;
  cpu_backend_gemm::Gemm(lhs_params, filter_data, rhs_params, input_data,
                         dst_params, output_data, gemm_params,
                         cpu_backend_context);
}


bool asn1_write_uint8(struct asn1_data *data, uint8_t v)
{
	return asn1_write(data, &v, 1);
}


static int qdm2_parse_packet(AVFormatContext *s, PayloadContext *qdm,

                             AVStream *st, AVPacket *pkt,

                             uint32_t *timestamp,

                             const uint8_t *buf, int len, int flags)

{

    int res = AVERROR_INVALIDDATA, n;

    const uint8_t *end = buf + len, *p = buf;

    if (len > 0) {

        if (len < 2)

            return AVERROR_INVALIDDATA;

        /* configuration block */

        if (*p == 0xff) {

            if (qdm->n_pkts > 0) {

                av_log(s, AV_LOG_WARNING,

                       "Out of sequence config - dropping queue\n");

                qdm->n_pkts = 0;

                memset(qdm->len, 0, sizeof(qdm->len));

            }

            if ((res = qdm2_parse_config(qdm, st, ++p, end)) < 0)

                return res;

            p += res;

            /* We set codec_id to CODEC_ID_NONE initially to

             * delay decoder initialization since extradata is

             * carried within the RTP stream, not SDP. Here,

             * by setting codec_id to CODEC_ID_QDM2, we are signalling

             * to the decoder that it is OK to initialize. */

            st->codec->codec_id = CODEC_ID_QDM2;

        }

        /* subpackets */

        while (end - p >= 4) {

            if ((res = qdm2_parse_subpacket(qdm, st, p, end)) < 0)

                return res;

            p += res;

        }

        qdm->timestamp = *timestamp;

        if (++qdm->n_pkts < qdm->subpkts_per_block)

        qdm->cache = 0;

        for (n = 0; n < 0x80; n++)

            if (qdm->len[n] > 0)

                qdm->cache++;

    }

    /* output the subpackets into freshly created superblock structures */

    if (!qdm->cache || (res = qdm2_restore_block(qdm, st, pkt)) < 0)

        return res;

    if (--qdm->cache == 0)

        qdm->n_pkts = 0;

    *timestamp = qdm->timestamp;

    qdm->timestamp = RTP_NOTS_VALUE;

    return (qdm->cache > 0) ? 1 : 0;

}


SmartScheduleClient(void)
{
    ClientPtr pClient, best = NULL;
    int bestRobin, robin;
    long now = SmartScheduleTime;
    long idle;
    int nready = 0;

    bestRobin = 0;
    idle = 2 * SmartScheduleSlice;

    xorg_list_for_each_entry(pClient, &ready_clients, ready) {
        nready++;

        /* Praise clients which haven't run in a while */
        if ((now - pClient->smart_stop_tick) >= idle) {
            if (pClient->smart_priority < 0)
                pClient->smart_priority++;
        }

        /* check priority to select best client */
        robin =
            (pClient->index -
             SmartLastIndex[pClient->smart_priority -
                            SMART_MIN_PRIORITY]) & 0xff;

        /* pick the best client */
        if (!best ||
            pClient->priority > best->priority ||
            (pClient->priority == best->priority &&
             (pClient->smart_priority > best->smart_priority ||
              (pClient->smart_priority == best->smart_priority && robin > bestRobin))))
        {
            best = pClient;
            bestRobin = robin;
        }
#ifdef SMART_DEBUG
        if ((now - SmartLastPrint) >= 5000)
            fprintf(stderr, " %2d: %3d", pClient->index, pClient->smart_priority);
#endif
    }
#ifdef SMART_DEBUG
    if ((now - SmartLastPrint) >= 5000) {
        fprintf(stderr, " use %2d\n", best->index);
        SmartLastPrint = now;
    }
#endif
    SmartLastIndex[best->smart_priority - SMART_MIN_PRIORITY] = best->index;
    /*
     * Set current client pointer
     */
    if (SmartLastClient != best) {
        best->smart_start_tick = now;
        SmartLastClient = best;
    }
    /*
     * Adjust slice
     */
    if (nready == 1 && SmartScheduleLatencyLimited == 0) {
        /*
         * If it's been a long time since another client
         * has run, bump the slice up to get maximal
         * performance from a single client
         */
        if ((now - best->smart_start_tick) > 1000 &&
            SmartScheduleSlice < SmartScheduleMaxSlice) {
            SmartScheduleSlice += SmartScheduleInterval;
        }
    }
    else {
        SmartScheduleSlice = SmartScheduleInterval;
    }
    return best;
}


void RenderFrameDevToolsAgentHost::RenderProcessGone(
    base::TerminationStatus status) {
  switch(status) {
    case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
    case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
#if defined(OS_CHROMEOS)
    case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
#endif
    case base::TERMINATION_STATUS_PROCESS_CRASHED:
#if defined(OS_ANDROID)
    case base::TERMINATION_STATUS_OOM_PROTECTED:
#endif
    case base::TERMINATION_STATUS_LAUNCH_FAILED:
      for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
        inspector->TargetCrashed();
      NotifyCrashed(status);
      break;
    default:
      for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
        inspector->TargetDetached("Render process gone.");
      break;
  }
}


static void ext4_clear_journal_err(struct super_block *sb,
				   struct ext4_super_block *es)
{
	journal_t *journal;
	int j_errno;
	const char *errstr;

	BUG_ON(!ext4_has_feature_journal(sb));

	journal = EXT4_SB(sb)->s_journal;

	/*
	 * Now check for any error status which may have been recorded in the
	 * journal by a prior ext4_error() or ext4_abort()
	 */

	j_errno = jbd2_journal_errno(journal);
	if (j_errno) {
		char nbuf[16];

		errstr = ext4_decode_error(sb, j_errno, nbuf);
		ext4_warning(sb, "Filesystem error recorded "
			     "from previous mount: %s", errstr);
		ext4_warning(sb, "Marking fs in need of filesystem check.");

		EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
		es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
		ext4_commit_super(sb, 1);

		jbd2_journal_clear_err(journal);
		jbd2_journal_update_sb_errno(journal);
	}
}


srs_compile_guarded(srs_t *srs,
				char *buf, int buflen,
				char *sendhost, char *senduser,
				const char *aliashost) {
	char	*srshost;
	char	*srsuser;
	char	*srshash;
	int		 len;
	int		 ret;

	if ((strncasecmp(senduser, SRS1TAG, 4) == 0) &&
		(strchr(srs_separators, senduser[4]) != NULL)) {
		/* Used as a temporary convenience var */
		srshash = senduser + 5;
		if (*srshash == '\0')
			return SRS_ENOSRS1HASH;
		/* Used as a temporary convenience var */
		srshost = strchr(srshash, SRSSEP);
		if (!STRINGP(srshost))
			return SRS_ENOSRS1HOST;
		*srshost++ = '\0';
		srsuser = strchr(srshost, SRSSEP);
		if (!STRINGP(srsuser))
			return SRS_ENOSRS1USER;
		*srsuser++ = '\0';
		srshash = alloca(srs->hashlength + 1);
		ret = srs_hash_create(srs, srshash, 2, srshost, srsuser);
		if (ret != SRS_SUCCESS)
			return ret;
		len = strlen(SRS1TAG) + 1 +
			srs->hashlength + 1 +
				strlen(srshost) + 1 + strlen(srsuser)
			+ 1 + strlen(aliashost);
		if (len >= buflen)
			return SRS_EBUFTOOSMALL;
		sprintf(buf, SRS1TAG "%c%s%c%s%c%s@%s", srs->separator,
						srshash, SRSSEP,
							srshost, SRSSEP, srsuser,
								aliashost);
		return SRS_SUCCESS;
	}
	else if ((strncasecmp(senduser, SRS0TAG, 4) == 0) &&
		(strchr(srs_separators, senduser[4]) != NULL)) {
		srsuser = senduser + 4;
		srshost = sendhost;
		srshash = alloca(srs->hashlength + 1);
		ret = srs_hash_create(srs, srshash, 2, srshost, srsuser);
		if (ret != SRS_SUCCESS)
			return ret;
		len = strlen(SRS1TAG) + 1 +
			srs->hashlength + 1 +
				strlen(srshost) + 1 + strlen(srsuser)
			+ 1 + strlen(aliashost);
		if (len >= buflen)
			return SRS_EBUFTOOSMALL;
		sprintf(buf, SRS1TAG "%c%s%c%s%c%s@%s", srs->separator,
						srshash, SRSSEP,
							srshost, SRSSEP, srsuser,
								aliashost);
	}
	else {
		return srs_compile_shortcut(srs, buf, buflen,
						sendhost, senduser, aliashost);
	}

	return SRS_SUCCESS;
}


void PageInfo::OnSiteDataAccessed() {
  PresentSiteData();
}


static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
	bool masked;

	if (!enable_vnmi)
		return vmx->loaded_vmcs->soft_vnmi_blocked;
	if (vmx->loaded_vmcs->nmi_known_unmasked)
		return false;
	masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
	vmx->loaded_vmcs->nmi_known_unmasked = !masked;
	return masked;
}


sBIT_error_fn(png_structp pp, png_infop pi)
{
   png_byte bit_depth;
   png_color_8 bad;

 if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
      bit_depth = 8;

 else
      bit_depth = png_get_bit_depth(pp, pi);

 /* Now we know the bit depth we can easily generate an invalid sBIT entry */
   bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
 (png_byte)(bit_depth+1);

    png_set_sBIT(pp, pi, &bad);
 }


v8::Handle<v8::Value> V8ThrowException::createGeneralError(v8::Isolate* isolate, const String& message)
{
    return v8::Exception::Error(v8String(isolate, message.isNull() ? "Error" : message));
}


static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
  size_t
    count,
    length;

  register ssize_t
    i;

  /*
    Max length is 255.
  */
  count=0;
  length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
  if (length ==  0)
    count+=WriteBlobByte(image,0);
  else
    {
      count+=WriteBlobByte(image,(unsigned char) length);
      count+=WriteBlob(image,length,(const unsigned char *) value);
    }
  length++;
  if ((length % padding) == 0)
    return(count);
  for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
    count+=WriteBlobByte(image,0);
  return(count);
}


PERL_STATIC_INLINE IV
S_invlist_previous_index(SV* const invlist)
{
    /* Returns cached index of previous search */

    PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;

    return *get_invlist_previous_index_addr(invlist);


TEST(LengthFieldFrameDecoder, FailTestLengthFieldEndOffset) {
  auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
  int called = 0;

  (*pipeline)
    .addBack(LengthFieldBasedFrameDecoder(4, 10, 4, -2, 4))
    .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
        ASSERT_EQ(nullptr, buf);
        called++;
      }))
    .finalize();

  auto bufFrame = createZeroedBuffer(8);
  RWPrivateCursor c(bufFrame.get());
  c.writeBE((uint32_t)0); // frame size
  c.write((uint32_t)0); // crap

  IOBufQueue q(IOBufQueue::cacheChainLength());

  q.append(std::move(bufFrame));
  pipeline->read(q);
  EXPECT_EQ(called, 1);
}


static int setup_kmem_cache_nodes(struct kmem_cache *cachep, gfp_t gfp)
{
	int ret;
	int node;
	struct kmem_cache_node *n;

	for_each_online_node(node) {
		ret = setup_kmem_cache_node(cachep, node, gfp, true);
		if (ret)
			goto fail;

	}

	return 0;

fail:
	if (!cachep->list.next) {
		/* Cache is not active yet. Roll back what we did */
		node--;
		while (node >= 0) {
			n = get_node(cachep, node);
			if (n) {
				kfree(n->shared);
				free_alien_cache(n->alien);
				kfree(n);
				cachep->node[node] = NULL;
			}
			node--;
		}
	}
	return -ENOMEM;
}


alias_for_import_name(struct compiling *c, const node *n, int store)
{
    /*
      import_as_name: NAME ['as' NAME]
      dotted_as_name: dotted_name ['as' NAME]
      dotted_name: NAME ('.' NAME)*
    */
    identifier str, name;

 loop:
    switch (TYPE(n)) {
        case import_as_name: {
            node *name_node = CHILD(n, 0);
            str = NULL;
            name = NEW_IDENTIFIER(name_node);
            if (!name)
                return NULL;
            if (NCH(n) == 3) {
                node *str_node = CHILD(n, 2);
                str = NEW_IDENTIFIER(str_node);
                if (!str)
                    return NULL;
                if (store && forbidden_name(c, str, str_node, 0))
                    return NULL;
            }
            else {
                if (forbidden_name(c, name, name_node, 0))
                    return NULL;
            }
            return alias(name, str, c->c_arena);
        }
        case dotted_as_name:
            if (NCH(n) == 1) {
                n = CHILD(n, 0);
                goto loop;
            }
            else {
                node *asname_node = CHILD(n, 2);
                alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
                if (!a)
                    return NULL;
                assert(!a->asname);
                a->asname = NEW_IDENTIFIER(asname_node);
                if (!a->asname)
                    return NULL;
                if (forbidden_name(c, a->asname, asname_node, 0))
                    return NULL;
                return a;
            }
            break;
        case dotted_name:
            if (NCH(n) == 1) {
                node *name_node = CHILD(n, 0);
                name = NEW_IDENTIFIER(name_node);
                if (!name)
                    return NULL;
                if (store && forbidden_name(c, name, name_node, 0))
                    return NULL;
                return alias(name, NULL, c->c_arena);
            }
            else {
                /* Create a string of the form "a.b.c" */
                int i;
                size_t len;
                char *s;
                PyObject *uni;

                len = 0;
                for (i = 0; i < NCH(n); i += 2)
                    /* length of string plus one for the dot */
                    len += strlen(STR(CHILD(n, i))) + 1;
                len--; /* the last name doesn't have a dot */
                str = PyBytes_FromStringAndSize(NULL, len);
                if (!str)
                    return NULL;
                s = PyBytes_AS_STRING(str);
                if (!s)
                    return NULL;
                for (i = 0; i < NCH(n); i += 2) {
                    char *sch = STR(CHILD(n, i));
                    strcpy(s, STR(CHILD(n, i)));
                    s += strlen(sch);
                    *s++ = '.';
                }
                --s;
                *s = '\0';
                uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
                                           PyBytes_GET_SIZE(str),
                                           NULL);
                Py_DECREF(str);
                if (!uni)
                    return NULL;
                str = uni;
                PyUnicode_InternInPlace(&str);
                if (PyArena_AddPyObject(c->c_arena, str) < 0) {
                    Py_DECREF(str);
                    return NULL;
                }
                return alias(str, NULL, c->c_arena);
            }
            break;
        case STAR:
            str = PyUnicode_InternFromString("*");
            if (!str)
                return NULL;
            if (PyArena_AddPyObject(c->c_arena, str) < 0) {
                Py_DECREF(str);
                return NULL;
            }
            return alias(str, NULL, c->c_arena);
        default:
            PyErr_Format(PyExc_SystemError,
                         "unexpected import name: %d", TYPE(n));
            return NULL;
    }

    PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
    return NULL;
}


static int sched(struct t3cdev *tdev, struct sk_buff *skb, void *ctx)
{
	struct iwch_ep_common *epc = ctx;

	get_ep(epc);

	/*
	 * Save ctx and tdev in the skb->cb area.
	 */
	*((void **) skb->cb) = ctx;
	*((struct t3cdev **) (skb->cb + sizeof(void *))) = tdev;

	/*
	 * Queue the skb and schedule the worker thread.
	 */
	skb_queue_tail(&rxq, skb);
	queue_work(workq, &skb_work);
	return 0;
}


static void gd_ungrab_pointer(GtkDisplayState *s)

{

#if GTK_CHECK_VERSION(3, 0, 0)

    GdkDisplay *display = gtk_widget_get_display(s->drawing_area);

    GdkDeviceManager *mgr = gdk_display_get_device_manager(display);

    GList *devices = gdk_device_manager_list_devices(mgr,

                                                     GDK_DEVICE_TYPE_MASTER);

    GList *tmp = devices;

    while (tmp) {

        GdkDevice *dev = tmp->data;

        if (gdk_device_get_source(dev) == GDK_SOURCE_MOUSE) {

            gdk_device_ungrab(dev,

                              GDK_CURRENT_TIME);

        }

        tmp = tmp->next;

    }

    g_list_free(devices);

#else

    gdk_pointer_ungrab(GDK_CURRENT_TIME);

#endif

}


status_t MPEG4Extractor::parseAC3SampleEntry(off64_t offset) {
    offset += 16;
 uint16_t channelCount;
 if (!mDataSource->getUInt16(offset, &channelCount)) {
 return ERROR_MALFORMED;
 }
    offset += 8;
 uint16_t sampleRate;
 if (!mDataSource->getUInt16(offset, &sampleRate)) {
        ALOGE("MPEG4Extractor: error while reading ac-3 block: cannot read sample rate");
 return ERROR_MALFORMED;
 }

    offset += 4;
 return parseAC3SpecificBox(offset, sampleRate);
}


static int amr_decode_fix_avctx ( AVCodecContext * avctx ) {
 const int is_amr_wb = 1 + ( avctx -> codec_id == AV_CODEC_ID_AMR_WB ) ;
 avctx -> sample_rate = 8000 * is_amr_wb ;
 if ( avctx -> channels > 1 ) {
 av_log_missing_feature ( avctx , "multi-channel AMR" , 0 ) ;
 return AVERROR_PATCHWELCOME ;
 }
 avctx -> channels = 1 ;
 avctx -> channel_layout = AV_CH_LAYOUT_MONO ;
 avctx -> sample_fmt = AV_SAMPLE_FMT_S16 ;
 return 0 ;
 }


static inline void RENAME(rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)

{

	unsigned i;

#ifdef HAVE_MMX

	long mmx_size= 23 - src_size;

	asm volatile (

		"test %%"REG_a", %%"REG_a"	\n\t"

		"jns 2f				\n\t"

		"movq "MANGLE(mask24r)", %%mm5	\n\t"

		"movq "MANGLE(mask24g)", %%mm6	\n\t"

		"movq "MANGLE(mask24b)", %%mm7	\n\t"

		ASMALIGN(4)

		"1:				\n\t"

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

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

		"movq   (%1, %%"REG_a"), %%mm1	\n\t" // BGR BGR BG

		"movq  2(%1, %%"REG_a"), %%mm2	\n\t" // R BGR BGR B

		"psllq $16, %%mm0		\n\t" // 00 BGR BGR

		"pand %%mm5, %%mm0		\n\t"

		"pand %%mm6, %%mm1		\n\t"

		"pand %%mm7, %%mm2		\n\t"

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

		"por %%mm2, %%mm1		\n\t"

		"movq  6(%1, %%"REG_a"), %%mm0	\n\t" // BGR BGR BG

		MOVNTQ" %%mm1,   (%2, %%"REG_a")\n\t" // RGB RGB RG

		"movq  8(%1, %%"REG_a"), %%mm1	\n\t" // R BGR BGR B

		"movq 10(%1, %%"REG_a"), %%mm2	\n\t" // GR BGR BGR

		"pand %%mm7, %%mm0		\n\t"

		"pand %%mm5, %%mm1		\n\t"

		"pand %%mm6, %%mm2		\n\t"

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

		"por %%mm2, %%mm1		\n\t"

		"movq 14(%1, %%"REG_a"), %%mm0	\n\t" // R BGR BGR B

		MOVNTQ" %%mm1,  8(%2, %%"REG_a")\n\t" // B RGB RGB R

		"movq 16(%1, %%"REG_a"), %%mm1	\n\t" // GR BGR BGR

		"movq 18(%1, %%"REG_a"), %%mm2	\n\t" // BGR BGR BG

		"pand %%mm6, %%mm0		\n\t"

		"pand %%mm7, %%mm1		\n\t"

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

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

		"por %%mm2, %%mm1		\n\t"

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

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

		" js 1b				\n\t"

		"2:				\n\t"

		: "+a" (mmx_size)

		: "r" (src-mmx_size), "r"(dst-mmx_size)

	);

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

	if(mmx_size==23) return; //finihsed, was multiple of 8

	src+= src_size;

	dst+= src_size;

	src_size= 23-mmx_size;

	src-= src_size;

	dst-= src_size;

#endif

	for(i=0; i<src_size; i+=3)

	{

		register uint8_t x;

		x          = src[i + 2];

		dst[i + 1] = src[i + 1];

		dst[i + 2] = src[i + 0];

		dst[i + 0] = x;

	}

}


void mk_vhost_free_all()
{
    struct host *host;
    struct host_alias *host_alias;
    struct error_page *ep;
    struct mk_list *head_host;
    struct mk_list *head_alias;
    struct mk_list *head_error;
    struct mk_list *tmp1, *tmp2;

    mk_list_foreach_safe(head_host, tmp1, &config->hosts) {
        host = mk_list_entry(head_host, struct host, _head);
        mk_list_del(&host->_head);

        mk_mem_free(host->file);

        /* Free aliases or servernames */
        mk_list_foreach_safe(head_alias, tmp2, &host->server_names) {
            host_alias = mk_list_entry(head_alias, struct host_alias, _head);
            mk_list_del(&host_alias->_head);
            mk_mem_free(host_alias->name);
            mk_mem_free(host_alias);
        }

        /* Free error pages */
        mk_list_foreach_safe(head_error, tmp2, &host->error_pages) {
            ep = mk_list_entry(head_error, struct error_page, _head);
            mk_list_del(&ep->_head);
            mk_mem_free(ep->file);
            mk_mem_free(ep->real_path);
            mk_mem_free(ep);
        }

        mk_ptr_free(&host->documentroot);
        mk_mem_free(host->host_signature);
        mk_ptr_free(&host->header_host_signature);

        /* Free source configuration */
        if (host->config) mk_config_free(host->config);
        mk_mem_free(host);
    }
}


bool JSTestEventTargetPrototype::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
    JSTestEventTargetPrototype* thisObject = jsCast<JSTestEventTargetPrototype*>(cell);
    return getStaticFunctionSlot<JSObject>(exec, &JSTestEventTargetPrototypeTable, thisObject, propertyName, slot);
}


start_xmit (struct sk_buff *skb, struct net_device *dev)
{
	struct netdev_private *np = netdev_priv(dev);
	struct netdev_desc *txdesc;
	unsigned entry;
	u32 ioaddr;
	u64 tfc_vlan_tag = 0;

	if (np->link_status == 0) {	/* Link Down */
		dev_kfree_skb(skb);
		return NETDEV_TX_OK;
	}
	ioaddr = dev->base_addr;
	entry = np->cur_tx % TX_RING_SIZE;
	np->tx_skbuff[entry] = skb;
	txdesc = &np->tx_ring[entry];

#if 0
	if (skb->ip_summed == CHECKSUM_PARTIAL) {
		txdesc->status |=
		    cpu_to_le64 (TCPChecksumEnable | UDPChecksumEnable |
				 IPChecksumEnable);
	}
#endif
	if (np->vlan) {
		tfc_vlan_tag = VLANTagInsert |
		    ((u64)np->vlan << 32) |
		    ((u64)skb->priority << 45);
	}
	txdesc->fraginfo = cpu_to_le64 (pci_map_single (np->pdev, skb->data,
							skb->len,
							PCI_DMA_TODEVICE));
	txdesc->fraginfo |= cpu_to_le64((u64)skb->len << 48);

	/* DL2K bug: DMA fails to get next descriptor ptr in 10Mbps mode
	 * Work around: Always use 1 descriptor in 10Mbps mode */
	if (entry % np->tx_coalesce == 0 || np->speed == 10)
		txdesc->status = cpu_to_le64 (entry | tfc_vlan_tag |
					      WordAlignDisable |
					      TxDMAIndicate |
					      (1 << FragCountShift));
	else
		txdesc->status = cpu_to_le64 (entry | tfc_vlan_tag |
					      WordAlignDisable |
					      (1 << FragCountShift));

	/* TxDMAPollNow */
	writel (readl (ioaddr + DMACtrl) | 0x00001000, ioaddr + DMACtrl);
	/* Schedule ISR */
	writel(10000, ioaddr + CountDown);
	np->cur_tx = (np->cur_tx + 1) % TX_RING_SIZE;
	if ((np->cur_tx - np->old_tx + TX_RING_SIZE) % TX_RING_SIZE
			< TX_QUEUE_LEN - 1 && np->speed != 10) {
		/* do nothing */
	} else if (!netif_queue_stopped(dev)) {
		netif_stop_queue (dev);
	}

	/* The first TFDListPtr */
	if (readl (dev->base_addr + TFDListPtr0) == 0) {
		writel (np->tx_ring_dma + entry * sizeof (struct netdev_desc),
			dev->base_addr + TFDListPtr0);
		writel (0, dev->base_addr + TFDListPtr1);
	}

	return NETDEV_TX_OK;
}


static int md5_export(struct shash_desc *desc, void *out)
{
	struct md5_state *ctx = shash_desc_ctx(desc);

	memcpy(out, ctx, sizeof(*ctx));
	return 0;
}


bool ExtensionPrefs::GetBrowserActionVisibility(const Extension* extension) {
  const DictionaryValue* extension_prefs = GetExtensionPref(extension->id());
  if (!extension_prefs)
    return true;
  bool visible = false;
  if (!extension_prefs->GetBoolean(kBrowserActionVisible, &visible) || visible)
    return true;

  return false;
}


void AXLayoutObject::addChildren() {
  ASSERT(!isDetached());
  ASSERT(!m_haveChildren);

  m_haveChildren = true;

  if (!canHaveChildren())
    return;

  HeapVector<Member<AXObject>> ownedChildren;
  computeAriaOwnsChildren(ownedChildren);

  for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) {
    if (!axObjectCache().isAriaOwned(obj)) {
      obj->setParent(this);
      addChild(obj);
    }
  }

  addHiddenChildren();
  addPopupChildren();
  addImageMapChildren();
  addTextFieldChildren();
  addCanvasChildren();
  addRemoteSVGChildren();
  addInlineTextBoxChildren(false);

  for (const auto& child : m_children) {
    if (!child->cachedParentObject())
      child->setParent(this);
  }

  for (const auto& ownedChild : ownedChildren)
    addChild(ownedChild);
}


void irc_ctcp_recv ( struct t_irc_server * server , time_t date , const char * command , struct t_irc_channel * channel , const char * address , const char * nick , const char * remote_nick , char * arguments , char * message ) {
 char * pos_end , * pos_space , * pos_args ;
 const char * reply ;
 char * decoded_reply ;
 struct t_irc_channel * ptr_channel ;
 struct t_irc_nick * ptr_nick ;
 int nick_is_me ;
 while ( arguments && arguments [ 0 ] ) {
 pos_end = strrchr ( arguments + 1 , '\01' ) ;
 if ( pos_end ) pos_end [ 0 ] = '\0' ;
 pos_args = NULL ;
 pos_space = strchr ( arguments + 1 , ' ' ) ;
 if ( pos_space ) {
 pos_space [ 0 ] = '\0' ;
 pos_args = pos_space + 1 ;
 while ( pos_args [ 0 ] == ' ' ) {
 pos_args ++ ;
 }
 }
 if ( strcmp ( arguments + 1 , "ACTION" ) == 0 ) {
 nick_is_me = ( irc_server_strcasecmp ( server , server -> nick , nick ) == 0 ) ;
 if ( channel ) {
 ptr_nick = irc_nick_search ( server , channel , nick ) ;
 irc_channel_nick_speaking_add ( channel , nick , ( pos_args ) ? weechat_string_has_highlight ( pos_args , server -> nick ) : 0 ) ;
 irc_channel_nick_speaking_time_remove_old ( channel ) ;
 irc_channel_nick_speaking_time_add ( server , channel , nick , time ( NULL ) ) ;
 weechat_printf_date_tags ( channel -> buffer , date , irc_protocol_tags ( command , ( nick_is_me ) ? "irc_action,self_msg,notify_none,no_highlight" : "irc_action,notify_message" , nick , address ) , "%s%s%s%s%s%s%s" , weechat_prefix ( "action" ) , irc_nick_mode_for_display ( server , ptr_nick , 0 ) , ( ptr_nick ) ? ptr_nick -> color : ( ( nick ) ? irc_nick_find_color ( nick ) : IRC_COLOR_CHAT_NICK ) , nick , ( pos_args ) ? IRC_COLOR_RESET : "" , ( pos_args ) ? " " : "" , ( pos_args ) ? pos_args : "" ) ;
 }
 else {
 ptr_channel = irc_channel_search ( server , remote_nick ) ;
 if ( ! ptr_channel ) {
 ptr_channel = irc_channel_new ( server , IRC_CHANNEL_TYPE_PRIVATE , remote_nick , 0 , 0 ) ;
 if ( ! ptr_channel ) {
 weechat_printf ( server -> buffer , _ ( "%s%s: cannot create new private buffer \"%s\"" ) , weechat_prefix ( "error" ) , IRC_PLUGIN_NAME , remote_nick ) ;
 }
 }
 if ( ptr_channel ) {
 if ( ! ptr_channel -> topic ) irc_channel_set_topic ( ptr_channel , address ) ;
 weechat_printf_date_tags ( ptr_channel -> buffer , date , irc_protocol_tags ( command , ( nick_is_me ) ? "irc_action,self_msg,notify_none,no_highlight" : "irc_action,notify_private" , nick , address ) , "%s%s%s%s%s%s" , weechat_prefix ( "action" ) , ( nick_is_me ) ? IRC_COLOR_CHAT_NICK_SELF : irc_nick_color_for_pv ( ptr_channel , nick ) , nick , ( pos_args ) ? IRC_COLOR_RESET : "" , ( pos_args ) ? " " : "" , ( pos_args ) ? pos_args : "" ) ;
 ( void ) weechat_hook_signal_send ( "irc_pv" , WEECHAT_HOOK_SIGNAL_STRING , message ) ;
 }
 }
 }
 else if ( strcmp ( arguments + 1 , "PING" ) == 0 ) {
 reply = irc_ctcp_get_reply ( server , arguments + 1 ) ;
 irc_ctcp_display_request ( server , date , command , channel , nick , address , arguments + 1 , pos_args , reply ) ;
 if ( ! reply || reply [ 0 ] ) {
 irc_ctcp_reply_to_nick ( server , command , channel , nick , arguments + 1 , pos_args ) ;
 }
 }
 else if ( strcmp ( arguments + 1 , "DCC" ) == 0 ) {
 irc_ctcp_recv_dcc ( server , nick , pos_args , message ) ;
 }
 else {
 reply = irc_ctcp_get_reply ( server , arguments + 1 ) ;
 if ( reply ) {
 irc_ctcp_display_request ( server , date , command , channel , nick , address , arguments + 1 , pos_args , reply ) ;
 if ( reply [ 0 ] ) {
 decoded_reply = irc_ctcp_replace_variables ( server , reply ) ;
 if ( decoded_reply ) {
 irc_ctcp_reply_to_nick ( server , command , channel , nick , arguments + 1 , decoded_reply ) ;
 free ( decoded_reply ) ;
 }
 }
 }
 else {
 if ( weechat_config_boolean ( irc_config_look_display_ctcp_unknown ) ) {
 weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server , nick , NULL , "ctcp" , ( channel ) ? channel -> buffer : NULL ) , date , irc_protocol_tags ( command , "irc_ctcp" , NULL , address ) , _ ( "%sUnknown CTCP requested by %s%s%s: %s%s%s%s%s" ) , weechat_prefix ( "network" ) , irc_nick_color_for_msg ( server , 0 , NULL , nick ) , nick , IRC_COLOR_RESET , IRC_COLOR_CHAT_CHANNEL , arguments + 1 , ( pos_args ) ? IRC_COLOR_RESET : "" , ( pos_args ) ? " " : "" , ( pos_args ) ? pos_args : "" ) ;
 }
 }
 }
 ( void ) weechat_hook_signal_send ( "irc_ctcp" , WEECHAT_HOOK_SIGNAL_STRING , message ) ;
 if ( pos_space ) pos_space [ 0 ] = ' ' ;
 if ( pos_end ) pos_end [ 0 ] = '\01' ;
 arguments = ( pos_end ) ? pos_end + 1 : NULL ;
 }
 }


ModuleExport size_t RegisterRAWImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("R");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw red samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("C");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw cyan samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("G");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw green samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("M");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw magenta samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("B");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw blue samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("Y");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw yellow samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("A");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw alpha samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("O");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw opacity samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  entry=SetMagickInfo("K");
  entry->decoder=(DecodeImageHandler *) ReadRAWImage;
  entry->encoder=(EncodeImageHandler *) WriteRAWImage;
  entry->raw=MagickTrue;
  entry->endian_support=MagickTrue;
  entry->description=ConstantString("Raw black samples");
  entry->module=ConstantString("RAW");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}


TSReturnCode TSUuidInitialize ( TSUuid uuid , TSUuidVersion v ) {
 sdk_assert ( sdk_sanity_check_null_ptr ( ( void * ) uuid ) == TS_SUCCESS ) ;
 ATSUuid * u = ( ATSUuid * ) uuid ;
 u -> initialize ( v ) ;
 return u -> valid ( ) ? TS_SUCCESS : TS_ERROR ;
 }


static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)

{

    GetBitContext *gb = &vc->gb;

    int i,j,k;

    vc->floor_count = get_bits(gb, 6) + 1;

    vc->floors = av_mallocz(vc->floor_count * sizeof(*vc->floors));

    for (i = 0; i < vc->floor_count; ++i) {

        vorbis_floor *floor_setup = &vc->floors[i];

        floor_setup->floor_type = get_bits(gb, 16);

        av_dlog(NULL, " %d. floor type %d \n", i, floor_setup->floor_type);

        if (floor_setup->floor_type == 1) {

            int maximum_class = -1;

            unsigned rangebits, rangemax, floor1_values = 2;

            floor_setup->decode = vorbis_floor1_decode;

            floor_setup->data.t1.partitions = get_bits(gb, 5);

            av_dlog(NULL, " %d.floor: %d partitions \n",

                    i, floor_setup->data.t1.partitions);

            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {

                floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);

                if (floor_setup->data.t1.partition_class[j] > maximum_class)

                    maximum_class = floor_setup->data.t1.partition_class[j];

                av_dlog(NULL, " %d. floor %d partition class %d \n",

                        i, j, floor_setup->data.t1.partition_class[j]);

            av_dlog(NULL, " maximum class %d \n", maximum_class);

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

                floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;

                floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);

                av_dlog(NULL, " %d floor %d class dim: %d subclasses %d \n", i, j,

                        floor_setup->data.t1.class_dimensions[j],

                        floor_setup->data.t1.class_subclasses[j]);

                if (floor_setup->data.t1.class_subclasses[j]) {

                    GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)

                    av_dlog(NULL, "   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);

                for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {

                    int16_t bits = get_bits(gb, 8) - 1;

                    if (bits != -1)

                        VALIDATE_INDEX(bits, vc->codebook_count)

                    floor_setup->data.t1.subclass_books[j][k] = bits;

                    av_dlog(NULL, "    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);

            floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;

            floor_setup->data.t1.x_list_dim = 2;

            for (j = 0; j < floor_setup->data.t1.partitions; ++j)

                floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];

            floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim *

                                                   sizeof(*floor_setup->data.t1.list));

            rangebits = get_bits(gb, 4);

            rangemax = (1 << rangebits);

            if (rangemax > vc->blocksize[1] / 2) {

                       "Floor value is too large for blocksize: %u (%"PRIu32")\n",

                       rangemax, vc->blocksize[1] / 2);

            floor_setup->data.t1.list[0].x = 0;

            floor_setup->data.t1.list[1].x = rangemax;

            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {

                for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {

                    floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);

                    av_dlog(NULL, " %u. floor1 Y coord. %d\n", floor1_values,

                            floor_setup->data.t1.list[floor1_values].x);

// Precalculate order of x coordinates - needed for decode

            if (ff_vorbis_ready_floor1_list(vc->avccontext,

                                            floor_setup->data.t1.list,

                                            floor_setup->data.t1.x_list_dim)) {

        } else if (floor_setup->floor_type == 0) {

            unsigned max_codebook_dim = 0;

            floor_setup->decode = vorbis_floor0_decode;

            floor_setup->data.t0.order          = get_bits(gb,  8);

            floor_setup->data.t0.rate           = get_bits(gb, 16);

            floor_setup->data.t0.bark_map_size  = get_bits(gb, 16);

            floor_setup->data.t0.amplitude_bits = get_bits(gb,  6);

            /* zero would result in a div by zero later *

             * 2^0 - 1 == 0                             */

            if (floor_setup->data.t0.amplitude_bits == 0) {

                       "Floor 0 amplitude bits is 0.\n");

            floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);

            floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;

            /* allocate mem for booklist */

            floor_setup->data.t0.book_list =

                av_malloc(floor_setup->data.t0.num_books);

            if (!floor_setup->data.t0.book_list)

                return AVERROR(ENOMEM);

            /* read book indexes */

            {

                int idx;

                unsigned book_idx;

                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {

                    GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)

                    floor_setup->data.t0.book_list[idx] = book_idx;

                    if (vc->codebooks[book_idx].dimensions > max_codebook_dim)

                        max_codebook_dim = vc->codebooks[book_idx].dimensions;

            create_map(vc, i);

            /* codebook dim is for padding if codebook dim doesn't *

             * divide order+1 then we need to read more data       */

            floor_setup->data.t0.lsp =

                av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)

                          * sizeof(*floor_setup->data.t0.lsp));

            if (!floor_setup->data.t0.lsp)

                return AVERROR(ENOMEM);

            /* debug output parsed headers */

            av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);

            av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);

            av_dlog(NULL, "floor0 bark map size: %u\n",

                    floor_setup->data.t0.bark_map_size);

            av_dlog(NULL, "floor0 amplitude bits: %u\n",

                    floor_setup->data.t0.amplitude_bits);

            av_dlog(NULL, "floor0 amplitude offset: %u\n",

                    floor_setup->data.t0.amplitude_offset);

            av_dlog(NULL, "floor0 number of books: %u\n",

                    floor_setup->data.t0.num_books);

            av_dlog(NULL, "floor0 book list pointer: %p\n",

                    floor_setup->data.t0.book_list);

            {

                int idx;

                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {

                    av_dlog(NULL, "  Book %d: %u\n", idx + 1,

                            floor_setup->data.t0.book_list[idx]);

        } else {

            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");

    return 0;


static void blkverify_refresh_filename(BlockDriverState *bs)

{

    BDRVBlkverifyState *s = bs->opaque;

    /* bs->file->bs has already been refreshed */

    bdrv_refresh_filename(s->test_file->bs);

    if (bs->file->bs->full_open_options

        && s->test_file->bs->full_open_options)

    {

        QDict *opts = qdict_new();

        qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("blkverify")));

        QINCREF(bs->file->bs->full_open_options);

        qdict_put_obj(opts, "raw", QOBJECT(bs->file->bs->full_open_options));

        QINCREF(s->test_file->bs->full_open_options);

        qdict_put_obj(opts, "test",

                      QOBJECT(s->test_file->bs->full_open_options));

        bs->full_open_options = opts;

    }

    if (bs->file->bs->exact_filename[0]

        && s->test_file->bs->exact_filename[0])

    {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "blkverify:%s:%s",

                 bs->file->bs->exact_filename,

                 s->test_file->bs->exact_filename);

    }

}


TfLiteTensor CreateFloatTensor(const float* data, TfLiteIntArray* dims,
                               bool is_variable) {
  TfLiteTensor result = CreateTensor(dims, is_variable);
  result.type = kTfLiteFloat32;
  result.data.f = const_cast<float*>(data);
  result.bytes = ElementCount(*dims) * sizeof(float);
  return result;
}


void empty_slot_init(target_phys_addr_t addr, uint64_t slot_size)

{

    if (slot_size > 0) {

        /* Only empty slots larger than 0 byte need handling. */

        DeviceState *dev;

        SysBusDevice *s;

        EmptySlot *e;

        dev = qdev_create(NULL, "empty_slot");

        s = sysbus_from_qdev(dev);

        e = FROM_SYSBUS(EmptySlot, s);

        e->size = slot_size;

        qdev_init_nofail(dev);

        sysbus_mmio_map(s, 0, addr);

    }

}


connection_ap_get_original_destination(entry_connection_t *conn,
                                       socks_request_t *req)
{
#ifdef TRANS_NETFILTER
  return destination_from_socket(conn, req);
#elif defined(TRANS_PF)
  const or_options_t *options = get_options();

  if (options->TransProxyType_parsed == TPT_PF_DIVERT)
    return destination_from_socket(conn, req);

  if (options->TransProxyType_parsed == TPT_DEFAULT ||
      options->TransProxyType_parsed == TPT_IPFW)
    return destination_from_pf(conn, req);

  (void)conn;
  (void)req;
  log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
           options->TransProxyType);
  return -1;
#else
  (void)conn;
  (void)req;
  log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
           "transparent proxy method was configured.");
  return -1;
#endif
}


static void vc1_mspel_mc(uint8_t *dst, const uint8_t *src, int stride, int mode, int rnd)

{

    int i, j;

    uint8_t tmp[8*11], *tptr;

    int m, r;

    m = (mode & 3);

    r = rnd;

    src -= stride;

    tptr = tmp;

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

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

            tptr[i] = vc1_mspel_filter(src + i, 1, m, r);

        src += stride;

        tptr += 8;

    }

    r = 1 - rnd;

    m = (mode >> 2) & 3;

    tptr = tmp + 8;

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

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

            dst[i] = vc1_mspel_filter(tptr + i, 8, m, r);

        dst += stride;

        tptr += 8;

    }

}


static void cfunbody(JF, js_Ast *name, js_Ast *params, js_Ast *body)
{
	F->lightweight = 1;
	F->arguments = 0;

	if (F->script)
		F->lightweight = 0;

	if (body)
		analyze(J, F, body);

	cparams(J, F, params);

	if (name) {
		emit(J, F, OP_CURRENT);
		if (F->lightweight) {
			addlocal(J, F, name, 0);
			emit(J, F, OP_INITLOCAL);
			emitraw(J, F, findlocal(J, F, name->string));
		} else {
			emitstring(J, F, OP_INITVAR, name->string);
		}
	}

	if (body) {
		cvardecs(J, F, body);
		cfundecs(J, F, body);
	}

	if (F->script) {
		emit(J, F, OP_UNDEF);
		cstmlist(J, F, body);
		emit(J, F, OP_RETURN);
	} else {
		cstmlist(J, F, body);
		emit(J, F, OP_UNDEF);
		emit(J, F, OP_RETURN);
	}
}


dbus_g_proxy_manager_unref (DBusGProxyManager *manager)
{
  g_assert (manager != NULL);
  g_assert (manager->refcount > 0);

  LOCK_MANAGER (manager);
  manager->refcount -= 1;
  if (manager->refcount == 0)
    {
      UNLOCK_MANAGER (manager);

      if (manager->bus_proxy)
	g_object_unref (manager->bus_proxy);

      if (manager->proxy_lists)
        {
          /* can't have any proxies left since they hold
           * a reference to the proxy manager.
           */
          g_assert (g_hash_table_size (manager->proxy_lists) == 0);

          g_hash_table_destroy (manager->proxy_lists);
          manager->proxy_lists = NULL;

        }

      if (manager->owner_match_rules)
        {
	  /* Since we destroyed all proxies, none can be tracking
	   * name owners
	   */
          g_assert (g_hash_table_size (manager->owner_match_rules) == 0);
          g_hash_table_destroy (manager->owner_match_rules);
          manager->owner_match_rules = NULL;
        }

      if (manager->owner_names)
	{
	  /* Since we destroyed all proxies, none can be tracking
	   * name owners
	   */
          g_assert (g_hash_table_size (manager->owner_names) == 0);

	  g_hash_table_destroy (manager->owner_names);
	  manager->owner_names = NULL;
	}

      g_assert (manager->unassociated_proxies == NULL);

      g_static_mutex_free (&manager->lock);

      g_static_mutex_lock (&connection_g_proxy_lock);

      dbus_connection_remove_filter (manager->connection, dbus_g_proxy_manager_filter,
                                     manager);

      dbus_connection_set_data (manager->connection,
                                g_proxy_manager_slot,
                                NULL, NULL);

      g_static_mutex_unlock (&connection_g_proxy_lock);

      dbus_connection_unref (manager->connection);
      g_free (manager);

      dbus_connection_free_data_slot (&g_proxy_manager_slot);
    }
  else
    {
      UNLOCK_MANAGER (manager);
    }
}


static bool IsJavaScriptUrl(const std::string& url) {
  return StartsWithASCII(url, "javascript:", false);
}


mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
{
	abort_appdomain_data user_data;
	guint32 start_time;
	int orig_timeout = timeout;
	int i;

	THREAD_DEBUG (g_message ("%s: starting abort", __func__));

	start_time = mono_msec_ticks ();
	do {
		mono_threads_lock ();

		user_data.domain = domain;
		user_data.wait.num = 0;
		/* This shouldn't take any locks */
		mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
		mono_threads_unlock ();

		if (user_data.wait.num > 0) {
			/* Abort the threads outside the threads lock */
			for (i = 0; i < user_data.wait.num; ++i)
				ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);

			/*
			 * We should wait for the threads either to abort, or to leave the
			 * domain. We can't do the latter, so we wait with a timeout.
			 */
			wait_for_tids (&user_data.wait, 100);
		}

		/* Update remaining time */
		timeout -= mono_msec_ticks () - start_time;
		start_time = mono_msec_ticks ();

		if (orig_timeout != -1 && timeout < 0)
			return FALSE;
	}
	while (user_data.wait.num > 0);

	THREAD_DEBUG (g_message ("%s: abort done", __func__));

	return TRUE;
}


static int sched_rt_global_constraints(void)
{
	int ret = 0;

	mutex_lock(&rt_constraints_mutex);
	read_lock(&tasklist_lock);
	ret = __rt_schedulable(NULL, 0, 0);
	read_unlock(&tasklist_lock);
	mutex_unlock(&rt_constraints_mutex);

	return ret;
}


static uint16_t tsc210x_read(TSC210xState *s)
{
    uint16_t ret = 0x0000;

    if (!s->command)
        fprintf(stderr, "tsc210x_read: SPI underrun!\n");

    switch (s->page) {
    case TSC_DATA_REGISTERS_PAGE:
        ret = tsc2102_data_register_read(s, s->offset);
        if (!s->dav)
            qemu_irq_raise(s->davint);
        break;
    case TSC_CONTROL_REGISTERS_PAGE:
        ret = tsc2102_control_register_read(s, s->offset);
        break;
    case TSC_AUDIO_REGISTERS_PAGE:
        ret = tsc2102_audio_register_read(s, s->offset);
        break;
    default:
        hw_error("tsc210x_read: wrong memory page\n");
    }

    tsc210x_pin_update(s);

    /* Allow sequential reads.  */
    s->offset ++;
    s->state = 0;
    return ret;
}


int URI_FUNC(ComposeQueryCharsRequired)(const URI_TYPE(QueryList) * queryList,
		int * charsRequired) {
	const UriBool spaceToPlus = URI_TRUE;
	const UriBool normalizeBreaks = URI_TRUE;

	return URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, charsRequired,
			spaceToPlus, normalizeBreaks);
}


void FrameLoader::DispatchDidClearDocumentOfWindowObject() {
  DCHECK(frame_->GetDocument());
  if (state_machine_.CreatingInitialEmptyDocument())
    return;
  if (!frame_->GetDocument()->CanExecuteScripts(kNotAboutToExecuteScript))
    return;

  Settings* settings = frame_->GetSettings();
  if (settings && settings->GetForceMainWorldInitialization()) {
    frame_->GetScriptController().WindowProxy(DOMWrapperWorld::MainWorld());
  }
  probe::didClearDocumentOfWindowObject(frame_);

  if (dispatching_did_clear_window_object_in_main_world_)
    return;
  base::AutoReset<bool> in_did_clear_window_object(
      &dispatching_did_clear_window_object_in_main_world_, true);
  Client()->DispatchDidClearWindowObjectInMainWorld();
}


static void netbios_cleanup ( void ) {
 reassembly_table_destroy ( & netbios_reassembly_table ) ;
 }


static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf)

{

    SCSIRequest *req = &r->req;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    uint64_t nb_sectors;

    int buflen = 0;

    int ret;

    switch (req->cmd.buf[0]) {

    case TEST_UNIT_READY:

        if (!bdrv_is_inserted(s->bs))

            goto not_ready;

	break;

    case REQUEST_SENSE:

        if (req->cmd.xfer < 4)

            goto illegal_request;

        memset(outbuf, 0, 4);

        buflen = 4;

        if (s->sense.key == NOT_READY && req->cmd.xfer >= 18) {

            memset(outbuf, 0, 18);

            buflen = 18;

            outbuf[7] = 10;

            /* asc 0x3a, ascq 0: Medium not present */

            outbuf[12] = 0x3a;

            outbuf[13] = 0;

        }

        outbuf[0] = 0xf0;

        outbuf[1] = 0;

        outbuf[2] = s->sense.key;

        scsi_disk_clear_sense(s);

        break;

    case INQUIRY:

        buflen = scsi_disk_emulate_inquiry(req, outbuf);

        if (buflen < 0)

            goto illegal_request;

	break;

    case MODE_SENSE:

    case MODE_SENSE_10:

        buflen = scsi_disk_emulate_mode_sense(req, outbuf);

        if (buflen < 0)

            goto illegal_request;

        break;

    case READ_TOC:

        buflen = scsi_disk_emulate_read_toc(req, outbuf);

        if (buflen < 0)

            goto illegal_request;

        break;

    case RESERVE:

        if (req->cmd.buf[1] & 1)

            goto illegal_request;

        break;

    case RESERVE_10:

        if (req->cmd.buf[1] & 3)

            goto illegal_request;

        break;

    case RELEASE:

        if (req->cmd.buf[1] & 1)

            goto illegal_request;

        break;

    case RELEASE_10:

        if (req->cmd.buf[1] & 3)

            goto illegal_request;

        break;

    case START_STOP:

        if (s->drive_kind == SCSI_CD && (req->cmd.buf[4] & 2)) {

            /* load/eject medium */

            bdrv_eject(s->bs, !(req->cmd.buf[4] & 1));

        }

	break;

    case ALLOW_MEDIUM_REMOVAL:

        bdrv_set_locked(s->bs, req->cmd.buf[4] & 1);

	break;

    case READ_CAPACITY:

        /* The normal LEN field for this command is zero.  */

	memset(outbuf, 0, 8);

	bdrv_get_geometry(s->bs, &nb_sectors);

        if (!nb_sectors)

            goto not_ready;

        nb_sectors /= s->cluster_size;

        /* Returned value is the address of the last sector.  */

        nb_sectors--;

        /* Remember the new size for read/write sanity checking. */

        s->max_lba = nb_sectors;

        /* Clip to 2TB, instead of returning capacity modulo 2TB. */

        if (nb_sectors > UINT32_MAX)

            nb_sectors = UINT32_MAX;

        outbuf[0] = (nb_sectors >> 24) & 0xff;

        outbuf[1] = (nb_sectors >> 16) & 0xff;

        outbuf[2] = (nb_sectors >> 8) & 0xff;

        outbuf[3] = nb_sectors & 0xff;

        outbuf[4] = 0;

        outbuf[5] = 0;

        outbuf[6] = s->cluster_size * 2;

        outbuf[7] = 0;

        buflen = 8;

	break;

    case SYNCHRONIZE_CACHE:

        ret = bdrv_flush(s->bs);

        if (ret < 0) {

            if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_FLUSH)) {

                return -1;

            }

        }

        break;

    case GET_CONFIGURATION:

        memset(outbuf, 0, 8);

        /* ??? This should probably return much more information.  For now

           just return the basic header indicating the CD-ROM profile.  */

        outbuf[7] = 8; // CD-ROM

        buflen = 8;

        break;

    case SERVICE_ACTION_IN:

        /* Service Action In subcommands. */

        if ((req->cmd.buf[1] & 31) == 0x10) {

            DPRINTF("SAI READ CAPACITY(16)\n");

            memset(outbuf, 0, req->cmd.xfer);

            bdrv_get_geometry(s->bs, &nb_sectors);

            if (!nb_sectors)

                goto not_ready;

            nb_sectors /= s->cluster_size;

            /* Returned value is the address of the last sector.  */

            nb_sectors--;

            /* Remember the new size for read/write sanity checking. */

            s->max_lba = nb_sectors;

            outbuf[0] = (nb_sectors >> 56) & 0xff;

            outbuf[1] = (nb_sectors >> 48) & 0xff;

            outbuf[2] = (nb_sectors >> 40) & 0xff;

            outbuf[3] = (nb_sectors >> 32) & 0xff;

            outbuf[4] = (nb_sectors >> 24) & 0xff;

            outbuf[5] = (nb_sectors >> 16) & 0xff;

            outbuf[6] = (nb_sectors >> 8) & 0xff;

            outbuf[7] = nb_sectors & 0xff;

            outbuf[8] = 0;

            outbuf[9] = 0;

            outbuf[10] = s->cluster_size * 2;

            outbuf[11] = 0;

            outbuf[12] = 0;

            outbuf[13] = get_physical_block_exp(&s->qdev.conf);

            /* set TPE bit if the format supports discard */

            if (s->qdev.conf.discard_granularity) {

                outbuf[14] = 0x80;

            }

            /* Protection, exponent and lowest lba field left blank. */

            buflen = req->cmd.xfer;

            break;

        }

        DPRINTF("Unsupported Service Action In\n");

        goto illegal_request;

    case REPORT_LUNS:

        if (req->cmd.xfer < 16)

            goto illegal_request;

        memset(outbuf, 0, 16);

        outbuf[3] = 8;

        buflen = 16;

        break;

    case VERIFY:

        break;

    case REZERO_UNIT:

        DPRINTF("Rezero Unit\n");

        if (!bdrv_is_inserted(s->bs)) {

            goto not_ready;

        }

        break;

    default:

        goto illegal_request;

    }

    scsi_req_set_status(r, GOOD, NO_SENSE);

    return buflen;

not_ready:

    scsi_command_complete(r, CHECK_CONDITION, NOT_READY);

    return -1;

illegal_request:

    scsi_command_complete(r, CHECK_CONDITION, ILLEGAL_REQUEST);

    return -1;

}


DevToolsWindow* DevToolsWindow::GetInstanceForInspectedWebContents(
    WebContents* inspected_web_contents) {
  if (!inspected_web_contents || g_instances == NULL)
    return NULL;
  DevToolsWindows* instances = g_instances.Pointer();
  for (DevToolsWindows::iterator it(instances->begin()); it != instances->end();
       ++it) {
    if ((*it)->GetInspectedWebContents() == inspected_web_contents)
      return *it;
  }
  return NULL;
}


dissect_dch_dl_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset)
{
    /* CFN control */
    guint cfn = tvb_get_guint8(tvb, offset);
    proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN);
    offset++;

    col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u", cfn);

    return offset;
}


  Handle<StringPrimitive> &strPrim() {
    assert(isHandle_ && "must be a handle");
    // Need to go through a variable to placate gcc4.9.
    char *buffer = strPrim_.buffer;
    return *reinterpret_cast<Handle<StringPrimitive> *>(buffer);
  }


png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size,
        png_bytep output, png_size_t output_size)
{
   png_size_t count = 0;

   png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */
   png_ptr->zstream.avail_in = size;

   while (1)
   {
      int ret, avail;

      /* Reset the output buffer each time round - we empty it
       * after every inflate call.
       */
      png_ptr->zstream.next_out = png_ptr->zbuf;
      png_ptr->zstream.avail_out = png_ptr->zbuf_size;

      ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
      avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out;

      /* First copy/count any new output - but only if we didn't
       * get an error code.
       */
      if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0)
      {
         if (output != 0 && output_size > count)
         {
            png_size_t copy = output_size - count;
            if ((png_size_t) avail < copy) copy = (png_size_t) avail;
            png_memcpy(output + count, png_ptr->zbuf, copy);
         }
         count += avail;
      }

      if (ret == Z_OK)
         continue;

      /* Termination conditions - always reset the zstream, it
       * must be left in inflateInit state.
       */
      png_ptr->zstream.avail_in = 0;
      inflateReset(&png_ptr->zstream);

      if (ret == Z_STREAM_END)
         return count; /* NOTE: may be zero. */

      /* Now handle the error codes - the API always returns 0
       * and the error message is dumped into the uncompressed
       * buffer if available.
       */
      {
         PNG_CONST char *msg;
         if (png_ptr->zstream.msg != 0)
            msg = png_ptr->zstream.msg;
         else
         {
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
            char umsg[52];

            switch (ret)
            {
               case Z_BUF_ERROR:
                  msg = "Buffer error in compressed datastream in %s chunk";
                  break;
               case Z_DATA_ERROR:
                  msg = "Data error in compressed datastream in %s chunk";
                  break;
               default:
                  msg = "Incomplete compressed datastream in %s chunk";
                  break;
            }

             png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name);
             msg = umsg;
 #else
             msg = "Damaged compressed datastream in chunk other than IDAT";
 #endif
          }

          png_warning(png_ptr, msg);
       }

       /* 0 means an error - notice that this code simple ignores
       * zero length compressed chunks as a result.
       */
      return 0;
   }
}


static void ir2_decode_plane(Ir2Context *ctx, int width, int height, uint8_t *dst, int stride,

                             const uint8_t *table)

{

    int i;

    int j;

    int out = 0;

    int c;

    int t;

    /* first line contain absolute values, other lines contain deltas */

    while (out < width){

        c = ir2_get_code(&ctx->gb);

        if(c > 0x80) { /* we have a run */

            c -= 0x80;

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

                dst[out++] = 0x80;

        } else { /* copy two values from table */

            dst[out++] = table[c * 2];

            dst[out++] = table[(c * 2) + 1];

        }

    }

    dst += stride;

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

        out = 0;

        while (out < width){

            c = ir2_get_code(&ctx->gb);

            if(c > 0x80) { /* we have a skip */

                c -= 0x80;

                for (i = 0; i < c * 2; i++) {

                    dst[out] = dst[out - stride];

                    out++;

                }

            } else { /* add two deltas from table */

                t = dst[out - stride] + (table[c * 2] - 128);

                CLAMP_TO_BYTE(t);

                dst[out] = t;

                out++;

                t = dst[out - stride] + (table[(c * 2) + 1] - 128);

                CLAMP_TO_BYTE(t);

                dst[out] = t;

                out++;

            }

        }

        dst += stride;

    }

}


static void inet_get_ping_group_range_table ( struct ctl_table * table , gid_t * low , gid_t * high ) {
 gid_t * data = table -> data ;
 unsigned int seq ;
 do {
 seq = read_seqbegin ( & sysctl_local_ports . lock ) ;
 * low = data [ 0 ] ;
 * high = data [ 1 ] ;
 }
 while ( read_seqretry ( & sysctl_local_ports . lock , seq ) ) ;
 }


static void nfc_llcp_recv_agf(struct nfc_llcp_local *local, struct sk_buff *skb)
{
	u8 ptype;
	u16 pdu_len;
	struct sk_buff *new_skb;

	if (skb->len <= LLCP_HEADER_SIZE) {
		pr_err("Malformed AGF PDU\n");
		return;
	}

	skb_pull(skb, LLCP_HEADER_SIZE);

	while (skb->len > LLCP_AGF_PDU_HEADER_SIZE) {
		pdu_len = skb->data[0] << 8 | skb->data[1];

		skb_pull(skb, LLCP_AGF_PDU_HEADER_SIZE);

		if (pdu_len < LLCP_HEADER_SIZE || pdu_len > skb->len) {
			pr_err("Malformed AGF PDU\n");
			return;
		}

		ptype = nfc_llcp_ptype(skb);

		if (ptype == LLCP_PDU_SYMM || ptype == LLCP_PDU_AGF)
			goto next;

		new_skb = nfc_alloc_recv_skb(pdu_len, GFP_KERNEL);
		if (new_skb == NULL) {
			pr_err("Could not allocate PDU\n");
			return;
		}

		skb_put_data(new_skb, skb->data, pdu_len);

		nfc_llcp_rx_skb(local, new_skb);

		kfree_skb(new_skb);
next:
		skb_pull(skb, pdu_len);
	}
}


int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
                                   int purpose, int trust)
{
    int idx;
    /* If purpose not set use default */
    if (!purpose)
        purpose = def_purpose;
    /* If we have a purpose then check it is valid */
    if (purpose) {
        X509_PURPOSE *ptmp;
        idx = X509_PURPOSE_get_by_id(purpose);
        if (idx == -1) {
            X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
                    X509_R_UNKNOWN_PURPOSE_ID);
            return 0;
        }
        ptmp = X509_PURPOSE_get0(idx);
        if (ptmp->trust == X509_TRUST_DEFAULT) {
            idx = X509_PURPOSE_get_by_id(def_purpose);
            if (idx == -1) {
                X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
                        X509_R_UNKNOWN_PURPOSE_ID);
                return 0;
            }
            ptmp = X509_PURPOSE_get0(idx);
        }
        /* If trust not set then get from purpose default */
        if (!trust)
            trust = ptmp->trust;
    }
    if (trust) {
        idx = X509_TRUST_get_by_id(trust);
        if (idx == -1) {
            X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
                    X509_R_UNKNOWN_TRUST_ID);
            return 0;
        }
    }

    if (purpose && !ctx->param->purpose)
        ctx->param->purpose = purpose;
    if (trust && !ctx->param->trust)
        ctx->param->trust = trust;
    return 1;
}


acpi_status acpi_os_signal(u32 function, void *info)
{
	switch (function) {
	case ACPI_SIGNAL_FATAL:
		printk(KERN_ERR PREFIX "Fatal opcode executed\n");
		break;
	case ACPI_SIGNAL_BREAKPOINT:
		/*
		 * AML Breakpoint
		 * ACPI spec. says to treat it as a NOP unless
		 * you are debugging.  So if/when we integrate
		 * AML debugger into the kernel debugger its
		 * hook will go here.  But until then it is
		 * not useful to print anything on breakpoints.
		 */
		break;
	default:
		break;
	}

	return AE_OK;
}


static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
                               unsigned int epid, dma_addr_t pctx,
                               uint32_t *ctx)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;

    trace_usb_xhci_ep_enable(slotid, epid);
    assert(slotid >= 1 && slotid <= xhci->numslots);
    assert(epid >= 1 && epid <= 31);

    slot = &xhci->slots[slotid-1];
    if (slot->eps[epid-1]) {
        xhci_disable_ep(xhci, slotid, epid);
    }

    epctx = xhci_alloc_epctx(xhci, slotid, epid);
    slot->eps[epid-1] = epctx;
    xhci_init_epctx(epctx, pctx, ctx);

    DPRINTF("xhci: endpoint %d.%d type is %d, max transaction (burst) "
            "size is %d\n", epid/2, epid%2, epctx->type, epctx->max_psize);

    epctx->mfindex_last = 0;

    epctx->state = EP_RUNNING;
    ctx[0] &= ~EP_STATE_MASK;
    ctx[0] |= EP_RUNNING;

    return CC_SUCCESS;
}


static int ifb_close(struct net_device *dev)
{
	struct ifb_private *dp = netdev_priv(dev);

	tasklet_kill(&dp->ifb_tasklet);
	netif_stop_queue(dev);
	__skb_queue_purge(&dp->rq);
	__skb_queue_purge(&dp->tq);
	return 0;
}


chrome::mojom::PrerenderCanceler* GetPrerenderCanceller(
    const base::Callback<content::WebContents*()>& wc_getter) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  auto* web_contents = wc_getter.Run();
  if (!web_contents)
    return nullptr;

  return prerender::PrerenderContents::FromWebContents(web_contents);
}


static void cirrus_vga_register_types(void)
{
    type_register_static(&isa_cirrus_vga_info);
    type_register_static(&cirrus_vga_info);
}


TfLiteRegistration* Register_FILL() {
  static TfLiteRegistration r = {/*init=*/nullptr, /*free=*/nullptr,
                                 fill::Prepare, fill::Eval};
  return &r;
}


static int fsl_lpspi_runtime_suspend(struct device *dev)
{
	struct spi_controller *controller = dev_get_drvdata(dev);
	struct fsl_lpspi_data *fsl_lpspi;

	fsl_lpspi = spi_controller_get_devdata(controller);

	clk_disable_unprepare(fsl_lpspi->clk_per);
	clk_disable_unprepare(fsl_lpspi->clk_ipg);

	return 0;
}


static int mszipd_flush_window ( struct mszipd_stream * zip , unsigned int data_flushed ) {
 zip -> bytes_output += data_flushed ;
 if ( zip -> bytes_output > MSZIP_FRAME_SIZE ) {
 D ( ( "overflow: %u bytes flushed, total is now %u" , data_flushed , zip -> bytes_output ) ) return 1 ;
 }
 return 0 ;
 }


void HTMLMediaElement::durationChanged() {
  BLINK_MEDIA_LOG << "durationChanged(" << (void*)this << ")";

  CHECK(m_webMediaPlayer);
  double newDuration = m_webMediaPlayer->duration();

  durationChanged(newDuration, currentPlaybackPosition() > newDuration);
}


uint16_t enc624j600ReadReg(NetInterface *interface, uint8_t address)
{
   uint16_t data;

   //Pull the CS pin low
   interface->spiDriver->assertCs();

   //Write opcode
   interface->spiDriver->transfer(ENC624J600_CMD_RCRU);
   //Write register address
   interface->spiDriver->transfer(address);
   //Read the lower 8 bits of data
   data = interface->spiDriver->transfer(0x00);
   //Read the upper 8 bits of data
   data |= interface->spiDriver->transfer(0x00) << 8;

   //Terminate the operation by raising the CS pin
   interface->spiDriver->deassertCs();

   //Return register contents
   return data;
}


static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
	struct ib_qp_attr qp_attr;
	int attr_mask;
	int ret;

	qp_attr.qp_state = IB_QPS_RTS;
	ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
	if (ret)
		goto out;

	qp_attr.max_rd_atomic = 4;

	ret = ib_modify_qp(qp, &qp_attr, attr_mask);

out:
	return ret;
}


int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
{
	if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
		return -EINVAL;
	return generic_file_mmap(file, vma);
}


bool ChromeClientImpl::OpenJavaScriptConfirmDelegate(LocalFrame* frame,
                                                     const String& message) {
  NotifyPopupOpeningObservers();
  WebLocalFrameImpl* webframe = WebLocalFrameImpl::FromFrame(frame);
  if (webframe->Client()) {
    if (WebUserGestureIndicator::IsProcessingUserGesture())
      WebUserGestureIndicator::DisableTimeout();
    return webframe->Client()->RunModalConfirmDialog(message);
  }
  return false;
}


int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
{
	return kvm_skip_emulated_instruction(vcpu);
}


void Magick::Image::distort(const DistortMethod method_,
  const size_t numberArguments_,const double *arguments_,const bool bestfit_)
{
  MagickCore::Image
    *newImage;

  GetPPException;
  newImage=DistortImage(constImage(), method_,numberArguments_,arguments_,
    bestfit_ == true ? MagickTrue : MagickFalse,exceptionInfo);
  replaceImage(newImage);
  ThrowImageException;
}


void TSLifecycleHookAdd ( TSLifecycleHookID id , TSCont contp ) {
 sdk_assert ( sdk_sanity_check_continuation ( contp ) == TS_SUCCESS ) ;
 sdk_assert ( sdk_sanity_check_lifecycle_hook_id ( id ) == TS_SUCCESS ) ;
 lifecycle_hooks -> append ( id , ( INKContInternal * ) contp ) ;
 }


void BaseRenderingContext2D::setTransform(double m11,
                                          double m12,
                                          double m21,
                                          double m22,
                                          double dx,
                                          double dy) {
  PaintCanvas* c = DrawingCanvas();
  if (!c)
    return;

  if (!std::isfinite(m11) || !std::isfinite(m21) || !std::isfinite(dx) ||
      !std::isfinite(m12) || !std::isfinite(m22) || !std::isfinite(dy))
    return;

  resetTransform();
  transform(m11, m12, m21, m22, dx, dy);
}


rdp_recv(uint8 * type)
{
	RD_BOOL is_fastpath;
	static STREAM rdp_s;
	uint16 length;

	while (1)
	{
		/* fill stream with data if needed for parsing a new packet */
		if ((rdp_s == NULL) || (g_next_packet >= rdp_s->end) || (g_next_packet == NULL))
		{
			rdp_s = sec_recv(&is_fastpath);
			if (rdp_s == NULL)
				return NULL;

			if (is_fastpath == True)
			{
				/* process_ts_fp_updates moves g_next_packet */
				process_ts_fp_updates(rdp_s);
				continue;
			}

			g_next_packet = rdp_s->p;
		}
		else
		{
			rdp_s->p = g_next_packet;
		}

		/* parse a TS_SHARECONTROLHEADER */
		if (rdp_ts_in_share_control_header(rdp_s, type, &length) == False)
			continue;

		break;
	}

	logger(Protocol, Debug, "rdp_recv(), RDP packet #%d, type 0x%x", ++g_packetno, *type);

	g_next_packet += length;
	return rdp_s;
}


static int ocfs2_write_begin_inline(struct address_space *mapping,
				    struct inode *inode,
				    struct ocfs2_write_ctxt *wc)
{
	int ret;
	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
	struct page *page;
	handle_t *handle;
	struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;

	handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
	if (IS_ERR(handle)) {
		ret = PTR_ERR(handle);
		mlog_errno(ret);
		goto out;
	}

	page = find_or_create_page(mapping, 0, GFP_NOFS);
	if (!page) {
		ocfs2_commit_trans(osb, handle);
		ret = -ENOMEM;
		mlog_errno(ret);
		goto out;
	}
	/*
	 * If we don't set w_num_pages then this page won't get unlocked
	 * and freed on cleanup of the write context.
	 */
	wc->w_pages[0] = wc->w_target_page = page;
	wc->w_num_pages = 1;

	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), wc->w_di_bh,
				      OCFS2_JOURNAL_ACCESS_WRITE);
	if (ret) {
		ocfs2_commit_trans(osb, handle);

		mlog_errno(ret);
		goto out;
	}

	if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
		ocfs2_set_inode_data_inline(inode, di);

	if (!PageUptodate(page)) {
		ret = ocfs2_read_inline_data(inode, page, wc->w_di_bh);
		if (ret) {
			ocfs2_commit_trans(osb, handle);

			goto out;
		}
	}

	wc->w_handle = handle;
out:
	return ret;
}


s32 gf_avc_read_sps_ext(const char *spse_data, u32 spse_size)
{
	GF_BitStream *bs;
	s32 sps_id;

	bs = gf_bs_new(spse_data, spse_size, GF_BITSTREAM_READ);
	sps_id = gf_avc_read_sps_ext_bs(bs);

	gf_bs_del(bs);
	return sps_id;
}


void GLES2DecoderImpl::DoGetBufferParameteriv(GLenum target,
                                              GLenum pname,
                                              GLint* params,
                                              GLsizei params_size) {
  buffer_manager()->ValidateAndDoGetBufferParameteriv(
      &state_, target, pname, params);
}


int Visualizer_init(VisualizerContext *pContext)
{
    pContext->mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
    pContext->mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
    pContext->mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
    pContext->mConfig.inputCfg.samplingRate = 44100;
    pContext->mConfig.inputCfg.bufferProvider.getBuffer = NULL;
    pContext->mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
    pContext->mConfig.inputCfg.bufferProvider.cookie = NULL;
    pContext->mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
    pContext->mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
    pContext->mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
    pContext->mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
    pContext->mConfig.outputCfg.samplingRate = 44100;
    pContext->mConfig.outputCfg.bufferProvider.getBuffer = NULL;
    pContext->mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
    pContext->mConfig.outputCfg.bufferProvider.cookie = NULL;
    pContext->mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;

    pContext->mCaptureSize = VISUALIZER_CAPTURE_SIZE_MAX;
    pContext->mScalingMode = VISUALIZER_SCALING_MODE_NORMALIZED;

    pContext->mChannelCount =
            audio_channel_count_from_out_mask(pContext->mConfig.inputCfg.channels);
    pContext->mMeasurementMode = MEASUREMENT_MODE_NONE;
    pContext->mMeasurementWindowSizeInBuffers = MEASUREMENT_WINDOW_MAX_SIZE_IN_BUFFERS;
    pContext->mMeasurementBufferIdx = 0;
 for (uint32_t i=0 ; i<pContext->mMeasurementWindowSizeInBuffers ; i++) {
        pContext->mPastMeasurements[i].mIsValid = false;
        pContext->mPastMeasurements[i].mPeakU16 = 0;
        pContext->mPastMeasurements[i].mRmsSquared = 0;
 }

 Visualizer_setConfig(pContext, &pContext->mConfig);

 return 0;
}


int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
{
	unsigned long flags;
	struct rq *rq;
	unsigned int dest_cpu;
	int ret = 0;

	rq = task_rq_lock(p, &flags);

	if (cpumask_equal(&p->cpus_allowed, new_mask))
		goto out;

	if (!cpumask_intersects(new_mask, cpu_active_mask)) {
		ret = -EINVAL;
		goto out;
	}

	do_set_cpus_allowed(p, new_mask);

	/* Can the task run on the task's current CPU? If so, we're done */
	if (cpumask_test_cpu(task_cpu(p), new_mask))
		goto out;

	dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
	if (p->on_rq) {
		struct migration_arg arg = { p, dest_cpu };
		/* Need help from migration thread: drop lock and wait. */
		task_rq_unlock(rq, p, &flags);
		stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
		tlb_migrate_finish(p->mm);
		return 0;
	}
out:
	task_rq_unlock(rq, p, &flags);

	return ret;
}


static void randomsleep(unsigned int t) {
    usleep2((unsigned long) (zrand() % PASSWD_FAILURE_DELAY));
    usleep2(t * PASSWD_FAILURE_DELAY);
}


void CServer::SetRconCID(int ClientID)
{
	m_RconClientID = ClientID;
}


  void NavigateActiveAndCommit(const GURL& url) {
    controller().LoadURL(
        url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string());
    TestRenderViewHost* old_rvh = test_rvh();

    if (old_rvh != active_rvh())
      old_rvh->SendShouldCloseACK(true);

    int32 max_page_id = contents()->GetMaxPageIDForSiteInstance(
        active_rvh()->GetSiteInstance());
    active_test_rvh()->SendNavigate(max_page_id + 1, url);

    if (old_rvh != active_rvh())
      old_rvh->OnSwapOutACK();
  }


bool CServer::IsAuthed(int ClientID)
{
	return m_aClients[ClientID].m_Authed;
}


void TabStripModel::SetSelectionFromModel(
    const TabStripSelectionModel& source) {
  DCHECK_NE(TabStripSelectionModel::kUnselectedIndex, source.active());
  int old_active_index = active_index();
  selection_model_.Copy(source);
  NotifySelectionChanged(old_active_index);
}


static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value TSRMLS_DC)
{
	image_info_data  *info_data;
	image_info_data  *list;

	if (value) {
		list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);
		image_info->info_list[section_index].list = list;
		info_data  = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];
		info_data->tag    = TAG_NONE;
		info_data->format = TAG_FMT_STRING;
		info_data->length = 1;
		info_data->name   = estrdup(name);
		info_data->value.s = estrdup(value);
		image_info->sections_found |= 1<<section_index;
		image_info->info_list[section_index].count++;
	}
}


void ftrace_graph_init_task(struct task_struct *t)
{
	/* Make sure we do not use the parent ret_stack */
	t->ret_stack = NULL;
	t->curr_ret_stack = -1;

	if (ftrace_graph_active) {
		struct ftrace_ret_stack *ret_stack;

		ret_stack = kmalloc(FTRACE_RETFUNC_DEPTH
				* sizeof(struct ftrace_ret_stack),
				GFP_KERNEL);
		if (!ret_stack)
			return;
		graph_init_task(t, ret_stack);
	}
}


void CharacterIterator::advance(int count)
{
    if (count <= 0) {
        ASSERT(count == 0);
        return;
    }

    m_atBreak = false;

    int remaining = m_textIterator.length() - m_runOffset;
    if (count < remaining) {
        m_runOffset += count;
        m_offset += count;
        return;
    }

    count -= remaining;
    m_offset += remaining;

    for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) {
        int runLength = m_textIterator.length();
        if (runLength == 0)
            m_atBreak = true;
        else {
            if (count < runLength) {
                m_runOffset = count;
                m_offset += count;
                return;
            }

            count -= runLength;
            m_offset += runLength;
        }
    }

    m_atBreak = true;
    m_runOffset = 0;
}


get_subscriber(struct list_head *p, bool is_src)
{
	if (is_src)
		return list_entry(p, struct snd_seq_subscribers, src_list);
	else
		return list_entry(p, struct snd_seq_subscribers, dest_list);
}