xref: /xv6-public/console.c (revision 55e95b16)
1 #include <types.h>
2 #include <x86.h>
3 #include "defs.h"
4 
5 void
6 cons_putc(int c)
7 {
8   int crtport = 0x3d4; // io port of CGA
9   unsigned short *crt = (unsigned short *) 0xB8000; // base of CGA memory
10   int ind;
11 
12   // cursor position, 16 bits, col + 80*row
13   outb(crtport, 14);
14   ind = inb(crtport + 1) << 8;
15   outb(crtport, 15);
16   ind |= inb(crtport + 1);
17 
18   c &= 0xff;
19 
20   if(c == '\n'){
21     ind -= (ind % 80);
22     ind += 80;
23   } else {
24     c |= 0x0700; // black on white
25     crt[ind] = c;
26     ind += 1;
27   }
28 
29   if((ind / 80) >= 24){
30     // scroll up
31     memcpy(crt, crt + 80, sizeof(crt[0]) * (23 * 80));
32     ind -= 80;
33     memset(crt + ind, 0, sizeof(crt[0]) * ((24 * 80) - ind));
34   }
35 
36   outb(crtport, 14);
37   outb(crtport + 1, ind >> 8);
38   outb(crtport, 15);
39   outb(crtport + 1, ind);
40 }
41 
42 void
43 printint(int xx, int base, int sgn)
44 {
45   char buf[16];
46   char digits[] = "0123456789ABCDEF";
47   int i = 0, neg = 0;
48   unsigned int x;
49 
50   if(sgn && xx < 0){
51     neg = 1;
52     x = 0 - xx;
53   } else {
54     x = xx;
55   }
56 
57   do {
58     buf[i++] = digits[x % base];
59   } while((x /= base) != 0);
60   if(neg)
61     buf[i++] = '-';
62 
63   while(i > 0){
64     i -= 1;
65     cons_putc(buf[i]);
66   }
67 }
68 
69 /*
70  * print to the console. only understands %d and %x.
71  */
72 void
73 cprintf(char *fmt, ...)
74 {
75   int i, state = 0, c;
76   unsigned int *ap = (unsigned int *) &fmt + 1;
77 
78   for(i = 0; fmt[i]; i++){
79     c = fmt[i] & 0xff;
80     if(state == 0){
81       if(c == '%'){
82         state = '%';
83       } else {
84         cons_putc(c);
85       }
86     } else if(state == '%'){
87       if(c == 'd'){
88         printint(*ap, 10, 1);
89         ap++;
90       } else if(c == 'x'){
91         printint(*ap, 16, 0);
92         ap++;
93       } else if(c == '%'){
94         cons_putc(c);
95       }
96       state = 0;
97     }
98   }
99 }
100 
101 void
102 panic(char *s)
103 {
104   cprintf(s, 0);
105   cprintf("\n", 0);
106   while(1)
107     ;
108 }
109