int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
{
	transaction_t *transaction = handle->h_transaction;
	journal_t *journal;
	struct journal_head *jh;
	int ret = 0;

	if (is_handle_aborted(handle))
		return -EROFS;
	if (!buffer_jbd(bh))
		return -EUCLEAN;

	/*
	 * We don't grab jh reference here since the buffer must be part
	 * of the running transaction.
	 */
	jh = bh2jh(bh);
	jbd_debug(5, "journal_head %p\n", jh);
	JBUFFER_TRACE(jh, "entry");

	/*
	 * This and the following assertions are unreliable since we may see jh
	 * in inconsistent state unless we grab bh_state lock. But this is
	 * crucial to catch bugs so let's do a reliable check until the
	 * lockless handling is fully proven.
	 */
	if (data_race(jh->b_transaction != transaction &&
	    jh->b_next_transaction != transaction)) {
		spin_lock(&jh->b_state_lock);
		J_ASSERT_JH(jh, jh->b_transaction == transaction ||
				jh->b_next_transaction == transaction);
		spin_unlock(&jh->b_state_lock);
	}
	if (jh->b_modified == 1) {
		/* If it's in our transaction it must be in BJ_Metadata list. */
		if (data_race(jh->b_transaction == transaction &&
		    jh->b_jlist != BJ_Metadata)) {
			spin_lock(&jh->b_state_lock);
			if (jh->b_transaction == transaction &&
			    jh->b_jlist != BJ_Metadata)
				pr_err("JBD2: assertion failure: h_type=%u "
				       "h_line_no=%u block_no=%llu jlist=%u\n",
				       handle->h_type, handle->h_line_no,
				       (unsigned long long) bh->b_blocknr,
				       jh->b_jlist);
			J_ASSERT_JH(jh, jh->b_transaction != transaction ||
					jh->b_jlist == BJ_Metadata);
			spin_unlock(&jh->b_state_lock);
		}
		goto out;
	}

	journal = transaction->t_journal;
	spin_lock(&jh->b_state_lock);

	if (jh->b_modified == 0) {
		/*
		 * This buffer's got modified and becoming part
		 * of the transaction. This needs to be done
		 * once a transaction -bzzz
		 */
		if (WARN_ON_ONCE(jbd2_handle_buffer_credits(handle) <= 0)) {
			ret = -ENOSPC;
			goto out_unlock_bh;
		}
		jh->b_modified = 1;
		handle->h_total_credits--;
	}

	/*
	 * fastpath, to avoid expensive locking.  If this buffer is already
	 * on the running transaction's metadata list there is nothing to do.
	 * Nobody can take it off again because there is a handle open.
	 * I _think_ we're OK here with SMP barriers - a mistaken decision will
	 * result in this test being false, so we go in and take the locks.
	 */
	if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {
		JBUFFER_TRACE(jh, "fastpath");
		if (unlikely(jh->b_transaction !=
			     journal->j_running_transaction)) {
			printk(KERN_ERR "JBD2: %s: "
			       "jh->b_transaction (%llu, %p, %u) != "
			       "journal->j_running_transaction (%p, %u)\n",
			       journal->j_devname,
			       (unsigned long long) bh->b_blocknr,
			       jh->b_transaction,
			       jh->b_transaction ? jh->b_transaction->t_tid : 0,
			       journal->j_running_transaction,
			       journal->j_running_transaction ?
			       journal->j_running_transaction->t_tid : 0);
			ret = -EINVAL;
		}
		goto out_unlock_bh;
	}

	set_buffer_jbddirty(bh);

	/*
	 * Metadata already on the current transaction list doesn't
	 * need to be filed.  Metadata on another transaction's list must
	 * be committing, and will be refiled once the commit completes:
	 * leave it alone for now.
	 */
	if (jh->b_transaction != transaction) {
		JBUFFER_TRACE(jh, "already on other transaction");
		if (unlikely(((jh->b_transaction !=
			       journal->j_committing_transaction)) ||
			     (jh->b_next_transaction != transaction))) {
			printk(KERN_ERR "jbd2_journal_dirty_metadata: %s: "
			       "bad jh for block %llu: "
			       "transaction (%p, %u), "
			       "jh->b_transaction (%p, %u), "
			       "jh->b_next_transaction (%p, %u), jlist %u\n",
			       journal->j_devname,
			       (unsigned long long) bh->b_blocknr,
			       transaction, transaction->t_tid,
			       jh->b_transaction,
			       jh->b_transaction ?
			       jh->b_transaction->t_tid : 0,
			       jh->b_next_transaction,
			       jh->b_next_transaction ?
			       jh->b_next_transaction->t_tid : 0,
			       jh->b_jlist);
			WARN_ON(1);
			ret = -EINVAL;
		}
		/* And this case is illegal: we can't reuse another
		 * transaction's data buffer, ever. */
		goto out_unlock_bh;
	}

	/* That test should have eliminated the following case: */
	J_ASSERT_JH(jh, jh->b_frozen_data == NULL);

	JBUFFER_TRACE(jh, "file as BJ_Metadata");
	spin_lock(&journal->j_list_lock);
	__jbd2_journal_file_buffer(jh, transaction, BJ_Metadata);
	spin_unlock(&journal->j_list_lock);
out_unlock_bh:
	spin_unlock(&jh->b_state_lock);
out:
	JBUFFER_TRACE(jh, "exit");
	return ret;
}


int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
                                     tinfl_put_buf_func_ptr pPut_buf_func,
                                     void *pPut_buf_user, int flags) {
  int result = 0;
  tinfl_decompressor decomp;
  mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
  size_t in_buf_ofs = 0, dict_ofs = 0;
  if (!pDict) return TINFL_STATUS_FAILED;
  tinfl_init(&decomp);
  for (;;) {
    size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
           dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
    tinfl_status status =
        tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
                         &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
                         (flags & ~(TINFL_FLAG_HAS_MORE_INPUT |
                                    TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
    in_buf_ofs += in_buf_size;
    if ((dst_buf_size) &&
        (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
      break;
    if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
      result = (status == TINFL_STATUS_DONE);
      break;
    }
    dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  }
  MZ_FREE(pDict);
  *pIn_buf_size = in_buf_ofs;
  return result;
}


Variant HHVM_FUNCTION(mb_http_input,
                      const Variant& opt_type) {
  const String type = convertArg(opt_type);

  int n;
  char *name;
  mbfl_encoding **entry;
  mbfl_encoding *result = nullptr;

  if (type.empty()) {
    result = MBSTRG(http_input_identify);
  } else {
    switch (*type.data()) {
    case 'G': case 'g': result = MBSTRG(http_input_identify_get);    break;
    case 'P': case 'p': result = MBSTRG(http_input_identify_post);   break;
    case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break;
    case 'S': case 's': result = MBSTRG(http_input_identify_string); break;
    case 'I': case 'i':
      {
        Array ret;
        entry = MBSTRG(http_input_list);
        n = MBSTRG(http_input_list_size);
        while (n > 0) {
          name = (char *)(*entry)->name;
          if (name) {
            ret.append(String(name, CopyString));
          }
          entry++;
          n--;
        }
        return ret;
      }
    case 'L': case 'l':
      {
        entry = MBSTRG(http_input_list);
        n = MBSTRG(http_input_list_size);
        StringBuffer list;
        while (n > 0) {
          name = (char *)(*entry)->name;
          if (name) {
            if (list.empty()) {
              list.append(name);
            } else {
              list.append(',');
              list.append(name);
            }
          }
          entry++;
          n--;
        }
        if (list.empty()) {
          return false;
        }
        return list.detach();
      }
    default:
      result = MBSTRG(http_input_identify);
      break;
    }
  }

  if (result != nullptr &&
      (name = (char *)(result)->name) != nullptr) {
    return String(name, CopyString);
  }
  return false;
}


struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)
{
	struct ring_buffer *rb;
	unsigned long size;
	void *all_buf;

	size = sizeof(struct ring_buffer);
	size += sizeof(void *);

	rb = kzalloc(size, GFP_KERNEL);
	if (!rb)
		goto fail;

	INIT_WORK(&rb->work, rb_free_work);

	all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
	if (!all_buf)
		goto fail_all_buf;

	rb->user_page = all_buf;
	rb->data_pages[0] = all_buf + PAGE_SIZE;
	rb->page_order = ilog2(nr_pages);
	rb->nr_pages = 1;

	ring_buffer_init(rb, watermark, flags);

	return rb;

fail_all_buf:
	kfree(rb);

fail:
	return NULL;
}


bool PasswordAutofillAgent::TextDidChangeInTextField(
    const WebInputElement& element) {
  WebInputElement mutable_element = element;  // We need a non-const.
  mutable_element.SetAutofillState(WebAutofillState::kNotFilled);

  auto iter = web_input_to_password_info_.find(element);
  if (iter != web_input_to_password_info_.end()) {
    iter->second.password_was_edited_last = false;
  }

  return ShowSuggestions(element, false, false);
}


 virtual status_t getConfig(
            node_id node, OMX_INDEXTYPE index,
 void *params, size_t size) {
 Parcel data, reply;
        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
        data.writeInt32((int32_t)node);
        data.writeInt32(index);
        data.writeInt64(size);
        data.write(params, size);
        remote()->transact(GET_CONFIG, data, &reply);

 status_t err = reply.readInt32();
 if (err != OK) {
 return err;
 }

        reply.read(params, size);

 return OK;
 }


void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size)
{
    DEBUG_VALIDATE_BUG_ON(det_ctx->tx_candidates);
    det_ctx->tx_candidates = SCCalloc(size, sizeof(RuleMatchCandidateTx));
    if (det_ctx->tx_candidates == NULL) {
        FatalError(SC_ERR_MEM_ALLOC, "failed to allocate %"PRIu64" bytes",
                (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
    }
    det_ctx->tx_candidates_size = size;
    SCLogDebug("array initialized to %u elements (%"PRIu64" bytes)",
            size, (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
}


static u32 tcp_illinois_ssthresh(struct sock *sk)
{
	struct tcp_sock *tp = tcp_sk(sk);
	struct illinois *ca = inet_csk_ca(sk);

	/* Multiplicative decrease */
	return max(tp->snd_cwnd - ((tp->snd_cwnd * ca->beta) >> BETA_SHIFT), 2U);
}


v8::Local<v8::Context> ScriptController::mainWorldContext(Frame* frame)
{
    if (!frame)
        return v8::Local<v8::Context>();

    return contextForWorld(frame->script(), mainThreadNormalWorld());
}


void nfc_llcp_accept_unlink(struct sock *sk)
{
	struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);

	pr_debug("state %d\n", sk->sk_state);

	list_del_init(&llcp_sock->accept_queue);
	sk_acceptq_removed(llcp_sock->parent);
	llcp_sock->parent = NULL;

	sock_put(sk);
}


dist_ppath(PG_FUNCTION_ARGS)
{
	Point	   *pt = PG_GETARG_POINT_P(0);
	PATH	   *path = PG_GETARG_PATH_P(1);
	float8		result = 0.0;	/* keep compiler quiet */
	bool		have_min = false;
	float8		tmp;
	int			i;
	LSEG		lseg;

	switch (path->npts)
	{
		case 0:
			/* no points in path? then result is undefined... */
			PG_RETURN_NULL();
		case 1:
			/* one point in path? then get distance between two points... */
			result = point_dt(pt, &path->p[0]);
			break;
		default:
			/* make sure the path makes sense... */
			Assert(path->npts > 1);

			/*
			 * the distance from a point to a path is the smallest distance
			 * from the point to any of its constituent segments.
			 */
			for (i = 0; i < path->npts; i++)
			{
				int			iprev;

				if (i > 0)
					iprev = i - 1;
				else
				{
					if (!path->closed)
						continue;
					iprev = path->npts - 1;		/* include the closure segment */
				}

				statlseg_construct(&lseg, &path->p[iprev], &path->p[i]);
				tmp = dist_ps_internal(pt, &lseg);
				if (!have_min || tmp < result)
				{
					result = tmp;
					have_min = true;
				}
			}
			break;
	}
	PG_RETURN_FLOAT8(result);
}


static int opsbb(RAsm *a, ut8 *data, const Opcode *op) {
	if (op->operands[1].type & OT_CONSTANT) {
		if (op->operands[0].type & OT_GPREG &&
		    op->operands[0].type & OT_WORD) {
			return process_16bit_group_1 (a, data, op, 0x18);
		}
		if (!is_al_reg (&op->operands[0])) {
			return process_group_1 (a, data, op);
		}
	}
	return process_1byte_op (a, data, op, 0x18);
}


static int qemuMonitorTextCommandNotFound ( const char * cmd , const char * reply ) {
 if ( STRPREFIX ( cmd , "info " ) ) {
 if ( strstr ( reply , "info version" ) ) return 1 ;
 }
 else {
 if ( strstr ( reply , "unknown command:" ) ) return 1 ;
 }
 return 0 ;
 }


static ssize_t block_crypto_init_func(QCryptoBlock *block,

                                      size_t headerlen,

                                      Error **errp,

                                      void *opaque)

{

    struct BlockCryptoCreateData *data = opaque;

    int ret;

    /* User provided size should reflect amount of space made

     * available to the guest, so we must take account of that

     * which will be used by the crypto header

     */

    data->size += headerlen;

    qemu_opt_set_number(data->opts, BLOCK_OPT_SIZE, data->size, &error_abort);

    ret = bdrv_create_file(data->filename, data->opts, errp);

    if (ret < 0) {

        return -1;

    }

    data->blk = blk_new_open(data->filename, NULL, NULL,

                             BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);

    if (!data->blk) {

        return -1;

    }

    return 0;

}


hook_infolist (struct t_weechat_plugin *plugin, const char *infolist_name,
               const char *description, const char *pointer_description,
               const char *args_description,
               t_hook_callback_infolist *callback, void *callback_data)
{
    struct t_hook *new_hook;
    struct t_hook_infolist *new_hook_infolist;
    int priority;
    const char *ptr_infolist_name;

    if (!infolist_name || !infolist_name[0] || !callback)
        return NULL;

    new_hook = malloc (sizeof (*new_hook));
    if (!new_hook)
        return NULL;
    new_hook_infolist = malloc (sizeof (*new_hook_infolist));
    if (!new_hook_infolist)
    {
        free (new_hook);
        return NULL;
    }

    hook_get_priority_and_name (infolist_name, &priority, &ptr_infolist_name);
    hook_init_data (new_hook, plugin, HOOK_TYPE_INFOLIST, priority,
                    callback_data);

    new_hook->hook_data = new_hook_infolist;
    new_hook_infolist->callback = callback;
    new_hook_infolist->infolist_name = strdup ((ptr_infolist_name) ?
                                               ptr_infolist_name : infolist_name);
    new_hook_infolist->description = strdup ((description) ? description : "");
    new_hook_infolist->pointer_description = strdup ((pointer_description) ?
                                                     pointer_description : "");
    new_hook_infolist->args_description = strdup ((args_description) ?
                                                  args_description : "");

    hook_add_to_list (new_hook);

    return new_hook;
}


static inline int8_t isAnonAuth ( relpTcp_t * pThis ) {
 return pThis -> ownCertFile == NULL ;
 }


int evdns_server_request_drop ( struct evdns_server_request * _req ) {
 struct server_request * req = TO_SERVER_REQUEST ( _req ) ;
 server_request_free ( req ) ;
 return 0 ;
 }


sf_close	(SNDFILE *sndfile)
{	SF_PRIVATE	*psf ;

	VALIDATE_SNDFILE_AND_ASSIGN_PSF (sndfile, psf, 1) ;

	return psf_close (psf) ;
} /* sf_close */


int yuv2rgb_c_init_tables (SwsContext *c, const int inv_table[4], int fullRange, int brightness, int contrast, int saturation)

{

    const int isRgb = isBGR(c->dstFormat);

    const int bpp = fmt_depth(c->dstFormat);

    int i;

    uint8_t table_Y[1024];

    uint32_t *table_32 = 0;

    uint16_t *table_16 = 0;

    uint8_t *table_8 = 0;

    uint8_t *table_332 = 0;

    uint8_t *table_121 = 0;

    uint8_t *table_1 = 0;

    int entry_size = 0;

    void *table_r = 0, *table_g = 0, *table_b = 0;

    void *table_start;

    int64_t crv =  inv_table[0];

    int64_t cbu =  inv_table[1];

    int64_t cgu = -inv_table[2];

    int64_t cgv = -inv_table[3];

    int64_t cy  = 1<<16;

    int64_t oy  = 0;

//printf("%lld %lld %lld %lld %lld\n", cy, crv, cbu, cgu, cgv);

    if(!fullRange){

	cy= (cy*255) / 219;

	oy= 16<<16;

    }else{

        crv= (crv*224) / 255;

        cbu= (cbu*224) / 255;

        cgu= (cgu*224) / 255;

        cgv= (cgv*224) / 255;

    }

    cy = (cy *contrast             )>>16;

    crv= (crv*contrast * saturation)>>32;

    cbu= (cbu*contrast * saturation)>>32;

    cgu= (cgu*contrast * saturation)>>32;

    cgv= (cgv*contrast * saturation)>>32;

//printf("%lld %lld %lld %lld %lld\n", cy, crv, cbu, cgu, cgv);

    oy -= 256*brightness;

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

	int j;

	j= (cy*(((i - 384)<<16) - oy) + (1<<31))>>32;

	j = (j < 0) ? 0 : ((j > 255) ? 255 : j);

	table_Y[i] = j;

    }

    switch (bpp) {

    case 32:

	table_start= table_32 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint32_t));

	entry_size = sizeof (uint32_t);

	table_r = table_32 + 197;

	table_b = table_32 + 197 + 685;

	table_g = table_32 + 197 + 2*682;

	for (i = -197; i < 256+197; i++)

	    ((uint32_t *)table_r)[i] = table_Y[i+384] << (isRgb ? 16 : 0);

	for (i = -132; i < 256+132; i++)

	    ((uint32_t *)table_g)[i] = table_Y[i+384] << 8;

	for (i = -232; i < 256+232; i++)

	    ((uint32_t *)table_b)[i] = table_Y[i+384] << (isRgb ? 0 : 16);

	break;

    case 24:

	table_start= table_8 = av_malloc ((256 + 2*232) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_g = table_b = table_8 + 232;

	for (i = -232; i < 256+232; i++)

	    ((uint8_t * )table_b)[i] = table_Y[i+384];

	break;

    case 15:

    case 16:

	table_start= table_16 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint16_t));

	entry_size = sizeof (uint16_t);

	table_r = table_16 + 197;

	table_b = table_16 + 197 + 685;

	table_g = table_16 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = table_Y[i+384] >> 3;

	    if (isRgb)

		j <<= ((bpp==16) ? 11 : 10);

	    ((uint16_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = table_Y[i+384] >> ((bpp==16) ? 2 : 3);

	    ((uint16_t *)table_g)[i] = j << 5;

	}

	for (i = -232; i < 256+232; i++) {

	    int j = table_Y[i+384] >> 3;

	    if (!isRgb)

		j <<= ((bpp==16) ? 11 : 10);

	    ((uint16_t *)table_b)[i] = j;

	}

	break;

    case 8:

	table_start= table_332 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_332 + 197;

	table_b = table_332 + 197 + 685;

	table_g = table_332 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = (table_Y[i+384 - 16] + 18)/36;

	    if (isRgb)

		j <<= 5;

	    ((uint8_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = (table_Y[i+384 - 16] + 18)/36;

	    if (!isRgb)

		j <<= 1;

	    ((uint8_t *)table_g)[i] = j << 2;

	}

	for (i = -232; i < 256+232; i++) {

	    int j = (table_Y[i+384 - 37] + 43)/85;

	    if (!isRgb)

		j <<= 6;

	    ((uint8_t *)table_b)[i] = j;

	}

	break;

    case 4:

    case 4|128:

	table_start= table_121 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_121 + 197;

	table_b = table_121 + 197 + 685;

	table_g = table_121 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = table_Y[i+384 - 110] >> 7;

	    if (isRgb)

		j <<= 3;

	    ((uint8_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = (table_Y[i+384 - 37]+ 43)/85;

	    ((uint8_t *)table_g)[i] = j << 1;

	}

	for (i = -232; i < 256+232; i++) {

	    int j =table_Y[i+384 - 110] >> 7;

	    if (!isRgb)

		j <<= 3;

	    ((uint8_t *)table_b)[i] = j;

	}

	break;

    case 1:

	table_start= table_1 = av_malloc (256*2 * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_g = table_1;

	table_r = table_b = NULL;

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

	    int j = table_Y[i + 384 - 110]>>7;

	    ((uint8_t *)table_g)[i] = j;

	}

	break;

    default:

	table_start= NULL;

	av_log(c, AV_LOG_ERROR, "%ibpp not supported by yuv2rgb\n", bpp);

	//free mem?

	return -1;

    }

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

	c->table_rV[i] = (uint8_t *)table_r + entry_size * div_round (crv * (i-128), 76309);

	c->table_gU[i] = (uint8_t *)table_g + entry_size * div_round (cgu * (i-128), 76309);

	c->table_gV[i] = entry_size * div_round (cgv * (i-128), 76309);

	c->table_bU[i] = (uint8_t *)table_b + entry_size * div_round (cbu * (i-128), 76309);

    }

    av_free(c->yuvTable);

    c->yuvTable= table_start;

    return 0;

}


static int parse_read_interval(const char *interval_spec,
                               ReadInterval *interval)
{
    int ret = 0;
    char *next, *p, *spec = av_strdup(interval_spec);
    if (!spec)
        return AVERROR(ENOMEM);

    if (!*spec) {
        av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
        ret = AVERROR(EINVAL);
        goto end;
    }

    p = spec;
    next = strchr(spec, '%');
    if (next)
        *next++ = 0;

    /* parse first part */
    if (*p) {
        interval->has_start = 1;

        if (*p == '+') {
            interval->start_is_offset = 1;
            p++;
        } else {
            interval->start_is_offset = 0;
        }

        ret = av_parse_time(&interval->start, p, 1);
        if (ret < 0) {
            av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
            goto end;
        }
    } else {
        interval->has_start = 0;
    }

    /* parse second part */
    p = next;
    if (p && *p) {
        int64_t us;
        interval->has_end = 1;

        if (*p == '+') {
            interval->end_is_offset = 1;
            p++;
        } else {
            interval->end_is_offset = 0;
        }

        if (interval->end_is_offset && *p == '#') {
            long long int lli;
            char *tail;
            interval->duration_frames = 1;
            p++;
            lli = strtoll(p, &tail, 10);
            if (*tail || lli < 0) {
                av_log(NULL, AV_LOG_ERROR,
                       "Invalid or negative value '%s' for duration number of frames\n", p);
                goto end;
            }
            interval->end = lli;
        } else {
            interval->duration_frames = 0;
            ret = av_parse_time(&us, p, 1);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
                goto end;
            }
            interval->end = us;
        }
    } else {
        interval->has_end = 0;
    }

end:
    av_free(spec);
    return ret;
}


static void init_utee_param(struct utee_params *up,
			const struct tee_ta_param *p, void *va[TEE_NUM_PARAMS])
{
	size_t n;

	up->types = p->types;
	for (n = 0; n < TEE_NUM_PARAMS; n++) {
		uintptr_t a;
		uintptr_t b;

		switch (TEE_PARAM_TYPE_GET(p->types, n)) {
		case TEE_PARAM_TYPE_MEMREF_INPUT:
		case TEE_PARAM_TYPE_MEMREF_OUTPUT:
		case TEE_PARAM_TYPE_MEMREF_INOUT:
			a = (uintptr_t)va[n];
			b = p->u[n].mem.size;
			break;
		case TEE_PARAM_TYPE_VALUE_INPUT:
		case TEE_PARAM_TYPE_VALUE_INOUT:
			a = p->u[n].val.a;
			b = p->u[n].val.b;
			break;
		default:
			a = 0;
			b = 0;
			break;
		}
		/* See comment for struct utee_params in utee_types.h */
		up->vals[n * 2] = a;
		up->vals[n * 2 + 1] = b;
	}
}


void do_interrupt(CPUARMState *env)

{

    uint32_t addr;

    uint32_t mask;

    int new_mode;

    uint32_t offset;

    if (IS_M(env)) {

        do_interrupt_v7m(env);

        return;

    }

    /* TODO: Vectored interrupt controller.  */

    switch (env->exception_index) {

    case EXCP_UDEF:

        new_mode = ARM_CPU_MODE_UND;

        addr = 0x04;

        mask = CPSR_I;

        if (env->thumb)

            offset = 2;

        else

            offset = 4;

        break;

    case EXCP_SWI:

        if (semihosting_enabled) {

            /* Check for semihosting interrupt.  */

            if (env->thumb) {

                mask = lduw_code(env->regs[15] - 2) & 0xff;

            } else {

                mask = ldl_code(env->regs[15] - 4) & 0xffffff;

            }

            /* Only intercept calls from privileged modes, to provide some

               semblance of security.  */

            if (((mask == 0x123456 && !env->thumb)

                    || (mask == 0xab && env->thumb))

                  && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        new_mode = ARM_CPU_MODE_SVC;

        addr = 0x08;

        mask = CPSR_I;

        /* The PC already points to the next instruction.  */

        offset = 0;

        break;

    case EXCP_BKPT:

        /* See if this is a semihosting syscall.  */

        if (env->thumb && semihosting_enabled) {

            mask = lduw_code(env->regs[15]) & 0xff;

            if (mask == 0xab

                  && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {

                env->regs[15] += 2;

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        /* Fall through to prefetch abort.  */

    case EXCP_PREFETCH_ABORT:

        new_mode = ARM_CPU_MODE_ABT;

        addr = 0x0c;

        mask = CPSR_A | CPSR_I;

        offset = 4;

        break;

    case EXCP_DATA_ABORT:

        new_mode = ARM_CPU_MODE_ABT;

        addr = 0x10;

        mask = CPSR_A | CPSR_I;

        offset = 8;

        break;

    case EXCP_IRQ:

        new_mode = ARM_CPU_MODE_IRQ;

        addr = 0x18;

        /* Disable IRQ and imprecise data aborts.  */

        mask = CPSR_A | CPSR_I;

        offset = 4;

        break;

    case EXCP_FIQ:

        new_mode = ARM_CPU_MODE_FIQ;

        addr = 0x1c;

        /* Disable FIQ, IRQ and imprecise data aborts.  */

        mask = CPSR_A | CPSR_I | CPSR_F;

        offset = 4;

        break;

    default:

        cpu_abort(env, "Unhandled exception 0x%x\n", env->exception_index);

        return; /* Never happens.  Keep compiler happy.  */

    }

    /* High vectors.  */

    if (env->cp15.c1_sys & (1 << 13)) {

        addr += 0xffff0000;

    }

    switch_mode (env, new_mode);

    env->spsr = cpsr_read(env);

    /* Clear IT bits.  */

    env->condexec_bits = 0;

    /* Switch to the new mode, and to the correct instruction set.  */

    env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;

    env->uncached_cpsr |= mask;

    env->thumb = (env->cp15.c1_sys & (1 << 30)) != 0;

    env->regs[14] = env->regs[15] + offset;

    env->regs[15] = addr;

    env->interrupt_request |= CPU_INTERRUPT_EXITTB;

}


insert_iCCP(png_structp png_ptr, png_infop info_ptr, int nparams,
   png_charpp params)
{
   png_bytep profile = NULL;
   png_uint_32 proflen = 0;
 int result;

   check_param_count(nparams, 2);

 switch (params[1][0])
 {
 case '<':
 {
 png_size_t filelen = load_file(params[1]+1, &profile);
 if (filelen > 0xfffffffc) /* Maximum profile length */
 {
               fprintf(stderr, "%s: file too long (%lu) for an ICC profile\n",
                  params[1]+1, (unsigned long)filelen);
               exit(1);
 }

            proflen = (png_uint_32)filelen;
 }
 break;

 case '0': case '1': case '2': case '3': case '4':
 case '5': case '6': case '7': case '8': case '9':
 {
 png_size_t fake_len = load_fake(params[1], &profile);

 if (fake_len > 0) /* else a simple parameter */
 {
 if (fake_len > 0xffffffff) /* Maximum profile length */
 {
                  fprintf(stderr,
 "%s: fake data too long (%lu) for an ICC profile\n",
                     params[1], (unsigned long)fake_len);
                  exit(1);
 }
               proflen = (png_uint_32)(fake_len & ~3U);
 /* Always fix up the profile length. */
               png_save_uint_32(profile, proflen);
 break;
 }
 }

 default:
         fprintf(stderr, "--insert iCCP \"%s\": unrecognized\n", params[1]);
         fprintf(stderr, "  use '<' to read a file: \"<filename\"\n");
         exit(1);
 }

   result = 1;

 if (proflen & 3)
 {
      fprintf(stderr,
 "makepng: --insert iCCP %s: profile length made a multiple of 4\n",
         params[1]);

 /* load_file allocates extra space for this padding, the ICC spec requires
       * padding with zero bytes.
       */
 while (proflen & 3)
         profile[proflen++] = 0;
 }

 if (profile != NULL && proflen > 3)
 {
      png_uint_32 prof_header = png_get_uint_32(profile);

 if (prof_header != proflen)
 {
         fprintf(stderr, "--insert iCCP %s: profile length field wrong:\n",
            params[1]);
         fprintf(stderr, "  actual %lu, recorded value %lu (corrected)\n",
 (unsigned long)proflen, (unsigned long)prof_header);
         png_save_uint_32(profile, proflen);
 }
 }

 if (result && profile != NULL && proflen >=4)
      png_set_iCCP(png_ptr, info_ptr, params[0], PNG_COMPRESSION_TYPE_BASE,
         profile, proflen);

 if (profile)
      free(profile);

 if (!result)
      exit(1);
}


void SkiaOutputSurfaceImplTest::TearDown() {
  output_surface_.reset();
  scoped_feature_list_.reset();
}


CompositeDeepScanLine::setFrameBuffer(const FrameBuffer& fr)
{

    //
    // count channels; build map between channels in frame buffer
    // and channels in internal buffers
    //

    _Data->_channels.resize(3);
    _Data->_channels[0]="Z";
    _Data->_channels[1]=_Data->_zback ? "ZBack" : "Z";
    _Data->_channels[2]="A";
    _Data->_bufferMap.resize(0);

    for(FrameBuffer::ConstIterator q=fr.begin();q!=fr.end();q++)
    {
        string name(q.name());
        if(name=="ZBack")
        {
            _Data->_bufferMap.push_back(1);
        }else if(name=="Z")
        {
            _Data->_bufferMap.push_back(0);
        }else if(name=="A")
        {
            _Data->_bufferMap.push_back(2);
        }else{
            _Data->_bufferMap.push_back(static_cast<int>(_Data->_channels.size()));
            _Data->_channels.push_back(name);
        }
    }

  _Data->_outputFrameBuffer=fr;
}


static void svgAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
    TestObjectPythonV8Internal::svgAttributeAttributeSetter(jsValue, info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


static TEE_Result check_ta_store(void)
{
	const struct user_ta_store_ops *op = NULL;

	SCATTERED_ARRAY_FOREACH(op, ta_stores, struct user_ta_store_ops)
		DMSG("TA store: \"%s\"", op->description);

	return TEE_SUCCESS;
}


static void s390_init(ram_addr_t my_ram_size,
                      const char *boot_device,
                      const char *kernel_filename,
                      const char *kernel_cmdline,
                      const char *initrd_filename,
                      const char *cpu_model)
{
    CPUState *env = NULL;
    MemoryRegion *sysmem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    ram_addr_t kernel_size = 0;
    ram_addr_t initrd_offset;
    ram_addr_t initrd_size = 0;
    int shift = 0;
    uint8_t *storage_keys;
    void *virtio_region;
    target_phys_addr_t virtio_region_len;
    target_phys_addr_t virtio_region_start;
    int i;
    /* s390x ram size detection needs a 16bit multiplier + an increment. So
       guests > 64GB can be specified in 2MB steps etc. */
    while ((my_ram_size >> (20 + shift)) > 65535) {
        shift++;
    }
    my_ram_size = my_ram_size >> (20 + shift) << (20 + shift);
    /* lets propagate the changed ram size into the global variable. */
    ram_size = my_ram_size;
    /* get a BUS */
    s390_bus = s390_virtio_bus_init(&my_ram_size);
    /* allocate RAM */
    memory_region_init_ram(ram, NULL, "s390.ram", my_ram_size);
    memory_region_add_subregion(sysmem, 0, ram);
    /* allocate storage keys */
    storage_keys = g_malloc0(my_ram_size / TARGET_PAGE_SIZE);
    /* init CPUs */
    if (cpu_model == NULL) {
        cpu_model = "host";
    }
    ipi_states = g_malloc(sizeof(CPUState *) * smp_cpus);
    for (i = 0; i < smp_cpus; i++) {
        CPUState *tmp_env;
        tmp_env = cpu_init(cpu_model);
        if (!env) {
            env = tmp_env;
        }
        ipi_states[i] = tmp_env;
        tmp_env->halted = 1;
        tmp_env->exception_index = EXCP_HLT;
        tmp_env->storage_keys = storage_keys;
    }
    /* One CPU has to run */
    s390_add_running_cpu(env);
    if (kernel_filename) {
        kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0));
        if (lduw_be_phys(KERN_IMAGE_START) != 0x0dd0) {
            fprintf(stderr, "Specified image is not an s390 boot image\n");
            exit(1);
        }
        env->psw.addr = KERN_IMAGE_START;
        env->psw.mask = 0x0000000180000000ULL;
    } else {
        ram_addr_t bios_size = 0;
        char *bios_filename;
        /* Load zipl bootloader */
        if (bios_name == NULL) {
            bios_name = ZIPL_FILENAME;
        }
        bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
        bios_size = load_image(bios_filename, qemu_get_ram_ptr(ZIPL_LOAD_ADDR));
        g_free(bios_filename);
        if ((long)bios_size < 0) {
            hw_error("could not load bootloader '%s'\n", bios_name);
        }
        if (bios_size > 4096) {
            hw_error("stage1 bootloader is > 4k\n");
        }
        env->psw.addr = ZIPL_START;
        env->psw.mask = 0x0000000180000000ULL;
    }
    if (initrd_filename) {
        initrd_offset = INITRD_START;
        while (kernel_size + 0x100000 > initrd_offset) {
            initrd_offset += 0x100000;
        }
        initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset));
        stq_be_phys(INITRD_PARM_START, initrd_offset);
        stq_be_phys(INITRD_PARM_SIZE, initrd_size);
    }
    if (kernel_cmdline) {
        cpu_physical_memory_write(KERN_PARM_AREA, kernel_cmdline,
                                  strlen(kernel_cmdline) + 1);
    }
    /* Create VirtIO network adapters */
    for(i = 0; i < nb_nics; i++) {
        NICInfo *nd = &nd_table[i];
        DeviceState *dev;
        if (!nd->model) {
            nd->model = g_strdup("virtio");
        }
        if (strcmp(nd->model, "virtio")) {
            fprintf(stderr, "S390 only supports VirtIO nics\n");
            exit(1);
        }
        dev = qdev_create((BusState *)s390_bus, "virtio-net-s390");
        qdev_set_nic_properties(dev, nd);
        qdev_init_nofail(dev);
    }
    /* Create VirtIO disk drives */
    for(i = 0; i < MAX_BLK_DEVS; i++) {
        DriveInfo *dinfo;
        DeviceState *dev;
        dinfo = drive_get(IF_IDE, 0, i);
        if (!dinfo) {
            continue;
        }
        dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390");
        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);
        qdev_init_nofail(dev);
    }
}


static bool isValidMIMEType(const String& type)
{
    size_t slashPosition = type.find('/');
    if (slashPosition == kNotFound || !slashPosition || slashPosition == type.length() - 1)
        return false;
    for (size_t i = 0; i < type.length(); ++i) {
        if (!isRFC2616TokenCharacter(type[i]) && i != slashPosition)
            return false;
    }
    return true;
}


static const struct arm_pmu *__init xscale2pmu_init(void)
{
	return &xscale2pmu;
}


mrb_obj_extend(mrb_state *mrb, mrb_int argc, mrb_value *argv, mrb_value obj)
{
  mrb_int i;

  if (argc == 0) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (at least 1)");
  }
  for (i = 0; i < argc; i++) {
    mrb_check_type(mrb, argv[i], MRB_TT_MODULE);
  }
  while (argc--) {
    mrb_funcall(mrb, argv[argc], "extend_object", 1, obj);
    mrb_funcall(mrb, argv[argc], "extended", 1, obj);
  }
  return obj;
}


Frame* V8Proxy::retrieveFrameForCallingContext()
{
    v8::Handle<v8::Context> context = v8::Context::GetCalling();
    if (context.IsEmpty())
        return 0;
    return retrieveFrame(context);
}


void spapr_vio_bus_register_withprop(VIOsPAPRDeviceInfo *info)

{

    info->qdev.init = spapr_vio_busdev_init;

    info->qdev.bus_info = &spapr_vio_bus_info;

    assert(info->qdev.size >= sizeof(VIOsPAPRDevice));

    qdev_register(&info->qdev);

}


void ReadAlignment(OpKernelConstruction* context,
                   bool* left_align_superdiagonal,
                   bool* left_align_subdiagonal) {
  string align;
  OP_REQUIRES_OK(context, context->GetAttr("align", &align));

  *left_align_superdiagonal = align == "LEFT_LEFT" || align == "LEFT_RIGHT";
  *left_align_subdiagonal = align == "LEFT_LEFT" || align == "RIGHT_LEFT";
}


struct file *open_exec(const char *name)
{
	struct filename *filename = getname_kernel(name);
	struct file *f = ERR_CAST(filename);

	if (!IS_ERR(filename)) {
		f = do_open_execat(AT_FDCWD, filename, 0);
		putname(filename);
	}
	return f;
}


Bool gf_cenc_validate_key_info(const u8 *key_info, u32 key_info_size)
{
	u32 i, n_keys, kpos, nb_missing = 19;
	if (!key_info|| (key_info_size<19))
		goto exit;

	n_keys = 1;
	if (key_info[0]) {
		n_keys = key_info[1];
		n_keys <<= 8;
		n_keys |= key_info[2];
	}
	kpos=3;
	for (i=0;i<n_keys; i++) {
		u8 iv_size;
		if (kpos + 17 > key_info_size) {
			nb_missing = kpos + 17 - key_info_size;
			goto exit;
		}
		iv_size = key_info[kpos];
		kpos += 17;
		if (!iv_size) {
			if (kpos + 1 > key_info_size) {
				nb_missing = kpos + 1  - key_info_size;
				goto exit;
			}
			iv_size = key_info[kpos];
			if (kpos + 1 + iv_size > key_info_size) {
				nb_missing = kpos + 1 + iv_size - key_info_size;
				goto exit;
			}
			kpos += 1 + iv_size;
		}
	}
	return GF_TRUE;

exit:
	GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Invalid key info format, missing %d bytes\n", nb_missing));
	return GF_FALSE;
}


ds1225y_t *ds1225y_init(target_phys_addr_t mem_base, const char *filename)

{

    ds1225y_t *s;

    int mem_index1, mem_index2;

    s = qemu_mallocz(sizeof(ds1225y_t));

    if (!s)

        return NULL;

    s->mem_base = mem_base;

    s->capacity = 0x2000; /* Fixed for ds1225y chip: 8K */

    s->filename = filename;

    /* Read/write memory */

    mem_index1 = cpu_register_io_memory(0, nvram_read, nvram_write, s);

    cpu_register_physical_memory(mem_base, s->capacity, mem_index1);

    /* Read-only memory */

    mem_index2 = cpu_register_io_memory(0, nvram_read, nvram_none, s);

    cpu_register_physical_memory(mem_base + s->capacity, s->capacity, mem_index2);

    return s;

}


nfs3svc_release_fhandle2(struct svc_rqst *rqstp, __be32 *p,
					struct nfsd3_fhandle_pair *resp)
{
	fh_put(&resp->fh1);
	fh_put(&resp->fh2);
	return 1;
}


static const URI_CHAR * URI_FUNC(ParseZeroMoreSlashSegs)(
		URI_TYPE(ParserState) * state, const URI_CHAR * first,
		const URI_CHAR * afterLast, UriMemoryManager * memory) {
	if (first >= afterLast) {
		return afterLast;
	}

	switch (*first) {
	case _UT('/'):
		{
			const URI_CHAR * const afterSegment
					= URI_FUNC(ParseSegment)(state, first + 1, afterLast, memory);
			if (afterSegment == NULL) {
				return NULL;
			}
			if (!URI_FUNC(PushPathSegment)(state, first + 1, afterSegment, memory)) { /* SEGMENT BOTH */
				URI_FUNC(StopMalloc)(state, memory);
				return NULL;
			}
			return URI_FUNC(ParseZeroMoreSlashSegs)(state, afterSegment, afterLast, memory);
		}

	default:
		return first;
	}
}


error::Error GLES2DecoderPassthroughImpl::DoGetBufferParameteriv(
    GLenum target,
    GLenum pname,
    GLsizei bufsize,
    GLsizei* length,
    GLint* params) {
  CheckErrorCallbackState();
  api()->glGetBufferParameterivRobustANGLEFn(target, pname, bufsize, length,
                                             params);
  if (CheckErrorCallbackState()) {
    return error::kNoError;
  }
  PatchGetBufferResults(target, pname, bufsize, length, params);
  return error::kNoError;
}


static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
  Image *image)
{
  char
    layer_name[MaxTextExtent];

  const char
    *property;

  const StringInfo
    *icc_profile,
    *info;

  Image
    *base_image,
    *next_image;

  MagickBooleanType
    status;

  MagickOffsetType
    *layer_size_offsets,
    size_offset;

  PSDInfo
    psd_info;

  register ssize_t
    i;

  size_t
    layer_count,
    layer_index,
    length,
    name_length,
    num_channels,
    packet_size,
    rounded_size,
    size;

  StringInfo
    *bim_profile;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFalse)
    return(status);
  packet_size=(size_t) (image->depth > 8 ? 6 : 3);
  if (image->matte != MagickFalse)
    packet_size+=image->depth > 8 ? 2 : 1;
  psd_info.version=1;
  if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
      (image->columns > 30000) || (image->rows > 30000))
    psd_info.version=2;
  (void) WriteBlob(image,4,(const unsigned char *) "8BPS");
  (void) WriteBlobMSBShort(image,psd_info.version);  /* version */
  for (i=1; i <= 6; i++)
    (void) WriteBlobByte(image, 0);  /* 6 bytes of reserved */
  /* When the image has a color profile it won't be converted to gray scale */
  if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) &&
      (SetImageGray(image,&image->exception) != MagickFalse))
    num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
  else
    if ((image_info->type != TrueColorType) && (image_info->type !=
         TrueColorMatteType) && (image->storage_class == PseudoClass))
      num_channels=(image->matte != MagickFalse ? 2UL : 1UL);
    else
      {
        if (image->storage_class == PseudoClass)
          (void) SetImageStorageClass(image,DirectClass);
        if (image->colorspace != CMYKColorspace)
          num_channels=(image->matte != MagickFalse ? 4UL : 3UL);
        else
          num_channels=(image->matte != MagickFalse ? 5UL : 4UL);
      }
  (void) WriteBlobMSBShort(image,(unsigned short) num_channels);
  (void) WriteBlobMSBLong(image,(unsigned int) image->rows);
  (void) WriteBlobMSBLong(image,(unsigned int) image->columns);
  if (IsGrayImage(image,&image->exception) != MagickFalse)
    {
      MagickBooleanType
        monochrome;

      /*
        Write depth & mode.
      */
      monochrome=IsMonochromeImage(image,&image->exception) &&
        (image->depth == 1) ? MagickTrue : MagickFalse;
      (void) WriteBlobMSBShort(image,(unsigned short)
        (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
      (void) WriteBlobMSBShort(image,(unsigned short)
        (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
    }
  else
    {
      (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
        PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
      if (((image_info->colorspace != UndefinedColorspace) ||
           (image->colorspace != CMYKColorspace)) &&
          (image_info->colorspace != CMYKColorspace))
        {
          (void) TransformImageColorspace(image,sRGBColorspace);
          (void) WriteBlobMSBShort(image,(unsigned short)
            (image->storage_class == PseudoClass ? IndexedMode : RGBMode));
        }
      else
        {
          if (image->colorspace != CMYKColorspace)
            (void) TransformImageColorspace(image,CMYKColorspace);
          (void) WriteBlobMSBShort(image,CMYKMode);
        }
    }
  if ((IsGrayImage(image,&image->exception) != MagickFalse) ||
      (image->storage_class == DirectClass) || (image->colors > 256))
    (void) WriteBlobMSBLong(image,0);
  else
    {
      /*
        Write PSD raster colormap.
      */
      (void) WriteBlobMSBLong(image,768);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(
          image->colormap[i].green));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
    }
  /*
    Image resource block.
  */
  length=28; /* 0x03EB */
  bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
  icc_profile=GetImageProfile(image,"icc");
  if (bim_profile != (StringInfo *) NULL)
    {
      bim_profile=CloneStringInfo(bim_profile);
      if (icc_profile != (StringInfo *) NULL)
        RemoveICCProfileFromResourceBlock(bim_profile);
      RemoveResolutionFromResourceBlock(bim_profile);
      length+=PSDQuantum(GetStringInfoLength(bim_profile));
    }
  if (icc_profile != (const StringInfo *) NULL)
    length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
  (void) WriteBlobMSBLong(image,(unsigned int) length);
  WriteResolutionResourceBlock(image);
  if (bim_profile != (StringInfo *) NULL)
    {
      (void) WriteBlob(image,GetStringInfoLength(bim_profile),
        GetStringInfoDatum(bim_profile));
      bim_profile=DestroyStringInfo(bim_profile);
    }
  if (icc_profile != (StringInfo *) NULL)
    {
      (void) WriteBlob(image,4,(const unsigned char *) "8BIM");
      (void) WriteBlobMSBShort(image,0x0000040F);
      (void) WriteBlobMSBShort(image,0);
      (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
        icc_profile));
      (void) WriteBlob(image,GetStringInfoLength(icc_profile),
        GetStringInfoDatum(icc_profile));
      if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
          PSDQuantum(GetStringInfoLength(icc_profile)))
        (void) WriteBlobByte(image,0);
    }
  base_image=GetNextImageInList(image);
  if (base_image == (Image *)NULL)
    base_image=image;
  size=0;
  size_offset=TellBlob(image);
  SetPSDSize(&psd_info,image,0);
  SetPSDSize(&psd_info,image,0);
  layer_count=0;
  for (next_image=base_image; next_image != NULL; )
  {
    layer_count++;
    next_image=GetNextImageInList(next_image);
  }
  if (image->matte != MagickFalse)
    size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);
  else
    size+=WriteBlobMSBShort(image,(unsigned short) layer_count);
  layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
    (size_t) layer_count,sizeof(MagickOffsetType));
  if (layer_size_offsets == (MagickOffsetType *) NULL)
    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
  layer_index=0;
  for (next_image=base_image; next_image != NULL; )
  {
    Image
      *mask;

    unsigned char
      default_color;

    unsigned short
      channels,
      total_channels;

    mask=(Image *) NULL;
    property=GetImageArtifact(next_image,"psd:opacity-mask");
    default_color=0;
    if (property != (const char *) NULL)
      {
        mask=(Image *) GetImageRegistry(ImageRegistryType,property,
          &image->exception);
        default_color=strlen(property) == 9 ? 255 : 0;
      }
    size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
    size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
    size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
      next_image->rows));
    size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
      next_image->columns));
    channels=1U;
    if ((next_image->storage_class != PseudoClass) &&
        (IsGrayImage(next_image,&next_image->exception) == MagickFalse))
      channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
    total_channels=channels;
    if (next_image->matte != MagickFalse)
      total_channels++;
    if (mask != (Image *) NULL)
      total_channels++;
    size+=WriteBlobMSBShort(image,total_channels);
    layer_size_offsets[layer_index++]=TellBlob(image);
    for (i=0; i < (ssize_t) channels; i++)
      size+=WriteChannelSize(&psd_info,image,(signed short) i);
    if (next_image->matte != MagickFalse)
      size+=WriteChannelSize(&psd_info,image,-1);
    if (mask != (Image *) NULL)
      size+=WriteChannelSize(&psd_info,image,-2);
    size+=WriteBlob(image,4,(const unsigned char *) "8BIM");
    size+=WriteBlob(image,4,(const unsigned char *)
      CompositeOperatorToPSDBlendMode(next_image->compose));
    property=GetImageArtifact(next_image,"psd:layer.opacity");
    if (property != (const char *) NULL)
      {
        Quantum
          opacity;

        opacity=(Quantum) StringToInteger(property);
        size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
        (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,
          &image->exception);
      }
    else
      size+=WriteBlobByte(image,255);
    size+=WriteBlobByte(image,0);
    size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
      1 << 0x02 : 1); /* layer properties - visible, etc. */
    size+=WriteBlobByte(image,0);
    info=GetAdditionalInformation(image_info,next_image);
    property=(const char *) GetImageProperty(next_image,"label");
    if (property == (const char *) NULL)
      {
        (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g",
          (double) layer_index);
        property=layer_name;
      }
    name_length=strlen(property)+1;
    if ((name_length % 4) != 0)
      name_length+=(4-(name_length % 4));
    if (info != (const StringInfo *) NULL)
      name_length+=GetStringInfoLength(info);
    name_length+=8;
    if (mask != (Image *) NULL)
      name_length+=20;
    size+=WriteBlobMSBLong(image,(unsigned int) name_length);
    if (mask == (Image *) NULL)
      size+=WriteBlobMSBLong(image,0);
    else
      {
        if (mask->compose != NoCompositeOp)
          (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
            default_color),MagickTrue,&image->exception);
        mask->page.y+=image->page.y;
        mask->page.x+=image->page.x;
        size+=WriteBlobMSBLong(image,20);
        size+=WriteBlobMSBSignedLong(image,mask->page.y);
        size+=WriteBlobMSBSignedLong(image,mask->page.x);
        size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+
          mask->page.y);
        size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+
          mask->page.x);
        size+=WriteBlobByte(image,default_color);
        size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
        size+=WriteBlobMSBShort(image,0);
      }
    size+=WriteBlobMSBLong(image,0);
    size+=WritePascalString(image,property,4);
    if (info != (const StringInfo *) NULL)
      size+=WriteBlob(image,GetStringInfoLength(info),
        GetStringInfoDatum(info));
    next_image=GetNextImageInList(next_image);
  }
  /*
    Now the image data!
  */
  next_image=base_image;
  layer_index=0;
  while (next_image != NULL)
  {
    length=WritePSDChannels(&psd_info,image_info,image,next_image,
      layer_size_offsets[layer_index++],MagickTrue);
    if (length == 0)
      {
        status=MagickFalse;
        break;
      }
    size+=length;
    next_image=GetNextImageInList(next_image);
  }
  (void) WriteBlobMSBLong(image,0);  /* user mask data */
  /*
    Remove the opacity mask from the registry
  */
  next_image=base_image;
  while (next_image != (Image *) NULL)
  {
    property=GetImageArtifact(next_image,"psd:opacity-mask");
    if (property != (const char *) NULL)
      DeleteImageRegistry(property);
    next_image=GetNextImageInList(next_image);
  }
  /*
    Write the total size
  */
  size_offset+=WritePSDSize(&psd_info,image,size+
    (psd_info.version == 1 ? 8 : 16),size_offset);
  if ((size/2) != ((size+1)/2))
    rounded_size=size+1;
  else
    rounded_size=size;
  (void) WritePSDSize(&psd_info,image,rounded_size,size_offset);
  layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
    layer_size_offsets);
  /*
    Write composite image.
  */
  if (status != MagickFalse)
    {
      CompressionType
        compression;

      compression=image->compression;
      if (image->compression == ZipCompression)
        image->compression=RLECompression;
      if (WritePSDChannels(&psd_info,image_info,image,image,0,
          MagickFalse) == 0)
        status=MagickFalse;
      image->compression=compression;
    }
  (void) CloseBlob(image);
  return(status);
}


static int allocate_cmdlines_buffer(unsigned int val,
				    struct saved_cmdlines_buffer *s)
{
	s->map_cmdline_to_pid = kmalloc_array(val,
					      sizeof(*s->map_cmdline_to_pid),
					      GFP_KERNEL);
	if (!s->map_cmdline_to_pid)
		return -ENOMEM;

	s->saved_cmdlines = kmalloc_array(TASK_COMM_LEN, val, GFP_KERNEL);
	if (!s->saved_cmdlines) {
		kfree(s->map_cmdline_to_pid);
		return -ENOMEM;
	}

	s->cmdline_idx = 0;
	s->cmdline_num = val;
	memset(&s->map_pid_to_cmdline, NO_CMDLINE_MAP,
	       sizeof(s->map_pid_to_cmdline));
	memset(s->map_cmdline_to_pid, NO_CMDLINE_MAP,
	       val * sizeof(*s->map_cmdline_to_pid));

	return 0;
}


PaintLayerScrollableArea::GetCompositorAnimationTimeline() const {
  return layer_->GetLayoutObject()
      .GetFrameView()
      ->GetCompositorAnimationTimeline();
}


SPL_METHOD(Array, getArrayCopy)
{
	zval *object = getThis(), *tmp;
	spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);

    array_init(return_value);
	zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*));
} /* }}} */

static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */


static void dec_sru(DisasContext *dc)

{

    if (dc->format == OP_FMT_RI) {

        LOG_DIS("srui r%d, r%d, %d\n", dc->r1, dc->r0, dc->imm5);

    } else {

        LOG_DIS("sru r%d, r%d, r%d\n", dc->r2, dc->r0, dc->r1);

    }

    if (!(dc->env->features & LM32_FEATURE_SHIFT)) {

        if (dc->format == OP_FMT_RI) {

            /* TODO: check r1 == 1 during runtime */

        } else {

            if (dc->imm5 != 1) {

                cpu_abort(dc->env, "hardware shifter is not available\n");

            }

        }

    }

    if (dc->format == OP_FMT_RI) {

        tcg_gen_shri_tl(cpu_R[dc->r1], cpu_R[dc->r0], dc->imm5);

    } else {

        TCGv t0 = tcg_temp_new();

        tcg_gen_andi_tl(t0, cpu_R[dc->r1], 0x1f);

        tcg_gen_shr_tl(cpu_R[dc->r2], cpu_R[dc->r0], t0);

        tcg_temp_free(t0);

    }

}


flatpak_dir_get_remote_install_authenticator_name (FlatpakDir *self,
                                                   const char *remote_name)
{
  GKeyFile *config = flatpak_dir_get_repo_config (self);
  g_autofree char *group = get_group (remote_name);

  if (config == NULL ||
      !g_key_file_get_boolean (config, group, "xa.authenticator-install", NULL))
    return NULL;

  return g_key_file_get_string (config, group, "xa.authenticator-name", NULL);
}


  void getReadBuffer(void** bufReturn, size_t* lenReturn) override {
    *bufReturn = nullptr;
    *lenReturn = 0;
  }


bool IntegrationCodecClient::waitForDisconnect(std::chrono::milliseconds time_to_wait) {
  Event::TimerPtr wait_timer;
  bool wait_timer_triggered = false;
  if (time_to_wait.count()) {
    wait_timer = connection_->dispatcher().createTimer([this, &wait_timer_triggered] {
      connection_->dispatcher().exit();
      wait_timer_triggered = true;
    });
    wait_timer->enableTimer(time_to_wait);
  }

  connection_->dispatcher().run(Event::Dispatcher::RunType::Block);

  // Disable the timer if it was created. This call is harmless if the timer already triggered.
  if (wait_timer) {
    wait_timer->disableTimer();
  }

  if (wait_timer_triggered && !disconnected_) {
    return false;
  }
  EXPECT_TRUE(disconnected_);

  return true;
}


nfa_regcomp_start(
    char_u	*expr,
    int		re_flags)	    // see vim_regcomp()
{
    size_t	postfix_size;
    int		nstate_max;

    nstate = 0;
    istate = 0;
    // A reasonable estimation for maximum size
    nstate_max = (int)(STRLEN(expr) + 1) * 25;

    // Some items blow up in size, such as [A-z].  Add more space for that.
    // When it is still not enough realloc_post_list() will be used.
    nstate_max += 1000;

    // Size for postfix representation of expr.
    postfix_size = sizeof(int) * nstate_max;

    post_start = alloc(postfix_size);
    if (post_start == NULL)
	return FAIL;
    post_ptr = post_start;
    post_end = post_start + nstate_max;
    wants_nfa = FALSE;
    rex.nfa_has_zend = FALSE;
    rex.nfa_has_backref = FALSE;

    // shared with BT engine
    regcomp_start(expr, re_flags);

    return OK;
}


gopherReadReply(const Comm::ConnectionPointer &conn, char *buf, size_t len, Comm::Flag flag, int xerrno, void *data)
{
    GopherStateData *gopherState = (GopherStateData *)data;
    StoreEntry *entry = gopherState->entry;
    int clen;
    int bin;
    size_t read_sz = BUFSIZ;
#if USE_DELAY_POOLS
    DelayId delayId = entry->mem_obj->mostBytesAllowed();
#endif

    /* Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us */

    if (flag == Comm::ERR_CLOSING) {
        return;
    }

    assert(buf == gopherState->replybuf);

    // XXX: Should update delayId, statCounter, etc. before bailing
    if (!entry->isAccepting()) {
        debugs(10, 3, "terminating due to bad " << *entry);
        // TODO: Do not abuse connection for triggering cleanup.
        gopherState->serverConn->close();
        return;
    }

#if USE_DELAY_POOLS
    read_sz = delayId.bytesWanted(1, read_sz);
#endif

    /* leave one space for \0 in gopherToHTML */

    if (flag == Comm::OK && len > 0) {
#if USE_DELAY_POOLS
        delayId.bytesIn(len);
#endif

        statCounter.server.all.kbytes_in += len;
        statCounter.server.other.kbytes_in += len;
    }

    debugs(10, 5, conn << " read len=" << len);

    if (flag == Comm::OK && len > 0) {
        AsyncCall::Pointer nil;
        commSetConnTimeout(conn, Config.Timeout.read, nil);
        ++IOStats.Gopher.reads;

        for (clen = len - 1, bin = 0; clen; ++bin)
            clen >>= 1;

        ++IOStats.Gopher.read_hist[bin];

        HttpRequest *req = gopherState->fwd->request;
        if (req->hier.bodyBytesRead < 0) {
            req->hier.bodyBytesRead = 0;
            // first bytes read, update Reply flags:
            gopherState->reply_->sources |= Http::Message::srcGopher;
        }

        req->hier.bodyBytesRead += len;
    }

    if (flag != Comm::OK) {
        debugs(50, DBG_IMPORTANT, "ERROR: " << MYNAME << "reading: " << xstrerr(xerrno));

        if (ignoreErrno(xerrno)) {
            AsyncCall::Pointer call = commCbCall(5,4, "gopherReadReply",
                                                 CommIoCbPtrFun(gopherReadReply, gopherState));
            comm_read(conn, buf, read_sz, call);
        } else {
            const auto err = new ErrorState(ERR_READ_ERROR, Http::scInternalServerError, gopherState->fwd->request, gopherState->fwd->al);
            err->xerrno = xerrno;
            gopherState->fwd->fail(err);
            gopherState->serverConn->close();
        }
    } else if (len == 0 && entry->isEmpty()) {
        gopherState->fwd->fail(new ErrorState(ERR_ZERO_SIZE_OBJECT, Http::scServiceUnavailable, gopherState->fwd->request, gopherState->fwd->al));
        gopherState->serverConn->close();
    } else if (len == 0) {
        /* Connection closed; retrieval done. */
        /* flush the rest of data in temp buf if there is one. */

        if (gopherState->conversion != GopherStateData::NORMAL)
            gopherEndHTML(gopherState);

        entry->timestampsSet();
        entry->flush();

        if (!gopherState->len && !gopherState->overflowed)
            gopherState->fwd->markStoredReplyAsWhole("gopher EOF after receiving/storing some bytes");

        gopherState->fwd->complete();
        gopherState->serverConn->close();
    } else {
        if (gopherState->conversion != GopherStateData::NORMAL) {
            gopherToHTML(gopherState, buf, len);
        } else {
            entry->append(buf, len);
        }
        AsyncCall::Pointer call = commCbCall(5,4, "gopherReadReply",
                                             CommIoCbPtrFun(gopherReadReply, gopherState));
        comm_read(conn, buf, read_sz, call);
    }
}


bool AccessibilityUIElement::isEnabled()
{
    return checkElementState(m_element, ATK_STATE_ENABLED);
}


static inline void writer_print_section_footer(WriterContext *wctx)
{
    int section_id = wctx->section[wctx->level]->id;
    int parent_section_id = wctx->level ?
        wctx->section[wctx->level-1]->id : SECTION_ID_NONE;

    if (parent_section_id != SECTION_ID_NONE)
        wctx->nb_item[wctx->level-1]++;
    if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
        if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
        else                                     wctx->nb_section_frame++;
    }
    if (wctx->writer->print_section_footer)
        wctx->writer->print_section_footer(wctx);
    wctx->level--;
}


static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno)
{
        const OPJ_CHAR *prog = 00;
        OPJ_INT32 i;
        OPJ_UINT32 tpnum = 1;
        opj_tcp_t *tcp = 00;
        opj_poc_t * l_current_poc = 00;

        /*  preconditions */
        assert(tileno < (cp->tw * cp->th));
        assert(pino < (cp->tcps[tileno].numpocs + 1));

        /* get the given tile coding parameter */
        tcp = &cp->tcps[tileno];
        assert(tcp != 00);

        l_current_poc = &(tcp->pocs[pino]);
        assert(l_current_poc != 0);

        /* get the progression order as a character string */
        prog = opj_j2k_convert_progression_order(tcp->prg);
        assert(strlen(prog) > 0);

        if (cp->m_specific_param.m_enc.m_tp_on == 1) {
                for (i=0;i<4;++i) {
                        switch (prog[i])
                        {
                                /* component wise */
                                case 'C':
                                        tpnum *= l_current_poc->compE;
                                        break;
                                /* resolution wise */
                                case 'R':
                                        tpnum *= l_current_poc->resE;
                                        break;
                                /* precinct wise */
                                case 'P':
                                        tpnum *= l_current_poc->prcE;
                                        break;
                                /* layer wise */
                                case 'L':
                                        tpnum *= l_current_poc->layE;
                                        break;
                        }
                        /* whould we split here ? */
                        if ( cp->m_specific_param.m_enc.m_tp_flag == prog[i] ) {
                                cp->m_specific_param.m_enc.m_tp_pos=i;
                                break;
                        }
                }
        }
        else {
                tpnum=1;
        }

        return tpnum;
}


static int getint(jas_stream_t *in, int sgnd, int prec, long *val)
{
	long v;
	int n;
	int c;
	assert((!sgnd && prec >= 1) || (sgnd && prec >= 2));
	n = (prec + 7) / 8;
	v = 0;
	while (--n >= 0) {
		if ((c = jas_stream_getc(in)) == EOF)
			return -1;
		v = (v << 8) | c;
	}
	v &= ((1 << prec) - 1);
	if (sgnd) {
		*val = decode_twos_comp(v, prec);
	} else {
		*val = v;
	}
	return 0;
}


static void taihu_405ep_init(ram_addr_t ram_size,

                             const char *boot_device,

                             const char *kernel_filename,

                             const char *kernel_cmdline,

                             const char *initrd_filename,

                             const char *cpu_model)

{

    char *filename;

    qemu_irq *pic;

    ram_addr_t bios_offset;

    target_phys_addr_t ram_bases[2], ram_sizes[2];

    long bios_size;

    target_ulong kernel_base, initrd_base;

    long kernel_size, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors;

    DriveInfo *dinfo;

    /* RAM is soldered to the board so the size cannot be changed */

    ram_bases[0] = qemu_ram_alloc(NULL, "taihu_405ep.ram-0", 0x04000000);

    ram_sizes[0] = 0x04000000;

    ram_bases[1] = qemu_ram_alloc(NULL, "taihu_405ep.ram-1", 0x04000000);

    ram_sizes[1] = 0x04000000;

    ram_size = 0x08000000;

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    ppc405ep_init(ram_bases, ram_sizes, 33333333, &pic,

                  kernel_filename == NULL ? 0 : 1);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#if defined(USE_FLASH_BIOS)

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 2MB */

        //        bios_size = 2 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", bios_size);

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at offset %08lx addr %lx '%s' %d\n",

               fl_idx, bios_size, bios_offset, -bios_size,

               bdrv_get_device_name(dinfo->bdrv), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size), bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", BIOS_SIZE);

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, qemu_get_ram_ptr(bios_offset));

        } else {

            bios_size = -1;

        }

        if (bios_size < 0 || bios_size > BIOS_SIZE) {

            fprintf(stderr, "qemu: could not load PowerPC bios '%s'\n",

                    bios_name);

            exit(1);

        }

        bios_size = (bios_size + 0xfff) & ~0xfff;

        cpu_register_physical_memory((uint32_t)(-bios_size),

                                     bios_size, bios_offset | IO_MEM_ROM);

    }

    /* Register Linux flash */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 32MB */

        bios_size = 32 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at offset %08lx  addr " TARGET_FMT_lx " '%s'\n",

               fl_idx, bios_size, bios_offset, (target_ulong)0xfc000000,

               bdrv_get_device_name(dinfo->bdrv));

#endif

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.flash", bios_size);

        pflash_cfi02_register(0xfc000000, bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    }

    /* Register CLPD & LCD display */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register CPLD\n", __func__);

#endif

    taihu_cpld_init(0x50100000);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr,

                        "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("%s: Done\n", __func__);

#endif

}


 JSValue JSDirectoryEntry::getDirectory(ExecState* exec)
 {
     if (exec->argumentCount() < 1)
        return throwError(exec, createTypeError(exec, "Not enough arguments"));

     DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
     const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
    if (exec->hadException())
        return jsUndefined();

    int argsCount = exec->argumentCount();
    if (argsCount <= 1) {
        imp->getDirectory(path);
        return jsUndefined();
    }

    RefPtr<WebKitFlags> flags;
    if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
        JSObject* object = exec->argument(1).getObject();
        flags = WebKitFlags::create();
        JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
        flags->setCreate(jsCreate.toBoolean(exec));
        JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
        flags->setExclusive(jsExclusive.toBoolean(exec));
    }
    if (exec->hadException())
        return jsUndefined();
    RefPtr<EntryCallback> successCallback;
    if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
        if (!exec->argument(2).isObject()) {
            setDOMException(exec, TYPE_MISMATCH_ERR);
            return jsUndefined();
        }
        successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
    }
    RefPtr<ErrorCallback> errorCallback;
    if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
        if (!exec->argument(3).isObject()) {
            setDOMException(exec, TYPE_MISMATCH_ERR);
            return jsUndefined();
        }
        errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
    }

    imp->getDirectory(path, flags, successCallback, errorCallback);
    return jsUndefined();
}


bool GetEnterpriseDomain(std::string* out_domain) {
  policy::BrowserPolicyConnectorChromeOS* policy_connector =
      g_browser_process->platform_part()->browser_policy_connector_chromeos();
  if (policy_connector->IsCloudManaged()) {
    *out_domain = policy_connector->GetEnterpriseDisplayDomain();
    return true;
  }
  return false;
}


bool SelectionController::HandleMousePressEvent(
    const MouseEventWithHitTestResults& event) {
  TRACE_EVENT0("blink", "SelectionController::handleMousePressEvent");

  mouse_down_may_start_select_ =
      (CanMouseDownStartSelect(event.InnerNode()) || IsLinkSelection(event)) &&
      !event.GetScrollbar();
  mouse_down_was_single_click_in_selection_ = false;
  if (!Selection().IsAvailable()) {
    mouse_down_allows_multi_click_ = !event.Event().FromTouch();
  } else {
    mouse_down_allows_multi_click_ =
        !event.Event().FromTouch() ||
        IsEditablePosition(
            Selection().ComputeVisibleSelectionInDOMTreeDeprecated().Start());
  }

  if (event.Event().click_count >= 3)
    return HandleTripleClick(event);
  if (event.Event().click_count == 2)
    return HandleDoubleClick(event);
  return HandleSingleClick(event);
}


static void perf_event_context_sched_in(struct perf_event_context *ctx,
					struct task_struct *task)
{
	struct perf_cpu_context *cpuctx;

	cpuctx = __get_cpu_context(ctx);
	if (cpuctx->task_ctx == ctx)
		return;

	perf_ctx_lock(cpuctx, ctx);
	perf_pmu_disable(ctx->pmu);
	/*
	 * We want to keep the following priority order:
	 * cpu pinned (that don't need to move), task pinned,
	 * cpu flexible, task flexible.
	 */
	cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
	perf_event_sched_in(cpuctx, ctx, task);
	perf_pmu_enable(ctx->pmu);
	perf_ctx_unlock(cpuctx, ctx);
}


static void schedule_bh(void (*handler)(void))
{
	WARN_ON(work_pending(&floppy_work));

	floppy_work_fn = handler;
	queue_work(floppy_wq, &floppy_work);
}


int32_t nghttp2_session_get_stream_local_window_size(nghttp2_session *session,
                                                     int32_t stream_id) {
  nghttp2_stream *stream;
  int32_t size;
  stream = nghttp2_session_get_stream(session, stream_id);
  if (stream == NULL) {
    return -1;
  }

  size = stream->local_window_size - stream->recv_window_size;

  /* size could be negative if local endpoint reduced
     SETTINGS_INITIAL_WINDOW_SIZE */
  if (size < 0) {
    return 0;
  }

  return size;
}


GF_SceneDumper *gf_sm_dumper_new(GF_SceneGraph *graph, char *_rad_name, Bool is_final_name, char indent_char, GF_SceneDumpFormat dump_mode)
{
	GF_SceneDumper *tmp;
	if (!graph) return NULL;
	GF_SAFEALLOC(tmp, GF_SceneDumper);
	if (!tmp) return NULL;

	/*store original*/
	tmp->dump_mode = dump_mode;

#ifndef GPAC_DISABLE_SVG
	if ((graph->RootNode && (graph->RootNode->sgprivate->tag>=GF_NODE_RANGE_LAST_VRML) )
	        || (dump_mode==GF_SM_DUMP_LASER) || (dump_mode==GF_SM_DUMP_SVG)) {
		tmp->XMLDump = GF_TRUE;
		if (dump_mode==GF_SM_DUMP_LASER) {
			tmp->LSRDump = GF_TRUE;
		}
		if (_rad_name) {
			const char* ext_name = tmp->LSRDump ? ".xsr" : ".svg";
			tmp->filename = (char *)gf_malloc(strlen(_rad_name) + strlen(ext_name) + 1);
			strcpy(tmp->filename, _rad_name);
			if (!is_final_name) strcat(tmp->filename, ext_name);
			tmp->trace = gf_fopen(tmp->filename, "wt");
			if (!tmp->trace) {
				gf_free(tmp);
				return NULL;
			}
		} else {
			tmp->trace = stdout;
		}
	} else
#endif
	{

		if (dump_mode==GF_SM_DUMP_AUTO_TXT) {
			if (!graph->RootNode || (graph->RootNode->sgprivate->tag<=GF_NODE_RANGE_LAST_MPEG4) ) {
				dump_mode = GF_SM_DUMP_BT;
			} else if (graph->RootNode->sgprivate->tag<=GF_NODE_RANGE_LAST_X3D) {
				dump_mode = GF_SM_DUMP_X3D_VRML;
			}
		}
		else if (dump_mode==GF_SM_DUMP_AUTO_XML) {
			if (!graph->RootNode || (graph->RootNode->sgprivate->tag<=GF_NODE_RANGE_LAST_MPEG4) ) {
				dump_mode = GF_SM_DUMP_XMTA;
			} else {
				dump_mode = GF_SM_DUMP_X3D_XML;
			}
		}

		if (_rad_name) {
			const char* ext_name;
			switch (dump_mode) {
			case GF_SM_DUMP_X3D_XML:
				ext_name = ".x3d";
				tmp->XMLDump = GF_TRUE;
				tmp->X3DDump = GF_TRUE;
				break;
			case GF_SM_DUMP_XMTA:
				ext_name = ".xmt";
				tmp->XMLDump = GF_TRUE;
				break;
			case GF_SM_DUMP_X3D_VRML:
				ext_name = ".x3dv";
				tmp->X3DDump = GF_TRUE;
				break;
			case GF_SM_DUMP_VRML:
				ext_name = ".wrl";
				break;
			default:
				ext_name = ".bt";
				break;
			}

			tmp->filename = (char *)gf_malloc(strlen(_rad_name ? _rad_name : "") + strlen(ext_name) + 1);
			strcpy(tmp->filename, _rad_name ? _rad_name : "");
			if (!is_final_name) strcat(tmp->filename, ext_name);
			tmp->trace = gf_fopen(tmp->filename, "wt");
			if (!tmp->trace) {
				gf_free(tmp);
				return NULL;
			}
		} else {
			tmp->trace = stdout;
			switch (dump_mode) {
			case GF_SM_DUMP_X3D_XML:
				tmp->XMLDump = GF_TRUE;
				tmp->X3DDump = GF_TRUE;
				break;
			case GF_SM_DUMP_XMTA:
				tmp->XMLDump = GF_TRUE;
				break;
			case GF_SM_DUMP_X3D_VRML:
				tmp->X3DDump = GF_TRUE;
				break;
			default:
				break;
			}
		}
	}
	tmp->ind_char = indent_char;
	tmp->dump_nodes = gf_list_new();
	tmp->mem_def_nodes = gf_list_new();
	tmp->inserted_routes = gf_list_new();
	tmp->sg = graph;
	return tmp;
}


static void scrub_missing_raid56_pages(struct scrub_block *sblock)
{
	struct scrub_ctx *sctx = sblock->sctx;
	struct btrfs_fs_info *fs_info = sctx->fs_info;
	u64 length = sblock->page_count * PAGE_SIZE;
	u64 logical = sblock->pagev[0]->logical;
	struct btrfs_bio *bbio = NULL;
	struct bio *bio;
	struct btrfs_raid_bio *rbio;
	int ret;
	int i;

	btrfs_bio_counter_inc_blocked(fs_info);
	ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
			&length, &bbio);
	if (ret || !bbio || !bbio->raid_map)
		goto bbio_out;

	if (WARN_ON(!sctx->is_dev_replace ||
		    !(bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK))) {
		/*
		 * We shouldn't be scrubbing a missing device. Even for dev
		 * replace, we should only get here for RAID 5/6. We either
		 * managed to mount something with no mirrors remaining or
		 * there's a bug in scrub_remap_extent()/btrfs_map_block().
		 */
		goto bbio_out;
	}

	bio = btrfs_io_bio_alloc(0);
	bio->bi_iter.bi_sector = logical >> 9;
	bio->bi_private = sblock;
	bio->bi_end_io = scrub_missing_raid56_end_io;

	rbio = raid56_alloc_missing_rbio(fs_info, bio, bbio, length);
	if (!rbio)
		goto rbio_out;

	for (i = 0; i < sblock->page_count; i++) {
		struct scrub_page *spage = sblock->pagev[i];

		raid56_add_scrub_pages(rbio, spage->page, spage->logical);
	}

	btrfs_init_work(&sblock->work, btrfs_scrub_helper,
			scrub_missing_raid56_worker, NULL, NULL);
	scrub_block_get(sblock);
	scrub_pending_bio_inc(sctx);
	raid56_submit_missing_rbio(rbio);
	return;

rbio_out:
	bio_put(bio);
bbio_out:
	btrfs_bio_counter_dec(fs_info);
	btrfs_put_bbio(bbio);
	spin_lock(&sctx->stat_lock);
	sctx->stat.malloc_errors++;
	spin_unlock(&sctx->stat_lock);
}


MigrationState *exec_start_outgoing_migration(const char *command,

                                             int64_t bandwidth_limit,

                                             int async)

{

    FdMigrationState *s;

    FILE *f;

    s = qemu_mallocz(sizeof(*s));

    if (s == NULL) {

        dprintf("Unable to allocate FdMigrationState\n");

        goto err;

    }

    f = popen(command, "w");

    if (f == NULL) {

        dprintf("Unable to popen exec target\n");

        goto err_after_alloc;

    }

    s->fd = fileno(f);

    if (s->fd == -1) {

        dprintf("Unable to retrieve file descriptor for popen'd handle\n");

        goto err_after_open;

    }

    if (fcntl(s->fd, F_SETFD, O_NONBLOCK) == -1) {

        dprintf("Unable to set nonblocking mode on file descriptor\n");

        goto err_after_open;

    }

    s->opaque = qemu_popen(f, "w");

    s->get_error = file_errno;

    s->write = file_write;

    s->mig_state.cancel = migrate_fd_cancel;

    s->mig_state.get_status = migrate_fd_get_status;

    s->mig_state.release = migrate_fd_release;

    s->state = MIG_STATE_ACTIVE;

    s->detach = !async;

    s->bandwidth_limit = bandwidth_limit;

    if (s->detach == 1) {

        dprintf("detaching from monitor\n");

        monitor_suspend();

        s->detach = 2;

    }

    migrate_fd_connect(s);

    return &s->mig_state;

err_after_open:

    pclose(f);

err_after_alloc:

    qemu_free(s);

err:

    return NULL;

}


_dbus_header_create (DBusHeader  *header,
                     int          message_type,
                     const char  *destination,
                     const char  *path,
                     const char  *interface,
                     const char  *member,
                     const char  *error_name)
{
  unsigned char v_BYTE;
  dbus_uint32_t v_UINT32;
  DBusTypeWriter writer;
  DBusTypeWriter array;

  _dbus_assert (((interface || message_type != DBUS_MESSAGE_TYPE_SIGNAL) && member) ||
                (error_name) ||
                !(interface || member || error_name));
  _dbus_assert (_dbus_string_get_length (&header->data) == 0);

  if (!reserve_header_padding (header))
    return FALSE;

  _dbus_type_writer_init_values_only (&writer, header->byte_order,
                                      &_dbus_header_signature_str, 0,
                                      &header->data,
                                      HEADER_END_BEFORE_PADDING (header));

  v_BYTE = header->byte_order;
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_BYTE,
                                      &v_BYTE))
    goto oom;

  v_BYTE = message_type;
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_BYTE,
                                      &v_BYTE))
    goto oom;

  v_BYTE = 0; /* flags */
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_BYTE,
                                      &v_BYTE))
    goto oom;

  v_BYTE = DBUS_MAJOR_PROTOCOL_VERSION;
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_BYTE,
                                      &v_BYTE))
    goto oom;

  v_UINT32 = 0; /* body length */
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_UINT32,
                                      &v_UINT32))
    goto oom;

  v_UINT32 = 0; /* serial */
  if (!_dbus_type_writer_write_basic (&writer, DBUS_TYPE_UINT32,
                                      &v_UINT32))
    goto oom;

  if (!_dbus_type_writer_recurse (&writer, DBUS_TYPE_ARRAY,
                                  &_dbus_header_signature_str,
                                  FIELDS_ARRAY_SIGNATURE_OFFSET,
                                  &array))
    goto oom;

  /* Marshal all the fields (Marshall Fields?) */

  if (path != NULL)
    {
      if (!write_basic_field (&array,
                              DBUS_HEADER_FIELD_PATH,
                              DBUS_TYPE_OBJECT_PATH,
                              &path))
        goto oom;
    }

  if (destination != NULL)
    {
      if (!write_basic_field (&array,
                              DBUS_HEADER_FIELD_DESTINATION,
                              DBUS_TYPE_STRING,
                              &destination))
        goto oom;
    }

  if (interface != NULL)
    {
      if (!write_basic_field (&array,
                              DBUS_HEADER_FIELD_INTERFACE,
                              DBUS_TYPE_STRING,
                              &interface))
        goto oom;
    }

  if (member != NULL)
    {
      if (!write_basic_field (&array,
                              DBUS_HEADER_FIELD_MEMBER,
                              DBUS_TYPE_STRING,
                              &member))
        goto oom;
    }

  if (error_name != NULL)
    {
      if (!write_basic_field (&array,
                              DBUS_HEADER_FIELD_ERROR_NAME,
                              DBUS_TYPE_STRING,
                              &error_name))
        goto oom;
    }

  if (!_dbus_type_writer_unrecurse (&writer, &array))
    goto oom;

  correct_header_padding (header);

  return TRUE;

 oom:
  _dbus_string_delete (&header->data, 0,
                       _dbus_string_get_length (&header->data) - header->padding);
  correct_header_padding (header);

  return FALSE;
}


static void *ion_handle_kmap_get(struct ion_handle *handle)
{
	struct ion_buffer *buffer = handle->buffer;
	void *vaddr;

	if (handle->kmap_cnt) {
		handle->kmap_cnt++;
		return buffer->vaddr;
	}
	vaddr = ion_buffer_kmap_get(buffer);
	if (IS_ERR(vaddr))
		return vaddr;
	handle->kmap_cnt++;
	return vaddr;
}


void MimeHandlerViewContainer::DidResizeElement(const gfx::Size& new_size) {
  element_size_ = new_size;

  CreateMimeHandlerViewGuestIfNecessary();

  if (!guest_created_)
    return;

  render_frame()->Send(new ExtensionsGuestViewHostMsg_ResizeGuest(
      render_frame()->GetRoutingID(), element_instance_id(), new_size));
}


int get_osversion(void)

{

    static int osversion;

    struct new_utsname buf;

    const char *s;

    int i, n, tmp;

    if (osversion)

        return osversion;

    if (qemu_uname_release && *qemu_uname_release) {

        s = qemu_uname_release;

    } else {

        if (sys_uname(&buf))

            return 0;

        s = buf.release;

    }

    tmp = 0;

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

        n = 0;

        while (*s >= '0' && *s <= '9') {

            n *= 10;

            n += *s - '0';

            s++;

        }

        tmp = (tmp << 8) + n;

        if (*s == '.')

            s++;

    }

    osversion = tmp;

    return osversion;

}


static int ref_pkt(git_pkt **out, const char *line, size_t len)
{
	int error;
	git_pkt_ref *pkt;
	size_t alloclen;

	pkt = git__malloc(sizeof(git_pkt_ref));
	GITERR_CHECK_ALLOC(pkt);

	memset(pkt, 0x0, sizeof(git_pkt_ref));
	pkt->type = GIT_PKT_REF;
	if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0)
		goto error_out;

	/* Check for a bit of consistency */
	if (line[GIT_OID_HEXSZ] != ' ') {
		giterr_set(GITERR_NET, "Error parsing pkt-line");
		error = -1;
		goto error_out;
	}

	/* Jump from the name */
	line += GIT_OID_HEXSZ + 1;
	len -= (GIT_OID_HEXSZ + 1);

	if (line[len - 1] == '\n')
		--len;

	GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
	pkt->head.name = git__malloc(alloclen);
	GITERR_CHECK_ALLOC(pkt->head.name);

	memcpy(pkt->head.name, line, len);
	pkt->head.name[len] = '\0';

	if (strlen(pkt->head.name) < len) {
		pkt->capabilities = strchr(pkt->head.name, '\0') + 1;
	}

	*out = (git_pkt *)pkt;
	return 0;

error_out:
	git__free(pkt);
	return error;
}


static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
{
	u64 num_dev;

	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
	if (!num_dev)
		num_dev = fs_info->fs_devices->rw_devices;

	return num_dev;
}


migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
	int cpu = (long)hcpu;
	unsigned long flags;
	struct rq *rq = cpu_rq(cpu);

	switch (action) {

	case CPU_UP_PREPARE:
	case CPU_UP_PREPARE_FROZEN:
		rq->calc_load_update = calc_load_update;
		break;

	case CPU_ONLINE:
	case CPU_ONLINE_FROZEN:
		/* Update our root-domain */
		raw_spin_lock_irqsave(&rq->lock, flags);
		if (rq->rd) {
			BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));

			set_rq_online(rq);
		}
		raw_spin_unlock_irqrestore(&rq->lock, flags);
		break;

#ifdef CONFIG_HOTPLUG_CPU
	case CPU_DEAD:
	case CPU_DEAD_FROZEN:
		migrate_live_tasks(cpu);
		/* Idle task back to normal (off runqueue, low prio) */
		raw_spin_lock_irq(&rq->lock);
		deactivate_task(rq, rq->idle, 0);
		__setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
		rq->idle->sched_class = &idle_sched_class;
		migrate_dead_tasks(cpu);
		raw_spin_unlock_irq(&rq->lock);
		migrate_nr_uninterruptible(rq);
		BUG_ON(rq->nr_running != 0);
		calc_global_load_remove(rq);
		break;

	case CPU_DYING:
	case CPU_DYING_FROZEN:
		/* Update our root-domain */
		raw_spin_lock_irqsave(&rq->lock, flags);
		if (rq->rd) {
			BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
			set_rq_offline(rq);
		}
		raw_spin_unlock_irqrestore(&rq->lock, flags);
		break;
#endif
	}
	return NOTIFY_OK;
}


static int nfs4_get_referral(struct inode *dir, const struct qstr *name,
			     struct nfs_fattr *fattr, struct nfs_fh *fhandle)
{
	int status = -ENOMEM;
	struct page *page = NULL;
	struct nfs4_fs_locations *locations = NULL;

	page = alloc_page(GFP_KERNEL);
	if (page == NULL)
		goto out;
	locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
	if (locations == NULL)
		goto out;

	status = nfs4_proc_fs_locations(dir, name, locations, page);
	if (status != 0)
		goto out;
	/* Make sure server returned a different fsid for the referral */
	if (nfs_fsid_equal(&NFS_SERVER(dir)->fsid, &locations->fattr.fsid)) {
		dprintk("%s: server did not return a different fsid for"
			" a referral at %s\n", __func__, name->name);
		status = -EIO;
		goto out;
	}
	/* Fixup attributes for the nfs_lookup() call to nfs_fhget() */
	nfs_fixup_referral_attributes(&locations->fattr);

	/* replace the lookup nfs_fattr with the locations nfs_fattr */
	memcpy(fattr, &locations->fattr, sizeof(struct nfs_fattr));
	memset(fhandle, 0, sizeof(struct nfs_fh));
out:
	if (page)
		__free_page(page);
	kfree(locations);
	return status;
}


static void dvcman_channel_free(void* arg)
{
	DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*) arg;
	UINT error = CHANNEL_RC_OK;

	if (channel)
	{
		if (channel->channel_callback)
		{
			IFCALL(channel->channel_callback->OnClose,
			       channel->channel_callback);
		}

		if (channel->status == CHANNEL_RC_OK)
		{
			IWTSVirtualChannel* ichannel = (IWTSVirtualChannel*) channel;

			if (channel->dvcman && channel->dvcman->drdynvc)
			{
				DrdynvcClientContext* context = channel->dvcman->drdynvc->context;

				if (context)
				{
					IFCALLRET(context->OnChannelDisconnected, error,
					          context, channel->channel_name,
					          channel->pInterface);
				}
			}

			error = IFCALLRESULT(CHANNEL_RC_OK, ichannel->Close, ichannel);

			if (error != CHANNEL_RC_OK)
				WLog_ERR(TAG, "Close failed with error %"PRIu32"!", error);
		}

		if (channel->dvc_data)
			Stream_Release(channel->dvc_data);

		DeleteCriticalSection(&(channel->lock));
		free(channel->channel_name);
	}

	free(channel);
}