ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
xfs_end_io_direct_write(
	struct kiocb		*iocb,
	loff_t			offset,
	ssize_t			size,
	void			*private)
{
	struct inode		*inode = file_inode(iocb->ki_filp);
	struct xfs_inode	*ip = XFS_I(inode);
	uintptr_t		flags = (uintptr_t)private;
	int			error = 0;

	trace_xfs_end_io_direct_write(ip, offset, size);

	if (XFS_FORCED_SHUTDOWN(ip->i_mount))
		return -EIO;

	if (size <= 0)
		return size;

	/*
	 * The flags tell us whether we are doing unwritten extent conversions
	 * or an append transaction that updates the on-disk file size. These
	 * cases are the only cases where we should *potentially* be needing
	 * to update the VFS inode size.
	 */
	if (flags == 0) {
		ASSERT(offset + size <= i_size_read(inode));
		return 0;
	}

	/*
	 * We need to update the in-core inode size here so that we don't end up
	 * with the on-disk inode size being outside the in-core inode size. We
	 * have no other method of updating EOF for AIO, so always do it here
	 * if necessary.
	 *
	 * We need to lock the test/set EOF update as we can be racing with
	 * other IO completions here to update the EOF. Failing to serialise
	 * here can result in EOF moving backwards and Bad Things Happen when
	 * that occurs.
	 */
	spin_lock(&ip->i_flags_lock);
	if (offset + size > i_size_read(inode))
		i_size_write(inode, offset + size);
	spin_unlock(&ip->i_flags_lock);

	if (flags & XFS_DIO_FLAG_COW)
		error = xfs_reflink_end_cow(ip, offset, size);
	if (flags & XFS_DIO_FLAG_UNWRITTEN) {
		trace_xfs_end_io_direct_write_unwritten(ip, offset, size);

		error = xfs_iomap_write_unwritten(ip, offset, size);
	}
	if (flags & XFS_DIO_FLAG_APPEND) {
		trace_xfs_end_io_direct_write_append(ip, offset, size);

		error = xfs_setfilesize(ip, offset, size);
	}

	return error;
}
static int __rb_allocate_pages(long nr_pages, struct list_head *pages, int cpu)
{
	struct buffer_page *bpage, *tmp;
	bool user_thread = current->mm != NULL;
	gfp_t mflags;
	long i;

	/*
	 * Check if the available memory is there first.
	 * Note, si_mem_available() only gives us a rough estimate of available
	 * memory. It may not be accurate. But we don't care, we just want
	 * to prevent doing any allocation when it is obvious that it is
	 * not going to succeed.
	 */
	i = si_mem_available();
	if (i < nr_pages)
		return -ENOMEM;

	/*
	 * __GFP_RETRY_MAYFAIL flag makes sure that the allocation fails
	 * gracefully without invoking oom-killer and the system is not
	 * destabilized.
	 */
	mflags = GFP_KERNEL | __GFP_RETRY_MAYFAIL;

	/*
	 * If a user thread allocates too much, and si_mem_available()
	 * reports there's enough memory, even though there is not.
	 * Make sure the OOM killer kills this thread. This can happen
	 * even with RETRY_MAYFAIL because another task may be doing
	 * an allocation after this task has taken all memory.
	 * This is the task the OOM killer needs to take out during this
	 * loop, even if it was triggered by an allocation somewhere else.
	 */
	if (user_thread)
		set_current_oom_origin();
	for (i = 0; i < nr_pages; i++) {
		struct page *page;

		bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
				    mflags, cpu_to_node(cpu));
		if (!bpage)
			goto free_pages;

		list_add(&bpage->list, pages);

		page = alloc_pages_node(cpu_to_node(cpu), mflags, 0);
		if (!page)
			goto free_pages;
		bpage->page = page_address(page);
		rb_init_page(bpage->page);

		if (user_thread && fatal_signal_pending(current))
			goto free_pages;
	}
	if (user_thread)
		clear_current_oom_origin();

	return 0;

free_pages:
	list_for_each_entry_safe(bpage, tmp, pages, list) {
		list_del_init(&bpage->list);
		free_buffer_page(bpage);
	}
	if (user_thread)
		clear_current_oom_origin();

	return -ENOMEM;
}
static int megasas_dcmd_set_properties(MegasasState *s, MegasasCmd *cmd)
{
    struct mfi_ctrl_props info;
    size_t dcmd_size = sizeof(info);

    if (cmd->iov_size < dcmd_size) {
        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
                                            dcmd_size);
        return MFI_STAT_INVALID_PARAMETER;
    }
    dma_buf_write((uint8_t *)&info, dcmd_size, &cmd->qsg);
    trace_megasas_dcmd_unsupported(cmd->index, cmd->iov_size);
    return MFI_STAT_OK;
}
bool make_text_string_connection(LEX_STRING *to,
                                   const LEX_STRING *from)
  {
    LEX_CSTRING cto;
    LEX_CSTRING cfrom;
    bool rc;
    cfrom.str= from->str;
    cfrom.length= from->length;
    rc= make_text_string_connection(&cto, &cfrom);
    to->str= (char*) cto.str;
    to->length= cto.length;
    return rc;
  }
static int show_vfsstat(struct seq_file *m, void *v)
{
	struct vfsmount *mnt = v;
	int err = 0;

	/* device */
	if (mnt->mnt_devname) {
		seq_puts(m, "device ");
		mangle(m, mnt->mnt_devname);
	} else
		seq_puts(m, "no device");

	/* mount point */
	seq_puts(m, " mounted on ");
	seq_path(m, mnt, mnt->mnt_root, " \t\n\\");
	seq_putc(m, ' ');

	/* file system type */
	seq_puts(m, "with fstype ");
	mangle(m, mnt->mnt_sb->s_type->name);

	/* optional statistics */
	if (mnt->mnt_sb->s_op->show_stats) {
		seq_putc(m, ' ');
		err = mnt->mnt_sb->s_op->show_stats(m, mnt);
	}

	seq_putc(m, '\n');
	return err;
}
dnsc_nonces_delkeyfunc(void *k, void* ATTR_UNUSED(arg))
{
    struct nonce_cache_key* nk = (struct nonce_cache_key*)k;
    lock_rw_destroy(&nk->entry.lock);
    free(nk);
}
static zend_string *spl_object_storage_get_hash(spl_SplObjectStorage *intern, zval *this, zval *obj) {
	if (intern->fptr_get_hash) {
		zval rv;
		zend_call_method_with_1_params(this, intern->std.ce, &intern->fptr_get_hash, "getHash", &rv, obj);
		if (!Z_ISUNDEF(rv)) {
			if (Z_TYPE(rv) == IS_STRING) {
				return Z_STR(rv);
			} else {
				zend_throw_exception(spl_ce_RuntimeException, "Hash needs to be a string", 0);

				zval_ptr_dtor(&rv);
				return NULL;
			}
		} else {
			return NULL;
		}
	} else {
		zend_string *hash = zend_string_alloc(sizeof(zend_object*), 0);
		memcpy(ZSTR_VAL(hash), (void*)&Z_OBJ_P(obj), sizeof(zend_object*));
		ZSTR_VAL(hash)[ZSTR_LEN(hash)] = '\0';
		return hash;
	}
}
nfs4_opendata_find_nfs4_state(struct nfs4_opendata *data)
{
	struct nfs4_state *state;
	struct inode *inode;

	inode = nfs4_opendata_get_inode(data);
	if (IS_ERR(inode))
		return ERR_CAST(inode);
	if (data->state != NULL && data->state->inode == inode) {
		state = data->state;
		refcount_inc(&state->count);
	} else
		state = nfs4_get_open_state(inode, data->owner);
	iput(inode);
	if (state == NULL)
		state = ERR_PTR(-ENOMEM);
	return state;
}
void monitorCommand(client *c) {
    /* ignore MONITOR if already slave or in monitor mode */
    if (c->flags & CLIENT_SLAVE) return;

    c->flags |= (CLIENT_SLAVE|CLIENT_MONITOR);
    listAddNodeTail(server.monitors,c);
    addReply(c,shared.ok);
}
static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
	struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr;
	struct sock *sk = sock->sk;
	struct l2cap_chan *chan = l2cap_pi(sk)->chan;

	BT_DBG("sock %p, sk %p", sock, sk);

	addr->sa_family = AF_BLUETOOTH;
	*len = sizeof(struct sockaddr_l2);

	if (peer) {
		la->l2_psm = chan->psm;
		bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst);
		la->l2_cid = cpu_to_le16(chan->dcid);
	} else {
		la->l2_psm = chan->sport;
		bacpy(&la->l2_bdaddr, &bt_sk(sk)->src);
		la->l2_cid = cpu_to_le16(chan->scid);
	}

	return 0;
}
static inline int acls_differ(const char *fname, struct file_struct *file, stat_x *sxp)
{
	if (preserve_acls) {
		if (!ACL_READY(*sxp))
			get_acl(fname, sxp);
		if (set_acl(NULL, file, sxp, file->mode))
			return 1;
	}

	return 0;
}
static inline void mb_set_bit(int bit, void *addr)
{
	addr = mb_correct_addr_and_bit(&bit, addr);
	ext4_set_bit(bit, addr);
}
rend_service_get_by_pk_digest(const char* digest)
{
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
                    if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
                        return s);
  return NULL;
}
string_str(PyObject *s)
{
    assert(PyString_Check(s));
    if (PyString_CheckExact(s)) {
        Py_INCREF(s);
        return s;
    }
    else {
        /* Subtype -- return genuine string with the same value. */
        PyStringObject *t = (PyStringObject *) s;
        return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
    }
}
empathy_adium_info_get_available_variants (GHashTable *info)
{
	GPtrArray *variants;
	const gchar *path;
	gchar *dirpath;
	GDir *dir;

	variants = tp_asv_get_boxed (info, "AvailableVariants", G_TYPE_PTR_ARRAY);
	if (variants != NULL) {
		return variants;
	}

	variants = g_ptr_array_new_with_free_func (g_free);
	tp_asv_take_boxed (info, g_strdup ("AvailableVariants"),
		G_TYPE_PTR_ARRAY, variants);

	path = tp_asv_get_string (info, "path");
	dirpath = g_build_filename (path, "Contents", "Resources", "Variants", NULL);
	dir = g_dir_open (dirpath, 0, NULL);
	if (dir != NULL) {
		const gchar *name;

		for (name = g_dir_read_name (dir);
		     name != NULL;
		     name = g_dir_read_name (dir)) {
			gchar *display_name;

			if (!g_str_has_suffix (name, ".css")) {
				continue;
			}

			display_name = g_strdup (name);
			strstr (display_name, ".css")[0] = '\0';
			g_ptr_array_add (variants, display_name);
		}
		g_dir_close (dir);
	}
	g_free (dirpath);

	if (adium_info_get_version (info) <= 2) {
		g_ptr_array_add (variants,
			g_strdup (adium_info_get_no_variant_name (info)));
	}

	return variants;
}
lys_features_find(const struct lys_module *module, const char *name)
{
    int i, j;

    /* module itself */
    for (i = 0; i < module->features_size; i++) {
        if (!strcmp(name, module->features[i].name)) {
            return &module->features[i];
        }
    }

    /* submodules */
    for (j = 0; j < module->inc_size; j++) {
        for (i = 0; i < module->inc[j].submodule->features_size; i++) {
            if (!strcmp(name, module->inc[j].submodule->features[i].name)) {
                return &module->inc[j].submodule->features[i];
            }
        }
    }

    return NULL;
}
static __u16 tcp_advertise_mss(struct sock *sk)
{
	struct tcp_sock *tp = tcp_sk(sk);
	const struct dst_entry *dst = __sk_dst_get(sk);
	int mss = tp->advmss;

	if (dst) {
		unsigned int metric = dst_metric_advmss(dst);

		if (metric < mss) {
			mss = metric;
			tp->advmss = mss;
		}
	}

	return (__u16)mss;
}
void QPaintEngineEx::clip(const QRect &r, Qt::ClipOperation op)
{
    qreal right = r.x() + r.width();
    qreal bottom = r.y() + r.height();
    qreal pts[] = { qreal(r.x()), qreal(r.y()),
                    right, qreal(r.y()),
                    right, bottom,
                    qreal(r.x()), bottom,
                    qreal(r.x()), qreal(r.y()) };
    QVectorPath vp(pts, 5, nullptr, QVectorPath::RectangleHint);
    clip(vp, op);
}
check_atype_tag(const struct atype_info *a, const taginfo *t)
{
    switch (a->type) {
    case atype_fn: {
        const struct fn_info *fn = a->tinfo;
        assert(fn->check_tag != NULL);
        return fn->check_tag(t);
    }
    case atype_sequence:
    case atype_nullterm_sequence_of:
    case atype_nonempty_nullterm_sequence_of:
        return (t->asn1class == UNIVERSAL && t->construction == CONSTRUCTED &&
                t->tagnum == ASN1_SEQUENCE);
    case atype_ptr: {
        const struct ptr_info *ptrinfo = a->tinfo;
        return check_atype_tag(ptrinfo->basetype, t);
    }
    case atype_offset: {
        const struct offset_info *off = a->tinfo;
        return check_atype_tag(off->basetype, t);
    }
    case atype_optional: {
        const struct optional_info *opt = a->tinfo;
        return check_atype_tag(opt->basetype, t);
    }
    case atype_counted: {
        const struct counted_info *counted = a->tinfo;
        switch (counted->basetype->type) {
        case cntype_string: {
            const struct string_info *string = counted->basetype->tinfo;
            return (t->asn1class == UNIVERSAL &&
                    t->construction == PRIMITIVE &&
                    t->tagnum == string->tagval);
        }
        case cntype_seqof:
            return (t->asn1class == UNIVERSAL &&
                    t->construction == CONSTRUCTED &&
                    t->tagnum == ASN1_SEQUENCE);
        case cntype_der:
            /*
             * We treat any tag as matching a stored DER encoding.  In some
             * cases we know what the tag should be; in others, we truly want
             * to accept any tag.  If it ever becomes an issue, we could add
             * optional tag info to the type and check it here.
             */
            return 1;
        case cntype_choice:
            /*
             * ASN.1 choices may or may not be extensible.  For now, we treat
             * all choices as extensible and match any tag.  We should consider
             * modeling whether choices are extensible before making the
             * encoder visible to plugins.
             */
            return 1;
        default:
            abort();
        }
    }
    case atype_tagged_thing: {
        const struct tagged_info *tag = a->tinfo;
        /* NOTE: Doesn't check construction bit for implicit tags. */
        if (!tag->implicit && t->construction != tag->construction)
            return 0;
        return (t->asn1class == tag->tagtype && t->tagnum == tag->tagval);
    }
    case atype_bool:
        return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
                t->tagnum == ASN1_BOOLEAN);
    case atype_int:
    case atype_uint:
    case atype_int_immediate:
        return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
                t->tagnum == ASN1_INTEGER);
    default:
        abort();
    }
}
int platform_device_register(struct platform_device *pdev)
{
	device_initialize(&pdev->dev);
	arch_setup_pdev_archdata(pdev);
	return platform_device_add(pdev);
}
static void aarp_purge(void)
{
	int ct;

	write_lock_bh(&aarp_lock);
	for (ct = 0; ct < AARP_HASH_SIZE; ct++) {
		__aarp_expire_all(&resolved[ct]);
		__aarp_expire_all(&unresolved[ct]);
		__aarp_expire_all(&proxies[ct]);
	}
	write_unlock_bh(&aarp_lock);
}
void LibRaw::raw2image_start()
{
  // restore color,sizes and internal data into raw_image fields
  memmove(&imgdata.color,&imgdata.rawdata.color,sizeof(imgdata.color));
  memmove(&imgdata.sizes,&imgdata.rawdata.sizes,sizeof(imgdata.sizes));
  memmove(&imgdata.idata,&imgdata.rawdata.iparams,sizeof(imgdata.idata));
  memmove(&libraw_internal_data.internal_output_params,&imgdata.rawdata.ioparams,sizeof(libraw_internal_data.internal_output_params));

  if (O.user_flip >= 0)
    S.flip = O.user_flip;

  switch ((S.flip+3600) % 360)
    {
    case 270:  S.flip = 5;  break;
    case 180:  S.flip = 3;  break;
    case  90:  S.flip = 6;  break;
    }

  // adjust for half mode!
  IO.shrink = P1.filters && (O.half_size ||
                             ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1) ));

  S.iheight = (S.height + IO.shrink) >> IO.shrink;
  S.iwidth  = (S.width  + IO.shrink) >> IO.shrink;

}
PHP_FUNCTION( locale_get_keywords )
{
    UEnumeration*   e        = NULL;
    UErrorCode      status   = U_ZERO_ERROR;

    const char*	 	kw_key        = NULL;
    int32_t         kw_key_len    = 0;

    const char*       	loc_name        = NULL;
    int        	 	loc_name_len    = 0;

/*
	ICU expects the buffer to be allocated  before calling the function
	and so the buffer size has been explicitly specified
	ICU uloc.h #define 	ULOC_KEYWORD_AND_VALUES_CAPACITY   100
	hence the kw_value buffer size is 100
*/
	char*	 	kw_value        = NULL;
    int32_t     kw_value_len    = 100;

    intl_error_reset( NULL TSRMLS_CC );

    if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
        &loc_name, &loc_name_len ) == FAILURE)
    {
        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
             "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC );

        RETURN_FALSE;
    }

    if(loc_name_len == 0) {
        loc_name = intl_locale_get_default(TSRMLS_C);
    }

	/* Get the keywords */
    e = uloc_openKeywords( loc_name, &status );
    if( e != NULL )
    {
		/* Traverse it, filling the return array. */
    	array_init( return_value );

    	while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){
			kw_value = ecalloc( 1 , kw_value_len  );

			/* Get the keyword value for each keyword */
			kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len ,  &status );
			if (status == U_BUFFER_OVERFLOW_ERROR) {
				status = U_ZERO_ERROR;
				kw_value = erealloc( kw_value , kw_value_len+1);
				kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 ,  &status );
			} else if(!U_FAILURE(status)) {
				kw_value = erealloc( kw_value , kw_value_len+1);
			}
			if (U_FAILURE(status)) {
	        		intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword  value for the  keyword", 0 TSRMLS_CC );
				if( kw_value){
					efree( kw_value );
				}
				zval_dtor(return_value);
        		RETURN_FALSE;
			}

       		add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0);
		} /* end of while */

	} /* end of if e!=NULL */

    uenum_close( e );
}
int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
    if (wpc->config.flags & CONFIG_MD5_CHECKSUM) {
        if (!wpc->config.md5_read && wpc->reader->can_seek (wpc->wv_in))
            seek_eof_information (wpc, NULL, FALSE);

        if (wpc->config.md5_read) {
            memcpy (data, wpc->config.md5_checksum, 16);
            return TRUE;
        }
    }

    return FALSE;
}
static int check_target(struct arpt_entry *e, struct net *net, const char *name)
{
	struct xt_entry_target *t = arpt_get_target(e);
	struct xt_tgchk_param par = {
		.net       = net,
		.table     = name,
		.entryinfo = e,
		.target    = t->u.kernel.target,
		.targinfo  = t->data,
		.hook_mask = e->comefrom,
		.family    = NFPROTO_ARP,
	};

	return xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false);
}
TEST(ImmutableConstantOpTest, FromFile) {
  const TensorShape kFileTensorShape({1000, 1});
  Env* env = Env::Default();
  auto root = Scope::NewRootScope().ExitOnError();

  string two_file, three_file;
  TF_ASSERT_OK(CreateTempFileFloat(env, 2.0f, 1000, &two_file));
  TF_ASSERT_OK(CreateTempFileFloat(env, 3.0f, 1000, &three_file));
  auto node1 = ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, two_file);
  auto node2 =
      ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, three_file);
  auto result = ops::MatMul(root, node1, node2, ops::MatMul::TransposeB(true));

  GraphDef graph_def;
  TF_ASSERT_OK(root.ToGraphDef(&graph_def));
  SessionOptions session_options;
  session_options.config.mutable_graph_options()
      ->mutable_optimizer_options()
      ->set_opt_level(OptimizerOptions::L0);
  std::unique_ptr<Session> session(NewSession(session_options));
  ASSERT_TRUE(session != nullptr) << "Failed to create session";
  TF_ASSERT_OK(session->Create(graph_def)) << "Can't create test graph";
  std::vector<Tensor> outputs;
  TF_ASSERT_OK(session->Run({}, {result.node()->name() + ":0"}, {}, &outputs));
  ASSERT_EQ(outputs.size(), 1);
  EXPECT_EQ(outputs.front().flat<float>()(0), 2.0f * 3.0f);
  EXPECT_EQ(outputs.front().flat<float>()(1), 2.0f * 3.0f);
  EXPECT_EQ(outputs.front().flat<float>()(2), 2.0f * 3.0f);
}
void ath_tx_aggr_wakeup(struct ath_softc *sc, struct ath_node *an)
{
	struct ath_atx_tid *tid;
	struct ath_atx_ac *ac;
	struct ath_txq *txq;
	int tidno;

	for (tidno = 0, tid = &an->tid[tidno];
	     tidno < IEEE80211_NUM_TIDS; tidno++, tid++) {

		ac = tid->ac;
		txq = ac->txq;

		ath_txq_lock(sc, txq);
		ac->clear_ps_filter = true;

		if (!tid->paused && ath_tid_has_buffered(tid)) {
			ath_tx_queue_tid(txq, tid);
			ath_txq_schedule(sc, txq);
		}

		ath_txq_unlock_complete(sc, txq);
	}
}
printer_req_free(struct usb_ep *ep, struct usb_request *req)
{
	if (ep != NULL && req != NULL) {
		kfree(req->buf);
		usb_ep_free_request(ep, req);
	}
}
QPDF_Stream::getRawStreamData()
{
    Pl_Buffer buf("stream data buffer");
    pipeStreamData(&buf, 0, qpdf_dl_none, false, false);
    QTC::TC("qpdf", "QPDF_Stream getRawStreamData");
    return buf.getBuffer();
}
Field *Type_handler_newdate::make_conversion_table_field(TABLE *table,
                                                         uint metadata,
                                                         const Field *target)
                                                         const
{
  return new(table->in_use->mem_root)
         Field_newdate(NULL, (uchar *) "", 1, Field::NONE, TMPNAME);
}
static void ipa_draw_rectangle(wmfAPI * API, wmfDrawRectangle_t * draw_rect)
{
  /* Save graphic wand */
  (void) PushDrawingWand(WmfDrawingWand);

  if (TO_FILL(draw_rect) || TO_DRAW(draw_rect))
    {
      util_set_pen(API, draw_rect->dc);
      util_set_brush(API, draw_rect->dc, BrushApplyFill);

      if ((draw_rect->width > 0) || (draw_rect->height > 0))
        DrawRoundRectangle(WmfDrawingWand,
                           XC(draw_rect->TL.x), YC(draw_rect->TL.y),
                           XC(draw_rect->BR.x), YC(draw_rect->BR.y),
                           draw_rect->width / 2, draw_rect->height / 2);
      else
        DrawRectangle(WmfDrawingWand,
                      XC(draw_rect->TL.x), YC(draw_rect->TL.y),
                      XC(draw_rect->BR.x), YC(draw_rect->BR.y));
    }

  /* Restore graphic wand */
  (void) PopDrawingWand(WmfDrawingWand);
}
static ssize_t wdm_read
(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
	int rv, cntr;
	int i = 0;
	struct wdm_device *desc = file->private_data;


	rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
	if (rv < 0)
		return -ERESTARTSYS;

	cntr = ACCESS_ONCE(desc->length);
	if (cntr == 0) {
		desc->read = 0;
retry:
		if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
			rv = -ENODEV;
			goto err;
		}
		i++;
		if (file->f_flags & O_NONBLOCK) {
			if (!test_bit(WDM_READ, &desc->flags)) {
				rv = cntr ? cntr : -EAGAIN;
				goto err;
			}
			rv = 0;
		} else {
			rv = wait_event_interruptible(desc->wait,
				test_bit(WDM_READ, &desc->flags));
		}

		/* may have happened while we slept */
		if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
			rv = -ENODEV;
			goto err;
		}
		if (test_bit(WDM_RESETTING, &desc->flags)) {
			rv = -EIO;
			goto err;
		}
		usb_mark_last_busy(interface_to_usbdev(desc->intf));
		if (rv < 0) {
			rv = -ERESTARTSYS;
			goto err;
		}

		spin_lock_irq(&desc->iuspin);

		if (desc->rerr) { /* read completed, error happened */
			desc->rerr = 0;
			spin_unlock_irq(&desc->iuspin);
			rv = -EIO;
			goto err;
		}
		/*
		 * recheck whether we've lost the race
		 * against the completion handler
		 */
		if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
			spin_unlock_irq(&desc->iuspin);
			goto retry;
		}
		if (!desc->reslength) { /* zero length read */
			dev_dbg(&desc->intf->dev, "%s: zero length - clearing WDM_READ\n", __func__);
			clear_bit(WDM_READ, &desc->flags);
			spin_unlock_irq(&desc->iuspin);
			goto retry;
		}
		cntr = desc->length;
		spin_unlock_irq(&desc->iuspin);
	}

	if (cntr > count)
		cntr = count;
	rv = copy_to_user(buffer, desc->ubuf, cntr);
	if (rv > 0) {
		rv = -EFAULT;
		goto err;
	}

	spin_lock_irq(&desc->iuspin);

	for (i = 0; i < desc->length - cntr; i++)
		desc->ubuf[i] = desc->ubuf[i + cntr];

	desc->length -= cntr;
	/* in case we had outstanding data */
	if (!desc->length)
		clear_bit(WDM_READ, &desc->flags);

	spin_unlock_irq(&desc->iuspin);

	rv = cntr;

err:
	mutex_unlock(&desc->rlock);
	return rv;
}