]> Zhao Yanbai Git Server - minix.git/blob - drivers/tty/tty.c
5bcc05b7fe15e10cb3b7d2ae4e5547e197c5a1ff
[minix.git] / drivers / tty / tty.c
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.
6 *
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.
18 *
19 * The valid messages and their parameters are:
20 *
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 * CANCEL: terminate a previous incomplete system call immediately
31 *
32 * m_type DEVICE USER_ENDPT COUNT POSITION IO_GRANT
33 * -----------------------------------------------------------------
34 * | HARD_INT | | | | | |
35 * |-------------+---------+---------+---------+---------+---------|
36 * | DEV_READ |minor dev| proc nr | count | | grant |
37 * |-------------+---------+---------+---------+---------+---------|
38 * | DEV_WRITE |minor dev| proc nr | count | | grant |
39 * |-------------+---------+---------+---------+---------+---------|
40 * | DEV_IOCTL |minor dev| proc nr |func code|user proc| |
41 * |-------------+---------+---------+---------+---------+---------|
42 * | DEV_OPEN |minor dev| proc nr | O_NOCTTY| | |
43 * |-------------+---------+---------+---------+---------+---------|
44 * | DEV_CLOSE |minor dev| proc nr | | | |
45 * |-------------+---------+---------+---------+---------+---------|
46 * | CANCEL |minor dev| proc nr | | | |
47 * |-------------+---------+---------+---------+---------+---------|
48 * | DEV_SELECT |minor dev| sel ops | | | |
49 * -----------------------------------------------------------------
50 *
51 * Changes:
52 * Jan 20, 2004 moved TTY driver to user-space (Jorrit N. Herder)
53 * Sep 20, 2004 local timer management/ sync alarms (Jorrit N. Herder)
54 * Jul 13, 2004 support for function key observers (Jorrit N. Herder)
55 */
56
57 #include <assert.h>
58 #include <minix/drivers.h>
59 #include <minix/driver.h>
60 #include <termios.h>
61 #include <sys/ioc_tty.h>
62 #include <signal.h>
63 #include <minix/keymap.h>
64 #include "tty.h"
65
66 #include <sys/time.h>
67 #include <sys/select.h>
68
69 unsigned long kbd_irq_set = 0;
70 unsigned long rs_irq_set = 0;
71
72 /* Address of a tty structure. */
73 #define tty_addr(line) (&tty_table[line])
74
75 /* Macros for magic tty types. */
76 #define isconsole(tp) ((tp) < tty_addr(NR_CONS))
77 #define ispty(tp) ((tp) != NULL && (tp)->tty_minor >= TTYPX_MINOR)
78
79 /* Macros for magic tty structure pointers. */
80 #define FIRST_TTY tty_addr(0)
81 #define END_TTY tty_addr(sizeof(tty_table) / sizeof(tty_table[0]))
82
83 /* A device exists if at least its 'devread' function is defined. */
84 #define tty_active(tp) ((tp)->tty_devread != NULL)
85
86 /* RS232 lines or pseudo terminals can be completely configured out. */
87 #if NR_RS_LINES == 0
88 #define rs_init(tp) ((void) 0)
89 #endif
90
91 #if NR_PTYS == 0
92 #define pty_init(tp) ((void) 0)
93 #define do_pty(tp, mp) ((void) 0)
94 #endif
95
96 struct kmessages kmess;
97
98 static void tty_timed_out(timer_t *tp);
99 static void settimer(tty_t *tty_ptr, int enable);
100 static void in_transfer(tty_t *tp);
101 static int tty_echo(tty_t *tp, int ch);
102 static void rawecho(tty_t *tp, int ch);
103 static int back_over(tty_t *tp);
104 static void reprint(tty_t *tp);
105 static void dev_ioctl(tty_t *tp);
106 static void setattr(tty_t *tp);
107 static void tty_icancel(tty_t *tp);
108 static void tty_init(void);
109 static void do_new_kmess(void);
110 static void set_console_line(char term[CONS_ARG]);
111 static void set_kernel_color(char color[CONS_ARG]);
112 static void set_color(tty_t *tp, int color);
113 static void reset_color(tty_t *tp);
114
115 static int do_open(devminor_t minor, int access, endpoint_t user_endpt);
116 static int do_close(devminor_t minor);
117 static ssize_t do_read(devminor_t minor, u64_t position, endpoint_t endpt,
118 cp_grant_id_t grant, size_t size, int flags, cdev_id_t id);
119 static ssize_t do_write(devminor_t minor, u64_t position, endpoint_t endpt,
120 cp_grant_id_t grant, size_t size, int flags, cdev_id_t id);
121 static int do_ioctl(devminor_t minor, unsigned long request, endpoint_t endpt,
122 cp_grant_id_t grant, int flags, endpoint_t user_endpt, cdev_id_t id);
123 static int do_cancel(devminor_t minor, endpoint_t endpt, cdev_id_t id);
124 static int do_select(devminor_t minor, unsigned int ops, endpoint_t endpt);
125
126 static struct chardriver tty_tab = {
127 .cdr_open = do_open,
128 .cdr_close = do_close,
129 .cdr_read = do_read,
130 .cdr_write = do_write,
131 .cdr_ioctl = do_ioctl,
132 .cdr_cancel = do_cancel,
133 .cdr_select = do_select
134 };
135
136 /* Default attributes. */
137 static struct termios termios_defaults = {
138 TINPUT_DEF, TOUTPUT_DEF, TCTRL_DEF, TLOCAL_DEF,
139 {
140 TEOF_DEF, TEOL_DEF, TERASE_DEF, TINTR_DEF, TKILL_DEF, TMIN_DEF,
141 TQUIT_DEF, TTIME_DEF, TSUSP_DEF, TSTART_DEF, TSTOP_DEF,
142 TREPRINT_DEF, TLNEXT_DEF, TDISCARD_DEF,
143 }, TSPEED_DEF, TSPEED_DEF,
144 };
145 static struct winsize winsize_defaults; /* = all zeroes */
146
147 /* Global variables for the TTY task (declared extern in tty.h). */
148 tty_t tty_table[NR_CONS+NR_RS_LINES+NR_PTYS];
149 int ccurrent; /* currently active console */
150 struct machine machine; /* kernel environment variables */
151 u32_t system_hz;
152 u32_t consoleline = CONS_MINOR;
153 u32_t kernel_msg_color = 0;
154
155 /* SEF functions and variables. */
156 static void sef_local_startup(void);
157 static int sef_cb_init_fresh(int type, sef_init_info_t *info);
158 static void sef_cb_signal_handler(int signo);
159
160 extern struct minix_kerninfo *_minix_kerninfo;
161
162 /*===========================================================================*
163 * tty_task *
164 *===========================================================================*/
165 int main(void)
166 {
167 /* Main routine of the terminal task. */
168
169 message tty_mess; /* buffer for all incoming messages */
170 int ipc_status;
171 unsigned line;
172 int r;
173 register tty_t *tp;
174
175 /* SEF local startup. */
176 sef_local_startup();
177 while (TRUE) {
178 /* Check for and handle any events on any of the ttys. */
179 for (tp = FIRST_TTY; tp < END_TTY; tp++) {
180 if (tp->tty_events) handle_events(tp);
181 }
182
183 /* Get a request message. */
184 r= driver_receive(ANY, &tty_mess, &ipc_status);
185 if (r != 0)
186 panic("driver_receive failed with: %d", r);
187
188 /* First handle all kernel notification types that the TTY supports.
189 * - An alarm went off, expire all timers and handle the events.
190 * - A hardware interrupt also is an invitation to check for events.
191 * - A new kernel message is available for printing.
192 * - Reset the console on system shutdown.
193 * Then see if this message is different from a normal device driver
194 * request and should be handled separately. These extra functions
195 * do not operate on a device, in constrast to the driver requests.
196 */
197
198 if (is_ipc_notify(ipc_status)) {
199 switch (_ENDPOINT_P(tty_mess.m_source)) {
200 case CLOCK:
201 /* run watchdogs of expired timers */
202 expire_timers(tty_mess.NOTIFY_TIMESTAMP);
203 break;
204 case HARDWARE:
205 /* hardware interrupt notification */
206
207 /* fetch chars from keyboard */
208 if (tty_mess.NOTIFY_ARG & kbd_irq_set)
209 kbd_interrupt(&tty_mess);
210 #if NR_RS_LINES > 0
211 /* serial I/O */
212 if (tty_mess.NOTIFY_ARG & rs_irq_set)
213 rs_interrupt(&tty_mess);
214 #endif
215 /* run watchdogs of expired timers */
216 expire_timers(tty_mess.NOTIFY_TIMESTAMP);
217 break;
218 default:
219 /* do nothing */
220 break;
221 }
222
223 /* done, get new message */
224 continue;
225 }
226
227 switch (tty_mess.m_type) {
228 case TTY_FKEY_CONTROL: /* (un)register a fkey observer */
229 do_fkey_ctl(&tty_mess);
230 continue;
231 case INPUT_EVENT:
232 do_kb_inject(&tty_mess);
233 continue;
234 default: /* should be a driver request */
235 ; /* do nothing; end switch */
236 }
237
238 if (!IS_DEV_RQ(tty_mess.m_type)) {
239 chardriver_process(&tty_tab, &tty_mess, ipc_status);
240 continue;
241 }
242
243 /* Only device requests should get to this point.
244 * All requests have a minor device number.
245 */
246 line = tty_mess.DEVICE;
247 if (line == KBD_MINOR || line == KBDAUX_MINOR) {
248 do_kbd(&tty_mess, ipc_status);
249 continue;
250 } else if (line == VIDEO_MINOR) {
251 do_video(&tty_mess, ipc_status);
252 continue;
253 } else if (line - PTYPX_MINOR < NR_PTYS &&
254 tty_mess.m_type != DEV_IOCTL_S) {
255 /* Terminals and pseudo terminals belong together. We can only
256 * make a distinction between the two based on position in the
257 * tty_table and not on minor number (i.e., use ispty macro).
258 * Hence this special case.
259 */
260 do_pty(&tty_mess, ipc_status);
261 continue;
262 }
263
264 /* Execute the requested device driver function. */
265 chardriver_process(&tty_tab, &tty_mess, ipc_status);
266 }
267
268 return 0;
269 }
270
271 static void
272 set_color(tty_t *tp, int color)
273 {
274 char buf[8];
275
276 buf[0] = '\033';
277 snprintf(&buf[1], sizeof(buf) - 1, "[1;%dm", color);
278 do_write(tp->tty_minor, 0, KERNEL, (cp_grant_id_t) buf, sizeof(buf),
279 FLG_OP_NONBLOCK, 0);
280 }
281
282 static void
283 reset_color(tty_t *tp)
284 {
285 char buf[8];
286
287 #define SGR_COLOR_RESET 39
288 buf[0] = '\033';
289 snprintf(&buf[1], sizeof(buf) - 1, "[0;%dm", SGR_COLOR_RESET);
290 do_write(tp->tty_minor, 0, KERNEL, (cp_grant_id_t) buf, sizeof(buf),
291 FLG_OP_NONBLOCK, 0);
292 }
293
294 tty_t *
295 line2tty(devminor_t line)
296 {
297 /* Convert a terminal line to tty_table pointer */
298
299 tty_t* tp;
300
301 /* /dev/log goes to /dev/console, and both may be redirected. */
302 if (line == CONS_MINOR || line == LOG_MINOR)
303 line = consoleline;
304
305 if (line == KBD_MINOR || line == KBDAUX_MINOR || line == VIDEO_MINOR) {
306 return(NULL);
307 } else if ((line - CONS_MINOR) < NR_CONS) {
308 tp = tty_addr(line - CONS_MINOR);
309 } else if ((line - RS232_MINOR) < NR_RS_LINES) {
310 tp = tty_addr(line - RS232_MINOR + NR_CONS);
311 } else if ((line - TTYPX_MINOR) < NR_PTYS) {
312 tp = tty_addr(line - TTYPX_MINOR + NR_CONS + NR_RS_LINES);
313 } else if ((line - PTYPX_MINOR) < NR_PTYS) {
314 tp = tty_addr(line - PTYPX_MINOR + NR_CONS + NR_RS_LINES);
315 } else {
316 tp = NULL;
317 }
318
319 if (tp != NULL && !tty_active(tp))
320 tp = NULL;
321
322 return(tp);
323 }
324
325 /*===========================================================================*
326 * sef_local_startup *
327 *===========================================================================*/
328 static void sef_local_startup()
329 {
330 /* Register init callbacks. */
331 sef_setcb_init_fresh(sef_cb_init_fresh);
332 sef_setcb_init_restart(sef_cb_init_fresh);
333
334 /* No live update support for now. */
335
336 /* Register signal callbacks. */
337 sef_setcb_signal_handler(sef_cb_signal_handler);
338
339 /* Let SEF perform startup. */
340 sef_startup();
341 }
342
343 /*===========================================================================*
344 * sef_cb_init_fresh *
345 *===========================================================================*/
346 static int sef_cb_init_fresh(int UNUSED(type), sef_init_info_t *UNUSED(info))
347 {
348 /* Initialize the tty driver. */
349 int r;
350 char val[CONS_ARG];
351
352 /* Get kernel environment (protected_mode, pc_at and ega are needed). */
353 if (OK != (r=sys_getmachine(&machine))) {
354 panic("Couldn't obtain kernel environment: %d", r);
355 }
356
357 if (env_get_param("console", val, sizeof(val)) == OK) {
358 set_console_line(val);
359 }
360
361 if ((r = env_get_param("kernelclr", val, sizeof(val))) == OK) {
362 set_kernel_color(val);
363 }
364
365 /* Initialize the TTY driver. */
366 tty_init();
367
368 /* Final one-time keyboard initialization. */
369 kb_init_once();
370
371 return(OK);
372 }
373
374 static void
375 set_console_line(char term[CONS_ARG])
376 {
377 /* Parse 'term' and redirect console output there. */
378 int i;
379
380 /* Console */
381 if (!strncmp(term, "console", CONS_ARG - 1)) {
382 consoleline = CONS_MINOR+0;
383 }
384
385 /* The other console terminals */
386 for (i = 1; i < NR_CONS; i++) {
387 char cons[6];
388 strlcpy(cons, "ttyc0", sizeof(cons));
389 cons[4] += i;
390 if (!strncmp(term, cons,
391 CONS_ARG < sizeof(cons) ? CONS_ARG-1 : sizeof(cons) - 1))
392 consoleline = CONS_MINOR + i;
393 }
394
395 /* Serial lines */
396 assert(NR_RS_LINES <= 9);/* below assumes this is the case */
397 for (i = 0; i < NR_RS_LINES; i++) {
398 char sercons[6];
399 strlcpy(sercons, "tty00", sizeof(sercons));
400 sercons[4] += i;
401 if (!strncmp(term, sercons,
402 CONS_ARG < sizeof(sercons) ? CONS_ARG-1:sizeof(sercons)-1))
403 consoleline = RS232_MINOR + i;
404 }
405 }
406
407 static void
408 set_kernel_color(char color[CONS_ARG])
409 {
410 int def_color;
411
412 #define SGR_COLOR_START 30
413 #define SGR_COLOR_END 37
414
415 def_color = atoi(color);
416 if ((SGR_COLOR_START + def_color) >= SGR_COLOR_START &&
417 (SGR_COLOR_START + def_color) <= SGR_COLOR_END) {
418 kernel_msg_color = def_color + SGR_COLOR_START;
419 }
420 }
421
422 static void
423 do_new_kmess(void)
424 {
425 /* Kernel wants to print a new message */
426 struct kmessages *kmess_ptr; /* kmessages structure */
427 char kernel_buf_copy[_KMESS_BUF_SIZE];
428 static int prev_next = 0;
429 int next, bytes, copy, restore = 0;
430 tty_t *tp, rtp;
431
432 assert(_minix_kerninfo);
433 kmess_ptr = _minix_kerninfo->kmessages;
434
435 /* The kernel buffer is circular; print only the new part. Determine
436 * how many new bytes there are with the help of current and
437 * previous 'next' index. This works fine if less than _KMESS_BUF_SIZE
438 * bytes is new data; else we miss % _KMESS_BUF_SIZE here. Obtain
439 * 'next' only once, since we are operating on shared memory here.
440 * Check for size being positive; the buffer might as well be emptied!
441 */
442 next = kmess_ptr->km_next;
443 bytes = ((next + _KMESS_BUF_SIZE) - prev_next) % _KMESS_BUF_SIZE;
444 if (bytes > 0) {
445 /* Copy from current position toward end of buffer */
446 copy = MIN(_KMESS_BUF_SIZE - prev_next, bytes);
447 memcpy(kernel_buf_copy, &kmess_ptr->km_buf[prev_next], copy);
448
449 /* Copy remainder from start of buffer */
450 if (copy < bytes) {
451 memcpy(&kernel_buf_copy[copy], &kmess_ptr->km_buf[0],
452 bytes - copy);
453 }
454
455 tp = line2tty(consoleline);
456 if (tp == NULL)
457 panic("Don't know where to send kernel messages");
458 if (tp->tty_outleft > 0) {
459 /* Terminal is already printing */
460 rtp = *tp; /* Make backup */
461 tp->tty_outleft = 0; /* So do_write is happy */
462 restore = 1;
463 }
464
465 if (kernel_msg_color != 0)
466 set_color(tp, kernel_msg_color);
467 do_write(tp->tty_minor, 0, KERNEL,
468 (cp_grant_id_t) kernel_buf_copy, bytes,
469 FLG_OP_NONBLOCK, 0);
470 if (kernel_msg_color != 0)
471 reset_color(tp);
472 if (restore) {
473 *tp = rtp;
474 }
475 }
476
477 /* Store 'next' pointer so that we can determine what part of the
478 * kernel messages buffer to print next time a notification arrives.
479 */
480 prev_next = next;
481 }
482
483 /*===========================================================================*
484 * sef_cb_signal_handler *
485 *===========================================================================*/
486 static void sef_cb_signal_handler(int signo)
487 {
488 /* Check for known signals, ignore anything else. */
489 switch(signo) {
490 /* There is a pending message from the kernel. */
491 case SIGKMESS:
492 do_new_kmess();
493 break;
494 /* Switch to primary console on termination. */
495 case SIGTERM:
496 cons_stop();
497 break;
498 }
499 }
500
501 /*===========================================================================*
502 * do_read *
503 *===========================================================================*/
504 static ssize_t do_read(devminor_t minor, u64_t UNUSED(position),
505 endpoint_t endpt, cp_grant_id_t grant, size_t size, int flags,
506 cdev_id_t id)
507 {
508 /* A process wants to read from a terminal. */
509 tty_t *tp;
510 int r;
511
512 if ((tp = line2tty(minor)) == NULL)
513 return ENXIO;
514
515 /* Check if there is already a process hanging in a read, check if the
516 * parameters are correct, do I/O.
517 */
518 if (tp->tty_incaller != NONE || tp->tty_inleft > 0)
519 return EIO;
520 if (size <= 0)
521 return EINVAL;
522
523 /* Copy information from the message to the tty struct. */
524 tp->tty_incaller = endpt;
525 tp->tty_inid = id;
526 tp->tty_ingrant = grant;
527 assert(tp->tty_incum == 0);
528 tp->tty_inleft = size;
529
530 if (!(tp->tty_termios.c_lflag & ICANON) && tp->tty_termios.c_cc[VTIME] > 0) {
531 if (tp->tty_termios.c_cc[VMIN] == 0) {
532 /* MIN & TIME specify a read timer that finishes the
533 * read in TIME/10 seconds if no bytes are available.
534 */
535 settimer(tp, TRUE);
536 tp->tty_min = 1;
537 } else {
538 /* MIN & TIME specify an inter-byte timer that may
539 * have to be cancelled if there are no bytes yet.
540 */
541 if (tp->tty_eotct == 0) {
542 settimer(tp, FALSE);
543 tp->tty_min = tp->tty_termios.c_cc[VMIN];
544 }
545 }
546 }
547
548 /* Anything waiting in the input buffer? Clear it out... */
549 in_transfer(tp);
550 /* ...then go back for more. */
551 handle_events(tp);
552 if (tp->tty_inleft == 0)
553 return EDONTREPLY; /* already done */
554
555 /* There were no bytes in the input queue available. */
556 if (flags & FLG_OP_NONBLOCK) {
557 tty_icancel(tp);
558 r = tp->tty_incum > 0 ? tp->tty_incum : EAGAIN;
559 tp->tty_inleft = tp->tty_incum = 0;
560 tp->tty_incaller = NONE;
561 return r;
562 }
563
564 if (tp->tty_select_ops)
565 select_retry(tp);
566
567 return EDONTREPLY; /* suspend the caller */
568 }
569
570 /*===========================================================================*
571 * do_write *
572 *===========================================================================*/
573 static ssize_t do_write(devminor_t minor, u64_t UNUSED(position),
574 endpoint_t endpt, cp_grant_id_t grant, size_t size, int flags,
575 cdev_id_t id)
576 {
577 /* A process wants to write on a terminal. */
578 tty_t *tp;
579 int r;
580
581 if ((tp = line2tty(minor)) == NULL)
582 return ENXIO;
583
584 /* Check if there is already a process hanging in a write, check if the
585 * parameters are correct, do I/O.
586 */
587 if (tp->tty_outcaller != NONE || tp->tty_outleft > 0)
588 return EIO;
589 if (size <= 0)
590 return EINVAL;
591
592 /* Copy message parameters to the tty structure. */
593 tp->tty_outcaller = endpt;
594 tp->tty_outid = id;
595 tp->tty_outgrant = grant;
596 assert(tp->tty_outcum == 0);
597 tp->tty_outleft = size;
598
599 /* Try to write. */
600 handle_events(tp);
601 if (tp->tty_outleft == 0)
602 return EDONTREPLY; /* already done */
603
604 /* None or not all the bytes could be written. */
605 if (flags & FLG_OP_NONBLOCK) {
606 r = tp->tty_outcum > 0 ? tp->tty_outcum : EAGAIN;
607 tp->tty_outleft = tp->tty_outcum = 0;
608 tp->tty_outcaller = NONE;
609 return r;
610 }
611
612 if (tp->tty_select_ops)
613 select_retry(tp);
614
615 return EDONTREPLY; /* suspend the caller */
616 }
617
618 /*===========================================================================*
619 * do_ioctl *
620 *===========================================================================*/
621 static int do_ioctl(devminor_t minor, unsigned long request, endpoint_t endpt,
622 cp_grant_id_t grant, int flags, endpoint_t user_endpt, cdev_id_t id)
623 {
624 /* Perform an IOCTL on this terminal. POSIX termios calls are handled
625 * by the IOCTL system call.
626 */
627 tty_t *tp;
628 int i, r;
629 size_t size;
630
631 if ((tp = line2tty(minor)) == NULL)
632 return ENXIO;
633
634 /* Size of the ioctl parameter. */
635 switch (request) {
636 case TCGETS: /* Posix tcgetattr function */
637 case TCSETS: /* Posix tcsetattr function, TCSANOW option */
638 case TCSETSW: /* Posix tcsetattr function, TCSADRAIN option */
639 case TCSETSF: /* Posix tcsetattr function, TCSAFLUSH option */
640 size = sizeof(struct termios);
641 break;
642
643 case TCSBRK: /* Posix tcsendbreak function */
644 case TCFLOW: /* Posix tcflow function */
645 case TCFLSH: /* Posix tcflush function */
646 case TIOCGPGRP: /* Posix tcgetpgrp function */
647 case TIOCSPGRP: /* Posix tcsetpgrp function */
648 size = sizeof(int);
649 break;
650
651 case TIOCGWINSZ: /* get window size (not Posix) */
652 case TIOCSWINSZ: /* set window size (not Posix) */
653 size = sizeof(struct winsize);
654 break;
655
656 case KIOCSMAP: /* load keymap (Minix extension) */
657 size = sizeof(keymap_t);
658 break;
659
660 case TIOCSFON: /* load font (Minix extension) */
661 size = sizeof(u8_t [8192]);
662 break;
663
664 case TCDRAIN: /* Posix tcdrain function -- no parameter */
665 default: size = 0;
666 }
667
668 r = OK;
669 switch (request) {
670 case TCGETS:
671 /* Get the termios attributes. */
672 r = sys_safecopyto(endpt, grant, 0, (vir_bytes) &tp->tty_termios,
673 size);
674 break;
675
676 case TCSETSW:
677 case TCSETSF:
678 case TCDRAIN:
679 if (tp->tty_outleft > 0) {
680 if (flags & FLG_OP_NONBLOCK)
681 return EAGAIN;
682 /* Wait for all ongoing output processing to finish. */
683 tp->tty_iocaller = endpt;
684 tp->tty_ioid = id;
685 tp->tty_ioreq = request;
686 tp->tty_iogrant = grant;
687 return EDONTREPLY; /* suspend the caller */
688 }
689 if (request == TCDRAIN) break;
690 if (request == TCSETSF) tty_icancel(tp);
691 /*FALL THROUGH*/
692 case TCSETS:
693 /* Set the termios attributes. */
694 r = sys_safecopyfrom(endpt, grant, 0, (vir_bytes) &tp->tty_termios,
695 size);
696 if (r != OK) break;
697 setattr(tp);
698 break;
699
700 case TCFLSH:
701 r = sys_safecopyfrom(endpt, grant, 0, (vir_bytes) &i, size);
702 if (r != OK) break;
703 switch (i) {
704 case TCIFLUSH: tty_icancel(tp); break;
705 case TCOFLUSH: (*tp->tty_ocancel)(tp, 0); break;
706 case TCIOFLUSH: tty_icancel(tp); (*tp->tty_ocancel)(tp, 0); break;
707 default: r = EINVAL;
708 }
709 break;
710
711 case TCFLOW:
712 r = sys_safecopyfrom(endpt, grant, 0, (vir_bytes) &i, size);
713 if (r != OK) break;
714 switch (i) {
715 case TCOOFF:
716 case TCOON:
717 tp->tty_inhibited = (i == TCOOFF);
718 tp->tty_events = 1;
719 break;
720 case TCIOFF:
721 (*tp->tty_echo)(tp, tp->tty_termios.c_cc[VSTOP]);
722 break;
723 case TCION:
724 (*tp->tty_echo)(tp, tp->tty_termios.c_cc[VSTART]);
725 break;
726 default:
727 r = EINVAL;
728 }
729 break;
730
731 case TCSBRK:
732 if (tp->tty_break != NULL) (*tp->tty_break)(tp,0);
733 break;
734
735 case TIOCGWINSZ:
736 r = sys_safecopyto(endpt, grant, 0, (vir_bytes) &tp->tty_winsize,
737 size);
738 break;
739
740 case TIOCSWINSZ:
741 r = sys_safecopyfrom(endpt, grant, 0, (vir_bytes) &tp->tty_winsize,
742 size);
743 sigchar(tp, SIGWINCH, 0);
744 break;
745
746 case KIOCSMAP:
747 /* Load a new keymap (only /dev/console). */
748 if (isconsole(tp)) r = kbd_loadmap(endpt, grant);
749 break;
750
751 case TIOCSFON:
752 /* Load a font into an EGA or VGA card (hs@hck.hr) */
753 if (isconsole(tp)) r = con_loadfont(endpt, grant);
754 break;
755
756 /* These Posix functions are allowed to fail if _POSIX_JOB_CONTROL is
757 * not defined.
758 */
759 case TIOCGPGRP:
760 case TIOCSPGRP:
761 default:
762 r = ENOTTY;
763 }
764
765 return r;
766 }
767
768 /*===========================================================================*
769 * do_open *
770 *===========================================================================*/
771 static int do_open(devminor_t minor, int access, endpoint_t user_endpt)
772 {
773 /* A tty line has been opened. Make it the callers controlling tty if
774 * O_NOCTTY is *not* set and it is not the log device. 1 is returned if
775 * the tty is made the controlling tty, otherwise OK or an error code.
776 */
777 tty_t *tp;
778 int r = OK;
779
780 if ((tp = line2tty(minor)) == NULL)
781 return ENXIO;
782
783 if (minor == LOG_MINOR && isconsole(tp)) {
784 /* The log device is a write-only diagnostics device. */
785 if (access & R_BIT) return EACCES;
786 } else {
787 if (!(access & O_NOCTTY)) {
788 tp->tty_pgrp = user_endpt;
789 r = 1;
790 }
791 tp->tty_openct++;
792 if (tp->tty_openct == 1) {
793 /* Tell the device that the tty is opened */
794 (*tp->tty_open)(tp, 0);
795 }
796 }
797
798 return r;
799 }
800
801 /*===========================================================================*
802 * do_close *
803 *===========================================================================*/
804 static int do_close(devminor_t minor)
805 {
806 /* A tty line has been closed. Clean up the line if it is the last close. */
807 tty_t *tp;
808
809 if ((tp = line2tty(minor)) == NULL)
810 return ENXIO;
811
812 if ((minor != LOG_MINOR || !isconsole(tp)) && --tp->tty_openct == 0) {
813 tp->tty_pgrp = 0;
814 tty_icancel(tp);
815 (*tp->tty_ocancel)(tp, 0);
816 (*tp->tty_close)(tp, 0);
817 tp->tty_termios = termios_defaults;
818 tp->tty_winsize = winsize_defaults;
819 setattr(tp);
820 }
821
822 return OK;
823 }
824
825 /*===========================================================================*
826 * do_cancel *
827 *===========================================================================*/
828 static int do_cancel(devminor_t minor, endpoint_t endpt, cdev_id_t id)
829 {
830 /* A signal has been sent to a process that is hanging trying to read or write.
831 * The pending read or write must be finished off immediately.
832 */
833 tty_t *tp;
834 int r;
835
836 if ((tp = line2tty(minor)) == NULL)
837 return ENXIO;
838
839 /* Check the parameters carefully, to avoid cancelling twice. */
840 r = EDONTREPLY;
841 if (tp->tty_inleft != 0 && endpt == tp->tty_incaller && id == tp->tty_inid) {
842 /* Process was reading when killed. Clean up input. */
843 tty_icancel(tp);
844 r = tp->tty_incum > 0 ? tp->tty_incum : EAGAIN;
845 tp->tty_inleft = tp->tty_incum = 0;
846 tp->tty_incaller = NONE;
847 } else if (tp->tty_outleft != 0 && endpt == tp->tty_outcaller &&
848 id == tp->tty_outid) {
849 /* Process was writing when killed. Clean up output. */
850 r = tp->tty_outcum > 0 ? tp->tty_outcum : EAGAIN;
851 tp->tty_outleft = tp->tty_outcum = 0;
852 tp->tty_outcaller = NONE;
853 } else if (tp->tty_ioreq != 0 && endpt == tp->tty_iocaller &&
854 id == tp->tty_ioid) {
855 /* Process was waiting for output to drain. */
856 r = EINTR;
857 tp->tty_ioreq = 0;
858 tp->tty_iocaller = NONE;
859 }
860 if (r != EDONTREPLY)
861 tp->tty_events = 1;
862 /* Only reply if we found a matching request. */
863 return r;
864 }
865
866 int select_try(struct tty *tp, int ops)
867 {
868 int ready_ops = 0;
869
870 /* Special case. If line is hung up, no operations will block.
871 * (and it can be seen as an exceptional condition.)
872 */
873 if (tp->tty_termios.c_ospeed == B0) {
874 ready_ops |= ops;
875 }
876
877 if (ops & SEL_RD) {
878 /* will i/o not block on read? */
879 if (tp->tty_inleft > 0) {
880 ready_ops |= SEL_RD; /* EIO - no blocking */
881 } else if (tp->tty_incount > 0) {
882 /* Is a regular read possible? tty_incount
883 * says there is data. But a read will only succeed
884 * in canonical mode if a newline has been seen.
885 */
886 if (!(tp->tty_termios.c_lflag & ICANON) ||
887 tp->tty_eotct > 0) {
888 ready_ops |= SEL_RD;
889 }
890 }
891 }
892
893 if (ops & SEL_WR) {
894 if (tp->tty_outleft > 0) ready_ops |= SEL_WR;
895 else if ((*tp->tty_devwrite)(tp, 1)) ready_ops |= SEL_WR;
896 }
897 return ready_ops;
898 }
899
900 int select_retry(struct tty *tp)
901 {
902 int ops;
903
904 if (tp->tty_select_ops && (ops = select_try(tp, tp->tty_select_ops))) {
905 chardriver_reply_select(tp->tty_select_proc, tp->tty_minor,
906 ops);
907 tp->tty_select_ops &= ~ops;
908 }
909 return OK;
910 }
911
912 /*===========================================================================*
913 * do_select *
914 *===========================================================================*/
915 static int do_select(devminor_t minor, unsigned int ops, endpoint_t endpt)
916 {
917 tty_t *tp;
918 int ready_ops, watch;
919
920 if ((tp = line2tty(minor)) == NULL)
921 return ENXIO;
922
923 /* Translated minor numbers are a problem when sending late replies. */
924 if (tp->tty_minor != minor)
925 return EBADF;
926
927 watch = (ops & SEL_NOTIFY);
928 ops &= (SEL_RD | SEL_WR | SEL_ERR);
929
930 ready_ops = select_try(tp, ops);
931
932 ops &= ~ready_ops;
933 if (ops && watch) {
934 tp->tty_select_ops |= ops;
935 tp->tty_select_proc = endpt;
936 }
937
938 assert(tp->tty_minor == minor);
939 return ready_ops;
940 }
941
942 /*===========================================================================*
943 * handle_events *
944 *===========================================================================*/
945 void handle_events(tp)
946 tty_t *tp; /* TTY to check for events. */
947 {
948 /* Handle any events pending on a TTY. These events are usually device
949 * interrupts.
950 *
951 * Two kinds of events are prominent:
952 * - a character has been received from the console or an RS232 line.
953 * - an RS232 line has completed a write request (on behalf of a user).
954 * The interrupt handler may delay the interrupt message at its discretion
955 * to avoid swamping the TTY task. Messages may be overwritten when the
956 * lines are fast or when there are races between different lines, input
957 * and output, because MINIX only provides single buffering for interrupt
958 * messages. This is handled by explicitly checking each line for fresh input
959 * and completed output on each interrupt.
960 */
961
962 do {
963 tp->tty_events = 0;
964
965 /* Read input and perform input processing. */
966 (*tp->tty_devread)(tp, 0);
967
968 /* Perform output processing and write output. */
969 (*tp->tty_devwrite)(tp, 0);
970
971 /* Ioctl waiting for some event? */
972 if (tp->tty_ioreq != 0) dev_ioctl(tp);
973 } while (tp->tty_events);
974
975 /* Transfer characters from the input queue to a waiting process. */
976 in_transfer(tp);
977
978 /* Reply if enough bytes are available. */
979 if (tp->tty_incum >= tp->tty_min && tp->tty_inleft > 0) {
980 chardriver_reply_task(tp->tty_incaller, tp->tty_inid, tp->tty_incum);
981 tp->tty_inleft = tp->tty_incum = 0;
982 tp->tty_incaller = NONE;
983 }
984 if (tp->tty_select_ops)
985 {
986 select_retry(tp);
987 }
988 #if NR_PTYS > 0
989 if (ispty(tp))
990 select_retry_pty(tp);
991 #endif
992 }
993
994 /*===========================================================================*
995 * in_transfer *
996 *===========================================================================*/
997 static void in_transfer(tp)
998 register tty_t *tp; /* pointer to terminal to read from */
999 {
1000 /* Transfer bytes from the input queue to a process reading from a terminal. */
1001
1002 int ch;
1003 int count;
1004 char buf[64], *bp;
1005
1006 /* Force read to succeed if the line is hung up, looks like EOF to reader. */
1007 if (tp->tty_termios.c_ospeed == B0) tp->tty_min = 0;
1008
1009 /* Anything to do? */
1010 if (tp->tty_inleft == 0 || tp->tty_eotct < tp->tty_min) return;
1011
1012 bp = buf;
1013 while (tp->tty_inleft > 0 && tp->tty_eotct > 0) {
1014 ch = *tp->tty_intail;
1015
1016 if (!(ch & IN_EOF)) {
1017 /* One character to be delivered to the user. */
1018 *bp = ch & IN_CHAR;
1019 tp->tty_inleft--;
1020 if (++bp == bufend(buf)) {
1021 /* Temp buffer full, copy to user space. */
1022 sys_safecopyto(tp->tty_incaller,
1023 tp->tty_ingrant, tp->tty_incum,
1024 (vir_bytes) buf, (vir_bytes) buflen(buf));
1025 tp->tty_incum += buflen(buf);
1026 bp = buf;
1027 }
1028 }
1029
1030 /* Remove the character from the input queue. */
1031 if (++tp->tty_intail == bufend(tp->tty_inbuf))
1032 tp->tty_intail = tp->tty_inbuf;
1033 tp->tty_incount--;
1034 if (ch & IN_EOT) {
1035 tp->tty_eotct--;
1036 /* Don't read past a line break in canonical mode. */
1037 if (tp->tty_termios.c_lflag & ICANON) tp->tty_inleft = 0;
1038 }
1039 }
1040
1041 if (bp > buf) {
1042 /* Leftover characters in the buffer. */
1043 count = bp - buf;
1044 sys_safecopyto(tp->tty_incaller, tp->tty_ingrant, tp->tty_incum,
1045 (vir_bytes) buf, (vir_bytes) count);
1046 tp->tty_incum += count;
1047 }
1048
1049 /* Usually reply to the reader, possibly even if incum == 0 (EOF). */
1050 if (tp->tty_inleft == 0) {
1051 chardriver_reply_task(tp->tty_incaller, tp->tty_inid, tp->tty_incum);
1052 tp->tty_inleft = tp->tty_incum = 0;
1053 tp->tty_incaller = NONE;
1054 }
1055 }
1056
1057 /*===========================================================================*
1058 * in_process *
1059 *===========================================================================*/
1060 static void in_process_send_byte(
1061 tty_t *tp, /* terminal on which character has arrived */
1062 int ch /* input character */
1063 )
1064 {
1065 /* Save the character in the input queue. */
1066 *tp->tty_inhead++ = ch;
1067 if (tp->tty_inhead == bufend(tp->tty_inbuf))
1068 tp->tty_inhead = tp->tty_inbuf;
1069 tp->tty_incount++;
1070 if (ch & IN_EOT) tp->tty_eotct++;
1071
1072 /* Try to finish input if the queue threatens to overflow. */
1073 if (tp->tty_incount == buflen(tp->tty_inbuf)) in_transfer(tp);
1074 }
1075
1076 int in_process(tp, buf, count, scode)
1077 register tty_t *tp; /* terminal on which character has arrived */
1078 char *buf; /* buffer with input characters */
1079 int count; /* number of input characters */
1080 int scode; /* scan code */
1081 {
1082 /* Characters have just been typed in. Process, save, and echo them. Return
1083 * the number of characters processed.
1084 */
1085
1086 int ch, sig, ct;
1087 int timeset = FALSE;
1088
1089 /* Send scancode if requested */
1090 if (tp->tty_termios.c_iflag & SCANCODES) {
1091 in_process_send_byte(tp, (scode & BYTE) | IN_EOT);
1092 }
1093
1094 for (ct = 0; ct < count; ct++) {
1095 /* Take one character. */
1096 ch = *buf++ & BYTE;
1097
1098 /* Strip to seven bits? */
1099 if (tp->tty_termios.c_iflag & ISTRIP) ch &= 0x7F;
1100
1101 /* Input extensions? */
1102 if (tp->tty_termios.c_lflag & IEXTEN) {
1103
1104 /* Previous character was a character escape? */
1105 if (tp->tty_escaped) {
1106 tp->tty_escaped = NOT_ESCAPED;
1107 ch |= IN_ESC; /* protect character */
1108 }
1109
1110 /* LNEXT (^V) to escape the next character? */
1111 if (ch == tp->tty_termios.c_cc[VLNEXT]) {
1112 tp->tty_escaped = ESCAPED;
1113 rawecho(tp, '^');
1114 rawecho(tp, '\b');
1115 continue; /* do not store the escape */
1116 }
1117
1118 /* REPRINT (^R) to reprint echoed characters? */
1119 if (ch == tp->tty_termios.c_cc[VREPRINT]) {
1120 reprint(tp);
1121 continue;
1122 }
1123 }
1124
1125 /* _POSIX_VDISABLE is a normal character value, so better escape it. */
1126 if (ch == _POSIX_VDISABLE) ch |= IN_ESC;
1127
1128 /* Map CR to LF, ignore CR, or map LF to CR. */
1129 if (ch == '\r') {
1130 if (tp->tty_termios.c_iflag & IGNCR) continue;
1131 if (tp->tty_termios.c_iflag & ICRNL) ch = '\n';
1132 } else
1133 if (ch == '\n') {
1134 if (tp->tty_termios.c_iflag & INLCR) ch = '\r';
1135 }
1136
1137 /* Canonical mode? */
1138 if (tp->tty_termios.c_lflag & ICANON) {
1139
1140 /* Erase processing (rub out of last character). */
1141 if (ch == tp->tty_termios.c_cc[VERASE]) {
1142 (void) back_over(tp);
1143 if (!(tp->tty_termios.c_lflag & ECHOE)) {
1144 (void) tty_echo(tp, ch);
1145 }
1146 continue;
1147 }
1148
1149 /* Kill processing (remove current line). */
1150 if (ch == tp->tty_termios.c_cc[VKILL]) {
1151 while (back_over(tp)) {}
1152 if (!(tp->tty_termios.c_lflag & ECHOE)) {
1153 (void) tty_echo(tp, ch);
1154 if (tp->tty_termios.c_lflag & ECHOK)
1155 rawecho(tp, '\n');
1156 }
1157 continue;
1158 }
1159
1160 /* EOF (^D) means end-of-file, an invisible "line break". */
1161 if (ch == tp->tty_termios.c_cc[VEOF]) ch |= IN_EOT | IN_EOF;
1162
1163 /* The line may be returned to the user after an LF. */
1164 if (ch == '\n') ch |= IN_EOT;
1165
1166 /* Same thing with EOL, whatever it may be. */
1167 if (ch == tp->tty_termios.c_cc[VEOL]) ch |= IN_EOT;
1168 }
1169
1170 /* Start/stop input control? */
1171 if (tp->tty_termios.c_iflag & IXON) {
1172
1173 /* Output stops on STOP (^S). */
1174 if (ch == tp->tty_termios.c_cc[VSTOP]) {
1175 tp->tty_inhibited = STOPPED;
1176 tp->tty_events = 1;
1177 continue;
1178 }
1179
1180 /* Output restarts on START (^Q) or any character if IXANY. */
1181 if (tp->tty_inhibited) {
1182 if (ch == tp->tty_termios.c_cc[VSTART]
1183 || (tp->tty_termios.c_iflag & IXANY)) {
1184 tp->tty_inhibited = RUNNING;
1185 tp->tty_events = 1;
1186 if (ch == tp->tty_termios.c_cc[VSTART])
1187 continue;
1188 }
1189 }
1190 }
1191
1192 if (tp->tty_termios.c_lflag & ISIG) {
1193 /* Check for INTR (^?) and QUIT (^\) characters. */
1194 if (ch == tp->tty_termios.c_cc[VINTR]
1195 || ch == tp->tty_termios.c_cc[VQUIT]) {
1196 sig = SIGINT;
1197 if (ch == tp->tty_termios.c_cc[VQUIT]) sig = SIGQUIT;
1198 sigchar(tp, sig, 1);
1199 (void) tty_echo(tp, ch);
1200 continue;
1201 }
1202 }
1203
1204 /* Is there space in the input buffer? */
1205 if (tp->tty_incount == buflen(tp->tty_inbuf)) {
1206 /* No space; discard in canonical mode, keep in raw mode. */
1207 if (tp->tty_termios.c_lflag & ICANON) continue;
1208 break;
1209 }
1210
1211 if (!(tp->tty_termios.c_lflag & ICANON)) {
1212 /* In raw mode all characters are "line breaks". */
1213 ch |= IN_EOT;
1214
1215 /* Start an inter-byte timer? */
1216 if (!timeset && tp->tty_termios.c_cc[VMIN] > 0
1217 && tp->tty_termios.c_cc[VTIME] > 0) {
1218 settimer(tp, TRUE);
1219 timeset = TRUE;
1220 }
1221 }
1222
1223 /* Perform the intricate function of echoing. */
1224 if (tp->tty_termios.c_lflag & (ECHO|ECHONL)) ch = tty_echo(tp, ch);
1225
1226 /* Send processed byte of input unless scancodes sent instead */
1227 if (!(tp->tty_termios.c_iflag & SCANCODES)) {
1228 in_process_send_byte(tp, ch);
1229 }
1230 }
1231 return ct;
1232 }
1233
1234 /*===========================================================================*
1235 * echo *
1236 *===========================================================================*/
1237 static int tty_echo(tp, ch)
1238 register tty_t *tp; /* terminal on which to echo */
1239 register int ch; /* pointer to character to echo */
1240 {
1241 /* Echo the character if echoing is on. Some control characters are echoed
1242 * with their normal effect, other control characters are echoed as "^X",
1243 * normal characters are echoed normally. EOF (^D) is echoed, but immediately
1244 * backspaced over. Return the character with the echoed length added to its
1245 * attributes.
1246 */
1247 int len, rp;
1248
1249 ch &= ~IN_LEN;
1250 if (!(tp->tty_termios.c_lflag & ECHO)) {
1251 if (ch == ('\n' | IN_EOT) && (tp->tty_termios.c_lflag
1252 & (ICANON|ECHONL)) == (ICANON|ECHONL))
1253 (*tp->tty_echo)(tp, '\n');
1254 return(ch);
1255 }
1256
1257 /* "Reprint" tells if the echo output has been messed up by other output. */
1258 rp = tp->tty_incount == 0 ? FALSE : tp->tty_reprint;
1259
1260 if ((ch & IN_CHAR) < ' ') {
1261 switch (ch & (IN_ESC|IN_EOF|IN_EOT|IN_CHAR)) {
1262 case '\t':
1263 len = 0;
1264 do {
1265 (*tp->tty_echo)(tp, ' ');
1266 len++;
1267 } while (len < TAB_SIZE && (tp->tty_position & TAB_MASK) != 0);
1268 break;
1269 case '\r' | IN_EOT:
1270 case '\n' | IN_EOT:
1271 (*tp->tty_echo)(tp, ch & IN_CHAR);
1272 len = 0;
1273 break;
1274 default:
1275 (*tp->tty_echo)(tp, '^');
1276 (*tp->tty_echo)(tp, '@' + (ch & IN_CHAR));
1277 len = 2;
1278 }
1279 } else
1280 if ((ch & IN_CHAR) == '\177') {
1281 /* A DEL prints as "^?". */
1282 (*tp->tty_echo)(tp, '^');
1283 (*tp->tty_echo)(tp, '?');
1284 len = 2;
1285 } else {
1286 (*tp->tty_echo)(tp, ch & IN_CHAR);
1287 len = 1;
1288 }
1289 if (ch & IN_EOF) while (len > 0) { (*tp->tty_echo)(tp, '\b'); len--; }
1290
1291 tp->tty_reprint = rp;
1292 return(ch | (len << IN_LSHIFT));
1293 }
1294
1295 /*===========================================================================*
1296 * rawecho *
1297 *===========================================================================*/
1298 static void rawecho(tp, ch)
1299 register tty_t *tp;
1300 int ch;
1301 {
1302 /* Echo without interpretation if ECHO is set. */
1303 int rp = tp->tty_reprint;
1304 if (tp->tty_termios.c_lflag & ECHO) (*tp->tty_echo)(tp, ch);
1305 tp->tty_reprint = rp;
1306 }
1307
1308 /*===========================================================================*
1309 * back_over *
1310 *===========================================================================*/
1311 static int back_over(tp)
1312 register tty_t *tp;
1313 {
1314 /* Backspace to previous character on screen and erase it. */
1315 u16_t *head;
1316 int len;
1317
1318 if (tp->tty_incount == 0) return(0); /* queue empty */
1319 head = tp->tty_inhead;
1320 if (head == tp->tty_inbuf) head = bufend(tp->tty_inbuf);
1321 if (*--head & IN_EOT) return(0); /* can't erase "line breaks" */
1322 if (tp->tty_reprint) reprint(tp); /* reprint if messed up */
1323 tp->tty_inhead = head;
1324 tp->tty_incount--;
1325 if (tp->tty_termios.c_lflag & ECHOE) {
1326 len = (*head & IN_LEN) >> IN_LSHIFT;
1327 while (len > 0) {
1328 rawecho(tp, '\b');
1329 rawecho(tp, ' ');
1330 rawecho(tp, '\b');
1331 len--;
1332 }
1333 }
1334 return(1); /* one character erased */
1335 }
1336
1337 /*===========================================================================*
1338 * reprint *
1339 *===========================================================================*/
1340 static void reprint(tp)
1341 register tty_t *tp; /* pointer to tty struct */
1342 {
1343 /* Restore what has been echoed to screen before if the user input has been
1344 * messed up by output, or if REPRINT (^R) is typed.
1345 */
1346 int count;
1347 u16_t *head;
1348
1349 tp->tty_reprint = FALSE;
1350
1351 /* Find the last line break in the input. */
1352 head = tp->tty_inhead;
1353 count = tp->tty_incount;
1354 while (count > 0) {
1355 if (head == tp->tty_inbuf) head = bufend(tp->tty_inbuf);
1356 if (head[-1] & IN_EOT) break;
1357 head--;
1358 count--;
1359 }
1360 if (count == tp->tty_incount) return; /* no reason to reprint */
1361
1362 /* Show REPRINT (^R) and move to a new line. */
1363 (void) tty_echo(tp, tp->tty_termios.c_cc[VREPRINT] | IN_ESC);
1364 rawecho(tp, '\r');
1365 rawecho(tp, '\n');
1366
1367 /* Reprint from the last break onwards. */
1368 do {
1369 if (head == bufend(tp->tty_inbuf)) head = tp->tty_inbuf;
1370 *head = tty_echo(tp, *head);
1371 head++;
1372 count++;
1373 } while (count < tp->tty_incount);
1374 }
1375
1376 /*===========================================================================*
1377 * out_process *
1378 *===========================================================================*/
1379 void out_process(tp, bstart, bpos, bend, icount, ocount)
1380 tty_t *tp;
1381 char *bstart, *bpos, *bend; /* start/pos/end of circular buffer */
1382 int *icount; /* # input chars / input chars used */
1383 int *ocount; /* max output chars / output chars used */
1384 {
1385 /* Perform output processing on a circular buffer. *icount is the number of
1386 * bytes to process, and the number of bytes actually processed on return.
1387 * *ocount is the space available on input and the space used on output.
1388 * (Naturally *icount < *ocount.) The column position is updated modulo
1389 * the TAB size, because we really only need it for tabs.
1390 */
1391
1392 int tablen;
1393 int ict = *icount;
1394 int oct = *ocount;
1395 int pos = tp->tty_position;
1396
1397 while (ict > 0) {
1398 switch (*bpos) {
1399 case '\7':
1400 break;
1401 case '\b':
1402 pos--;
1403 break;
1404 case '\r':
1405 pos = 0;
1406 break;
1407 case '\n':
1408 if ((tp->tty_termios.c_oflag & (OPOST|ONLCR))
1409 == (OPOST|ONLCR)) {
1410 /* Map LF to CR+LF if there is space. Note that the
1411 * next character in the buffer is overwritten, so
1412 * we stop at this point.
1413 */
1414 if (oct >= 2) {
1415 *bpos = '\r';
1416 if (++bpos == bend) bpos = bstart;
1417 *bpos = '\n';
1418 pos = 0;
1419 ict--;
1420 oct -= 2;
1421 }
1422 goto out_done; /* no space or buffer got changed */
1423 }
1424 break;
1425 case '\t':
1426 /* Best guess for the tab length. */
1427 tablen = TAB_SIZE - (pos & TAB_MASK);
1428
1429 if ((tp->tty_termios.c_oflag & (OPOST|XTABS))
1430 == (OPOST|XTABS)) {
1431 /* Tabs must be expanded. */
1432 if (oct >= tablen) {
1433 pos += tablen;
1434 ict--;
1435 oct -= tablen;
1436 do {
1437 *bpos = ' ';
1438 if (++bpos == bend) bpos = bstart;
1439 } while (--tablen != 0);
1440 }
1441 goto out_done;
1442 }
1443 /* Tabs are output directly. */
1444 pos += tablen;
1445 break;
1446 default:
1447 /* Assume any other character prints as one character. */
1448 pos++;
1449 }
1450 if (++bpos == bend) bpos = bstart;
1451 ict--;
1452 oct--;
1453 }
1454 out_done:
1455 tp->tty_position = pos & TAB_MASK;
1456
1457 *icount -= ict; /* [io]ct are the number of chars not used */
1458 *ocount -= oct; /* *[io]count are the number of chars that are used */
1459 }
1460
1461 /*===========================================================================*
1462 * dev_ioctl *
1463 *===========================================================================*/
1464 static void dev_ioctl(tp)
1465 tty_t *tp;
1466 {
1467 /* The ioctl's TCSETSW, TCSETSF and TCDRAIN wait for output to finish to make
1468 * sure that an attribute change doesn't affect the processing of current
1469 * output. Once output finishes the ioctl is executed as in do_ioctl().
1470 */
1471 int result = EINVAL;
1472
1473 if (tp->tty_outleft > 0) return; /* output not finished */
1474
1475 if (tp->tty_ioreq != TCDRAIN) {
1476 if (tp->tty_ioreq == TCSETSF) tty_icancel(tp);
1477 result = sys_safecopyfrom(tp->tty_iocaller, tp->tty_iogrant, 0,
1478 (vir_bytes) &tp->tty_termios,
1479 (vir_bytes) sizeof(tp->tty_termios));
1480 if (result == OK) setattr(tp);
1481 }
1482 tp->tty_ioreq = 0;
1483 chardriver_reply_task(tp->tty_iocaller, tp->tty_ioid, result);
1484 tp->tty_iocaller = NONE;
1485 }
1486
1487 /*===========================================================================*
1488 * setattr *
1489 *===========================================================================*/
1490 static void setattr(tp)
1491 tty_t *tp;
1492 {
1493 /* Apply the new line attributes (raw/canonical, line speed, etc.) */
1494 u16_t *inp;
1495 int count;
1496
1497 if (!(tp->tty_termios.c_lflag & ICANON)) {
1498 /* Raw mode; put a "line break" on all characters in the input queue.
1499 * It is undefined what happens to the input queue when ICANON is
1500 * switched off, a process should use TCSAFLUSH to flush the queue.
1501 * Keeping the queue to preserve typeahead is the Right Thing, however
1502 * when a process does use TCSANOW to switch to raw mode.
1503 */
1504 count = tp->tty_eotct = tp->tty_incount;
1505 inp = tp->tty_intail;
1506 while (count > 0) {
1507 *inp |= IN_EOT;
1508 if (++inp == bufend(tp->tty_inbuf)) inp = tp->tty_inbuf;
1509 --count;
1510 }
1511 }
1512
1513 /* Inspect MIN and TIME. */
1514 settimer(tp, FALSE);
1515 if (tp->tty_termios.c_lflag & ICANON) {
1516 /* No MIN & TIME in canonical mode. */
1517 tp->tty_min = 1;
1518 } else {
1519 /* In raw mode MIN is the number of chars wanted, and TIME how long
1520 * to wait for them. With interesting exceptions if either is zero.
1521 */
1522 tp->tty_min = tp->tty_termios.c_cc[VMIN];
1523 if (tp->tty_min == 0 && tp->tty_termios.c_cc[VTIME] > 0)
1524 tp->tty_min = 1;
1525 }
1526
1527 if (!(tp->tty_termios.c_iflag & IXON)) {
1528 /* No start/stop output control, so don't leave output inhibited. */
1529 tp->tty_inhibited = RUNNING;
1530 tp->tty_events = 1;
1531 }
1532
1533 /* Setting the output speed to zero hangs up the phone. */
1534 if (tp->tty_termios.c_ospeed == B0) sigchar(tp, SIGHUP, 1);
1535
1536 /* SCANCODES is supported only for the console */
1537 if (!isconsole(tp)) tp->tty_termios.c_iflag &= ~SCANCODES;
1538
1539 /* Set new line speed, character size, etc at the device level. */
1540 (*tp->tty_ioctl)(tp, 0);
1541 }
1542
1543 /*===========================================================================*
1544 * sigchar *
1545 *===========================================================================*/
1546 void sigchar(tp, sig, mayflush)
1547 register tty_t *tp;
1548 int sig; /* SIGINT, SIGQUIT, SIGKILL or SIGHUP */
1549 int mayflush;
1550 {
1551 /* Process a SIGINT, SIGQUIT or SIGKILL char from the keyboard or SIGHUP from
1552 * a tty close, "stty 0", or a real RS-232 hangup. PM will send the signal to
1553 * the process group (INT, QUIT), all processes (KILL), or the session leader
1554 * (HUP).
1555 */
1556 int status;
1557
1558 if (tp->tty_pgrp != 0) {
1559 if (OK != (status = sys_kill(tp->tty_pgrp, sig))) {
1560 panic("Error; call to sys_kill failed: %d", status);
1561 }
1562 }
1563
1564 if (mayflush && !(tp->tty_termios.c_lflag & NOFLSH)) {
1565 tp->tty_incount = tp->tty_eotct = 0; /* kill earlier input */
1566 tp->tty_intail = tp->tty_inhead;
1567 (*tp->tty_ocancel)(tp, 0); /* kill all output */
1568 tp->tty_inhibited = RUNNING;
1569 tp->tty_events = 1;
1570 }
1571 }
1572
1573 /*===========================================================================*
1574 * tty_icancel *
1575 *===========================================================================*/
1576 static void tty_icancel(tp)
1577 register tty_t *tp;
1578 {
1579 /* Discard all pending input, tty buffer or device. */
1580
1581 tp->tty_incount = tp->tty_eotct = 0;
1582 tp->tty_intail = tp->tty_inhead;
1583 (*tp->tty_icancel)(tp, 0);
1584 }
1585
1586 /*===========================================================================*
1587 * tty_devnop *
1588 *===========================================================================*/
1589 static int tty_devnop(tty_t *UNUSED(tp), int UNUSED(try))
1590 {
1591 /* Some functions need not be implemented at the device level. */
1592 return 0;
1593 }
1594
1595 /*===========================================================================*
1596 * tty_init *
1597 *===========================================================================*/
1598 static void tty_init()
1599 {
1600 /* Initialize tty structure and call device initialization routines. */
1601
1602 register tty_t *tp;
1603 int s;
1604
1605 system_hz = sys_hz();
1606
1607 /* Initialize the terminal lines. */
1608 memset(tty_table, '\0' , sizeof(tty_table));
1609
1610 for (tp = FIRST_TTY,s=0; tp < END_TTY; tp++,s++) {
1611
1612 tp->tty_index = s;
1613 init_timer(&tp->tty_tmr);
1614
1615 tp->tty_intail = tp->tty_inhead = tp->tty_inbuf;
1616 tp->tty_min = 1;
1617 tp->tty_incaller = tp->tty_outcaller = tp->tty_iocaller = NONE;
1618 tp->tty_termios = termios_defaults;
1619 tp->tty_icancel = tp->tty_ocancel = tp->tty_ioctl = tp->tty_close =
1620 tp->tty_open = tty_devnop;
1621 if (tp < tty_addr(NR_CONS)) {
1622 scr_init(tp);
1623
1624 /* Initialize the keyboard driver. */
1625 kb_init(tp);
1626
1627 tp->tty_minor = CONS_MINOR + s;
1628 } else
1629 if (tp < tty_addr(NR_CONS+NR_RS_LINES)) {
1630 rs_init(tp);
1631 tp->tty_minor = RS232_MINOR + s-NR_CONS;
1632 } else {
1633 pty_init(tp);
1634 tp->tty_minor = s - (NR_CONS+NR_RS_LINES) + TTYPX_MINOR;
1635 }
1636 }
1637
1638 }
1639
1640 /*===========================================================================*
1641 * tty_timed_out *
1642 *===========================================================================*/
1643 static void tty_timed_out(timer_t *tp)
1644 {
1645 /* This timer has expired. Set the events flag, to force processing. */
1646 tty_t *tty_ptr;
1647 tty_ptr = &tty_table[tmr_arg(tp)->ta_int];
1648 tty_ptr->tty_min = 0; /* force read to succeed */
1649 tty_ptr->tty_events = 1;
1650 }
1651
1652 /*===========================================================================*
1653 * settimer *
1654 *===========================================================================*/
1655 static void settimer(tty_ptr, enable)
1656 tty_t *tty_ptr; /* line to set or unset a timer on */
1657 int enable; /* set timer if true, otherwise unset */
1658 {
1659 clock_t ticks;
1660
1661 if (enable) {
1662 ticks = tty_ptr->tty_termios.c_cc[VTIME] * (system_hz/10);
1663
1664 /* Set a new timer for enabling the TTY events flags. */
1665 set_timer(&tty_ptr->tty_tmr, ticks, tty_timed_out, tty_ptr->tty_index);
1666 } else {
1667 /* Remove the timer from the active and expired lists. */
1668 cancel_timer(&tty_ptr->tty_tmr);
1669 }
1670 }