Chinaunix首页 | 论坛 | 博客
  • 博客访问: 312826
  • 博文数量: 169
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 12
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-10 12:00
文章分类

全部博文(169)

文章存档

2014年(38)

2013年(131)

我的朋友

分类: LINUX

2013-07-23 14:19:13

原文地址:linux 串口驱动(三) 作者:wangbaolin719


三、串口的打开
在用户空间执行open操作的时候,就会执行uart_ops->open. Uart_ops的定义如下:
 
tty_open=>init_dev=>initialize_tty_struct=>tty_ldisc_assign=>
将tty_ldisc_N_TTY复制给该dev
然后tty->driver->open(tty, filp);

tty->driver为上面uart_register_driver时注册的tty_driver驱动,它的操作方法集为uart_ops.
tty_fops.tty_open=>
tty->driver->open就是uart_ops.uart_open=>uart_startup=>
port->ops->startup(port)这里port的ops就是serial_pxa_pops;也这就是该物理uart口,struct uart_port的操作函数
serial_pxa_pops.startup就是serial_pxa_startup

static const struct tty_operations uart_ops = {
     .open         = uart_open,
     .close        = uart_close,
     .write        = uart_write,
     .put_char = uart_put_char,
     .flush_chars  = uart_flush_chars,
     .write_room   = uart_write_room,
     .chars_in_buffer= uart_chars_in_buffer,
     .flush_buffer = uart_flush_buffer,
     .ioctl        = uart_ioctl,
     .throttle = uart_throttle,
     .unthrottle   = uart_unthrottle,
     .send_xchar   = uart_send_xchar,
     .set_termios  = uart_set_termios,
     .stop         = uart_stop,
     .start        = uart_start,
     .hangup       = uart_hangup,
     .break_ctl    = uart_break_ctl,
     .wait_until_sent= uart_wait_until_sent,
#ifdef CONFIG_PROC_FS
     .read_proc    = uart_read_proc,
#endif
     .tiocmget = uart_tiocmget,
     .tiocmset = uart_tiocmset,
};
对应open的操作接口为uart_open.代码如下:
static int uart_open(struct tty_struct *tty, struct file *filp)
{
     struct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;
     struct uart_state *state;
     int retval, line = tty->index;

     BUG_ON(!kernel_locked());
     pr_debug("uart_open(%d) called\n", line);

     /*
      * tty->driver->num won't change, so we won't fail here with
      * tty->driver_data set to something non-NULL (and therefore
      * we won't get caught by uart_close()).
      */
     retval = -ENODEV;
     if (line >= tty->driver->num)
         goto fail;

     /*
      * We take the semaphore inside uart_get to guarantee that we won't
      * be re-entered while allocating the info structure, or while we
      * request any IRQs that the driver may need.  This also has the nice
      * side-effect that it delays the action of uart_hangup, so we can
      * guarantee that info->tty will always contain something reasonable.
      */
     state = uart_get(drv, line);
     if (IS_ERR(state)) {
         retval = PTR_ERR(state);
         goto fail;
     }

     /*
      * Once we set tty->driver_data here, we are guaranteed that
      * uart_close() will decrement the driver module use count.
      * Any failures from here onwards should not touch the count.
      */
     tty->driver_data = state;
     tty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0;
     tty->alt_speed = 0;
     state->info->tty = tty;

     /*
      * If the port is in the middle of closing, bail out now.
      */
     if (tty_hung_up_p(filp)) {
         retval = -EAGAIN;
         state->count--;
         mutex_unlock(&state->mutex);
         goto fail;
     }

     /*
      * Make sure the device is in D0 state.
      */
     if (state->count == 1)
         uart_change_pm(state, 0);

     /*
      * Start up the serial port.
      */
     retval = uart_startup(state, 0);

     /*
      * If we succeeded, wait until the port is ready.
      */
     if (retval == 0)
         retval = uart_block_til_ready(filp, state);
     mutex_unlock(&state->mutex);

     /*
      * If this is the first open to succeed, adjust things to suit.
      */
     if (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) {
         state->info->flags |= UIF_NORMAL_ACTIVE;

         uart_update_termios(state);
     }

fail:
     return retval;
}
在这里函数里,继续完成操作的设备文件所对应state初始化.现在用户空间open这个设备了.即要对这个文件进行操作了.那uart_port也要开始工作了.即调用uart_startup()使其进入工作状态.当然,也需要初始化uart_port所对应的环形缓冲区circ_buf.即state->info-> xmit.
特别要注意,在这里将tty->driver_data = state;这是因为以后的操作只有port相关了,不需要去了解uart_driver的相关信息.
跟踪看一下里面调用的两个重要的子函数. uart_get()和uart_startup().先分析uart_get().代码如下:
static struct uart_state *uart_get(struct uart_driver *drv, int line)
{
     struct uart_state *state;
     int ret = 0;

     state = drv->state + line;
     if (mutex_lock_interruptible(&state->mutex)) {
         ret = -ERESTARTSYS;
         goto err;
     }

     state->count++;
     if (!state->port || state->port->flags & UPF_DEAD) {
         ret = -ENXIO;
         goto err_unlock;
     }

     if (!state->info) {
         state->info = kzalloc(sizeof(struct uart_info), GFP_KERNEL);
         if (state->info) {
              init_waitqueue_head(&state->info->open_wait);
              init_waitqueue_head(&state->info->delta_msr_wait);

              /*
               * Link the info into the other structures.
               */
              state->port->info = state->info;

              tasklet_init(&state->info->tlet, uart_tasklet_action,
                        (unsigned long)state);
         } else {
              ret = -ENOMEM;
              goto err_unlock;
         }
     }
     return state;

err_unlock:
     state->count--;
     mutex_unlock(&state->mutex);
err:
     return ERR_PTR(ret);
}
//从代码中可以看出.这里注要是操作是初始化state->info.注意port->info就是state->info的一个副本.即port直接通过port->info可以找到它要操作的缓存区.

//uart_startup()代码如下:
static int uart_startup(struct tty_struct *tty, struct uart_state *state, int init_hw)
{
 struct uart_port *uport = state->uart_port;
 struct tty_port *port = &state->port;
 unsigned long page;
 int retval = 0;

 if (port->flags & ASYNC_INITIALIZED)
  return 0;

 /*
  * Set the TTY IO error marker - we will only clear this
  * once we have successfully opened the port.  Also set
  * up the tty->alt_speed kludge
  */
 set_bit(TTY_IO_ERROR, &tty->flags);

 if (uport->type == PORT_UNKNOWN)
  return 0;

 /*
  * Initialise and allocate the transmit and temporary
  * buffer.
  */
 if (!state->xmit.buf) {
  /* This is protected by the per port mutex */
  page = get_zeroed_page(GFP_KERNEL);
  if (!page)
   return -ENOMEM;

  state->xmit.buf = (unsigned char *) page;
  uart_circ_clear(&state->xmit);
 }
 //在这里,注要完成对环形缓冲,即info->xmit的初始化.然后调用port->ops->startup( )将这个port带入到工作状态.
 
 retval = uport->ops->startup(uport);//调用8250.c中的serial8250_startup()函数
 if (retval == 0) {
  if (init_hw) {
   /*
    * Initialise the hardware port settings.
    */
   uart_change_speed(tty, state, NULL);

   /*
    * Setup the RTS and DTR signals once the
    * port is open and ready to respond.
    */
   if (tty->termios->c_cflag & CBAUD)
    uart_set_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
  }

  if (port->flags & ASYNC_CTS_FLOW) {
   spin_lock_irq(&uport->lock);
   if (!(uport->ops->get_mctrl(uport) & TIOCM_CTS))
    tty->hw_stopped = 1;
   spin_unlock_irq(&uport->lock);
  }

  set_bit(ASYNCB_INITIALIZED, &port->flags);

  clear_bit(TTY_IO_ERROR, &tty->flags);
 }

 if (retval && capable(CAP_SYS_ADMIN))
  retval = 0;

 return retval;
}

static int serial8250_startup(struct uart_port *port)
{
    struct uart_8250_port *up = (struct uart_8250_port *)port;
    unsigned long flags;
    unsigned char lsr, iir;
    int retval;
 
     //从结构体uart_config中取得相应的配置
    up->capabilities = uart_config[up->port.type].flags;
    up->mcr = 0;
    
    if (up->port.type == PORT_16C950) {  //这里我们没有调用
      ……………………
    }
#ifdef CONFIG_SERIAL_8250_RSA
    enable_rsa(up);
#endif

   //清楚FIFO  buffers并 disable 他们,但会在以后set_termios()函数中,重新使能他们
    serial8250_clear_fifos(up);  

  //复位LSR,RX,IIR,MSR寄存器
    (void) serial_inp(up, UART_LSR);
    (void) serial_inp(up, UART_RX);
    (void) serial_inp(up, UART_IIR);
    (void) serial_inp(up, UART_MSR);

    //若LSR寄存器中的值为0xFF.异常
    if (!(up->port.flags & UPF_BUGGY_UART) &&(serial_inp(up, UART_LSR) == 0xff)) {
        printk("ttyS%d: LSR safety check engaged!\n", up->port.line);
        return -ENODEV;
    }

   //16850系列芯片的处理,忽略
    if (up->port.type == PORT_16850) {
  ………………………………………………
    }
    if (is_real_interrupt(up->port.irq)) {
            /*
             * Test for UARTs that do not reassert THRE when the
             * transmitter is idle and the interrupt has already
             * been cleared.  Real 16550s should always reassert
             * this interrupt whenever the transmitter is idle and
             * the interrupt is enabled.  Delays are necessary to
             * allow register changes to become visible.
             */
            spin_lock_irqsave(&up->port.lock, flags);
            wait_for_xmitr(up, UART_LSR_THRE);
            serial_out_sync(up, UART_IER, UART_IER_THRI);
      udelay(1); /* allow THRE to set */
            serial_in(up, UART_IIR);
            serial_out(up, UART_IER, 0);
            serial_out_sync(up, UART_IER, UART_IER_THRI);
            udelay(1); /* allow a working UART time to re-assert THRE */
            iir = serial_in(up, UART_IIR);
            serial_out(up, UART_IER, 0);
            spin_unlock_irqrestore(&up->port.lock, flags);
            /*
             * If the interrupt is not reasserted, setup a timer to
             * kick the UART on a regular basis.
             */
            if (iir & UART_IIR_NO_INT) {
                    pr_debug("ttyS%d - using backup timer\n", port->line);
                    up->timer.function = serial8250_backup_timeout;
                    up->timer.data = (unsigned long)up;
                    mod_timer(&up->timer, jiffies +poll_timeout(up->port.timeout) + HZ/5);
            }
    }
 //如果中断号有效,还要进一步判断这个中断号是否有效.具体操作为,先等待8250发送寄存器空.然后允许发送中断空的中断.然后判断IIR寄存器是否收到中断.
 //如果有没有收到中断,则说明这根中断线无效.只能采用轮询的方式.关于轮询方式,我们在之后再以独立章节的形式给出分析
    if (!is_real_interrupt(up->port.irq)) {
            up->timer.data = (unsigned long)up;
        mod_timer(&up->timer, jiffies + poll_timeout(up->port.timeout));
    } else {
            retval = serial_link_irq_chain(up);//定义串口的中断函数
            if (retval)
                    return retval;
    }
 //如果没有设置中断号,则采用轮询方式;如果中断后有效.流程转入serial_link_irq_chain().在这个里面.会注册中断处理函数
    serial_outp(up, UART_LCR, UART_LCR_WLEN8);  //ULCR.WLS=11,即选择8位
    spin_lock_irqsave(&up->port.lock, flags);
    if (up->port.flags & UPF_FOURPORT) {
            if (!is_real_interrupt(up->port.irq))
                    up->port.mctrl |= TIOCM_OUT1;
    }
    else
    {
      //Most PC uarts need OUT2 raised to enable interrupts.
     if (is_real_interrupt(up->port.irq))
       up->port.mctrl |= TIOCM_OUT2;
    }
    serial8250_set_mctrl(&up->port, up->port.mctrl);
    /*
     * Do a quick test to see if we receive an
     * interrupt when we enable the TX irq.
     */
    serial_outp(up, UART_IER, UART_IER_THRI);
  lsr = serial_in(up, UART_LSR);
    iir = serial_in(up, UART_IIR);
    serial_outp(up, UART_IER, 0);
    if (lsr & UART_LSR_TEMT && iir & UART_IIR_NO_INT) {
            if (!(up->bugs & UART_BUG_TXEN)) {
                    up->bugs |= UART_BUG_TXEN;
                    pr_debug("ttyS%d - enabling bad tx status workarounds\n",port->line);
            }
    } else {
            up->bugs &= ~UART_BUG_TXEN;
    }
    spin_unlock_irqrestore(&up->port.lock, flags);
    /*
     * Finally, enable interrupts.  Note: Modem status interrupts
     * are set via set_termios(), which will be occurring imminently
     * anyway, so we don't enable them here.
     */
    up->ier = UART_IER_RLSI | UART_IER_RDI;
    serial_outp(up, UART_IER, up->ier);
    if (up->port.flags & UPF_FOURPORT) {
            unsigned int icp;
            //Enable interrupts on the AST Fourport board
            icp = (up->port.iobase & 0xfe0) | 0x01f;
          outb_p(0x80, icp);
            (void) inb_p(icp);
    }
    /*
     * And clear the interrupt registers again for luck.
     */
    (void) serial_inp(up, UART_LSR);
    (void) serial_inp(up, UART_RX);
    (void) serial_inp(up, UART_IIR);
    (void) serial_inp(up, UART_MSR);
    return 0;
}

四、串口的读
tty_driver中并末提供read接口.上层的read操作是直接到ldsic的缓存区中读数据的.那ldsic的数据是怎么送入进去的呢?继续看中断处理中的数据接收流程.即为: receive_chars().代码片段如下:
//这个应该是UART接受数据的函数uart_port结构定义在serial——core.h中
//port中断函数serial8250_handle_port()调用这个函数:
static void receive_chars(struct uart_8250_port *up, unsigned int *status)
{
     ……
     ……
     uart_insert_char(&up->port, lsr, UART_LSR_OE, ch, flag);
}
//最后流据会转入uart_inset_char().这个函数是uart层提供的一个接口,代码如下:
static inline void uart_insert_char(struct uart_port *port, unsigned int status,unsigned int overrun, unsigned int ch, unsigned int flag)
{
     struct tty_struct *tty = port->info->tty;
 
     if ((status & port->ignore_status_mask & ~overrun) == 0)
         tty_insert_flip_char(tty, ch, flag);
 
     /*
      * Overrun is special.  Since it's reported immediately,
      * it doesn't affect the current character.
      */
     if (status & ~port->ignore_status_mask & overrun)
         tty_insert_flip_char(tty, 0, TTY_OVERRUN);
}
//tty_insert_filp()函数数据就直接交给了ldisc.

读数据时,read()--->调用tty_io.c中的tty_read()--->n_tty.c中的 n_tty_read(),n_tty_read()从ldisc中读取数据。
五、串口的写
static const struct file_operations tty_fops = {
 .llseek  = no_llseek,
 .read  = tty_read,
 .write  = tty_write,
 .poll  = tty_poll,
 .unlocked_ioctl = tty_ioctl,
 .compat_ioctl = tty_compat_ioctl,
 .open  = tty_open,
 .release = tty_release,
 .fasync  = tty_fasync,
};
写数据时,write()--->调用tty_io.c中的 tty_write()--->调用n_tty.c中的 n_tty_write()--->调用serial_core.c中 uart_write()--->调用serial_core.c中 uart_start()--->__uart_start()--->

调用serial_core.c中 uart_send_xchar()--->调用8250.c中的写出函数serial8250_start_tx()--->调用8250.c中的transmit_chars()--->调用8250.c中的serial_outp()--->调用8250.c中的mem_serial_out()写出去

阅读(754) | 评论(0) | 转发(0) |
0

上一篇:linux console驱动详解

下一篇:GPIO接口解析

给主人留下些什么吧!~~