Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核文件描述符(六):fd 分配中的 expand_files

本文延續文件描述符系列,分析 fd 分配過程中負責擴展描述符表的 expand_files 與 expand_fdtable。(環境:2.6.14 內核、ARM920T)

expand_files

int expand_files(struct files_struct *files, int nr)
{
  int err, expand = 0;
  struct fdtable *fdt;

  fdt = files_fdtable(files);
  if (nr >= fdt->max_fdset || nr >= fdt->max_fds) {  //初始時 max_fdset = 1024,max_fds = 32
    if (fdt->max_fdset >= NR_OPEN ||  //#define NR_OPEN (1024*1024) /* Absolute upper limit on fd num */
        fdt->max_fds >= NR_OPEN || nr >= NR_OPEN) {
        err = -EMFILE;  //max_fdset 和 max_fds 都不能大於 NR_OPEN,否則返回 -EMFILE,即打開太多文件
        goto out;
    }
    expand = 1;
    if ((err = expand_fdtable(files, nr)))//真正進行擴展
        goto out;
  }
  err = expand;
out:
  return err;
}

這個函式先做檢查,若需要的 fd 編號超出目前表格容量且未達 NR_OPEN 上限,就呼叫 expand_fdtable 進行擴展。

expand_fdtable

static int expand_fdtable(struct files_struct *files, int nr)
  __releases(files->file_lock)
  __acquires(files->file_lock)
{
  int error = 0;
  struct fdtable *fdt;
  struct fdtable *nfdt = NULL;

  spin_unlock(&files->file_lock);
  nfdt = alloc_fdtable(nr);//根據 nr 重新創建一個新的 fdtable
  if (!nfdt) {
    error = -ENOMEM;
    spin_lock(&files->file_lock);
    goto out;
  }

  spin_lock(&files->file_lock);
  fdt = files_fdtable(files);
  /*
   * Check again since another task may have expanded the
   * fd table while we dropped the lock
   */
  if (nr >= fdt->max_fds || nr >= fdt->max_fdset) { //nr 值必須大於 max_fds 和 max_fdset,這裡再次檢查是防止另一個進程進行了 expand
    copy_fdtable(nfdt, fdt); //將舊的 fdtable 中的內容拷貝至新的 fdtable
  } else {
    /* Somebody expanded while we dropped file_lock */
    spin_unlock(&files->file_lock);
    __free_fdtable(nfdt);
    spin_lock(&files->file_lock);
    goto out;
  }
  rcu_assign_pointer(files->fdt, nfdt);//用新的 fdtable 替換舊的 fdtable
  free_fdtable(fdt);//釋放舊的 fdtable
out:
  return error;
}

幾個設計細節值得注意

配置新表時會先釋放 file_lock,因為 alloc_fdtable 可能阻塞(需要記憶體配置)。但也正因為放開了鎖,其他任務可能已在這段期間完成擴展,所以重新上鎖後必須再檢查一次;若發現別人已經擴展好,就把自己剛配置的新表釋放掉,直接返回。最後以 rcu_assign_pointer 原子性地替換指標,舊表則交給 free_fdtable 回收——這種 RCU 風格的更新讓讀者在無鎖狀態下也能安全取得 fdtable。

Copyright © Linux教程網 All Rights Reserved