交互
如果对内核的其他部分无益,那么在页和缓冲区之间建立关联就没起作用。一些与块设备之间的传输操作,传输单位的长度依赖于底层设备的块长度,而内核的许多部分更喜欢按页的粒度来执行I/O操作,因为这使得其他事情更容易处理,特别是内存管理方面。在这种场景下,缓冲头区充当了双方的中介。
从缓冲区中读取整页
首先考察内核在从块设备读取整页时采用的方法,以block_read_full_page为例。我们讨论缓冲区实现所关注的部分。
- /*
- * Generic "read page" function for block devices that have the normal
- * get_block functionality. This is most of the block device filesystems.
- * Reads the page asynchronously --- the unlock_buffer() and
- * set/clear_buffer_uptodate() functions propagate buffer state into the
- * page struct once IO has completed.
- */
- int block_read_full_page(struct page *page, get_block_t *get_block)
- {
- struct inode *inode = page->mapping->host;
- sector_t iblock, lblock;
- struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
- unsigned int blocksize;
- int nr, i;
- int fully_mapped = 1;
- BUG_ON(!PageLocked(page));
- blocksize = 1 << inode->i_blkbits;
- /*检查页是否有相关联的缓冲区,如果没有,则创建他*/
- if (!page_has_buffers(page))
- create_empty_buffers(page, blocksize, 0);
- /*获得这些缓冲区,无论是新建的还是已经存在的
- 只是将page的private成员转换为buffer_head指针,因为按照
- 惯例,private指向与page关联的第一个缓冲头*/
- head = page_buffers(page);
- iblock = (sector_t)page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
- lblock = (i_size_read(inode)+blocksize-1) >> inode->i_blkbits;
- bh = head;
- nr = 0;
- i = 0;
- /*内核遍历与页面关联的所有缓冲区*/
- do {
- /*如果缓冲区内容是最新的,内核继续处理下一个
- 缓冲区。在这种情况下,页面缓冲区中的数据与块
- 设备匹配,无需额外的读操作*/
- if (buffer_uptodate(bh))
- continue;
- /*如果没有映射*/
- if (!buffer_mapped(bh)) {
- int err = 0;
- fully_mapped = 0;
- if (iblock < lblock) {
- WARN_ON(bh->b_size != blocksize);
- /*确定块在块设备上的位置*/
- err = get_block(inode, iblock, bh, 0);
- if (err)
- SetPageError(page);
- }
- if (!buffer_mapped(bh)) {
- zero_user(page, i * blocksize, blocksize);
- if (!err)
- set_buffer_uptodate(bh);
- continue;
- }
- /*
- * get_block() might have updated the buffer
- * synchronously
- */
- if (buffer_uptodate(bh))
- continue;
- }
- /*如果缓冲区已经建立了与块的映射,但是其内容不是最新
- 的则将缓冲区放置到一个临时的数组中*/
- arr[nr++] = bh;
- } while (i++, iblock++, (bh = bh->b_this_page) != head);
- if (fully_mapped)
- SetPageMappedToDisk(page);
- if (!nr) {
- /*
- * All buffers are uptodate - we can set the page uptodate
- * as well. But not if get_block() returned an error.
- */
- if (!PageError(page))
- SetPageUptodate(page);
- unlock_page(page);
- return 0;
- }
- /* Stage two: lock the buffers */
- for (i = 0; i < nr; i++) {
- bh = arr[i];
- lock_buffer(bh);
- /*将b_end_io设置为end_buffer_async_read,该函数将在数据传输结构时
- 调用*/
- mark_buffer_async_read(bh);
- }
- /*
- * Stage 3: start the IO. Check for uptodateness
- * inside the buffer lock in case another process reading
- * the underlying blockdev brought it uptodate (the sct fix).
- */
- for (i = 0; i < nr; i++) {
- bh = arr[i];
- if (buffer_uptodate(bh))
- end_buffer_async_read(bh, 1);
- else
- /*将所有需要读取的缓冲区转交给块层
- 也就是BIO层,在其中开始读操作*/
- submit_bh(READ, bh);
- }
- return 0;
- }
