1 /*
2  * Copyright (c) 2006-2023, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2023-11-30     Shell        init ver.
9  */
10 #define DBG_TAG "lwp.ctty"
11 #define DBG_LVL DBG_INFO
12 #include <rtdbg.h>
13 
14 #define TTY_CONF_INCLUDE_CCHARS
15 #include "tty_config.h"
16 #include "tty_internal.h"
17 #include "terminal.h"
18 
fops_open(struct dfs_file * file)19 static int fops_open(struct dfs_file *file)
20 {
21     return -EINVAL;
22 }
23 
ctty_readlink(struct rt_device * dev,char * buf,int len)24 static rt_err_t ctty_readlink(struct rt_device *dev, char *buf, int len)
25 {
26     int rc = -ENXIO;
27     lwp_tty_t tp;
28     rt_session_t sess;
29     rt_processgroup_t pgrp;
30     rt_lwp_t lwp;
31 
32     lwp = lwp_self();
33     if (lwp)
34     {
35         pgrp = lwp->pgrp;
36         if (pgrp)
37         {
38             sess = pgrp->session;
39             if (sess)
40             {
41                 tp = sess->ctty;
42                 if (tp)
43                 {
44                     tty_lock(tp);
45 
46                     if (lwp->pgrp == pgrp && pgrp->session == sess && sess->ctty == tp)
47                     {
48                         rt_strncpy(buf, tp->parent.parent.name, len);
49                         rc = RT_EOK;
50                     }
51 
52                     tty_unlock(tp);
53                 }
54             }
55         }
56     }
57 
58     return rc;
59 }
60 
61 static struct dfs_file_ops ctty_file_ops = {
62     .open = fops_open,
63 };
64 
65 /* character device for tty */
66 #ifdef RT_USING_DEVICE_OPS
67 const static struct rt_device_ops tty_dev_ops = {
68     /* IO directly through device is not allowed */
69 };
70 #else
71 #error Must enable RT_USING_DEVICE_OPS in Kconfig
72 #endif
73 
device_setup(rt_device_t ctty)74 rt_inline void device_setup(rt_device_t ctty)
75 {
76     ctty->type = RT_Device_Class_Char;
77 #ifdef RT_USING_DEVICE_OPS
78     ctty->ops = &tty_dev_ops;
79 #else
80 #error Must enable RT_USING_DEVICE_OPS in Kconfig
81 #endif
82 }
83 
84 /* register device to DFS */
lwp_ctty_register(rt_device_t ctty)85 static int lwp_ctty_register(rt_device_t ctty)
86 {
87     rt_err_t rc = -RT_ENOMEM;
88     const char *tty_name = "tty";
89 
90     device_setup(ctty);
91     rc = rt_device_register(ctty, tty_name, RT_DEVICE_FLAG_DYNAMIC);
92     if (rc == RT_EOK)
93     {
94         ctty->readlink = &ctty_readlink;
95         ctty->fops = &ctty_file_ops;
96     }
97     return rc;
98 }
99 
100 static struct rt_device ctty;
101 
lwp_ctty_init(void)102 static int lwp_ctty_init(void)
103 {
104     return lwp_ctty_register(&ctty);
105 }
106 INIT_DEVICE_EXPORT(lwp_ctty_init);
107