6.7 Exercise: The Console Device
The console device is simpler than many of the others. Instead of using the generic ring mechanism, where a single ring contains requests and responses, it provides two rings containing input and output characters, respectively. This is because console interaction on the dumb terminal model is intrinsically composed of two unidirectional systems. The keyboard writes data into the system in response to the user, whereas the screen displays text without providing any information.
The console interface itself is very simple. Listing 6.2 describes the structure found on the shared memory page used by the console. The machine address of this page is passed to the guest in the start info structure.
Listing 6.2. Xen Console interface structure
[from: xen/include/public/io/console.h]
34 struct xencons_interface { 35 char in[1024]; 36 char out[2048]; 37 XENCONS_RING_IDX in_cons, in_prod; 38 XENCONS_RING_IDX out_cons, out_prod; 39 };
Before the console can be used, the guest needs to map it into its address space. This is done as per the example in Chapter 5. After this has been accomplished, the event channel for console events must be bound. This will be covered in more detail in the next chapter; for now, we will treat the console as a write-only device, and try to display a boot message.
Listing 6.3 shows how to map the console. We will leave some space here for setting up the event handler, and come back to that in the next chapter, after detailed discussion of the events system. We will keep a record of the event channel that is being used for the console in the console_evtchn variable.
Listing 6.3. Mapping the console
[from: examples/chapter6/console.c]
10 /* Initialise the console */ 11 int console_init(start_info_t * start) 12 { 13 console = (struct xencons_interface*) 14 ((machine_to_phys_mapping[start->console.domU.mfn] << 12) 15 + 16 ((unsigned long)&_text)); 17 console_evt = start->console.domU.evtchn; 18 /* TODO: Set up the event channel */ 19 return 0; 20 }
When we want to write something to the screen, we have to copy it into the buffer, assuming that there is space. If there is insufficient space, we have to wait until there is. Typically, copying a load of data would be done using memcpy. Because we are not linking against the C standard library, however, this is not an option for us. Instead, we have to implement the copy operation ourselves. The version shown here is not at all optimized; it is possible to make it significantly faster. This is not particularly important for a console driver, because the console is typically a fairly low data rate device; however, for other drivers, it is probably worth copying a well-optimized memcpy implementation, assuming you don't already have one in your kernel.
Listing 6.4 contains a simple function for writing a string to the console. The function loops for each character on an input string until it encounters a NULL, copying the character from the input string to the buffer.
Listing 6.4. Writing data to the console
[from: examples/chapter6/console.c]
22 /* Write a NULL–terminated string */ 23 int console_write(char * message) 24 { 25 struct evtchn_send event; 26 event.port = console_evt; 27 int length = 0; 28 while(*message !='\0') 29 { 30 /* Wait for the back–end to clear enough space in the buffer */ 31 XENCONS_RING_IDX data; 32 do 33 { 34 data = console->out_prod – console->out_cons; 35 HYPERVISOR_event_channel_op(EVTCHNOP_send, &event); 36 mb(); 37 } while(data >= sizeof(console->out)); 38 /* Copy the byte */ 39 int ring_index = MASK_XENCONS_IDX(console->out_prod, console->out); 40 console->out[ring_index]= *message; 41 /* Ensure that the data really is in the ring before continuing */ 42 wmb(); 43 /* Increment input and output pointers */ 44 console->out_prod++; 45 length++; 46 message++; 47 } 48 HYPERVISOR_event_channel_op(EVTCHNOP_send, &event); 49 return 0; 50 }
Note the use of the MASK_XENCNOS_IDX macro. This is used because the console rings, like other I/O rings in Xen, use free-running counters. The least-significant n bits of these are used to indicate the position within the ring. The advantage of this approach is that there is no need to test whether the counters have overflowed the buffer. In addition, comparisons of the form producer –consumer will always give the correct result, as long as the size of the maximum value of the index variable is greater than twice the size of the buffer, and the producer counter doesn't overflow twice before the consumer counter overflows once.
This means that we only need to test for one condition before adding something to a ring—that producer – consumer < ring size. Because producer – consumer always gives you the amount of data in the ring, this does not allow you to proceed if the ring is full. In a full implementation of the console, we would wait until an event is received before proceeding here.
After putting data in the buffer, we need to signal the back end to remove it and display it. This is done via the event channel mechanism. Events will be discussed in detail in the next chapter, including how to handle incoming ones. For now, we will just signal the event channel, and look at what is actually happening in the next chapter.
Signaling the event channel is fairly simple, and can be thought of in the same way as sending a UNIX signal. The console_evtchn variable holds the number of the event channel being used for the console. This is similar to the signal number in UNIX, but is decided at runtime, rather than compile time. Note that sending an event after each character has been placed into the ring is highly inefficient. It is more efficient to only send an event at the end of sending, or when the buffer is full. This is left as an exercise for the reader.
To issue the signal, we use the HYPERVISOR_event_channel_op hypercall. The command we give to this tells it to send the event, and the control structure takes a single argument, indicating the event channel to be signaled.
We will add one more function for our simple half-console driver. This flushs the output buffer by blocking until the buffer is empty (that is, the consumer counter has caught up with the producer in the output ring). Because the function is just spinning while waiting for the back end to catch up, we issue a hypercall to notify the hypervisor that it should schedule other virtual machines while we are waiting. The memory barrier here is almost certainly not needed, because a hypercall (and the resulting ring transition) is a memory barrier, but is left in for clarity. Listing 6.5 shows the flush function.
Now that we have something that is hopefully a working implementation of a write-only console driver (we are not reading text input by the user yet), we should try using it. Let's create a console.h file that contains prototypes to our two functions, and then try calling them. Listing 6.6 gives the body of a kernel that writes "Hello world" to the console. "Hello world" is the obligatory first output message from any system, but it's a bit boring. Let's print the Xen magic string, containing the running Xen version, as well.
Listing 6.5. Flushing the console output buffer
[from: examples/chapter6/console.c]
52 /* Block while data is in the out buffer */ 53 void console_flush(void) 54 { 55 /* While there is data in the out channel */ 56 while(console->out_cons < console->out_prod) 57 { 58 /* Let other processes run */ 59 HYPERVISOR_sched_op(SCHEDOP_yield, 0); 60 mb(); 61 } 62 }
Note that we call the console_flush () function before exiting. This is because the console ring buffer ceases to exist when the domain is destroyed, and if we are not very lucky, this will happen before the back end has read the contents of the buffer.
All that remains now is to add console.o to the Makefile, build, and test our kernel. When we launched our last simple kernel, we used xm create. This creates the new domain in the background. When we start this one, we want to see the output from the console. We do this by adding the -c flag, which tells xm to automatically attach to the console:
# xm create -c domain_config Using config file "./domain_config". Started domain Simplest_Kernel Hello world! Xen magic string: xen-3.0-x86_32p #
The new domain is then destroyed, because we told the kernel to exit after writing the message. If this happens, everything is working as expected. We can now use the console for output during the rest of our boot procedure. When we have mapped the event channel, we can use it for input as well.
Currently, the console output is a little bit raw. It would be nice to add something like the C standard printf () function. This is left as an exercise to the reader. A good approach is to take a look at the vfprintf () function in an existing C library (the OpenBSD implementation is a good bet here) and replace the function or macro used for actually outputting characters with a call to our console_write () function.
Listing 6.6. The body of the "hello world" kernel.
[from: examples/chapter6/kernel.c]
12 /* Main kernel entry point, called by trampoline */ 13 void start_kernel (start_info_t * start_info) 14 { 15 /* Map the shared info page */ 16 HYPERVISOR_update_va_mapping((unsigned long) &shared_info, 17 _ _pte( startinfo->shared_info | 7 ), 18 UVMF_INVLPG); 19 /* Set the pointer used in the bootstrap for reenabling 20 * event delivery after an upcall */ 21 HYPERVISOR_shared_info = & shared_info; 22 /* Set up and unmask events */ 23 init_events(); 24 /* Initialise the console */ 25 console_init(start_info); 26 /* Write a message to check that it worked */ 27 console_write("Hello␣world!\r\n"); 28 /* Loop, handling events */ 29 while(1) 30 { 31 HYPERVISOR_sched_op(SCHEDOP_block,0); 32 } 33 }