1 // SPDX-License-Identifier: GPL-2.0+
6 * Copyright (C) 2004 IBM Corporation
8 * Additional Author(s):
12 #include <linux/console.h>
13 #include <linux/cpumask.h>
14 #include <linux/init.h>
15 #include <linux/kbd_kern.h>
16 #include <linux/kernel.h>
17 #include <linux/kthread.h>
18 #include <linux/list.h>
19 #include <linux/major.h>
20 #include <linux/atomic.h>
21 #include <linux/sysrq.h>
22 #include <linux/tty.h>
23 #include <linux/tty_flip.h>
24 #include <linux/sched.h>
25 #include <linux/spinlock.h>
26 #include <linux/delay.h>
27 #include <linux/freezer.h>
28 #include <linux/slab.h>
29 #include <linux/serial_core.h>
31 #include <linux/uaccess.h>
33 #include "hvc_console.h"
39 * Wait this long per iteration while trying to push buffered data to the
40 * hypervisor before allowing the tty to complete a close operation.
42 #define HVC_CLOSE_WAIT (HZ/100) /* 1/10 of a second */
45 * These sizes are most efficient for vio, because they are the
46 * native transfer size. We could make them selectable in the
47 * future to better deal with backends that want other buffer sizes.
52 #define __ALIGNED__ __attribute__((__aligned__(sizeof(long))))
54 static struct tty_driver *hvc_driver;
55 static struct task_struct *hvc_task;
57 /* Picks up late kicks after list walk but before schedule() */
58 static int hvc_kicked;
60 /* hvc_init is triggered from hvc_alloc, i.e. only when actually used */
61 static atomic_t hvc_needs_init __read_mostly = ATOMIC_INIT(-1);
63 static int hvc_init(void);
65 #ifdef CONFIG_MAGIC_SYSRQ
66 static int sysrq_pressed;
69 /* dynamic list of hvc_struct instances */
70 static LIST_HEAD(hvc_structs);
73 * Protect the list of hvc_struct instances from inserts and removals during
76 static DEFINE_SPINLOCK(hvc_structs_lock);
79 * This value is used to assign a tty->index value to a hvc_struct based
80 * upon order of exposure via hvc_probe(), when we can not match it to
81 * a console candidate registered with hvc_instantiate().
83 static int last_hvc = -1;
86 * Do not call this function with either the hvc_structs_lock or the hvc_struct
87 * lock held. If successful, this function increments the kref reference
88 * count against the target hvc_struct so it should be released when finished.
90 static struct hvc_struct *hvc_get_by_index(int index)
92 struct hvc_struct *hp;
95 spin_lock(&hvc_structs_lock);
97 list_for_each_entry(hp, &hvc_structs, next) {
98 spin_lock_irqsave(&hp->lock, flags);
99 if (hp->index == index) {
100 tty_port_get(&hp->port);
101 spin_unlock_irqrestore(&hp->lock, flags);
102 spin_unlock(&hvc_structs_lock);
105 spin_unlock_irqrestore(&hp->lock, flags);
109 spin_unlock(&hvc_structs_lock);
115 * Initial console vtermnos for console API usage prior to full console
116 * initialization. Any vty adapter outside this range will not have usable
117 * console interfaces but can still be used as a tty device. This has to be
118 * static because kmalloc will not work during early console init.
120 static const struct hv_ops *cons_ops[MAX_NR_HVC_CONSOLES];
121 static uint32_t vtermnos[MAX_NR_HVC_CONSOLES] =
122 {[0 ... MAX_NR_HVC_CONSOLES - 1] = -1};
125 * Console APIs, NOT TTY. These APIs are available immediately when
126 * hvc_console_setup() finds adapters.
129 static void hvc_console_print(struct console *co, const char *b,
132 char c[N_OUTBUF] __ALIGNED__;
133 unsigned i = 0, n = 0;
134 int r, donecr = 0, index = co->index;
136 /* Console access attempt outside of acceptable console range. */
137 if (index >= MAX_NR_HVC_CONSOLES)
140 /* This console adapter was removed so it is not usable. */
141 if (vtermnos[index] == -1)
144 while (count > 0 || i > 0) {
145 if (count > 0 && i < sizeof(c)) {
146 if (b[n] == '\n' && !donecr) {
155 r = cons_ops[index]->put_chars(vtermnos[index], c, i);
157 /* throw away characters on error
158 * but spin in case of -EAGAIN */
170 static struct tty_driver *hvc_console_device(struct console *c, int *index)
172 if (vtermnos[c->index] == -1)
179 static int hvc_console_setup(struct console *co, char *options)
181 if (co->index < 0 || co->index >= MAX_NR_HVC_CONSOLES)
184 if (vtermnos[co->index] == -1)
190 static struct console hvc_console = {
192 .write = hvc_console_print,
193 .device = hvc_console_device,
194 .setup = hvc_console_setup,
195 .flags = CON_PRINTBUFFER,
200 * Early console initialization. Precedes driver initialization.
202 * (1) we are first, and the user specified another driver
203 * -- index will remain -1
204 * (2) we are first and the user specified no driver
205 * -- index will be set to 0, then we will fail setup.
206 * (3) we are first and the user specified our driver
207 * -- index will be set to user specified driver, and we will fail
208 * (4) we are after driver, and this initcall will register us
209 * -- if the user didn't specify a driver then the console will match
211 * Note that for cases 2 and 3, we will match later when the io driver
212 * calls hvc_instantiate() and call register again.
214 static int __init hvc_console_init(void)
216 register_console(&hvc_console);
219 console_initcall(hvc_console_init);
221 /* callback when the kboject ref count reaches zero. */
222 static void hvc_port_destruct(struct tty_port *port)
224 struct hvc_struct *hp = container_of(port, struct hvc_struct, port);
227 spin_lock(&hvc_structs_lock);
229 spin_lock_irqsave(&hp->lock, flags);
230 list_del(&(hp->next));
231 spin_unlock_irqrestore(&hp->lock, flags);
233 spin_unlock(&hvc_structs_lock);
238 static void hvc_check_console(int index)
240 /* Already enabled, bail out */
241 if (hvc_console.flags & CON_ENABLED)
244 /* If this index is what the user requested, then register
245 * now (setup won't fail at this point). It's ok to just
246 * call register again if previously .setup failed.
248 if (index == hvc_console.index)
249 register_console(&hvc_console);
253 * hvc_instantiate() is an early console discovery method which locates
254 * consoles * prior to the vio subsystem discovering them. Hotplugged
255 * vty adapters do NOT get an hvc_instantiate() callback since they
256 * appear after early console init.
258 int hvc_instantiate(uint32_t vtermno, int index, const struct hv_ops *ops)
260 struct hvc_struct *hp;
262 if (index < 0 || index >= MAX_NR_HVC_CONSOLES)
265 if (vtermnos[index] != -1)
268 /* make sure no no tty has been registered in this index */
269 hp = hvc_get_by_index(index);
271 tty_port_put(&hp->port);
275 vtermnos[index] = vtermno;
276 cons_ops[index] = ops;
278 /* reserve all indices up to and including this index */
279 if (last_hvc < index)
282 /* check if we need to re-register the kernel console */
283 hvc_check_console(index);
287 EXPORT_SYMBOL_GPL(hvc_instantiate);
289 /* Wake the sleeping khvcd */
293 wake_up_process(hvc_task);
295 EXPORT_SYMBOL_GPL(hvc_kick);
297 static void hvc_unthrottle(struct tty_struct *tty)
302 static int hvc_install(struct tty_driver *driver, struct tty_struct *tty)
304 struct hvc_struct *hp;
307 /* Auto increments kref reference if found. */
308 hp = hvc_get_by_index(tty->index);
312 tty->driver_data = hp;
314 rc = tty_port_install(&hp->port, driver, tty);
316 tty_port_put(&hp->port);
321 * The TTY interface won't be used until after the vio layer has exposed the vty
322 * adapter to the kernel.
324 static int hvc_open(struct tty_struct *tty, struct file * filp)
326 struct hvc_struct *hp = tty->driver_data;
330 spin_lock_irqsave(&hp->port.lock, flags);
331 /* Check and then increment for fast path open. */
332 if (hp->port.count++ > 0) {
333 spin_unlock_irqrestore(&hp->port.lock, flags);
336 } /* else count == 0 */
337 spin_unlock_irqrestore(&hp->port.lock, flags);
339 tty_port_tty_set(&hp->port, tty);
341 if (hp->ops->notifier_add)
342 rc = hp->ops->notifier_add(hp, hp->data);
345 * If the notifier fails we return an error. The tty layer
346 * will call hvc_close() after a failed open but we don't want to clean
347 * up there so we'll clean up here and clear out the previously set
348 * tty fields and return the kref reference.
351 tty_port_tty_set(&hp->port, NULL);
352 tty->driver_data = NULL;
353 tty_port_put(&hp->port);
354 printk(KERN_ERR "hvc_open: request_irq failed with rc %d.\n", rc);
356 /* We are ready... raise DTR/RTS */
358 if (hp->ops->dtr_rts)
359 hp->ops->dtr_rts(hp, 1);
361 /* Force wakeup of the polling thread */
367 static void hvc_close(struct tty_struct *tty, struct file * filp)
369 struct hvc_struct *hp;
372 if (tty_hung_up_p(filp))
376 * No driver_data means that this close was issued after a failed
377 * hvc_open by the tty layer's release_dev() function and we can just
378 * exit cleanly because the kref reference wasn't made.
380 if (!tty->driver_data)
383 hp = tty->driver_data;
385 spin_lock_irqsave(&hp->port.lock, flags);
387 if (--hp->port.count == 0) {
388 spin_unlock_irqrestore(&hp->port.lock, flags);
389 /* We are done with the tty pointer now. */
390 tty_port_tty_set(&hp->port, NULL);
393 if (hp->ops->dtr_rts)
394 hp->ops->dtr_rts(hp, 0);
396 if (hp->ops->notifier_del)
397 hp->ops->notifier_del(hp, hp->data);
399 /* cancel pending tty resize work */
400 cancel_work_sync(&hp->tty_resize);
403 * Chain calls chars_in_buffer() and returns immediately if
404 * there is no buffered data otherwise sleeps on a wait queue
405 * waking periodically to check chars_in_buffer().
407 tty_wait_until_sent(tty, HVC_CLOSE_WAIT);
409 if (hp->port.count < 0)
410 printk(KERN_ERR "hvc_close %X: oops, count is %d\n",
411 hp->vtermno, hp->port.count);
412 spin_unlock_irqrestore(&hp->port.lock, flags);
416 static void hvc_cleanup(struct tty_struct *tty)
418 struct hvc_struct *hp = tty->driver_data;
420 tty_port_put(&hp->port);
423 static void hvc_hangup(struct tty_struct *tty)
425 struct hvc_struct *hp = tty->driver_data;
431 /* cancel pending tty resize work */
432 cancel_work_sync(&hp->tty_resize);
434 spin_lock_irqsave(&hp->port.lock, flags);
437 * The N_TTY line discipline has problems such that in a close vs
438 * open->hangup case this can be called after the final close so prevent
439 * that from happening for now.
441 if (hp->port.count <= 0) {
442 spin_unlock_irqrestore(&hp->port.lock, flags);
447 spin_unlock_irqrestore(&hp->port.lock, flags);
448 tty_port_tty_set(&hp->port, NULL);
452 if (hp->ops->notifier_hangup)
453 hp->ops->notifier_hangup(hp, hp->data);
457 * Push buffered characters whether they were just recently buffered or waiting
458 * on a blocked hypervisor. Call this function with hp->lock held.
460 static int hvc_push(struct hvc_struct *hp)
464 n = hp->ops->put_chars(hp->vtermno, hp->outbuf, hp->n_outbuf);
466 if (n == 0 || n == -EAGAIN) {
470 /* throw away output on error; this happens when
471 there is no session connected to the vterm. */
475 if (hp->n_outbuf > 0)
476 memmove(hp->outbuf, hp->outbuf + n, hp->n_outbuf);
483 static int hvc_write(struct tty_struct *tty, const unsigned char *buf, int count)
485 struct hvc_struct *hp = tty->driver_data;
487 int rsize, written = 0;
489 /* This write was probably executed during a tty close. */
493 /* FIXME what's this (unprotected) check for? */
494 if (hp->port.count <= 0)
497 spin_lock_irqsave(&hp->lock, flags);
499 /* Push pending writes */
500 if (hp->n_outbuf > 0)
503 while (count > 0 && (rsize = hp->outbuf_size - hp->n_outbuf) > 0) {
506 memcpy(hp->outbuf + hp->n_outbuf, buf, rsize);
509 hp->n_outbuf += rsize;
513 spin_unlock_irqrestore(&hp->lock, flags);
516 * Racy, but harmless, kick thread if there is still pending data.
525 * hvc_set_winsz() - Resize the hvc tty terminal window.
526 * @work: work structure.
528 * The routine shall not be called within an atomic context because it
533 static void hvc_set_winsz(struct work_struct *work)
535 struct hvc_struct *hp;
536 unsigned long hvc_flags;
537 struct tty_struct *tty;
540 hp = container_of(work, struct hvc_struct, tty_resize);
542 tty = tty_port_tty_get(&hp->port);
546 spin_lock_irqsave(&hp->lock, hvc_flags);
548 spin_unlock_irqrestore(&hp->lock, hvc_flags);
550 tty_do_resize(tty, &ws);
555 * This is actually a contract between the driver and the tty layer outlining
556 * how much write room the driver can guarantee will be sent OR BUFFERED. This
557 * driver MUST honor the return value.
559 static int hvc_write_room(struct tty_struct *tty)
561 struct hvc_struct *hp = tty->driver_data;
566 return hp->outbuf_size - hp->n_outbuf;
569 static int hvc_chars_in_buffer(struct tty_struct *tty)
571 struct hvc_struct *hp = tty->driver_data;
579 * timeout will vary between the MIN and MAX values defined here. By default
580 * and during console activity we will use a default MIN_TIMEOUT of 10. When
581 * the console is idle, we increase the timeout value on each pass through
582 * msleep until we reach the max. This may be noticeable as a brief (average
583 * one second) delay on the console before the console responds to input when
584 * there has been no input for some time.
586 #define MIN_TIMEOUT (10)
587 #define MAX_TIMEOUT (2000)
588 static u32 timeout = MIN_TIMEOUT;
590 #define HVC_POLL_READ 0x00000001
591 #define HVC_POLL_WRITE 0x00000002
593 int hvc_poll(struct hvc_struct *hp)
595 struct tty_struct *tty;
596 int i, n, poll_mask = 0;
597 char buf[N_INBUF] __ALIGNED__;
600 int written_total = 0;
602 spin_lock_irqsave(&hp->lock, flags);
604 /* Push pending writes */
605 if (hp->n_outbuf > 0)
606 written_total = hvc_push(hp);
608 /* Reschedule us if still some write pending */
609 if (hp->n_outbuf > 0) {
610 poll_mask |= HVC_POLL_WRITE;
611 /* If hvc_push() was not able to write, sleep a few msecs */
612 timeout = (written_total) ? 0 : MIN_TIMEOUT;
615 /* No tty attached, just skip */
616 tty = tty_port_tty_get(&hp->port);
620 /* Now check if we can get data (are we throttled ?) */
621 if (tty_throttled(tty))
624 /* If we aren't notifier driven and aren't throttled, we always
625 * request a reschedule
627 if (!hp->irq_requested)
628 poll_mask |= HVC_POLL_READ;
630 /* Read data if any */
632 int count = tty_buffer_request_room(&hp->port, N_INBUF);
634 /* If flip is full, just reschedule a later read */
636 poll_mask |= HVC_POLL_READ;
640 n = hp->ops->get_chars(hp->vtermno, buf, count);
642 /* Hangup the tty when disconnected from host */
644 spin_unlock_irqrestore(&hp->lock, flags);
646 spin_lock_irqsave(&hp->lock, flags);
647 } else if ( n == -EAGAIN ) {
649 * Some back-ends can only ensure a certain min
650 * num of bytes read, which may be > 'count'.
651 * Let the tty clear the flip buff to make room.
653 poll_mask |= HVC_POLL_READ;
657 for (i = 0; i < n; ++i) {
658 #ifdef CONFIG_MAGIC_SYSRQ
659 if (hp->index == hvc_console.index) {
660 /* Handle the SysRq Hack */
661 /* XXX should support a sequence */
662 if (buf[i] == '\x0f') { /* ^O */
663 /* if ^O is pressed again, reset
664 * sysrq_pressed and flip ^O char */
665 sysrq_pressed = !sysrq_pressed;
668 } else if (sysrq_pressed) {
669 handle_sysrq(buf[i]);
674 #endif /* CONFIG_MAGIC_SYSRQ */
675 tty_insert_flip_char(&hp->port, buf[i], 0);
681 /* Wakeup write queue if necessary */
687 spin_unlock_irqrestore(&hp->lock, flags);
690 /* Activity is occurring, so reset the polling backoff value to
691 a minimum for performance. */
692 timeout = MIN_TIMEOUT;
694 tty_flip_buffer_push(&hp->port);
700 EXPORT_SYMBOL_GPL(hvc_poll);
703 * __hvc_resize() - Update terminal window size information.
704 * @hp: HVC console pointer
705 * @ws: Terminal window size structure
707 * Stores the specified window size information in the hvc structure of @hp.
708 * The function schedule the tty resize update.
710 * Locking: Locking free; the function MUST be called holding hp->lock
712 void __hvc_resize(struct hvc_struct *hp, struct winsize ws)
715 schedule_work(&hp->tty_resize);
717 EXPORT_SYMBOL_GPL(__hvc_resize);
720 * This kthread is either polling or interrupt driven. This is determined by
721 * calling hvc_poll() who determines whether a console adapter support
724 static int khvcd(void *unused)
727 struct hvc_struct *hp;
735 if (!cpus_are_in_xmon()) {
736 spin_lock(&hvc_structs_lock);
737 list_for_each_entry(hp, &hvc_structs, next) {
738 poll_mask |= hvc_poll(hp);
740 spin_unlock(&hvc_structs_lock);
742 poll_mask |= HVC_POLL_READ;
745 set_current_state(TASK_INTERRUPTIBLE);
750 unsigned long j_timeout;
752 if (timeout < MAX_TIMEOUT)
753 timeout += (timeout >> 6) + 1;
756 * We don't use msleep_interruptible otherwise
757 * "kick" will fail to wake us up
759 j_timeout = msecs_to_jiffies(timeout) + 1;
760 schedule_timeout_interruptible(j_timeout);
763 __set_current_state(TASK_RUNNING);
764 } while (!kthread_should_stop());
769 static int hvc_tiocmget(struct tty_struct *tty)
771 struct hvc_struct *hp = tty->driver_data;
773 if (!hp || !hp->ops->tiocmget)
775 return hp->ops->tiocmget(hp);
778 static int hvc_tiocmset(struct tty_struct *tty,
779 unsigned int set, unsigned int clear)
781 struct hvc_struct *hp = tty->driver_data;
783 if (!hp || !hp->ops->tiocmset)
785 return hp->ops->tiocmset(hp, set, clear);
788 #ifdef CONFIG_CONSOLE_POLL
789 static int hvc_poll_init(struct tty_driver *driver, int line, char *options)
794 static int hvc_poll_get_char(struct tty_driver *driver, int line)
796 struct tty_struct *tty = driver->ttys[0];
797 struct hvc_struct *hp = tty->driver_data;
801 n = hp->ops->get_chars(hp->vtermno, &ch, 1);
809 static void hvc_poll_put_char(struct tty_driver *driver, int line, char ch)
811 struct tty_struct *tty = driver->ttys[0];
812 struct hvc_struct *hp = tty->driver_data;
816 n = hp->ops->put_chars(hp->vtermno, &ch, 1);
821 static const struct tty_operations hvc_ops = {
822 .install = hvc_install,
825 .cleanup = hvc_cleanup,
827 .hangup = hvc_hangup,
828 .unthrottle = hvc_unthrottle,
829 .write_room = hvc_write_room,
830 .chars_in_buffer = hvc_chars_in_buffer,
831 .tiocmget = hvc_tiocmget,
832 .tiocmset = hvc_tiocmset,
833 #ifdef CONFIG_CONSOLE_POLL
834 .poll_init = hvc_poll_init,
835 .poll_get_char = hvc_poll_get_char,
836 .poll_put_char = hvc_poll_put_char,
840 static const struct tty_port_operations hvc_port_ops = {
841 .destruct = hvc_port_destruct,
844 struct hvc_struct *hvc_alloc(uint32_t vtermno, int data,
845 const struct hv_ops *ops,
848 struct hvc_struct *hp;
851 /* We wait until a driver actually comes along */
852 if (atomic_inc_not_zero(&hvc_needs_init)) {
853 int err = hvc_init();
858 hp = kzalloc(ALIGN(sizeof(*hp), sizeof(long)) + outbuf_size,
861 return ERR_PTR(-ENOMEM);
863 hp->vtermno = vtermno;
866 hp->outbuf_size = outbuf_size;
867 hp->outbuf = &((char *)hp)[ALIGN(sizeof(*hp), sizeof(long))];
869 tty_port_init(&hp->port);
870 hp->port.ops = &hvc_port_ops;
872 INIT_WORK(&hp->tty_resize, hvc_set_winsz);
873 spin_lock_init(&hp->lock);
874 spin_lock(&hvc_structs_lock);
878 * see if this vterm id matches one registered for console.
880 for (i=0; i < MAX_NR_HVC_CONSOLES; i++)
881 if (vtermnos[i] == hp->vtermno &&
882 cons_ops[i] == hp->ops)
885 /* no matching slot, just use a counter */
886 if (i >= MAX_NR_HVC_CONSOLES)
891 vtermnos[i] = vtermno;
893 list_add_tail(&(hp->next), &hvc_structs);
894 spin_unlock(&hvc_structs_lock);
896 /* check if we need to re-register the kernel console */
897 hvc_check_console(i);
901 EXPORT_SYMBOL_GPL(hvc_alloc);
903 int hvc_remove(struct hvc_struct *hp)
906 struct tty_struct *tty;
908 tty = tty_port_tty_get(&hp->port);
911 spin_lock_irqsave(&hp->lock, flags);
912 if (hp->index < MAX_NR_HVC_CONSOLES) {
913 vtermnos[hp->index] = -1;
914 cons_ops[hp->index] = NULL;
917 /* Don't whack hp->irq because tty_hangup() will need to free the irq. */
919 spin_unlock_irqrestore(&hp->lock, flags);
923 * We 'put' the instance that was grabbed when the kref instance
924 * was initialized using kref_init(). Let the last holder of this
925 * kref cause it to be removed, which will probably be the tty_vhangup
928 tty_port_put(&hp->port);
931 * This function call will auto chain call hvc_hangup.
939 EXPORT_SYMBOL_GPL(hvc_remove);
941 /* Driver initialization: called as soon as someone uses hvc_alloc(). */
942 static int hvc_init(void)
944 struct tty_driver *drv;
947 /* We need more than hvc_count adapters due to hotplug additions. */
948 drv = alloc_tty_driver(HVC_ALLOC_TTY_ADAPTERS);
954 drv->driver_name = "hvc";
956 drv->major = HVC_MAJOR;
957 drv->minor_start = HVC_MINOR;
958 drv->type = TTY_DRIVER_TYPE_SYSTEM;
959 drv->init_termios = tty_std_termios;
960 drv->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_RESET_TERMIOS;
961 tty_set_operations(drv, &hvc_ops);
963 /* Always start the kthread because there can be hotplug vty adapters
965 hvc_task = kthread_run(khvcd, NULL, "khvcd");
966 if (IS_ERR(hvc_task)) {
967 printk(KERN_ERR "Couldn't create kthread for console.\n");
968 err = PTR_ERR(hvc_task);
972 err = tty_register_driver(drv);
974 printk(KERN_ERR "Couldn't register hvc console driver\n");
979 * Make sure tty is fully registered before allowing it to be
980 * found by hvc_console_device.
987 kthread_stop(hvc_task);