1 /******************************************************************************
2  * console.c
3  *
4  * Emergency console I/O for Xen and the domain-0 guest OS.
5  *
6  * Copyright (c) 2002-2004, K A Fraser.
7  *
8  * Added printf_ratelimit
9  *     Taken from Linux - Author: Andi Kleen (net_ratelimit)
10  *     Ported to Xen - Steven Rostedt - Red Hat
11  */
12 
13 #include <xen/version.h>
14 #include <xen/lib.h>
15 #include <xen/init.h>
16 #include <xen/event.h>
17 #include <xen/console.h>
18 #include <xen/param.h>
19 #include <xen/serial.h>
20 #include <xen/softirq.h>
21 #include <xen/keyhandler.h>
22 #include <xen/guest_access.h>
23 #include <xen/watchdog.h>
24 #include <xen/shutdown.h>
25 #include <xen/video.h>
26 #include <xen/kexec.h>
27 #include <xen/ctype.h>
28 #include <xen/warning.h>
29 #include <asm/debugger.h>
30 #include <asm/div64.h>
31 #include <xen/hypercall.h> /* for do_console_io */
32 #include <xen/early_printk.h>
33 #include <xen/warning.h>
34 #include <xen/pv_console.h>
35 #include <asm/setup.h>
36 
37 #ifdef CONFIG_X86
38 #include <xen/consoled.h>
39 #include <asm/guest.h>
40 #endif
41 #ifdef CONFIG_SBSA_VUART_CONSOLE
42 #include <asm/vpl011.h>
43 #endif
44 
45 /* console: comma-separated list of console outputs. */
46 static char __initdata opt_console[30] = OPT_CONSOLE_STR;
47 string_param("console", opt_console);
48 
49 /* conswitch: a character pair controlling console switching. */
50 /* Char 1: CTRL+<char1> is used to switch console input between Xen and DOM0 */
51 /* Char 2: If this character is 'x', then do not auto-switch to DOM0 when it */
52 /*         boots. Any other value, or omitting the char, enables auto-switch */
53 static unsigned char __read_mostly opt_conswitch[3] = "a";
54 string_runtime_param("conswitch", opt_conswitch);
55 
56 /* sync_console: force synchronous console output (useful for debugging). */
57 static bool_t __initdata opt_sync_console;
58 boolean_param("sync_console", opt_sync_console);
59 static const char __initconst warning_sync_console[] =
60     "WARNING: CONSOLE OUTPUT IS SYNCHRONOUS\n"
61     "This option is intended to aid debugging of Xen by ensuring\n"
62     "that all output is synchronously delivered on the serial line.\n"
63     "However it can introduce SIGNIFICANT latencies and affect\n"
64     "timekeeping. It is NOT recommended for production use!\n";
65 
66 /* console_to_ring: send guest (incl. dom 0) console data to console ring. */
67 static bool_t __read_mostly opt_console_to_ring;
68 boolean_param("console_to_ring", opt_console_to_ring);
69 
70 /* console_timestamps: include a timestamp prefix on every Xen console line. */
71 enum con_timestamp_mode
72 {
73     TSM_NONE,          /* No timestamps */
74     TSM_DATE,          /* [YYYY-MM-DD HH:MM:SS] */
75     TSM_DATE_MS,       /* [YYYY-MM-DD HH:MM:SS.mmm] */
76     TSM_BOOT,          /* [SSSSSS.uuuuuu] */
77     TSM_RAW,           /* [XXXXXXXXXXXXXXXX] */
78 };
79 
80 static enum con_timestamp_mode __read_mostly opt_con_timestamp_mode = TSM_NONE;
81 
82 #ifdef CONFIG_HYPFS
83 static const char con_timestamp_mode_2_string[][7] = {
84     [TSM_NONE] = "none",
85     [TSM_DATE] = "date",
86     [TSM_DATE_MS] = "datems",
87     [TSM_BOOT] = "boot",
88     [TSM_RAW] = "raw",
89 };
90 
con_timestamp_mode_upd(struct param_hypfs * par)91 static void con_timestamp_mode_upd(struct param_hypfs *par)
92 {
93     const char *val = con_timestamp_mode_2_string[opt_con_timestamp_mode];
94 
95     custom_runtime_set_var_sz(par, val, 7);
96 }
97 #else
98 #define con_timestamp_mode_upd(par)
99 #endif
100 
101 static int parse_console_timestamps(const char *s);
102 custom_runtime_param("console_timestamps", parse_console_timestamps,
103                      con_timestamp_mode_upd);
104 
105 /* conring_size: allows a large console ring than default (16kB). */
106 static uint32_t __initdata opt_conring_size;
107 size_param("conring_size", opt_conring_size);
108 
109 #define _CONRING_SIZE 16384
110 #define CONRING_IDX_MASK(i) ((i)&(conring_size-1))
111 static char __initdata _conring[_CONRING_SIZE];
112 static char *__read_mostly conring = _conring;
113 static uint32_t __read_mostly conring_size = _CONRING_SIZE;
114 static uint32_t conringc, conringp;
115 
116 static int __read_mostly sercon_handle = -1;
117 
118 #ifdef CONFIG_X86
119 /* Tristate: 0 disabled, 1 user enabled, -1 default enabled */
120 int8_t __read_mostly opt_console_xen; /* console=xen */
121 #endif
122 
123 static DEFINE_SPINLOCK(console_lock);
124 
125 /*
126  * To control the amount of printing, thresholds are added.
127  * These thresholds correspond to the XENLOG logging levels.
128  * There's an upper and lower threshold for non-guest messages and for
129  * guest-provoked messages.  This works as follows, for a given log level L:
130  *
131  * L < lower_threshold                     : always logged
132  * lower_threshold <= L < upper_threshold  : rate-limited logging
133  * upper_threshold <= L                    : never logged
134  *
135  * Note, in the above algorithm, to disable rate limiting simply make
136  * the lower threshold equal to the upper.
137  */
138 #ifdef NDEBUG
139 #define XENLOG_UPPER_THRESHOLD       2 /* Do not print INFO and DEBUG  */
140 #define XENLOG_LOWER_THRESHOLD       2 /* Always print ERR and WARNING */
141 #define XENLOG_GUEST_UPPER_THRESHOLD 2 /* Do not print INFO and DEBUG  */
142 #define XENLOG_GUEST_LOWER_THRESHOLD 0 /* Rate-limit ERR and WARNING   */
143 #else
144 #define XENLOG_UPPER_THRESHOLD       4 /* Do not discard anything      */
145 #define XENLOG_LOWER_THRESHOLD       4 /* Print everything             */
146 #define XENLOG_GUEST_UPPER_THRESHOLD 4 /* Do not discard anything      */
147 #define XENLOG_GUEST_LOWER_THRESHOLD 4 /* Print everything             */
148 #endif
149 /*
150  * The XENLOG_DEFAULT is the default given to printks that
151  * do not have any print level associated with them.
152  */
153 #define XENLOG_DEFAULT       1 /* XENLOG_WARNING */
154 #define XENLOG_GUEST_DEFAULT 1 /* XENLOG_WARNING */
155 
156 static int __read_mostly xenlog_upper_thresh = XENLOG_UPPER_THRESHOLD;
157 static int __read_mostly xenlog_lower_thresh = XENLOG_LOWER_THRESHOLD;
158 static int __read_mostly xenlog_guest_upper_thresh =
159     XENLOG_GUEST_UPPER_THRESHOLD;
160 static int __read_mostly xenlog_guest_lower_thresh =
161     XENLOG_GUEST_LOWER_THRESHOLD;
162 
163 static int parse_loglvl(const char *s);
164 static int parse_guest_loglvl(const char *s);
165 
166 #ifdef CONFIG_HYPFS
167 #define LOGLVL_VAL_SZ 16
168 static char xenlog_val[LOGLVL_VAL_SZ];
169 static char xenlog_guest_val[LOGLVL_VAL_SZ];
170 
171 static char *lvl2opt[] = { "none", "error", "warning", "info", "all" };
172 
xenlog_update_val(int lower,int upper,char * val)173 static void xenlog_update_val(int lower, int upper, char *val)
174 {
175     snprintf(val, LOGLVL_VAL_SZ, "%s/%s", lvl2opt[lower], lvl2opt[upper]);
176 }
177 
xenlog_init(struct param_hypfs * par)178 static void __init xenlog_init(struct param_hypfs *par)
179 {
180     xenlog_update_val(xenlog_lower_thresh, xenlog_upper_thresh, xenlog_val);
181     custom_runtime_set_var(par, xenlog_val);
182 }
183 
xenlog_guest_init(struct param_hypfs * par)184 static void __init xenlog_guest_init(struct param_hypfs *par)
185 {
186     xenlog_update_val(xenlog_guest_lower_thresh, xenlog_guest_upper_thresh,
187                       xenlog_guest_val);
188     custom_runtime_set_var(par, xenlog_guest_val);
189 }
190 #else
191 #define xenlog_val       NULL
192 #define xenlog_guest_val NULL
193 
xenlog_update_val(int lower,int upper,char * val)194 static void xenlog_update_val(int lower, int upper, char *val)
195 {
196 }
197 #endif
198 
199 /*
200  * <lvl> := none|error|warning|info|debug|all
201  * loglvl=<lvl_print_always>[/<lvl_print_ratelimit>]
202  *  <lvl_print_always>: log level which is always printed
203  *  <lvl_print_rlimit>: log level which is rate-limit printed
204  * Similar definitions for guest_loglvl, but applies to guest tracing.
205  * Defaults: loglvl=warning ; guest_loglvl=none/warning
206  */
207 custom_runtime_param("loglvl", parse_loglvl, xenlog_init);
208 custom_runtime_param("guest_loglvl", parse_guest_loglvl, xenlog_guest_init);
209 
210 static atomic_t print_everything = ATOMIC_INIT(0);
211 
212 #define ___parse_loglvl(s, ps, lvlstr, lvlnum)          \
213     if ( !strncmp((s), (lvlstr), strlen(lvlstr)) ) {    \
214         *(ps) = (s) + strlen(lvlstr);                   \
215         return (lvlnum);                                \
216     }
217 
__parse_loglvl(const char * s,const char ** ps)218 static int __parse_loglvl(const char *s, const char **ps)
219 {
220     ___parse_loglvl(s, ps, "none",    0);
221     ___parse_loglvl(s, ps, "error",   1);
222     ___parse_loglvl(s, ps, "warning", 2);
223     ___parse_loglvl(s, ps, "info",    3);
224     ___parse_loglvl(s, ps, "debug",   4);
225     ___parse_loglvl(s, ps, "all",     4);
226     return 2; /* sane fallback */
227 }
228 
_parse_loglvl(const char * s,int * lower,int * upper,char * val)229 static int _parse_loglvl(const char *s, int *lower, int *upper, char *val)
230 {
231     *lower = *upper = __parse_loglvl(s, &s);
232     if ( *s == '/' )
233         *upper = __parse_loglvl(s+1, &s);
234     if ( *upper < *lower )
235         *upper = *lower;
236 
237     xenlog_update_val(*lower, *upper, val);
238 
239     return *s ? -EINVAL : 0;
240 }
241 
parse_loglvl(const char * s)242 static int parse_loglvl(const char *s)
243 {
244     int ret;
245 
246     ret = _parse_loglvl(s, &xenlog_lower_thresh, &xenlog_upper_thresh,
247                         xenlog_val);
248     custom_runtime_set_var(param_2_parfs(parse_loglvl), xenlog_val);
249 
250     return ret;
251 }
252 
parse_guest_loglvl(const char * s)253 static int parse_guest_loglvl(const char *s)
254 {
255     int ret;
256 
257     ret = _parse_loglvl(s, &xenlog_guest_lower_thresh,
258                         &xenlog_guest_upper_thresh, xenlog_guest_val);
259     custom_runtime_set_var(param_2_parfs(parse_guest_loglvl),
260                            xenlog_guest_val);
261 
262     return ret;
263 }
264 
loglvl_str(int lvl)265 static char *loglvl_str(int lvl)
266 {
267     switch ( lvl )
268     {
269     case 0: return "Nothing";
270     case 1: return "Errors";
271     case 2: return "Errors and warnings";
272     case 3: return "Errors, warnings and info";
273     case 4: return "All";
274     }
275     return "???";
276 }
277 
278 static int *__read_mostly upper_thresh_adj = &xenlog_upper_thresh;
279 static int *__read_mostly lower_thresh_adj = &xenlog_lower_thresh;
280 static const char *__read_mostly thresh_adj = "standard";
281 
do_toggle_guest(unsigned char key,struct cpu_user_regs * regs)282 static void do_toggle_guest(unsigned char key, struct cpu_user_regs *regs)
283 {
284     if ( upper_thresh_adj == &xenlog_upper_thresh )
285     {
286         upper_thresh_adj = &xenlog_guest_upper_thresh;
287         lower_thresh_adj = &xenlog_guest_lower_thresh;
288         thresh_adj = "guest";
289     }
290     else
291     {
292         upper_thresh_adj = &xenlog_upper_thresh;
293         lower_thresh_adj = &xenlog_lower_thresh;
294         thresh_adj = "standard";
295     }
296     printk("'%c' pressed -> %s log level adjustments enabled\n",
297            key, thresh_adj);
298 }
299 
do_adj_thresh(unsigned char key)300 static void do_adj_thresh(unsigned char key)
301 {
302     if ( *upper_thresh_adj < *lower_thresh_adj )
303         *upper_thresh_adj = *lower_thresh_adj;
304     printk("'%c' pressed -> %s log level: %s (rate limited %s)\n",
305            key, thresh_adj, loglvl_str(*lower_thresh_adj),
306            loglvl_str(*upper_thresh_adj));
307 }
308 
do_inc_thresh(unsigned char key,struct cpu_user_regs * regs)309 static void do_inc_thresh(unsigned char key, struct cpu_user_regs *regs)
310 {
311     ++*lower_thresh_adj;
312     do_adj_thresh(key);
313 }
314 
do_dec_thresh(unsigned char key,struct cpu_user_regs * regs)315 static void do_dec_thresh(unsigned char key, struct cpu_user_regs *regs)
316 {
317     if ( *lower_thresh_adj )
318         --*lower_thresh_adj;
319     do_adj_thresh(key);
320 }
321 
322 /*
323  * ********************************************************
324  * *************** ACCESS TO CONSOLE RING *****************
325  * ********************************************************
326  */
327 
conring_puts(const char * str,size_t len)328 static void conring_puts(const char *str, size_t len)
329 {
330     ASSERT(spin_is_locked(&console_lock));
331 
332     while ( len-- )
333         conring[CONRING_IDX_MASK(conringp++)] = *str++;
334 
335     if ( conringp - conringc > conring_size )
336         conringc = conringp - conring_size;
337 }
338 
read_console_ring(struct xen_sysctl_readconsole * op)339 long read_console_ring(struct xen_sysctl_readconsole *op)
340 {
341     XEN_GUEST_HANDLE_PARAM(char) str;
342     uint32_t idx, len, max, sofar, c, p;
343 
344     str   = guest_handle_cast(op->buffer, char),
345     max   = op->count;
346     sofar = 0;
347 
348     c = read_atomic(&conringc);
349     p = read_atomic(&conringp);
350     if ( op->incremental &&
351          (c <= p ? c < op->index && op->index <= p
352                  : c < op->index || op->index <= p) )
353         c = op->index;
354 
355     while ( (c != p) && (sofar < max) )
356     {
357         idx = CONRING_IDX_MASK(c);
358         len = p - c;
359         if ( (idx + len) > conring_size )
360             len = conring_size - idx;
361         if ( (sofar + len) > max )
362             len = max - sofar;
363         if ( copy_to_guest_offset(str, sofar, &conring[idx], len) )
364             return -EFAULT;
365         sofar += len;
366         c += len;
367     }
368 
369     if ( op->clear )
370     {
371         spin_lock_irq(&console_lock);
372         conringc = p - c > conring_size ? p - conring_size : c;
373         spin_unlock_irq(&console_lock);
374     }
375 
376     op->count = sofar;
377     op->index = c;
378 
379     return 0;
380 }
381 
382 
383 /*
384  * *******************************************************
385  * *************** ACCESS TO SERIAL LINE *****************
386  * *******************************************************
387  */
388 
389 /* Characters received over the serial line are buffered for domain 0. */
390 #define SERIAL_RX_SIZE 128
391 #define SERIAL_RX_MASK(_i) ((_i)&(SERIAL_RX_SIZE-1))
392 static char serial_rx_ring[SERIAL_RX_SIZE];
393 static unsigned int serial_rx_cons, serial_rx_prod;
394 
395 static void (*serial_steal_fn)(const char *, size_t nr) = early_puts;
396 
console_steal(int handle,void (* fn)(const char *,size_t nr))397 int console_steal(int handle, void (*fn)(const char *, size_t nr))
398 {
399     if ( (handle == -1) || (handle != sercon_handle) )
400         return 0;
401 
402     if ( serial_steal_fn != NULL )
403         return -EBUSY;
404 
405     serial_steal_fn = fn;
406     return 1;
407 }
408 
console_giveback(int id)409 void console_giveback(int id)
410 {
411     if ( id == 1 )
412         serial_steal_fn = NULL;
413 }
414 
console_serial_puts(const char * s,size_t nr)415 void console_serial_puts(const char *s, size_t nr)
416 {
417     if ( serial_steal_fn != NULL )
418         serial_steal_fn(s, nr);
419     else
420         serial_puts(sercon_handle, s, nr);
421 
422     /* Copy all serial output into PV console */
423     pv_console_puts(s, nr);
424 }
425 
dump_console_ring_key(unsigned char key)426 static void dump_console_ring_key(unsigned char key)
427 {
428     uint32_t idx, len, sofar, c;
429     unsigned int order;
430     char *buf;
431 
432     printk("'%c' pressed -> dumping console ring buffer (dmesg)\n", key);
433 
434     /* create a buffer in which we'll copy the ring in the correct
435        order and NUL terminate */
436     order = get_order_from_bytes(conring_size + 1);
437     buf = alloc_xenheap_pages(order, 0);
438     if ( buf == NULL )
439     {
440         printk("unable to allocate memory!\n");
441         return;
442     }
443 
444     c = conringc;
445     sofar = 0;
446     while ( (c != conringp) )
447     {
448         idx = CONRING_IDX_MASK(c);
449         len = conringp - c;
450         if ( (idx + len) > conring_size )
451             len = conring_size - idx;
452         memcpy(buf + sofar, &conring[idx], len);
453         sofar += len;
454         c += len;
455     }
456 
457     console_serial_puts(buf, sofar);
458     video_puts(buf, sofar);
459 
460     free_xenheap_pages(buf, order);
461 }
462 
463 /*
464  * CTRL-<switch_char> changes input direction, rotating among Xen, Dom0,
465  * and the DomUs started from Xen at boot.
466  */
467 #define switch_code (opt_conswitch[0]-'a'+1)
468 /*
469  * console_rx=0 => input to xen
470  * console_rx=1 => input to dom0
471  * console_rx=N => input to dom(N-1)
472  */
473 static unsigned int __read_mostly console_rx = 0;
474 
475 /* Make sure to rcu_unlock_domain after use */
console_input_domain(void)476 struct domain *console_input_domain(void)
477 {
478     if ( console_rx == 0 )
479             return NULL;
480     return rcu_lock_domain_by_id(console_rx - 1);
481 }
482 
switch_serial_input(void)483 static void switch_serial_input(void)
484 {
485     if ( console_rx == max_init_domid + 1 )
486     {
487         console_rx = 0;
488         printk("*** Serial input to Xen");
489     }
490     else
491     {
492         console_rx++;
493         printk("*** Serial input to DOM%d", console_rx - 1);
494     }
495 
496     if ( switch_code )
497         printk(" (type 'CTRL-%c' three times to switch input)",
498                opt_conswitch[0]);
499     printk("\n");
500 }
501 
__serial_rx(char c,struct cpu_user_regs * regs)502 static void __serial_rx(char c, struct cpu_user_regs *regs)
503 {
504     switch ( console_rx )
505     {
506     case 0:
507         return handle_keypress(c, regs);
508 
509     case 1:
510         /*
511          * Deliver input to the hardware domain buffer, unless it is
512          * already full.
513          */
514         if ( (serial_rx_prod - serial_rx_cons) != SERIAL_RX_SIZE )
515             serial_rx_ring[SERIAL_RX_MASK(serial_rx_prod++)] = c;
516 
517         /*
518          * Always notify the hardware domain: prevents receive path from
519          * getting stuck.
520          */
521         send_global_virq(VIRQ_CONSOLE);
522         break;
523 
524 #ifdef CONFIG_SBSA_VUART_CONSOLE
525     default:
526     {
527         struct domain *d = rcu_lock_domain_by_any_id(console_rx - 1);
528 
529         /*
530          * If we have a properly initialized vpl011 console for the
531          * domain, without a full PV ring to Dom0 (in that case input
532          * comes from the PV ring), then send the character to it.
533          */
534         if ( d != NULL &&
535              !d->arch.vpl011.backend_in_domain &&
536              d->arch.vpl011.backend.xen != NULL )
537             vpl011_rx_char_xen(d, c);
538         else
539             printk("Cannot send chars to Dom%d: no UART available\n",
540                    console_rx - 1);
541 
542         if ( d != NULL )
543             rcu_unlock_domain(d);
544     }
545 #endif
546     }
547 
548 #ifdef CONFIG_X86
549     if ( pv_shim && pv_console )
550         consoled_guest_tx(c);
551 #endif
552 }
553 
serial_rx(char c,struct cpu_user_regs * regs)554 static void serial_rx(char c, struct cpu_user_regs *regs)
555 {
556     static int switch_code_count = 0;
557 
558     if ( switch_code && (c == switch_code) )
559     {
560         /* We eat CTRL-<switch_char> in groups of 3 to switch console input. */
561         if ( ++switch_code_count == 3 )
562         {
563             switch_serial_input();
564             switch_code_count = 0;
565         }
566         return;
567     }
568 
569     for ( ; switch_code_count != 0; switch_code_count-- )
570         __serial_rx(switch_code, regs);
571 
572     /* Finally process the just-received character. */
573     __serial_rx(c, regs);
574 }
575 
notify_dom0_con_ring(void * unused)576 static void notify_dom0_con_ring(void *unused)
577 {
578     send_global_virq(VIRQ_CON_RING);
579 }
580 static DECLARE_SOFTIRQ_TASKLET(notify_dom0_con_ring_tasklet,
581                                notify_dom0_con_ring, NULL);
582 
583 #ifdef CONFIG_X86
xen_console_write_debug_port(const char * buf,size_t len)584 static inline void xen_console_write_debug_port(const char *buf, size_t len)
585 {
586     unsigned long tmp;
587     asm volatile ( "rep outsb;"
588                    : "=&S" (tmp), "=&c" (tmp)
589                    : "0" (buf), "1" (len), "d" (XEN_HVM_DEBUGCONS_IOPORT) );
590 }
591 #endif
592 
guest_console_write(XEN_GUEST_HANDLE_PARAM (char)buffer,unsigned int count)593 static long guest_console_write(XEN_GUEST_HANDLE_PARAM(char) buffer,
594                                 unsigned int count)
595 {
596     char kbuf[128];
597     unsigned int kcount = 0;
598     struct domain *cd = current->domain;
599 
600     while ( count > 0 )
601     {
602         if ( kcount && hypercall_preempt_check() )
603             return hypercall_create_continuation(
604                 __HYPERVISOR_console_io, "iih",
605                 CONSOLEIO_write, count, buffer);
606 
607         kcount = min((size_t)count, sizeof(kbuf) - 1);
608         if ( copy_from_guest(kbuf, buffer, kcount) )
609             return -EFAULT;
610 
611         if ( is_hardware_domain(cd) )
612         {
613             /* Use direct console output as it could be interactive */
614             spin_lock_irq(&console_lock);
615 
616             console_serial_puts(kbuf, kcount);
617             video_puts(kbuf, kcount);
618 
619 #ifdef CONFIG_X86
620             if ( opt_console_xen )
621             {
622                 if ( xen_guest )
623                     xen_hypercall_console_write(kbuf, kcount);
624                 else
625                     xen_console_write_debug_port(kbuf, kcount);
626             }
627 #endif
628 
629             if ( opt_console_to_ring )
630             {
631                 conring_puts(kbuf, kcount);
632                 tasklet_schedule(&notify_dom0_con_ring_tasklet);
633             }
634 
635             spin_unlock_irq(&console_lock);
636         }
637         else
638         {
639             char *kin = kbuf, *kout = kbuf, c;
640 
641             /* Strip non-printable characters */
642             do
643             {
644                 c = *kin++;
645                 if ( c == '\n' )
646                     break;
647                 if ( isprint(c) || c == '\t' )
648                     *kout++ = c;
649             } while ( --kcount > 0 );
650 
651             *kout = '\0';
652             spin_lock(&cd->pbuf_lock);
653             kcount = kin - kbuf;
654             if ( c != '\n' &&
655                  (cd->pbuf_idx + (kout - kbuf) < (DOMAIN_PBUF_SIZE - 1)) )
656             {
657                 /* buffer the output until a newline */
658                 memcpy(cd->pbuf + cd->pbuf_idx, kbuf, kout - kbuf);
659                 cd->pbuf_idx += (kout - kbuf);
660             }
661             else
662             {
663                 cd->pbuf[cd->pbuf_idx] = '\0';
664                 guest_printk(cd, XENLOG_G_DEBUG "%s%s\n", cd->pbuf, kbuf);
665                 cd->pbuf_idx = 0;
666             }
667             spin_unlock(&cd->pbuf_lock);
668         }
669 
670         guest_handle_add_offset(buffer, kcount);
671         count -= kcount;
672     }
673 
674     return 0;
675 }
676 
do_console_io(unsigned int cmd,unsigned int count,XEN_GUEST_HANDLE_PARAM (char)buffer)677 long do_console_io(unsigned int cmd, unsigned int count,
678                    XEN_GUEST_HANDLE_PARAM(char) buffer)
679 {
680     long rc;
681     unsigned int idx, len;
682 
683     rc = xsm_console_io(XSM_OTHER, current->domain, cmd);
684     if ( rc )
685         return rc;
686 
687     switch ( cmd )
688     {
689     case CONSOLEIO_write:
690         rc = guest_console_write(buffer, count);
691         break;
692     case CONSOLEIO_read:
693         /*
694          * The return value is either the number of characters read or
695          * a negative value in case of error. So we need to prevent
696          * overlap between the two sets.
697          */
698         rc = -E2BIG;
699         if ( count > INT_MAX )
700             break;
701 
702         rc = 0;
703         while ( (serial_rx_cons != serial_rx_prod) && (rc < count) )
704         {
705             idx = SERIAL_RX_MASK(serial_rx_cons);
706             len = serial_rx_prod - serial_rx_cons;
707             if ( (idx + len) > SERIAL_RX_SIZE )
708                 len = SERIAL_RX_SIZE - idx;
709             if ( (rc + len) > count )
710                 len = count - rc;
711             if ( copy_to_guest_offset(buffer, rc, &serial_rx_ring[idx], len) )
712             {
713                 rc = -EFAULT;
714                 break;
715             }
716             rc += len;
717             serial_rx_cons += len;
718         }
719         break;
720     default:
721         rc = -ENOSYS;
722         break;
723     }
724 
725     return rc;
726 }
727 
728 
729 /*
730  * *****************************************************
731  * *************** GENERIC CONSOLE I/O *****************
732  * *****************************************************
733  */
734 
735 static bool_t console_locks_busted;
736 
__putstr(const char * str)737 static void __putstr(const char *str)
738 {
739     size_t len = strlen(str);
740 
741     ASSERT(spin_is_locked(&console_lock));
742 
743     console_serial_puts(str, len);
744     video_puts(str, len);
745 
746 #ifdef CONFIG_X86
747     if ( opt_console_xen )
748     {
749         if ( xen_guest )
750             xen_hypercall_console_write(str, len);
751         else
752             xen_console_write_debug_port(str, len);
753     }
754 #endif
755 
756     conring_puts(str, len);
757 
758     if ( !console_locks_busted )
759         tasklet_schedule(&notify_dom0_con_ring_tasklet);
760 }
761 
printk_prefix_check(char * p,char ** pp)762 static int printk_prefix_check(char *p, char **pp)
763 {
764     int loglvl = -1;
765     int upper_thresh = ACCESS_ONCE(xenlog_upper_thresh);
766     int lower_thresh = ACCESS_ONCE(xenlog_lower_thresh);
767 
768     while ( (p[0] == '<') && (p[1] != '\0') && (p[2] == '>') )
769     {
770         switch ( p[1] )
771         {
772         case 'G':
773             upper_thresh = ACCESS_ONCE(xenlog_guest_upper_thresh);
774             lower_thresh = ACCESS_ONCE(xenlog_guest_lower_thresh);
775             if ( loglvl == -1 )
776                 loglvl = XENLOG_GUEST_DEFAULT;
777             break;
778         case '0' ... '3':
779             loglvl = p[1] - '0';
780             break;
781         }
782         p += 3;
783     }
784 
785     if ( loglvl == -1 )
786         loglvl = XENLOG_DEFAULT;
787 
788     *pp = p;
789 
790     return ((atomic_read(&print_everything) != 0) ||
791             (loglvl < lower_thresh) ||
792             ((loglvl < upper_thresh) && printk_ratelimit()));
793 }
794 
parse_console_timestamps(const char * s)795 static int parse_console_timestamps(const char *s)
796 {
797     switch ( parse_bool(s, NULL) )
798     {
799     case 0:
800         opt_con_timestamp_mode = TSM_NONE;
801         con_timestamp_mode_upd(param_2_parfs(parse_console_timestamps));
802         return 0;
803     case 1:
804         opt_con_timestamp_mode = TSM_DATE;
805         con_timestamp_mode_upd(param_2_parfs(parse_console_timestamps));
806         return 0;
807     }
808     if ( *s == '\0' || /* Compat for old booleanparam() */
809          !strcmp(s, "date") )
810         opt_con_timestamp_mode = TSM_DATE;
811     else if ( !strcmp(s, "datems") )
812         opt_con_timestamp_mode = TSM_DATE_MS;
813     else if ( !strcmp(s, "boot") )
814         opt_con_timestamp_mode = TSM_BOOT;
815     else if ( !strcmp(s, "raw") )
816         opt_con_timestamp_mode = TSM_RAW;
817     else if ( !strcmp(s, "none") )
818         opt_con_timestamp_mode = TSM_NONE;
819     else
820         return -EINVAL;
821 
822     con_timestamp_mode_upd(param_2_parfs(parse_console_timestamps));
823 
824     return 0;
825 }
826 
printk_start_of_line(const char * prefix)827 static void printk_start_of_line(const char *prefix)
828 {
829     enum con_timestamp_mode mode = ACCESS_ONCE(opt_con_timestamp_mode);
830     struct tm tm;
831     char tstr[32];
832     uint64_t sec, nsec;
833 
834     __putstr(prefix);
835 
836     switch ( mode )
837     {
838     case TSM_DATE:
839     case TSM_DATE_MS:
840         tm = wallclock_time(&nsec);
841 
842         if ( tm.tm_mday == 0 )
843             /* nothing */;
844         else if ( mode == TSM_DATE )
845         {
846             snprintf(tstr, sizeof(tstr), "[%04u-%02u-%02u %02u:%02u:%02u] ",
847                      1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
848                      tm.tm_hour, tm.tm_min, tm.tm_sec);
849             break;
850         }
851         else
852         {
853             snprintf(tstr, sizeof(tstr),
854                      "[%04u-%02u-%02u %02u:%02u:%02u.%03"PRIu64"] ",
855                      1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
856                      tm.tm_hour, tm.tm_min, tm.tm_sec, nsec / 1000000);
857             break;
858         }
859         /* fall through */
860     case TSM_BOOT:
861         sec = NOW();
862         nsec = do_div(sec, 1000000000);
863 
864         if ( sec | nsec )
865         {
866             snprintf(tstr, sizeof(tstr), "[%5"PRIu64".%06"PRIu64"] ",
867                      sec, nsec / 1000);
868             break;
869         }
870         /* fall through */
871     case TSM_RAW:
872         snprintf(tstr, sizeof(tstr), "[%016"PRIx64"] ", get_cycles());
873         break;
874 
875     case TSM_NONE:
876     default:
877         return;
878     }
879 
880     __putstr(tstr);
881 }
882 
vprintk_common(const char * prefix,const char * fmt,va_list args)883 static void vprintk_common(const char *prefix, const char *fmt, va_list args)
884 {
885     struct vps {
886         bool_t continued, do_print;
887     }            *state;
888     static DEFINE_PER_CPU(struct vps, state);
889     static char   buf[1024];
890     char         *p, *q;
891     unsigned long flags;
892 
893     /* console_lock can be acquired recursively from __printk_ratelimit(). */
894     local_irq_save(flags);
895     spin_lock_recursive(&console_lock);
896     state = &this_cpu(state);
897 
898     (void)vsnprintf(buf, sizeof(buf), fmt, args);
899 
900     p = buf;
901 
902     while ( (q = strchr(p, '\n')) != NULL )
903     {
904         *q = '\0';
905         if ( !state->continued )
906             state->do_print = printk_prefix_check(p, &p);
907         if ( state->do_print )
908         {
909             if ( !state->continued )
910                 printk_start_of_line(prefix);
911             __putstr(p);
912             __putstr("\n");
913         }
914         state->continued = 0;
915         p = q + 1;
916     }
917 
918     if ( *p != '\0' )
919     {
920         if ( !state->continued )
921             state->do_print = printk_prefix_check(p, &p);
922         if ( state->do_print )
923         {
924             if ( !state->continued )
925                 printk_start_of_line(prefix);
926             __putstr(p);
927         }
928         state->continued = 1;
929     }
930 
931     spin_unlock_recursive(&console_lock);
932     local_irq_restore(flags);
933 }
934 
printk(const char * fmt,...)935 void printk(const char *fmt, ...)
936 {
937     va_list args;
938     va_start(args, fmt);
939     vprintk_common("(XEN) ", fmt, args);
940     va_end(args);
941 }
942 
guest_printk(const struct domain * d,const char * fmt,...)943 void guest_printk(const struct domain *d, const char *fmt, ...)
944 {
945     va_list args;
946     char prefix[16];
947 
948     snprintf(prefix, sizeof(prefix), "(d%d) ", d->domain_id);
949 
950     va_start(args, fmt);
951     vprintk_common(prefix, fmt, args);
952     va_end(args);
953 }
954 
console_init_preirq(void)955 void __init console_init_preirq(void)
956 {
957     char *p;
958     int sh;
959 
960     serial_init_preirq();
961 
962     /* Where should console output go? */
963     for ( p = opt_console; p != NULL; p = strchr(p, ',') )
964     {
965         if ( *p == ',' )
966             p++;
967         if ( !strncmp(p, "vga", 3) )
968             video_init();
969         else if ( !strncmp(p, "pv", 2) )
970             pv_console_init();
971 #ifdef CONFIG_X86
972         else if ( !strncmp(p, "xen", 3) )
973             opt_console_xen = 1;
974 #endif
975         else if ( !strncmp(p, "none", 4) )
976             continue;
977         else if ( (sh = serial_parse_handle(p)) >= 0 )
978         {
979             sercon_handle = sh;
980             serial_steal_fn = NULL;
981         }
982         else
983         {
984             char *q = strchr(p, ',');
985             if ( q != NULL )
986                 *q = '\0';
987             printk("Bad console= option '%s'\n", p);
988             if ( q != NULL )
989                 *q = ',';
990         }
991     }
992 
993 #ifdef CONFIG_X86
994     if ( opt_console_xen == -1 )
995         opt_console_xen = 0;
996 #endif
997 
998     serial_set_rx_handler(sercon_handle, serial_rx);
999     pv_console_set_rx_handler(serial_rx);
1000 
1001     /* HELLO WORLD --- start-of-day banner text. */
1002     spin_lock(&console_lock);
1003     __putstr(xen_banner());
1004     spin_unlock(&console_lock);
1005     printk("Xen version %d.%d%s (%s@%s) (%s) debug=%c " gcov_string " %s\n",
1006            xen_major_version(), xen_minor_version(), xen_extra_version(),
1007            xen_compile_by(), xen_compile_domain(),
1008            xen_compiler(), debug_build() ? 'y' : 'n', xen_compile_date());
1009     printk("Latest ChangeSet: %s\n", xen_changeset());
1010 
1011     /* Locate and print the buildid, if applicable. */
1012     xen_build_init();
1013 
1014     if ( opt_sync_console )
1015     {
1016         serial_start_sync(sercon_handle);
1017         add_taint(TAINT_SYNC_CONSOLE);
1018         printk("Console output is synchronous.\n");
1019         warning_add(warning_sync_console);
1020     }
1021 }
1022 
console_init_ring(void)1023 void __init console_init_ring(void)
1024 {
1025     char *ring;
1026     unsigned int i, order, memflags;
1027     unsigned long flags;
1028 
1029     if ( !opt_conring_size )
1030         return;
1031 
1032     order = get_order_from_bytes(max(opt_conring_size, conring_size));
1033     memflags = MEMF_bits(crashinfo_maxaddr_bits);
1034     while ( (ring = alloc_xenheap_pages(order, memflags)) == NULL )
1035     {
1036         BUG_ON(order == 0);
1037         order--;
1038     }
1039     opt_conring_size = PAGE_SIZE << order;
1040 
1041     spin_lock_irqsave(&console_lock, flags);
1042     for ( i = conringc ; i != conringp; i++ )
1043         ring[i & (opt_conring_size - 1)] = conring[i & (conring_size - 1)];
1044     conring = ring;
1045     smp_wmb(); /* Allow users of console_force_unlock() to see larger buffer. */
1046     conring_size = opt_conring_size;
1047     spin_unlock_irqrestore(&console_lock, flags);
1048 
1049     printk("Allocated console ring of %u KiB.\n", opt_conring_size >> 10);
1050 }
1051 
console_init_irq(void)1052 void __init console_init_irq(void)
1053 {
1054     serial_init_irq();
1055 }
1056 
console_init_postirq(void)1057 void __init console_init_postirq(void)
1058 {
1059     serial_init_postirq();
1060     pv_console_init_postirq();
1061 
1062     if ( conring != _conring )
1063         return;
1064 
1065     if ( !opt_conring_size )
1066         opt_conring_size = num_present_cpus() << (9 + xenlog_lower_thresh);
1067 
1068     console_init_ring();
1069 }
1070 
console_endboot(void)1071 void __init console_endboot(void)
1072 {
1073     printk("Std. Loglevel: %s", loglvl_str(xenlog_lower_thresh));
1074     if ( xenlog_upper_thresh != xenlog_lower_thresh )
1075         printk(" (Rate-limited: %s)", loglvl_str(xenlog_upper_thresh));
1076     printk("\nGuest Loglevel: %s", loglvl_str(xenlog_guest_lower_thresh));
1077     if ( xenlog_guest_upper_thresh != xenlog_guest_lower_thresh )
1078         printk(" (Rate-limited: %s)", loglvl_str(xenlog_guest_upper_thresh));
1079     printk("\n");
1080 
1081     warning_print();
1082 
1083     video_endboot();
1084 
1085     /*
1086      * If user specifies so, we fool the switch routine to redirect input
1087      * straight back to Xen. I use this convoluted method so we still print
1088      * a useful 'how to switch' message.
1089      */
1090     if ( opt_conswitch[1] == 'x' )
1091         console_rx = max_init_domid + 1;
1092 
1093     register_keyhandler('w', dump_console_ring_key,
1094                         "synchronously dump console ring buffer (dmesg)", 0);
1095     register_irq_keyhandler('+', &do_inc_thresh,
1096                             "increase log level threshold", 0);
1097     register_irq_keyhandler('-', &do_dec_thresh,
1098                             "decrease log level threshold", 0);
1099     register_irq_keyhandler('G', &do_toggle_guest,
1100                             "toggle host/guest log level adjustment", 0);
1101 
1102     /* Serial input is directed to DOM0 by default. */
1103     switch_serial_input();
1104 }
1105 
console_has(const char * device)1106 int __init console_has(const char *device)
1107 {
1108     char *p;
1109 
1110     for ( p = opt_console; p != NULL; p = strchr(p, ',') )
1111     {
1112         if ( *p == ',' )
1113             p++;
1114         if ( strncmp(p, device, strlen(device)) == 0 )
1115             return 1;
1116     }
1117 
1118     return 0;
1119 }
1120 
console_start_log_everything(void)1121 void console_start_log_everything(void)
1122 {
1123     serial_start_log_everything(sercon_handle);
1124     atomic_inc(&print_everything);
1125 }
1126 
console_end_log_everything(void)1127 void console_end_log_everything(void)
1128 {
1129     serial_end_log_everything(sercon_handle);
1130     atomic_dec(&print_everything);
1131 }
1132 
console_lock_recursive_irqsave(void)1133 unsigned long console_lock_recursive_irqsave(void)
1134 {
1135     unsigned long flags;
1136 
1137     local_irq_save(flags);
1138     spin_lock_recursive(&console_lock);
1139 
1140     return flags;
1141 }
1142 
console_unlock_recursive_irqrestore(unsigned long flags)1143 void console_unlock_recursive_irqrestore(unsigned long flags)
1144 {
1145     spin_unlock_recursive(&console_lock);
1146     local_irq_restore(flags);
1147 }
1148 
console_force_unlock(void)1149 void console_force_unlock(void)
1150 {
1151     watchdog_disable();
1152     spin_debug_disable();
1153     spin_lock_init(&console_lock);
1154     serial_force_unlock(sercon_handle);
1155     console_locks_busted = 1;
1156     console_start_sync();
1157 }
1158 
console_start_sync(void)1159 void console_start_sync(void)
1160 {
1161     atomic_inc(&print_everything);
1162     serial_start_sync(sercon_handle);
1163 }
1164 
console_end_sync(void)1165 void console_end_sync(void)
1166 {
1167     serial_end_sync(sercon_handle);
1168     atomic_dec(&print_everything);
1169 }
1170 
1171 /*
1172  * printk rate limiting, lifted from Linux.
1173  *
1174  * This enforces a rate limit: not more than one kernel message
1175  * every printk_ratelimit_ms (millisecs).
1176  */
__printk_ratelimit(int ratelimit_ms,int ratelimit_burst)1177 int __printk_ratelimit(int ratelimit_ms, int ratelimit_burst)
1178 {
1179     static DEFINE_SPINLOCK(ratelimit_lock);
1180     static unsigned long toks = 10 * 5 * 1000;
1181     static unsigned long last_msg;
1182     static int missed;
1183     unsigned long flags;
1184     unsigned long long now = NOW(); /* ns */
1185     unsigned long ms;
1186 
1187     do_div(now, 1000000);
1188     ms = (unsigned long)now;
1189 
1190     spin_lock_irqsave(&ratelimit_lock, flags);
1191     toks += ms - last_msg;
1192     last_msg = ms;
1193     if ( toks > (ratelimit_burst * ratelimit_ms))
1194         toks = ratelimit_burst * ratelimit_ms;
1195     if ( toks >= ratelimit_ms )
1196     {
1197         int lost = missed;
1198         missed = 0;
1199         toks -= ratelimit_ms;
1200         spin_unlock(&ratelimit_lock);
1201         if ( lost )
1202         {
1203             char lost_str[8];
1204             snprintf(lost_str, sizeof(lost_str), "%d", lost);
1205             /* console_lock may already be acquired by printk(). */
1206             spin_lock_recursive(&console_lock);
1207             printk_start_of_line("(XEN) ");
1208             __putstr("printk: ");
1209             __putstr(lost_str);
1210             __putstr(" messages suppressed.\n");
1211             spin_unlock_recursive(&console_lock);
1212         }
1213         local_irq_restore(flags);
1214         return 1;
1215     }
1216     missed++;
1217     spin_unlock_irqrestore(&ratelimit_lock, flags);
1218     return 0;
1219 }
1220 
1221 /* minimum time in ms between messages */
1222 static int __read_mostly printk_ratelimit_ms = 5 * 1000;
1223 
1224 /* number of messages we send before ratelimiting */
1225 static int __read_mostly printk_ratelimit_burst = 10;
1226 
printk_ratelimit(void)1227 int printk_ratelimit(void)
1228 {
1229     return __printk_ratelimit(printk_ratelimit_ms, printk_ratelimit_burst);
1230 }
1231 
1232 /*
1233  * **************************************************************
1234  * ********************** Error-report **************************
1235  * **************************************************************
1236  */
1237 
panic(const char * fmt,...)1238 void panic(const char *fmt, ...)
1239 {
1240     va_list args;
1241     unsigned long flags;
1242     static DEFINE_SPINLOCK(lock);
1243     static char buf[128];
1244 
1245     spin_debug_disable();
1246     spinlock_profile_printall('\0');
1247     debugtrace_dump();
1248 
1249     /* Protects buf[] and ensure multi-line message prints atomically. */
1250     spin_lock_irqsave(&lock, flags);
1251 
1252     va_start(args, fmt);
1253     (void)vsnprintf(buf, sizeof(buf), fmt, args);
1254     va_end(args);
1255 
1256     console_start_sync();
1257     printk("\n****************************************\n");
1258     printk("Panic on CPU %d:\n", smp_processor_id());
1259     printk("%s", buf);
1260     printk("****************************************\n\n");
1261     if ( opt_noreboot )
1262         printk("Manual reset required ('noreboot' specified)\n");
1263     else
1264 #ifdef CONFIG_X86
1265         printk("%s in five seconds...\n", pv_shim ? "Crash" : "Reboot");
1266 #else
1267         printk("Reboot in five seconds...\n");
1268 #endif
1269 
1270     spin_unlock_irqrestore(&lock, flags);
1271 
1272     debugger_trap_immediate();
1273 
1274     kexec_crash();
1275 
1276     if ( opt_noreboot )
1277         machine_halt();
1278     else
1279         machine_restart(5000);
1280 }
1281 
1282 /*
1283  * **************************************************************
1284  * ****************** Console suspend/resume ********************
1285  * **************************************************************
1286  */
1287 
suspend_steal_fn(const char * str,size_t nr)1288 static void suspend_steal_fn(const char *str, size_t nr) { }
1289 static int suspend_steal_id;
1290 
console_suspend(void)1291 int console_suspend(void)
1292 {
1293     suspend_steal_id = console_steal(sercon_handle, suspend_steal_fn);
1294     serial_suspend();
1295     return 0;
1296 }
1297 
console_resume(void)1298 int console_resume(void)
1299 {
1300     serial_resume();
1301     console_giveback(suspend_steal_id);
1302     return 0;
1303 }
1304 
1305 /*
1306  * Local variables:
1307  * mode: C
1308  * c-file-style: "BSD"
1309  * c-basic-offset: 4
1310  * tab-width: 4
1311  * indent-tabs-mode: nil
1312  * End:
1313  */
1314 
1315