Subject: Re: Question on ptr_ring linux header

From: "Michael S. Tsirkin" <[email-masked]>
Date: Wed, 16 Jan 2019 09:09:26 -0500

On Wed, Jan 16, 2019 at 06:48:41AM +0000, Cheng Fei Phung wrote:
> Hi,
> 
> > https://gist.github.com/promach/65e9331d55a43a2815239430a28e29c6#file-circ_ring-c-L62
> > racy if there are multiple consumers.
> > just call ptr_ring_consume_any.
> 
> If I modify pop_circ_queue() below to directly use ptr_ring_consume_any() without
> ptr_ring_empty_any() , I am afraid I am running into system crash due to NULL pointer
> deferencing for *item_pop:   
> 
>           *item_pop = *((struct item *)ptr_ring_consume_any(buffer));

Yes - you want to check the returned pointer before dereferencing.

> Just one silly beginner question, why will ptr_ring_empty_any() lead to data race problem ?

because ring can become empty between the check and the call to consume?

> 
> inline int pop_circ_queue(struct ptr_ring * buffer, struct item * item_pop)
> {
> 	DEBUG_MSG(KERN_INFO "Before pop, head = %u , tail = %u\n", buffer->consumer_head, buffer->consumer_tail);
> 
> 	/* extract one item struct containing two unsigned integers from the buffer */
> 	*item_pop = *((struct item *)ptr_ring_consume_any(buffer));
> 
> 	if((item_pop != NULL) && (item_pop->val1 > 0)) 
> 	{ 
> 	// val1 will never be zero since the event number starts from 1 (so, val1 in push_circ_queue() will not be zero, same case after pop_circ_queue()), and 0 is only possible during initialization, not during pop_circ_queue()
> 
> 		DEBUG_MSG(KERN_INFO "val1 = %u , val2 = %u\n", item_pop->val1, item_pop->val2);	    
> 
> 		DEBUG_MSG(KERN_INFO "After pop, head = %u , tail = %u\n", buffer->consumer_head, buffer->consumer_tail);
> 
> 		return 0; 
> 	}
> 
> 	else {
> 		DEBUG_MSG(KERN_INFO "empty, nothing to pop from the ring\n");
> 
> 		return 1;
> 	}
> }
> 
> 
> 
> Regards,
> Phung