kernel: scheduling fix for ARM
[minix.git] / drivers / tty / tty.c
blobc1dc41a02ef552cc106dba28f485d7d1bbcc58f3
1 /* This file contains the terminal driver, both for the IBM console and regular
2 * ASCII terminals. It handles only the device-independent part of a TTY, the
3 * device dependent parts are in console.c, rs232.c, etc. This file contains
4 * two main entry points, tty_task() and tty_wakeup(), and several minor entry
5 * points for use by the device-dependent code.
7 * The device-independent part accepts "keyboard" input from the device-
8 * dependent part, performs input processing (special key interpretation),
9 * and sends the input to a process reading from the TTY. Output to a TTY
10 * is sent to the device-dependent code for output processing and "screen"
11 * display. Input processing is done by the device by calling 'in_process'
12 * on the input characters, output processing may be done by the device itself
13 * or by calling 'out_process'. The TTY takes care of input queuing, the
14 * device does the output queuing. If a device receives an external signal,
15 * like an interrupt, then it causes tty_wakeup() to be run by the CLOCK task
16 * to, you guessed it, wake up the TTY to check if input or output can
17 * continue.
19 * The valid messages and their parameters are:
21 * notify from HARDWARE: output has been completed or input has arrived
22 * notify from SYSTEM : e.g., MINIX wants to shutdown; run code to
23 * cleanly stop
24 * DEV_READ: a process wants to read from a terminal
25 * DEV_WRITE: a process wants to write on a terminal
26 * DEV_IOCTL: a process wants to change a terminal's parameters
27 * DEV_OPEN: a tty line has been opened
28 * DEV_CLOSE: a tty line has been closed
29 * DEV_SELECT: start select notification request
30 * DEV_STATUS: FS wants to know status for SELECT or REVIVE
31 * CANCEL: terminate a previous incomplete system call immediately
33 * m_type TTY_LINE USER_ENDPT COUNT TTY_SPEKS IO_GRANT
34 * -----------------------------------------------------------------
35 * | HARD_INT | | | | | |
36 * |-------------+---------+---------+---------+---------+---------|
37 * | SYS_SIG | sig set | | | | |
38 * |-------------+---------+---------+---------+---------+---------|
39 * | DEV_READ |minor dev| proc nr | count | | grant |
40 * |-------------+---------+---------+---------+---------+---------|
41 * | DEV_WRITE |minor dev| proc nr | count | | grant |
42 * |-------------+---------+---------+---------+---------+---------|
43 * | DEV_IOCTL |minor dev| proc nr |func code|erase etc| |
44 * |-------------+---------+---------+---------+---------+---------|
45 * | DEV_OPEN |minor dev| proc nr | O_NOCTTY| | |
46 * |-------------+---------+---------+---------+---------+---------|
47 * | DEV_CLOSE |minor dev| proc nr | | | |
48 * |-------------+---------+---------+---------+---------+---------|
49 * | DEV_STATUS | | | | | |
50 * |-------------+---------+---------+---------+---------+---------|
51 * | CANCEL |minor dev| proc nr | | | |
52 * -----------------------------------------------------------------
54 * Changes:
55 * Jan 20, 2004 moved TTY driver to user-space (Jorrit N. Herder)
56 * Sep 20, 2004 local timer management/ sync alarms (Jorrit N. Herder)
57 * Jul 13, 2004 support for function key observers (Jorrit N. Herder)
60 #include <assert.h>
61 #include <minix/drivers.h>
62 #include <minix/driver.h>
63 #include <termios.h>
64 #include <sys/ioc_tty.h>
65 #include <signal.h>
66 #include <minix/callnr.h>
67 #include <minix/sys_config.h>
68 #include <minix/tty.h>
69 #include <minix/keymap.h>
70 #include <minix/endpoint.h>
71 #include "tty.h"
73 #include <sys/time.h>
74 #include <sys/select.h>
76 unsigned long kbd_irq_set = 0;
77 unsigned long rs_irq_set = 0;
79 /* Address of a tty structure. */
80 #define tty_addr(line) (&tty_table[line])
82 /* Macros for magic tty types. */
83 #define isconsole(tp) ((tp) < tty_addr(NR_CONS))
84 #define ispty(tp) ((tp) != NULL && (tp)->tty_minor >= TTYPX_MINOR)
86 /* Macros for magic tty structure pointers. */
87 #define FIRST_TTY tty_addr(0)
88 #define END_TTY tty_addr(sizeof(tty_table) / sizeof(tty_table[0]))
90 /* A device exists if at least its 'devread' function is defined. */
91 #define tty_active(tp) ((tp)->tty_devread != NULL)
93 /* RS232 lines or pseudo terminals can be completely configured out. */
94 #if NR_RS_LINES == 0
95 #define rs_init(tp) ((void) 0)
96 #endif
98 #if NR_PTYS == 0
99 #define pty_init(tp) ((void) 0)
100 #define do_pty(tp, mp) ((void) 0)
101 #endif
103 struct kmessages kmess;
105 static void tty_timed_out(timer_t *tp);
106 static void settimer(tty_t *tty_ptr, int enable);
107 static void do_cancel(tty_t *tp, message *m_ptr);
108 static void do_ioctl(tty_t *tp, message *m_ptr);
109 static void do_open(tty_t *tp, message *m_ptr);
110 static void do_close(tty_t *tp, message *m_ptr);
111 static void do_read(tty_t *tp, message *m_ptr);
112 static void do_write(tty_t *tp, message *m_ptr);
113 static void do_select(tty_t *tp, message *m_ptr);
114 static void do_status(message *m_ptr);
115 static void in_transfer(tty_t *tp);
116 static int tty_echo(tty_t *tp, int ch);
117 static void rawecho(tty_t *tp, int ch);
118 static int back_over(tty_t *tp);
119 static void reprint(tty_t *tp);
120 static void dev_ioctl(tty_t *tp);
121 static void setattr(tty_t *tp);
122 static void tty_icancel(tty_t *tp);
123 static void tty_init(void);
124 static void do_new_kmess(void);
125 static tty_t * line2tty(int line);
126 static void set_console_line(char term[CONS_ARG]);
127 static void set_kernel_color(char color[CONS_ARG]);
128 static void set_color(tty_t *tp, int color);
129 static void reset_color(tty_t *tp);
131 /* Default attributes. */
132 static struct termios termios_defaults = {
133 TINPUT_DEF, TOUTPUT_DEF, TCTRL_DEF, TLOCAL_DEF, TSPEED_DEF, TSPEED_DEF,
135 TEOF_DEF, TEOL_DEF, TERASE_DEF, TINTR_DEF, TKILL_DEF, TMIN_DEF,
136 TQUIT_DEF, TTIME_DEF, TSUSP_DEF, TSTART_DEF, TSTOP_DEF,
137 TREPRINT_DEF, TLNEXT_DEF, TDISCARD_DEF,
140 static struct winsize winsize_defaults; /* = all zeroes */
142 /* Global variables for the TTY task (declared extern in tty.h). */
143 tty_t tty_table[NR_CONS+NR_RS_LINES+NR_PTYS];
144 int ccurrent; /* currently active console */
145 struct machine machine; /* kernel environment variables */
146 u32_t system_hz;
147 u32_t consoleline = CONS_MINOR;
148 u32_t kernel_msg_color = 0;
150 /* SEF functions and variables. */
151 static void sef_local_startup(void);
152 static int sef_cb_init_fresh(int type, sef_init_info_t *info);
153 static void sef_cb_signal_handler(int signo);
155 extern struct minix_kerninfo *_minix_kerninfo;
157 /*===========================================================================*
158 * tty_task *
159 *===========================================================================*/
160 int main(void)
162 /* Main routine of the terminal task. */
164 message tty_mess; /* buffer for all incoming messages */
165 int ipc_status;
166 unsigned line;
167 int r;
168 register tty_t *tp;
170 /* SEF local startup. */
171 sef_local_startup();
172 while (TRUE) {
173 /* Check for and handle any events on any of the ttys. */
174 for (tp = FIRST_TTY; tp < END_TTY; tp++) {
175 if (tp->tty_events) handle_events(tp);
178 /* Get a request message. */
179 r= driver_receive(ANY, &tty_mess, &ipc_status);
180 if (r != 0)
181 panic("driver_receive failed with: %d", r);
183 /* First handle all kernel notification types that the TTY supports.
184 * - An alarm went off, expire all timers and handle the events.
185 * - A hardware interrupt also is an invitation to check for events.
186 * - A new kernel message is available for printing.
187 * - Reset the console on system shutdown.
188 * Then see if this message is different from a normal device driver
189 * request and should be handled separately. These extra functions
190 * do not operate on a device, in constrast to the driver requests.
193 if (is_ipc_notify(ipc_status)) {
194 switch (_ENDPOINT_P(tty_mess.m_source)) {
195 case CLOCK:
196 /* run watchdogs of expired timers */
197 expire_timers(tty_mess.NOTIFY_TIMESTAMP);
198 break;
199 case HARDWARE:
200 /* hardware interrupt notification */
202 /* fetch chars from keyboard */
203 if (tty_mess.NOTIFY_ARG & kbd_irq_set)
204 kbd_interrupt(&tty_mess);
205 #if NR_RS_LINES > 0
206 /* serial I/O */
207 if (tty_mess.NOTIFY_ARG & rs_irq_set)
208 rs_interrupt(&tty_mess);
209 #endif
210 /* run watchdogs of expired timers */
211 expire_timers(tty_mess.NOTIFY_TIMESTAMP);
212 break;
213 default:
214 /* do nothing */
215 break;
218 /* done, get new message */
219 continue;
222 switch (tty_mess.m_type) {
223 case FKEY_CONTROL: /* (un)register a fkey observer */
224 do_fkey_ctl(&tty_mess);
225 continue;
226 case INPUT_EVENT:
227 do_kb_inject(&tty_mess);
228 continue;
229 default: /* should be a driver request */
230 ; /* do nothing; end switch */
233 /* Only device requests should get to this point. All requests,
234 * except DEV_STATUS, have a minor device number. Check this
235 * exception and get the minor device number otherwise.
237 if (tty_mess.m_type == DEV_STATUS) {
238 do_status(&tty_mess);
239 continue;
241 line = tty_mess.TTY_LINE;
242 if (line == CONS_MINOR || line == LOG_MINOR) {
243 /* /dev/log output goes to /dev/console */
244 if (consoleline != CONS_MINOR) {
245 /* Console output must redirected */
246 line = consoleline;
247 tty_mess.TTY_LINE = line;
250 if (line == KBD_MINOR) {
251 do_kbd(&tty_mess);
252 continue;
253 } else if (line == KBDAUX_MINOR) {
254 do_kbdaux(&tty_mess);
255 continue;
256 } else if (line == VIDEO_MINOR) {
257 do_video(&tty_mess);
258 continue;
259 } else {
260 tp = line2tty(line);
262 /* Terminals and pseudo terminals belong together. We can only
263 * make a distinction between the two based on position in the
264 * tty_table and not on minor number (i.e., use ispty macro).
265 * Hence this special case.
267 if (line - PTYPX_MINOR < NR_PTYS &&
268 tty_mess.m_type != DEV_IOCTL_S){
269 do_pty(tp, &tty_mess);
270 continue;
274 /* If the device doesn't exist or is not configured return ENXIO. */
275 if (tp == NULL || ! tty_active(tp)) {
276 if (tty_mess.m_source != LOG_PROC_NR) {
277 tty_reply(TASK_REPLY, tty_mess.m_source,
278 tty_mess.USER_ENDPT, ENXIO);
280 continue;
283 /* Execute the requested device driver function. */
284 switch (tty_mess.m_type) {
285 case DEV_READ_S: do_read(tp, &tty_mess); break;
286 case DEV_WRITE_S: do_write(tp, &tty_mess); break;
287 case DEV_IOCTL_S: do_ioctl(tp, &tty_mess); break;
288 case DEV_OPEN: do_open(tp, &tty_mess); break;
289 case DEV_CLOSE: do_close(tp, &tty_mess); break;
290 case DEV_SELECT: do_select(tp, &tty_mess); break;
291 case CANCEL: do_cancel(tp, &tty_mess); break;
292 default:
293 printf("Warning, TTY got unexpected request %d from %d\n",
294 tty_mess.m_type, tty_mess.m_source);
295 tty_reply(TASK_REPLY, tty_mess.m_source,
296 tty_mess.USER_ENDPT, EINVAL);
300 return 0;
303 static void
304 set_color(tty_t *tp, int color)
306 message msg;
307 char buf[8];
309 buf[0] = '\033';
310 snprintf(&buf[1], sizeof(buf) - 1, "[1;%dm", color);
311 msg.m_source = KERNEL;
312 msg.IO_GRANT = buf;
313 msg.COUNT = sizeof(buf);
314 do_write(tp, &msg);
317 static void
318 reset_color(tty_t *tp)
320 message msg;
321 char buf[8];
323 #define SGR_COLOR_RESET 39
324 buf[0] = '\033';
325 snprintf(&buf[1], sizeof(buf) - 1, "[0;%dm", SGR_COLOR_RESET);
326 msg.m_source = KERNEL;
327 msg.IO_GRANT = buf;
328 msg.COUNT = sizeof(buf);
329 do_write(tp, &msg);
332 static tty_t *
333 line2tty(int line)
335 /* Convert a terminal line to tty_table pointer */
337 tty_t* tp;
339 if (line == KBD_MINOR || line == KBDAUX_MINOR || line == VIDEO_MINOR) {
340 return(NULL);
341 } else if ((line - CONS_MINOR) < NR_CONS) {
342 tp = tty_addr(line - CONS_MINOR);
343 } else if (line == LOG_MINOR) {
344 tp = tty_addr(consoleline);
345 } else if ((line - RS232_MINOR) < NR_RS_LINES) {
346 tp = tty_addr(line - RS232_MINOR + NR_CONS);
347 } else if ((line - TTYPX_MINOR) < NR_PTYS) {
348 tp = tty_addr(line - TTYPX_MINOR + NR_CONS + NR_RS_LINES);
349 } else if ((line - PTYPX_MINOR) < NR_PTYS) {
350 tp = tty_addr(line - PTYPX_MINOR + NR_CONS + NR_RS_LINES);
351 } else {
352 tp = NULL;
355 return(tp);
358 /*===========================================================================*
359 * sef_local_startup *
360 *===========================================================================*/
361 static void sef_local_startup()
363 /* Register init callbacks. */
364 sef_setcb_init_fresh(sef_cb_init_fresh);
365 sef_setcb_init_restart(sef_cb_init_fresh);
367 /* No live update support for now. */
369 /* Register signal callbacks. */
370 sef_setcb_signal_handler(sef_cb_signal_handler);
372 /* Let SEF perform startup. */
373 sef_startup();
376 /*===========================================================================*
377 * sef_cb_init_fresh *
378 *===========================================================================*/
379 static int sef_cb_init_fresh(int UNUSED(type), sef_init_info_t *UNUSED(info))
381 /* Initialize the tty driver. */
382 int r;
383 char val[CONS_ARG];
385 /* Get kernel environment (protected_mode, pc_at and ega are needed). */
386 if (OK != (r=sys_getmachine(&machine))) {
387 panic("Couldn't obtain kernel environment: %d", r);
390 if (env_get_param("console", val, sizeof(val)) == OK) {
391 set_console_line(val);
394 if ((r = env_get_param("kernelclr", val, sizeof(val))) == OK) {
395 set_kernel_color(val);
398 /* Initialize the TTY driver. */
399 tty_init();
401 /* Final one-time keyboard initialization. */
402 kb_init_once();
404 return(OK);
407 static void
408 set_console_line(char term[CONS_ARG])
410 /* Parse 'term' and redirect console output there. */
411 int i;
413 /* Console */
414 if (!strncmp(term, "console", CONS_ARG - 1)) {
415 consoleline = CONS_MINOR+0;
418 /* The other console terminals */
419 for (i = 1; i < NR_CONS; i++) {
420 char cons[6];
421 strlcpy(cons, "ttyc0", sizeof(cons));
422 cons[4] += i;
423 if (!strncmp(term, cons,
424 CONS_ARG < sizeof(cons) ? CONS_ARG-1 : sizeof(cons) - 1))
425 consoleline = CONS_MINOR + i;
428 /* Serial lines */
429 for (i = 0; i < NR_RS_LINES; i++) {
430 char sercons[6];
431 strlcpy(sercons, "tty00", sizeof(sercons));
432 sercons[4] += i;
433 if (!strncmp(term, sercons,
434 CONS_ARG < sizeof(sercons) ? CONS_ARG-1:sizeof(sercons)-1))
435 consoleline = RS232_MINOR + i;
439 static void
440 set_kernel_color(char color[CONS_ARG])
442 int def_color;
444 #define SGR_COLOR_START 30
445 #define SGR_COLOR_END 37
447 def_color = atoi(color);
448 if ((SGR_COLOR_START + def_color) >= SGR_COLOR_START &&
449 (SGR_COLOR_START + def_color) <= SGR_COLOR_END) {
450 kernel_msg_color = def_color + SGR_COLOR_START;
454 static void
455 do_new_kmess(void)
457 /* Kernel wants to print a new message */
458 struct kmessages *kmess_ptr; /* kmessages structure */
459 char kernel_buf_copy[_KMESS_BUF_SIZE];
460 static int prev_next = 0;
461 int next, bytes, copy, restore = 0;
462 tty_t *tp, rtp;
463 message print_kmsg;
465 assert(_minix_kerninfo);
466 kmess_ptr = _minix_kerninfo->kmessages;
468 /* The kernel buffer is circular; print only the new part. Determine
469 * how many new bytes there are with the help of current and
470 * previous 'next' index. This works fine if less than _KMESS_BUF_SIZE
471 * bytes is new data; else we miss % _KMESS_BUF_SIZE here. Obtain
472 * 'next' only once, since we are operating on shared memory here.
473 * Check for size being positive; the buffer might as well be emptied!
475 next = kmess_ptr->km_next;
476 bytes = ((next + _KMESS_BUF_SIZE) - prev_next) % _KMESS_BUF_SIZE;
477 if (bytes > 0) {
478 /* Copy from current position toward end of buffer */
479 copy = MIN(_KMESS_BUF_SIZE - prev_next, bytes);
480 memcpy(kernel_buf_copy, &kmess_ptr->km_buf[prev_next], copy);
482 /* Copy remainder from start of buffer */
483 if (copy < bytes) {
484 memcpy(&kernel_buf_copy[copy], &kmess_ptr->km_buf[0],
485 bytes - copy);
488 tp = line2tty(consoleline);
489 if (tp == NULL || !tty_active(tp))
490 panic("Don't know where to send kernel messages");
491 if (tp->tty_outleft > 0) {
492 /* Terminal is already printing */
493 rtp = *tp; /* Make backup */
494 tp->tty_outleft = 0; /* So do_write is happy */
495 restore = 1;
498 if (kernel_msg_color != 0)
499 set_color(tp, kernel_msg_color);
500 print_kmsg.m_source = KERNEL;
501 print_kmsg.IO_GRANT = kernel_buf_copy;
502 print_kmsg.COUNT = bytes;
503 do_write(tp, &print_kmsg);
504 if (kernel_msg_color != 0)
505 reset_color(tp);
506 if (restore) {
507 *tp = rtp;
511 /* Store 'next' pointer so that we can determine what part of the
512 * kernel messages buffer to print next time a notification arrives.
514 prev_next = next;
517 /*===========================================================================*
518 * sef_cb_signal_handler *
519 *===========================================================================*/
520 static void sef_cb_signal_handler(int signo)
522 /* Check for known signals, ignore anything else. */
523 switch(signo) {
524 /* There is a pending message from the kernel. */
525 case SIGKMESS:
526 do_new_kmess();
527 break;
528 /* Switch to primary console on termination. */
529 case SIGTERM:
530 cons_stop();
531 break;
535 /*===========================================================================*
536 * do_status *
537 *===========================================================================*/
538 static void do_status(m_ptr)
539 message *m_ptr;
541 register struct tty *tp;
542 int event_found;
543 int status;
544 int ops;
546 /* Check for select or revive events on any of the ttys. If we found an,
547 * event return a single status message for it. The FS will make another
548 * call to see if there is more.
550 event_found = 0;
551 for (tp = FIRST_TTY; tp < END_TTY; tp++) {
552 if ((ops = select_try(tp, tp->tty_select_ops)) &&
553 tp->tty_select_proc == m_ptr->m_source) {
555 /* I/O for a selected minor device is ready. */
556 m_ptr->m_type = DEV_IO_READY;
557 m_ptr->DEV_MINOR = tp->tty_minor;
558 m_ptr->DEV_SEL_OPS = ops;
560 tp->tty_select_ops &= ~ops; /* unmark select event */
561 event_found = 1;
562 break;
564 else if (tp->tty_inrevived && tp->tty_incaller == m_ptr->m_source) {
566 /* Suspended request finished. Send a REVIVE. */
567 m_ptr->m_type = DEV_REVIVE;
568 m_ptr->REP_ENDPT = tp->tty_inproc;
569 m_ptr->REP_IO_GRANT = tp->tty_ingrant;
570 m_ptr->REP_STATUS = tp->tty_incum;
572 tp->tty_inleft = tp->tty_incum = 0;
573 tp->tty_inrevived = 0; /* unmark revive event */
574 tp->tty_ingrant = GRANT_INVALID;
575 event_found = 1;
576 break;
578 else if (tp->tty_outrevived && tp->tty_outcaller == m_ptr->m_source) {
580 /* Suspended request finished. Send a REVIVE. */
581 m_ptr->m_type = DEV_REVIVE;
582 m_ptr->REP_ENDPT = tp->tty_outproc;
583 m_ptr->REP_IO_GRANT = tp->tty_outgrant;
584 m_ptr->REP_STATUS = tp->tty_outcum;
586 tp->tty_outcum = 0;
587 tp->tty_outrevived = 0; /* unmark revive event */
588 tp->tty_outgrant = GRANT_INVALID;
589 event_found = 1;
590 break;
592 else if (tp->tty_iorevived && tp->tty_iocaller == m_ptr->m_source) {
594 /* Suspended request finished. Send a REVIVE. */
595 m_ptr->m_type = DEV_REVIVE;
596 m_ptr->REP_ENDPT = tp->tty_ioproc;
597 m_ptr->REP_IO_GRANT = tp->tty_iogrant;
598 m_ptr->REP_STATUS = tp->tty_iostatus;
599 tp->tty_iorevived = 0; /* unmark revive event */
600 tp->tty_iogrant = GRANT_INVALID;
601 event_found = 1;
602 break;
606 #if NR_PTYS > 0
607 if (!event_found)
608 event_found = pty_status(m_ptr);
609 #endif
610 if (!event_found)
611 event_found= kbd_status(m_ptr);
613 if (! event_found) {
614 /* No events of interest were found. Return an empty message. */
615 m_ptr->m_type = DEV_NO_STATUS;
618 /* Almost done. Send back the reply message to the caller. */
619 status = send(m_ptr->m_source, m_ptr);
620 if (status != OK) {
621 printf("tty`do_status: send to %d failed: %d\n",
622 m_ptr->m_source, status);
626 /*===========================================================================*
627 * do_read *
628 *===========================================================================*/
629 static void do_read(tp, m_ptr)
630 register tty_t *tp; /* pointer to tty struct */
631 register message *m_ptr; /* pointer to message sent to the task */
633 /* A process wants to read from a terminal. */
634 int r;
636 /* Check if there is already a process hanging in a read, check if the
637 * parameters are correct, do I/O.
639 if (tp->tty_inleft > 0) {
640 r = EIO;
641 } else
642 if (m_ptr->COUNT <= 0) {
643 r = EINVAL;
644 } else if (tp->tty_ingrant != GRANT_INVALID) {
645 /* This is actually a fundamental problem with TTY; it can handle
646 * only one reader per minor device. If we don't return an error,
647 * we'll overwrite the previous reader and that process will get
648 * stuck forever. */
649 r = ENOBUFS;
650 } else {
651 /* Copy information from the message to the tty struct. */
652 tp->tty_inrepcode = TASK_REPLY;
653 tp->tty_incaller = m_ptr->m_source;
654 tp->tty_inproc = m_ptr->USER_ENDPT;
655 tp->tty_ingrant = (cp_grant_id_t) m_ptr->IO_GRANT;
656 tp->tty_inoffset = 0;
657 tp->tty_inleft = m_ptr->COUNT;
659 if (!(tp->tty_termios.c_lflag & ICANON)
660 && tp->tty_termios.c_cc[VTIME] > 0) {
661 if (tp->tty_termios.c_cc[VMIN] == 0) {
662 /* MIN & TIME specify a read timer that finishes the
663 * read in TIME/10 seconds if no bytes are available.
665 settimer(tp, TRUE);
666 tp->tty_min = 1;
667 } else {
668 /* MIN & TIME specify an inter-byte timer that may
669 * have to be cancelled if there are no bytes yet.
671 if (tp->tty_eotct == 0) {
672 settimer(tp, FALSE);
673 tp->tty_min = tp->tty_termios.c_cc[VMIN];
678 /* Anything waiting in the input buffer? Clear it out... */
679 in_transfer(tp);
680 /* ...then go back for more. */
681 handle_events(tp);
682 if (tp->tty_inleft == 0) {
683 return; /* already done */
686 /* There were no bytes in the input queue available, so suspend
687 * the caller.
689 r = SUSPEND; /* suspend the caller */
690 tp->tty_inrepcode = TTY_REVIVE;
692 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, r);
693 if (tp->tty_select_ops)
694 select_retry(tp);
697 /*===========================================================================*
698 * do_write *
699 *===========================================================================*/
700 static void do_write(tp, m_ptr)
701 register tty_t *tp;
702 register message *m_ptr; /* pointer to message sent to the task */
704 /* A process wants to write on a terminal. */
705 int r;
707 /* Check if there is already a process hanging in a write, check if the
708 * parameters are correct, do I/O.
710 if (tp->tty_outleft > 0) {
711 r = EIO;
712 } else
713 if (m_ptr->COUNT <= 0) {
714 r = EINVAL;
715 } else {
716 /* Copy message parameters to the tty structure. */
717 tp->tty_outrepcode = TASK_REPLY;
718 tp->tty_outcaller = m_ptr->m_source;
719 tp->tty_outproc = m_ptr->USER_ENDPT;
720 tp->tty_outgrant = (cp_grant_id_t) m_ptr->IO_GRANT;
721 tp->tty_outoffset = 0;
722 tp->tty_outleft = m_ptr->COUNT;
724 /* Try to write. */
725 handle_events(tp);
726 if (tp->tty_outleft == 0)
727 return; /* already done */
729 /* None or not all the bytes could be written, so suspend the
730 * caller.
732 r = SUSPEND; /* suspend the caller */
733 tp->tty_outrepcode = TTY_REVIVE;
735 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, r);
738 /*===========================================================================*
739 * do_ioctl *
740 *===========================================================================*/
741 static void do_ioctl(tp, m_ptr)
742 register tty_t *tp;
743 message *m_ptr; /* pointer to message sent to task */
745 /* Perform an IOCTL on this terminal. Posix termios calls are handled
746 * by the IOCTL system call
749 int r;
750 union {
751 int i;
752 } param;
753 size_t size;
755 /* Size of the ioctl parameter. */
756 switch (m_ptr->TTY_REQUEST) {
757 case TCGETS: /* Posix tcgetattr function */
758 case TCSETS: /* Posix tcsetattr function, TCSANOW option */
759 case TCSETSW: /* Posix tcsetattr function, TCSADRAIN option */
760 case TCSETSF: /* Posix tcsetattr function, TCSAFLUSH option */
761 size = sizeof(struct termios);
762 break;
764 case TCSBRK: /* Posix tcsendbreak function */
765 case TCFLOW: /* Posix tcflow function */
766 case TCFLSH: /* Posix tcflush function */
767 case TIOCGPGRP: /* Posix tcgetpgrp function */
768 case TIOCSPGRP: /* Posix tcsetpgrp function */
769 size = sizeof(int);
770 break;
772 case TIOCGWINSZ: /* get window size (not Posix) */
773 case TIOCSWINSZ: /* set window size (not Posix) */
774 size = sizeof(struct winsize);
775 break;
777 case KIOCSMAP: /* load keymap (Minix extension) */
778 size = sizeof(keymap_t);
779 break;
781 case TIOCSFON: /* load font (Minix extension) */
782 size = sizeof(u8_t [8192]);
783 break;
785 case TCDRAIN: /* Posix tcdrain function -- no parameter */
786 default: size = 0;
789 r = OK;
790 switch (m_ptr->TTY_REQUEST) {
791 case TCGETS:
792 /* Get the termios attributes. */
793 r = sys_safecopyto(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT, 0,
794 (vir_bytes) &tp->tty_termios, (vir_bytes) size);
795 break;
797 case TCSETSW:
798 case TCSETSF:
799 case TCDRAIN:
800 if (tp->tty_outleft > 0) {
801 /* Wait for all ongoing output processing to finish. */
802 tp->tty_iocaller = m_ptr->m_source;
803 tp->tty_ioproc = m_ptr->USER_ENDPT;
804 tp->tty_ioreq = m_ptr->REQUEST;
805 tp->tty_iogrant = (cp_grant_id_t) m_ptr->IO_GRANT;
806 r = SUSPEND;
807 break;
809 if (m_ptr->TTY_REQUEST == TCDRAIN) break;
810 if (m_ptr->TTY_REQUEST == TCSETSF) tty_icancel(tp);
811 /*FALL THROUGH*/
812 case TCSETS:
813 /* Set the termios attributes. */
814 r = sys_safecopyfrom(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT,
815 0, (vir_bytes) &tp->tty_termios, (vir_bytes) size);
816 if (r != OK) break;
817 setattr(tp);
818 break;
820 case TCFLSH:
821 r = sys_safecopyfrom(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT,
822 0, (vir_bytes) &param.i, (vir_bytes) size);
823 if (r != OK) break;
824 switch (param.i) {
825 case TCIFLUSH: tty_icancel(tp); break;
826 case TCOFLUSH: (*tp->tty_ocancel)(tp, 0); break;
827 case TCIOFLUSH: tty_icancel(tp); (*tp->tty_ocancel)(tp, 0); break;
828 default: r = EINVAL;
830 break;
832 case TCFLOW:
833 r = sys_safecopyfrom(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT,
834 0, (vir_bytes) &param.i, (vir_bytes) size);
835 if (r != OK) break;
836 switch (param.i) {
837 case TCOOFF:
838 case TCOON:
839 tp->tty_inhibited = (param.i == TCOOFF);
840 tp->tty_events = 1;
841 break;
842 case TCIOFF:
843 (*tp->tty_echo)(tp, tp->tty_termios.c_cc[VSTOP]);
844 break;
845 case TCION:
846 (*tp->tty_echo)(tp, tp->tty_termios.c_cc[VSTART]);
847 break;
848 default:
849 r = EINVAL;
851 break;
853 case TCSBRK:
854 if (tp->tty_break != NULL) (*tp->tty_break)(tp,0);
855 break;
857 case TIOCGWINSZ:
858 r = sys_safecopyto(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT, 0,
859 (vir_bytes) &tp->tty_winsize, (vir_bytes) size);
860 break;
862 case TIOCSWINSZ:
863 r = sys_safecopyfrom(m_ptr->m_source, (cp_grant_id_t) m_ptr->IO_GRANT,
864 0, (vir_bytes) &tp->tty_winsize, (vir_bytes) size);
865 sigchar(tp, SIGWINCH, 0);
866 break;
868 case KIOCSMAP:
869 /* Load a new keymap (only /dev/console). */
870 if (isconsole(tp)) r = kbd_loadmap(m_ptr);
871 break;
873 case TIOCSFON_OLD:
874 printf("TTY: old TIOCSFON ignored.\n");
875 break;
876 case TIOCSFON:
877 /* Load a font into an EGA or VGA card (hs@hck.hr) */
878 if (isconsole(tp)) r = con_loadfont(m_ptr);
879 break;
881 /* These Posix functions are allowed to fail if _POSIX_JOB_CONTROL is
882 * not defined.
884 case TIOCGPGRP:
885 case TIOCSPGRP:
886 default:
887 r = ENOTTY;
890 /* Send the reply. */
891 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, r);
894 /*===========================================================================*
895 * do_open *
896 *===========================================================================*/
897 static void do_open(tp, m_ptr)
898 register tty_t *tp;
899 message *m_ptr; /* pointer to message sent to task */
901 /* A tty line has been opened. Make it the callers controlling tty if
902 * O_NOCTTY is *not* set and it is not the log device. 1 is returned if
903 * the tty is made the controlling tty, otherwise OK or an error code.
905 int r = OK;
907 if (m_ptr->TTY_LINE == LOG_MINOR) {
908 /* The log device is a write-only diagnostics device. */
909 if (m_ptr->COUNT & R_BIT) r = EACCES;
910 } else {
911 if (!(m_ptr->COUNT & O_NOCTTY)) {
912 tp->tty_pgrp = m_ptr->USER_ENDPT;
913 r = 1;
915 tp->tty_openct++;
916 if (tp->tty_openct == 1) {
917 /* Tell the device that the tty is opened */
918 (*tp->tty_open)(tp, 0);
921 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, r);
924 /*===========================================================================*
925 * do_close *
926 *===========================================================================*/
927 static void do_close(tp, m_ptr)
928 register tty_t *tp;
929 message *m_ptr; /* pointer to message sent to task */
931 /* A tty line has been closed. Clean up the line if it is the last close. */
933 if (m_ptr->TTY_LINE != LOG_MINOR && --tp->tty_openct == 0) {
934 tp->tty_pgrp = 0;
935 tty_icancel(tp);
936 (*tp->tty_ocancel)(tp, 0);
937 (*tp->tty_close)(tp, 0);
938 tp->tty_termios = termios_defaults;
939 tp->tty_winsize = winsize_defaults;
940 setattr(tp);
942 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, OK);
945 /*===========================================================================*
946 * do_cancel *
947 *===========================================================================*/
948 static void do_cancel(tp, m_ptr)
949 register tty_t *tp;
950 message *m_ptr; /* pointer to message sent to task */
952 /* A signal has been sent to a process that is hanging trying to read or write.
953 * The pending read or write must be finished off immediately.
956 int proc_nr;
957 int mode;
958 int r = EINTR;
960 /* Check the parameters carefully, to avoid cancelling twice. */
961 proc_nr = m_ptr->USER_ENDPT;
962 mode = m_ptr->COUNT;
963 if ((mode & R_BIT) && tp->tty_inleft != 0 && proc_nr == tp->tty_inproc &&
964 tp->tty_ingrant == (cp_grant_id_t) m_ptr->IO_GRANT) {
965 /* Process was reading when killed. Clean up input. */
966 tty_icancel(tp);
967 r = tp->tty_incum > 0 ? tp->tty_incum : EAGAIN;
968 tp->tty_inleft = tp->tty_incum = tp->tty_inrevived = 0;
969 tp->tty_ingrant = GRANT_INVALID;
971 if ((mode & W_BIT) && tp->tty_outleft != 0 && proc_nr == tp->tty_outproc &&
972 tp->tty_outgrant == (cp_grant_id_t) m_ptr->IO_GRANT) {
973 /* Process was writing when killed. Clean up output. */
974 r = tp->tty_outcum > 0 ? tp->tty_outcum : EAGAIN;
975 tp->tty_outleft = tp->tty_outcum = tp->tty_outrevived = 0;
976 tp->tty_outgrant = GRANT_INVALID;
978 if (tp->tty_ioreq != 0 && proc_nr == tp->tty_ioproc) {
979 /* Process was waiting for output to drain. */
980 tp->tty_ioreq = 0;
982 tp->tty_events = 1;
983 tty_reply(TASK_REPLY, m_ptr->m_source, proc_nr, r);
986 int select_try(struct tty *tp, int ops)
988 int ready_ops = 0;
990 /* Special case. If line is hung up, no operations will block.
991 * (and it can be seen as an exceptional condition.)
993 if (tp->tty_termios.c_ospeed == B0) {
994 ready_ops |= ops;
997 if (ops & SEL_RD) {
998 /* will i/o not block on read? */
999 if (tp->tty_inleft > 0) {
1000 ready_ops |= SEL_RD; /* EIO - no blocking */
1001 } else if (tp->tty_incount > 0) {
1002 /* Is a regular read possible? tty_incount
1003 * says there is data. But a read will only succeed
1004 * in canonical mode if a newline has been seen.
1006 if (!(tp->tty_termios.c_lflag & ICANON) ||
1007 tp->tty_eotct > 0) {
1008 ready_ops |= SEL_RD;
1013 if (ops & SEL_WR) {
1014 if (tp->tty_outleft > 0) ready_ops |= SEL_WR;
1015 else if ((*tp->tty_devwrite)(tp, 1)) ready_ops |= SEL_WR;
1017 return ready_ops;
1020 int select_retry(struct tty *tp)
1022 if (tp->tty_select_ops && select_try(tp, tp->tty_select_ops))
1023 notify(tp->tty_select_proc);
1024 return OK;
1027 /*===========================================================================*
1028 * handle_events *
1029 *===========================================================================*/
1030 void handle_events(tp)
1031 tty_t *tp; /* TTY to check for events. */
1033 /* Handle any events pending on a TTY. These events are usually device
1034 * interrupts.
1036 * Two kinds of events are prominent:
1037 * - a character has been received from the console or an RS232 line.
1038 * - an RS232 line has completed a write request (on behalf of a user).
1039 * The interrupt handler may delay the interrupt message at its discretion
1040 * to avoid swamping the TTY task. Messages may be overwritten when the
1041 * lines are fast or when there are races between different lines, input
1042 * and output, because MINIX only provides single buffering for interrupt
1043 * messages (in proc.c). This is handled by explicitly checking each line
1044 * for fresh input and completed output on each interrupt.
1047 do {
1048 tp->tty_events = 0;
1050 /* Read input and perform input processing. */
1051 (*tp->tty_devread)(tp, 0);
1053 /* Perform output processing and write output. */
1054 (*tp->tty_devwrite)(tp, 0);
1056 /* Ioctl waiting for some event? */
1057 if (tp->tty_ioreq != 0) dev_ioctl(tp);
1058 } while (tp->tty_events);
1060 /* Transfer characters from the input queue to a waiting process. */
1061 in_transfer(tp);
1063 /* Reply if enough bytes are available. */
1064 if (tp->tty_incum >= tp->tty_min && tp->tty_inleft > 0) {
1065 if (tp->tty_inrepcode == TTY_REVIVE) {
1066 notify(tp->tty_incaller);
1067 tp->tty_inrevived = 1;
1068 } else {
1069 tty_reply(tp->tty_inrepcode, tp->tty_incaller,
1070 tp->tty_inproc, tp->tty_incum);
1071 tp->tty_inleft = tp->tty_incum = 0;
1072 tp->tty_inrevived = 0;
1073 tp->tty_ingrant = GRANT_INVALID;
1076 if (tp->tty_select_ops)
1078 select_retry(tp);
1080 #if NR_PTYS > 0
1081 if (ispty(tp))
1082 select_retry_pty(tp);
1083 #endif
1086 /*===========================================================================*
1087 * in_transfer *
1088 *===========================================================================*/
1089 static void in_transfer(tp)
1090 register tty_t *tp; /* pointer to terminal to read from */
1092 /* Transfer bytes from the input queue to a process reading from a terminal. */
1094 int ch;
1095 int count;
1096 char buf[64], *bp;
1098 /* Force read to succeed if the line is hung up, looks like EOF to reader. */
1099 if (tp->tty_termios.c_ospeed == B0) tp->tty_min = 0;
1101 /* Anything to do? */
1102 if (tp->tty_inleft == 0 || tp->tty_eotct < tp->tty_min) return;
1104 bp = buf;
1105 while (tp->tty_inleft > 0 && tp->tty_eotct > 0) {
1106 ch = *tp->tty_intail;
1108 if (!(ch & IN_EOF)) {
1109 /* One character to be delivered to the user. */
1110 *bp = ch & IN_CHAR;
1111 tp->tty_inleft--;
1112 if (++bp == bufend(buf)) {
1113 /* Temp buffer full, copy to user space. */
1114 sys_safecopyto(tp->tty_incaller,
1115 tp->tty_ingrant, tp->tty_inoffset,
1116 (vir_bytes) buf,
1117 (vir_bytes) buflen(buf));
1118 tp->tty_inoffset += buflen(buf);
1119 tp->tty_incum += buflen(buf);
1120 bp = buf;
1124 /* Remove the character from the input queue. */
1125 if (++tp->tty_intail == bufend(tp->tty_inbuf))
1126 tp->tty_intail = tp->tty_inbuf;
1127 tp->tty_incount--;
1128 if (ch & IN_EOT) {
1129 tp->tty_eotct--;
1130 /* Don't read past a line break in canonical mode. */
1131 if (tp->tty_termios.c_lflag & ICANON) tp->tty_inleft = 0;
1135 if (bp > buf) {
1136 /* Leftover characters in the buffer. */
1137 count = bp - buf;
1138 sys_safecopyto(tp->tty_incaller,
1139 tp->tty_ingrant, tp->tty_inoffset,
1140 (vir_bytes) buf, (vir_bytes) count);
1141 tp->tty_inoffset += count;
1142 tp->tty_incum += count;
1145 /* Usually reply to the reader, possibly even if incum == 0 (EOF). */
1146 if (tp->tty_inleft == 0) {
1147 if (tp->tty_inrepcode == TTY_REVIVE) {
1148 notify(tp->tty_incaller);
1149 tp->tty_inrevived = 1;
1150 } else {
1151 tty_reply(tp->tty_inrepcode, tp->tty_incaller,
1152 tp->tty_inproc, tp->tty_incum);
1153 tp->tty_inleft = tp->tty_incum = 0;
1154 tp->tty_inrevived = 0;
1155 tp->tty_ingrant = GRANT_INVALID;
1160 /*===========================================================================*
1161 * in_process *
1162 *===========================================================================*/
1163 static void in_process_send_byte(
1164 tty_t *tp, /* terminal on which character has arrived */
1165 int ch /* input character */
1168 /* Save the character in the input queue. */
1169 *tp->tty_inhead++ = ch;
1170 if (tp->tty_inhead == bufend(tp->tty_inbuf))
1171 tp->tty_inhead = tp->tty_inbuf;
1172 tp->tty_incount++;
1173 if (ch & IN_EOT) tp->tty_eotct++;
1175 /* Try to finish input if the queue threatens to overflow. */
1176 if (tp->tty_incount == buflen(tp->tty_inbuf)) in_transfer(tp);
1179 int in_process(tp, buf, count, scode)
1180 register tty_t *tp; /* terminal on which character has arrived */
1181 char *buf; /* buffer with input characters */
1182 int count; /* number of input characters */
1183 int scode; /* scan code */
1185 /* Characters have just been typed in. Process, save, and echo them. Return
1186 * the number of characters processed.
1189 int ch, sig, ct;
1190 int timeset = FALSE;
1192 /* Send scancode if requested */
1193 if (tp->tty_termios.c_iflag & SCANCODES) {
1194 in_process_send_byte(tp, (scode & BYTE) | IN_EOT);
1197 for (ct = 0; ct < count; ct++) {
1198 /* Take one character. */
1199 ch = *buf++ & BYTE;
1201 /* Strip to seven bits? */
1202 if (tp->tty_termios.c_iflag & ISTRIP) ch &= 0x7F;
1204 /* Input extensions? */
1205 if (tp->tty_termios.c_lflag & IEXTEN) {
1207 /* Previous character was a character escape? */
1208 if (tp->tty_escaped) {
1209 tp->tty_escaped = NOT_ESCAPED;
1210 ch |= IN_ESC; /* protect character */
1213 /* LNEXT (^V) to escape the next character? */
1214 if (ch == tp->tty_termios.c_cc[VLNEXT]) {
1215 tp->tty_escaped = ESCAPED;
1216 rawecho(tp, '^');
1217 rawecho(tp, '\b');
1218 continue; /* do not store the escape */
1221 /* REPRINT (^R) to reprint echoed characters? */
1222 if (ch == tp->tty_termios.c_cc[VREPRINT]) {
1223 reprint(tp);
1224 continue;
1228 /* _POSIX_VDISABLE is a normal character value, so better escape it. */
1229 if (ch == _POSIX_VDISABLE) ch |= IN_ESC;
1231 /* Map CR to LF, ignore CR, or map LF to CR. */
1232 if (ch == '\r') {
1233 if (tp->tty_termios.c_iflag & IGNCR) continue;
1234 if (tp->tty_termios.c_iflag & ICRNL) ch = '\n';
1235 } else
1236 if (ch == '\n') {
1237 if (tp->tty_termios.c_iflag & INLCR) ch = '\r';
1240 /* Canonical mode? */
1241 if (tp->tty_termios.c_lflag & ICANON) {
1243 /* Erase processing (rub out of last character). */
1244 if (ch == tp->tty_termios.c_cc[VERASE]) {
1245 (void) back_over(tp);
1246 if (!(tp->tty_termios.c_lflag & ECHOE)) {
1247 (void) tty_echo(tp, ch);
1249 continue;
1252 /* Kill processing (remove current line). */
1253 if (ch == tp->tty_termios.c_cc[VKILL]) {
1254 while (back_over(tp)) {}
1255 if (!(tp->tty_termios.c_lflag & ECHOE)) {
1256 (void) tty_echo(tp, ch);
1257 if (tp->tty_termios.c_lflag & ECHOK)
1258 rawecho(tp, '\n');
1260 continue;
1263 /* EOF (^D) means end-of-file, an invisible "line break". */
1264 if (ch == tp->tty_termios.c_cc[VEOF]) ch |= IN_EOT | IN_EOF;
1266 /* The line may be returned to the user after an LF. */
1267 if (ch == '\n') ch |= IN_EOT;
1269 /* Same thing with EOL, whatever it may be. */
1270 if (ch == tp->tty_termios.c_cc[VEOL]) ch |= IN_EOT;
1273 /* Start/stop input control? */
1274 if (tp->tty_termios.c_iflag & IXON) {
1276 /* Output stops on STOP (^S). */
1277 if (ch == tp->tty_termios.c_cc[VSTOP]) {
1278 tp->tty_inhibited = STOPPED;
1279 tp->tty_events = 1;
1280 continue;
1283 /* Output restarts on START (^Q) or any character if IXANY. */
1284 if (tp->tty_inhibited) {
1285 if (ch == tp->tty_termios.c_cc[VSTART]
1286 || (tp->tty_termios.c_iflag & IXANY)) {
1287 tp->tty_inhibited = RUNNING;
1288 tp->tty_events = 1;
1289 if (ch == tp->tty_termios.c_cc[VSTART])
1290 continue;
1295 if (tp->tty_termios.c_lflag & ISIG) {
1296 /* Check for INTR (^?) and QUIT (^\) characters. */
1297 if (ch == tp->tty_termios.c_cc[VINTR]
1298 || ch == tp->tty_termios.c_cc[VQUIT]) {
1299 sig = SIGINT;
1300 if (ch == tp->tty_termios.c_cc[VQUIT]) sig = SIGQUIT;
1301 sigchar(tp, sig, 1);
1302 (void) tty_echo(tp, ch);
1303 continue;
1307 /* Is there space in the input buffer? */
1308 if (tp->tty_incount == buflen(tp->tty_inbuf)) {
1309 /* No space; discard in canonical mode, keep in raw mode. */
1310 if (tp->tty_termios.c_lflag & ICANON) continue;
1311 break;
1314 if (!(tp->tty_termios.c_lflag & ICANON)) {
1315 /* In raw mode all characters are "line breaks". */
1316 ch |= IN_EOT;
1318 /* Start an inter-byte timer? */
1319 if (!timeset && tp->tty_termios.c_cc[VMIN] > 0
1320 && tp->tty_termios.c_cc[VTIME] > 0) {
1321 settimer(tp, TRUE);
1322 timeset = TRUE;
1326 /* Perform the intricate function of echoing. */
1327 if (tp->tty_termios.c_lflag & (ECHO|ECHONL)) ch = tty_echo(tp, ch);
1329 /* Send processed byte of input unless scancodes sent instead */
1330 if (!(tp->tty_termios.c_iflag & SCANCODES)) {
1331 in_process_send_byte(tp, ch);
1334 return ct;
1337 /*===========================================================================*
1338 * echo *
1339 *===========================================================================*/
1340 static int tty_echo(tp, ch)
1341 register tty_t *tp; /* terminal on which to echo */
1342 register int ch; /* pointer to character to echo */
1344 /* Echo the character if echoing is on. Some control characters are echoed
1345 * with their normal effect, other control characters are echoed as "^X",
1346 * normal characters are echoed normally. EOF (^D) is echoed, but immediately
1347 * backspaced over. Return the character with the echoed length added to its
1348 * attributes.
1350 int len, rp;
1352 ch &= ~IN_LEN;
1353 if (!(tp->tty_termios.c_lflag & ECHO)) {
1354 if (ch == ('\n' | IN_EOT) && (tp->tty_termios.c_lflag
1355 & (ICANON|ECHONL)) == (ICANON|ECHONL))
1356 (*tp->tty_echo)(tp, '\n');
1357 return(ch);
1360 /* "Reprint" tells if the echo output has been messed up by other output. */
1361 rp = tp->tty_incount == 0 ? FALSE : tp->tty_reprint;
1363 if ((ch & IN_CHAR) < ' ') {
1364 switch (ch & (IN_ESC|IN_EOF|IN_EOT|IN_CHAR)) {
1365 case '\t':
1366 len = 0;
1367 do {
1368 (*tp->tty_echo)(tp, ' ');
1369 len++;
1370 } while (len < TAB_SIZE && (tp->tty_position & TAB_MASK) != 0);
1371 break;
1372 case '\r' | IN_EOT:
1373 case '\n' | IN_EOT:
1374 (*tp->tty_echo)(tp, ch & IN_CHAR);
1375 len = 0;
1376 break;
1377 default:
1378 (*tp->tty_echo)(tp, '^');
1379 (*tp->tty_echo)(tp, '@' + (ch & IN_CHAR));
1380 len = 2;
1382 } else
1383 if ((ch & IN_CHAR) == '\177') {
1384 /* A DEL prints as "^?". */
1385 (*tp->tty_echo)(tp, '^');
1386 (*tp->tty_echo)(tp, '?');
1387 len = 2;
1388 } else {
1389 (*tp->tty_echo)(tp, ch & IN_CHAR);
1390 len = 1;
1392 if (ch & IN_EOF) while (len > 0) { (*tp->tty_echo)(tp, '\b'); len--; }
1394 tp->tty_reprint = rp;
1395 return(ch | (len << IN_LSHIFT));
1398 /*===========================================================================*
1399 * rawecho *
1400 *===========================================================================*/
1401 static void rawecho(tp, ch)
1402 register tty_t *tp;
1403 int ch;
1405 /* Echo without interpretation if ECHO is set. */
1406 int rp = tp->tty_reprint;
1407 if (tp->tty_termios.c_lflag & ECHO) (*tp->tty_echo)(tp, ch);
1408 tp->tty_reprint = rp;
1411 /*===========================================================================*
1412 * back_over *
1413 *===========================================================================*/
1414 static int back_over(tp)
1415 register tty_t *tp;
1417 /* Backspace to previous character on screen and erase it. */
1418 u16_t *head;
1419 int len;
1421 if (tp->tty_incount == 0) return(0); /* queue empty */
1422 head = tp->tty_inhead;
1423 if (head == tp->tty_inbuf) head = bufend(tp->tty_inbuf);
1424 if (*--head & IN_EOT) return(0); /* can't erase "line breaks" */
1425 if (tp->tty_reprint) reprint(tp); /* reprint if messed up */
1426 tp->tty_inhead = head;
1427 tp->tty_incount--;
1428 if (tp->tty_termios.c_lflag & ECHOE) {
1429 len = (*head & IN_LEN) >> IN_LSHIFT;
1430 while (len > 0) {
1431 rawecho(tp, '\b');
1432 rawecho(tp, ' ');
1433 rawecho(tp, '\b');
1434 len--;
1437 return(1); /* one character erased */
1440 /*===========================================================================*
1441 * reprint *
1442 *===========================================================================*/
1443 static void reprint(tp)
1444 register tty_t *tp; /* pointer to tty struct */
1446 /* Restore what has been echoed to screen before if the user input has been
1447 * messed up by output, or if REPRINT (^R) is typed.
1449 int count;
1450 u16_t *head;
1452 tp->tty_reprint = FALSE;
1454 /* Find the last line break in the input. */
1455 head = tp->tty_inhead;
1456 count = tp->tty_incount;
1457 while (count > 0) {
1458 if (head == tp->tty_inbuf) head = bufend(tp->tty_inbuf);
1459 if (head[-1] & IN_EOT) break;
1460 head--;
1461 count--;
1463 if (count == tp->tty_incount) return; /* no reason to reprint */
1465 /* Show REPRINT (^R) and move to a new line. */
1466 (void) tty_echo(tp, tp->tty_termios.c_cc[VREPRINT] | IN_ESC);
1467 rawecho(tp, '\r');
1468 rawecho(tp, '\n');
1470 /* Reprint from the last break onwards. */
1471 do {
1472 if (head == bufend(tp->tty_inbuf)) head = tp->tty_inbuf;
1473 *head = tty_echo(tp, *head);
1474 head++;
1475 count++;
1476 } while (count < tp->tty_incount);
1479 /*===========================================================================*
1480 * out_process *
1481 *===========================================================================*/
1482 void out_process(tp, bstart, bpos, bend, icount, ocount)
1483 tty_t *tp;
1484 char *bstart, *bpos, *bend; /* start/pos/end of circular buffer */
1485 int *icount; /* # input chars / input chars used */
1486 int *ocount; /* max output chars / output chars used */
1488 /* Perform output processing on a circular buffer. *icount is the number of
1489 * bytes to process, and the number of bytes actually processed on return.
1490 * *ocount is the space available on input and the space used on output.
1491 * (Naturally *icount < *ocount.) The column position is updated modulo
1492 * the TAB size, because we really only need it for tabs.
1495 int tablen;
1496 int ict = *icount;
1497 int oct = *ocount;
1498 int pos = tp->tty_position;
1500 while (ict > 0) {
1501 switch (*bpos) {
1502 case '\7':
1503 break;
1504 case '\b':
1505 pos--;
1506 break;
1507 case '\r':
1508 pos = 0;
1509 break;
1510 case '\n':
1511 if ((tp->tty_termios.c_oflag & (OPOST|ONLCR))
1512 == (OPOST|ONLCR)) {
1513 /* Map LF to CR+LF if there is space. Note that the
1514 * next character in the buffer is overwritten, so
1515 * we stop at this point.
1517 if (oct >= 2) {
1518 *bpos = '\r';
1519 if (++bpos == bend) bpos = bstart;
1520 *bpos = '\n';
1521 pos = 0;
1522 ict--;
1523 oct -= 2;
1525 goto out_done; /* no space or buffer got changed */
1527 break;
1528 case '\t':
1529 /* Best guess for the tab length. */
1530 tablen = TAB_SIZE - (pos & TAB_MASK);
1532 if ((tp->tty_termios.c_oflag & (OPOST|XTABS))
1533 == (OPOST|XTABS)) {
1534 /* Tabs must be expanded. */
1535 if (oct >= tablen) {
1536 pos += tablen;
1537 ict--;
1538 oct -= tablen;
1539 do {
1540 *bpos = ' ';
1541 if (++bpos == bend) bpos = bstart;
1542 } while (--tablen != 0);
1544 goto out_done;
1546 /* Tabs are output directly. */
1547 pos += tablen;
1548 break;
1549 default:
1550 /* Assume any other character prints as one character. */
1551 pos++;
1553 if (++bpos == bend) bpos = bstart;
1554 ict--;
1555 oct--;
1557 out_done:
1558 tp->tty_position = pos & TAB_MASK;
1560 *icount -= ict; /* [io]ct are the number of chars not used */
1561 *ocount -= oct; /* *[io]count are the number of chars that are used */
1564 /*===========================================================================*
1565 * dev_ioctl *
1566 *===========================================================================*/
1567 static void dev_ioctl(tp)
1568 tty_t *tp;
1570 /* The ioctl's TCSETSW, TCSETSF and TCDRAIN wait for output to finish to make
1571 * sure that an attribute change doesn't affect the processing of current
1572 * output. Once output finishes the ioctl is executed as in do_ioctl().
1574 int result = EINVAL;
1576 if (tp->tty_outleft > 0) return; /* output not finished */
1578 if (tp->tty_ioreq != TCDRAIN) {
1579 if (tp->tty_ioreq == TCSETSF) tty_icancel(tp);
1580 result = sys_safecopyfrom(tp->tty_iocaller, tp->tty_iogrant, 0,
1581 (vir_bytes) &tp->tty_termios,
1582 (vir_bytes) sizeof(tp->tty_termios));
1583 if (result == OK) setattr(tp);
1585 tp->tty_ioreq = 0;
1586 notify(tp->tty_iocaller);
1587 tp->tty_iorevived = 1;
1588 tp->tty_iostatus = result;
1591 /*===========================================================================*
1592 * setattr *
1593 *===========================================================================*/
1594 static void setattr(tp)
1595 tty_t *tp;
1597 /* Apply the new line attributes (raw/canonical, line speed, etc.) */
1598 u16_t *inp;
1599 int count;
1601 if (!(tp->tty_termios.c_lflag & ICANON)) {
1602 /* Raw mode; put a "line break" on all characters in the input queue.
1603 * It is undefined what happens to the input queue when ICANON is
1604 * switched off, a process should use TCSAFLUSH to flush the queue.
1605 * Keeping the queue to preserve typeahead is the Right Thing, however
1606 * when a process does use TCSANOW to switch to raw mode.
1608 count = tp->tty_eotct = tp->tty_incount;
1609 inp = tp->tty_intail;
1610 while (count > 0) {
1611 *inp |= IN_EOT;
1612 if (++inp == bufend(tp->tty_inbuf)) inp = tp->tty_inbuf;
1613 --count;
1617 /* Inspect MIN and TIME. */
1618 settimer(tp, FALSE);
1619 if (tp->tty_termios.c_lflag & ICANON) {
1620 /* No MIN & TIME in canonical mode. */
1621 tp->tty_min = 1;
1622 } else {
1623 /* In raw mode MIN is the number of chars wanted, and TIME how long
1624 * to wait for them. With interesting exceptions if either is zero.
1626 tp->tty_min = tp->tty_termios.c_cc[VMIN];
1627 if (tp->tty_min == 0 && tp->tty_termios.c_cc[VTIME] > 0)
1628 tp->tty_min = 1;
1631 if (!(tp->tty_termios.c_iflag & IXON)) {
1632 /* No start/stop output control, so don't leave output inhibited. */
1633 tp->tty_inhibited = RUNNING;
1634 tp->tty_events = 1;
1637 /* Setting the output speed to zero hangs up the phone. */
1638 if (tp->tty_termios.c_ospeed == B0) sigchar(tp, SIGHUP, 1);
1640 /* SCANCODES is supported only for the console */
1641 if (!isconsole(tp)) tp->tty_termios.c_iflag &= ~SCANCODES;
1643 /* Set new line speed, character size, etc at the device level. */
1644 (*tp->tty_ioctl)(tp, 0);
1647 /*===========================================================================*
1648 * tty_reply *
1649 *===========================================================================*/
1650 void
1651 tty_reply_f(
1652 file, line, code, replyee, proc_nr, status)
1653 char *file;
1654 int line;
1655 int code; /* TASK_REPLY or REVIVE */
1656 int replyee; /* destination address for the reply */
1657 int proc_nr; /* to whom should the reply go? */
1658 int status; /* reply code */
1660 /* Send a reply to a process that wanted to read or write data. */
1661 message tty_mess;
1663 tty_mess.m_type = code;
1664 tty_mess.REP_ENDPT = proc_nr;
1665 tty_mess.REP_STATUS = status;
1667 /* Don't reply to KERNEL (kernel messages) */
1668 if (replyee == KERNEL) return;
1670 /* TTY is not supposed to send a TTY_REVIVE message. The
1671 * REVIVE message is gone, TTY_REVIVE is only used as an internal
1672 * placeholder for something that is not supposed to be a message.
1674 if(code == TTY_REVIVE) {
1675 printf("%s:%d: ", file, line);
1676 panic("tty_reply sending TTY_REVIVE");
1679 status = send(replyee, &tty_mess);
1680 if (status != OK)
1681 printf("tty`tty_reply: send to %d failed: %d\n", replyee, status);
1684 /*===========================================================================*
1685 * sigchar *
1686 *===========================================================================*/
1687 void sigchar(tp, sig, mayflush)
1688 register tty_t *tp;
1689 int sig; /* SIGINT, SIGQUIT, SIGKILL or SIGHUP */
1690 int mayflush;
1692 /* Process a SIGINT, SIGQUIT or SIGKILL char from the keyboard or SIGHUP from
1693 * a tty close, "stty 0", or a real RS-232 hangup. PM will send the signal to
1694 * the process group (INT, QUIT), all processes (KILL), or the session leader
1695 * (HUP).
1697 int status;
1699 if (tp->tty_pgrp != 0) {
1700 if (OK != (status = sys_kill(tp->tty_pgrp, sig))) {
1701 panic("Error; call to sys_kill failed: %d", status);
1705 if (mayflush && !(tp->tty_termios.c_lflag & NOFLSH)) {
1706 tp->tty_incount = tp->tty_eotct = 0; /* kill earlier input */
1707 tp->tty_intail = tp->tty_inhead;
1708 (*tp->tty_ocancel)(tp, 0); /* kill all output */
1709 tp->tty_inhibited = RUNNING;
1710 tp->tty_events = 1;
1714 /*===========================================================================*
1715 * tty_icancel *
1716 *===========================================================================*/
1717 static void tty_icancel(tp)
1718 register tty_t *tp;
1720 /* Discard all pending input, tty buffer or device. */
1722 tp->tty_incount = tp->tty_eotct = 0;
1723 tp->tty_intail = tp->tty_inhead;
1724 (*tp->tty_icancel)(tp, 0);
1727 /*===========================================================================*
1728 * tty_devnop *
1729 *===========================================================================*/
1730 static int tty_devnop(tty_t *UNUSED(tp), int UNUSED(try))
1732 /* Some functions need not be implemented at the device level. */
1733 return 0;
1736 /*===========================================================================*
1737 * tty_init *
1738 *===========================================================================*/
1739 static void tty_init()
1741 /* Initialize tty structure and call device initialization routines. */
1743 register tty_t *tp;
1744 int s;
1746 system_hz = sys_hz();
1748 /* Initialize the terminal lines. */
1749 memset(tty_table, '\0' , sizeof(tty_table));
1751 for (tp = FIRST_TTY,s=0; tp < END_TTY; tp++,s++) {
1753 tp->tty_index = s;
1754 init_timer(&tp->tty_tmr);
1756 tp->tty_intail = tp->tty_inhead = tp->tty_inbuf;
1757 tp->tty_min = 1;
1758 tp->tty_ingrant = tp->tty_outgrant = tp->tty_iogrant = GRANT_INVALID;
1759 tp->tty_termios = termios_defaults;
1760 tp->tty_icancel = tp->tty_ocancel = tp->tty_ioctl = tp->tty_close =
1761 tp->tty_open = tty_devnop;
1762 if (tp < tty_addr(NR_CONS)) {
1763 scr_init(tp);
1765 /* Initialize the keyboard driver. */
1766 kb_init(tp);
1768 tp->tty_minor = CONS_MINOR + s;
1769 } else
1770 if (tp < tty_addr(NR_CONS+NR_RS_LINES)) {
1771 rs_init(tp);
1772 tp->tty_minor = RS232_MINOR + s-NR_CONS;
1773 } else {
1774 pty_init(tp);
1775 tp->tty_minor = s - (NR_CONS+NR_RS_LINES) + TTYPX_MINOR;
1781 /*===========================================================================*
1782 * tty_timed_out *
1783 *===========================================================================*/
1784 static void tty_timed_out(timer_t *tp)
1786 /* This timer has expired. Set the events flag, to force processing. */
1787 tty_t *tty_ptr;
1788 tty_ptr = &tty_table[tmr_arg(tp)->ta_int];
1789 tty_ptr->tty_min = 0; /* force read to succeed */
1790 tty_ptr->tty_events = 1;
1793 /*===========================================================================*
1794 * settimer *
1795 *===========================================================================*/
1796 static void settimer(tty_ptr, enable)
1797 tty_t *tty_ptr; /* line to set or unset a timer on */
1798 int enable; /* set timer if true, otherwise unset */
1800 clock_t ticks;
1802 if (enable) {
1803 ticks = tty_ptr->tty_termios.c_cc[VTIME] * (system_hz/10);
1805 /* Set a new timer for enabling the TTY events flags. */
1806 set_timer(&tty_ptr->tty_tmr, ticks, tty_timed_out, tty_ptr->tty_index);
1807 } else {
1808 /* Remove the timer from the active and expired lists. */
1809 cancel_timer(&tty_ptr->tty_tmr);
1813 /*===========================================================================*
1814 * do_select *
1815 *===========================================================================*/
1816 static void do_select(tp, m_ptr)
1817 register tty_t *tp; /* pointer to tty struct */
1818 register message *m_ptr; /* pointer to message sent to the task */
1820 int ops, ready_ops = 0, watch;
1822 ops = m_ptr->USER_ENDPT & (SEL_RD|SEL_WR|SEL_ERR);
1823 watch = (m_ptr->USER_ENDPT & SEL_NOTIFY) ? 1 : 0;
1825 ready_ops = select_try(tp, ops);
1827 if (!ready_ops && ops && watch) {
1828 tp->tty_select_ops |= ops;
1829 tp->tty_select_proc = m_ptr->m_source;
1832 tty_reply(TASK_REPLY, m_ptr->m_source, m_ptr->USER_ENDPT, ready_ops);
1834 return;