c - Unable to understand the spacefree function in scullpipe driver -


i reading "linux device drivers 3" , having trouble understanding following code:

/* how space free */ static int spacefree(struct scull_pipe *dev){   if(dev->rp == dev->wp)      return dev->buffersize - 1;   return ((dev->rp + dev->buffersize - dev->wp) % dev->buffersize) - 1; } 

based on understanding: 1. *buffer beginning of buffer. 2. *end ending of buffer. 3. end = buffer + buffersize 4. so, buffersize total size of buffer.

if(dev->rp == dev->wp)      return dev->buffersize - 1; 

the above code correct, if both read pointer (rp) , write pointer (wp) @ beginning of buffer. because if no data written buffer, write pointer (wp) @ beginning of buffer (unless write pointer (wp) has wrapped), hence, total amount of free space equal buffersize.

but not sure whether above code correct, if both read pointer (rp) , write pointer (wp) point end of buffer (or point memory location in middle of buffer). if write pointer (wp) points end of buffer, total amount of free space should 0, right?

return ((dev->rp + dev->buffersize - dev->wp) % dev->buffersize) - 1; 

based on understanding, above code should return total amount of free space in buffer when read pointer (rp) , write pointer (wp) do not point same memory location in buffer.

shouldn't possible calculate total amount of free space based on location of write pointer (wp) alone?

for ex: dev->end - dev->wp

can please explain code.

thanks

i understood code:

  1. the buffer circular.
  2. after data read memory location, data (in memory location) cleared. memory locations before read pointer (rp) , after write pointer (wp) empty.
  3. if read pointer (rp) , write pointer (wp) point same memory location, buffer empty.
  4. if write pointer (wp) present right behind read pointer, buffer full.

    return ((dev->rp + dev->buffersize - dev->wp) % dev->buffersize) - 1;

to understand above code snippet:

consider circular buffer 10 memory locations:

 8 9 10 | 1 2 3 4 5 6 7 

if read pointer (rp) @ memory location 3 , write pointer @ memory location 7, 5 memory locations free:

8, 9, 10, 1, 2 

plugging in values:

return ((dev->rp + dev->buffersize - dev->wp) % dev->buffersize) - 1;

return ((3 + 10 - 7) % 10) -1

return ((6) % 10) -1

return 6-1

return 5


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -