编写适用于 Oracle® Solaris 11.2 的设备驱动程序

退出打印视图

更新时间: 2014 年 9 月
 
 

open() 入口点(块驱动程序)

open(9E) 入口点用于访问给定的设备。当用户线程对与次要设备相关的块特殊文件发出 open(2)mount(2) 系统调用时,或者当分层驱动程序调用 open(9E) 时,均会调用块驱动程序的 open(9E) 例程。有关更多信息,请参见File I/O

open() 入口点会检查下列条件:

  • 设备可以打开,即设备已联机并准备就绪。

  • 设备可以应请求而打开。设备支持该操作。设备的当前状态与请求不冲突。

  • 调用方具有打开设备的权限。

以下示例说明了块驱动程序 open(9E) 入口点。

示例 16-2  块驱动程序 open(9E) 例程
static int
xxopen(dev_t *devp, int flags, int otyp, cred_t *credp)
{
    minor_t         instance;
    struct xxstate        *xsp;

    instance = getminor(*devp);
    xsp = ddi_get_soft_state(statep, instance);
    if (xsp == NULL)
        return (ENXIO);
    mutex_enter(&xsp->mu);
    /*
     * only honor FEXCL. If a regular open or a layered open
     * is still outstanding on the device, the exclusive open
     * must fail.
     */
    if ((flags & FEXCL) && (xsp->open || xsp->nlayered)) {
        mutex_exit(&xsp->mu);
        return (EAGAIN);
    }
    switch (otyp) {
      case OTYP_LYR:
          xsp->nlayered++;
          break;
      case OTYP_BLK:
          xsp->open = 1;
          break;
      default:
          mutex_exit(&xsp->mu);
          return (EINVAL);
    }
    mutex_exit(&xsp->mu);
    return (0);
}

otyp 参数用于指定设备的打开类型。OTYP_BLK 是块设备的典型打开类型。将 otyp 设置为 OTYP_BLK 后,可以多次打开设备。最后关闭设备的 OTYP_BLK 类型时,仅调用一次 close(9E)。如果将设备用作分层设备,则 otyp 设置为 OTYP_LYR。每次打开 OTYP_LYR 类型,分层驱动程序都会发出类型为 OTYP_LYR 的对应关闭。此示例跟踪每种类型的打开,因此驱动程序可以确定何时设备不用于 close(9E)