xref: /openbmc/qemu/hw/display/xenfb.c (revision 7d87775f)
1 /*
2  *  xen paravirt framebuffer backend
3  *
4  *  Copyright IBM, Corp. 2005-2006
5  *  Copyright Red Hat, Inc. 2006-2008
6  *
7  *  Authors:
8  *       Anthony Liguori <aliguori@us.ibm.com>,
9  *       Markus Armbruster <armbru@redhat.com>,
10  *       Daniel P. Berrange <berrange@redhat.com>,
11  *       Pat Campbell <plc@novell.com>,
12  *       Gerd Hoffmann <kraxel@redhat.com>
13  *
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; under version 2 of the License.
17  *
18  *  This program is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *  GNU General Public License for more details.
22  *
23  *  You should have received a copy of the GNU General Public License along
24  *  with this program; if not, see <http://www.gnu.org/licenses/>.
25  */
26 
27 #include "qemu/osdep.h"
28 #include "qemu/units.h"
29 
30 #include "ui/input.h"
31 #include "ui/console.h"
32 #include "sysemu/sysemu.h"
33 #include "hw/xen/xen-legacy-backend.h"
34 
35 #include "hw/xen/interface/io/fbif.h"
36 #include "hw/xen/interface/io/kbdif.h"
37 #include "hw/xen/interface/io/protocols.h"
38 
39 #include "trace.h"
40 
41 #ifndef BTN_LEFT
42 #define BTN_LEFT 0x110 /* from <linux/input.h> */
43 #endif
44 
45 /* -------------------------------------------------------------------- */
46 
47 struct common {
48     struct XenLegacyDevice  xendev;  /* must be first */
49     void              *page;
50 };
51 
52 struct XenInput {
53     struct common c;
54     int abs_pointer_wanted; /* Whether guest supports absolute pointer */
55     int raw_pointer_wanted; /* Whether guest supports raw (unscaled) pointer */
56     QemuInputHandlerState *qkbd;
57     QemuInputHandlerState *qmou;
58     int axis[INPUT_AXIS__MAX];
59     int wheel;
60 };
61 
62 #define UP_QUEUE 8
63 
64 struct XenFB {
65     struct common     c;
66     QemuConsole       *con;
67     size_t            fb_len;
68     int               row_stride;
69     int               depth;
70     int               width;
71     int               height;
72     int               offset;
73     void              *pixels;
74     int               fbpages;
75     int               feature_update;
76     int               bug_trigger;
77     int               do_resize;
78 
79     struct {
80         int x,y,w,h;
81     } up_rects[UP_QUEUE];
82     int               up_count;
83     int               up_fullscreen;
84 };
85 static const GraphicHwOps xenfb_ops;
86 
87 /* -------------------------------------------------------------------- */
88 
89 static int common_bind(struct common *c)
90 {
91     uint64_t val;
92     xen_pfn_t mfn;
93 
94     if (xenstore_read_fe_uint64(&c->xendev, "page-ref", &val) == -1)
95         return -1;
96     mfn = (xen_pfn_t)val;
97     assert(val == mfn);
98 
99     if (xenstore_read_fe_int(&c->xendev, "event-channel", &c->xendev.remote_port) == -1)
100         return -1;
101 
102     c->page = qemu_xen_foreignmem_map(c->xendev.dom, NULL,
103                                       PROT_READ | PROT_WRITE, 1, &mfn,
104                                       NULL);
105     if (c->page == NULL)
106         return -1;
107 
108     xen_be_bind_evtchn(&c->xendev);
109     xen_pv_printf(&c->xendev, 1,
110                   "ring mfn %"PRI_xen_pfn", remote-port %d, local-port %d\n",
111                   mfn, c->xendev.remote_port, c->xendev.local_port);
112 
113     return 0;
114 }
115 
116 static void common_unbind(struct common *c)
117 {
118     xen_pv_unbind_evtchn(&c->xendev);
119     if (c->page) {
120         qemu_xen_foreignmem_unmap(c->page, 1);
121         c->page = NULL;
122     }
123 }
124 
125 /* -------------------------------------------------------------------- */
126 /* Send an event to the keyboard frontend driver */
127 static int xenfb_kbd_event(struct XenInput *xenfb,
128                            union xenkbd_in_event *event)
129 {
130     struct xenkbd_page *page = xenfb->c.page;
131     uint32_t prod;
132 
133     if (xenfb->c.xendev.be_state != XenbusStateConnected)
134         return 0;
135     if (!page)
136         return 0;
137 
138     prod = page->in_prod;
139     if (prod - page->in_cons == XENKBD_IN_RING_LEN) {
140         errno = EAGAIN;
141         return -1;
142     }
143 
144     xen_mb();           /* ensure ring space available */
145     XENKBD_IN_RING_REF(page, prod) = *event;
146     xen_wmb();          /* ensure ring contents visible */
147     page->in_prod = prod + 1;
148     return xen_pv_send_notify(&xenfb->c.xendev);
149 }
150 
151 /* Send a keyboard (or mouse button) event */
152 static int xenfb_send_key(struct XenInput *xenfb, bool down, int keycode)
153 {
154     union xenkbd_in_event event;
155 
156     memset(&event, 0, XENKBD_IN_EVENT_SIZE);
157     event.type = XENKBD_TYPE_KEY;
158     event.key.pressed = down ? 1 : 0;
159     event.key.keycode = keycode;
160 
161     return xenfb_kbd_event(xenfb, &event);
162 }
163 
164 /* Send a relative mouse movement event */
165 static int xenfb_send_motion(struct XenInput *xenfb,
166                              int rel_x, int rel_y, int rel_z)
167 {
168     union xenkbd_in_event event;
169 
170     memset(&event, 0, XENKBD_IN_EVENT_SIZE);
171     event.type = XENKBD_TYPE_MOTION;
172     event.motion.rel_x = rel_x;
173     event.motion.rel_y = rel_y;
174     event.motion.rel_z = rel_z;
175 
176     return xenfb_kbd_event(xenfb, &event);
177 }
178 
179 /* Send an absolute mouse movement event */
180 static int xenfb_send_position(struct XenInput *xenfb,
181                                int abs_x, int abs_y, int z)
182 {
183     union xenkbd_in_event event;
184 
185     memset(&event, 0, XENKBD_IN_EVENT_SIZE);
186     event.type = XENKBD_TYPE_POS;
187     event.pos.abs_x = abs_x;
188     event.pos.abs_y = abs_y;
189     event.pos.rel_z = z;
190 
191     return xenfb_kbd_event(xenfb, &event);
192 }
193 
194 /*
195  * Send a key event from the client to the guest OS
196  * QEMU gives us a QCode.
197  * We have to turn this into a Linux Input layer keycode.
198  *
199  * Wish we could just send scancodes straight to the guest which
200  * already has code for dealing with this...
201  */
202 static void xenfb_key_event(DeviceState *dev, QemuConsole *src,
203                             InputEvent *evt)
204 {
205     struct XenInput *xenfb = (struct XenInput *)dev;
206     InputKeyEvent *key = evt->u.key.data;
207     int qcode = qemu_input_key_value_to_qcode(key->key);
208     int lnx;
209 
210     if (qcode < qemu_input_map_qcode_to_linux_len) {
211         lnx = qemu_input_map_qcode_to_linux[qcode];
212 
213         if (lnx) {
214             trace_xenfb_key_event(xenfb, lnx, key->down);
215             xenfb_send_key(xenfb, key->down, lnx);
216         }
217     }
218 }
219 
220 /*
221  * Send a mouse event from the client to the guest OS
222  *
223  * The QEMU mouse can be in either relative, or absolute mode.
224  * Movement is sent separately from button state, which has to
225  * be encoded as virtual key events. We also don't actually get
226  * given any button up/down events, so have to track changes in
227  * the button state.
228  */
229 static void xenfb_mouse_event(DeviceState *dev, QemuConsole *src,
230                               InputEvent *evt)
231 {
232     struct XenInput *xenfb = (struct XenInput *)dev;
233     InputBtnEvent *btn;
234     InputMoveEvent *move;
235     QemuConsole *con;
236     DisplaySurface *surface;
237     int scale;
238 
239     switch (evt->type) {
240     case INPUT_EVENT_KIND_BTN:
241         btn = evt->u.btn.data;
242         switch (btn->button) {
243         case INPUT_BUTTON_LEFT:
244             xenfb_send_key(xenfb, btn->down, BTN_LEFT);
245             break;
246         case INPUT_BUTTON_RIGHT:
247             xenfb_send_key(xenfb, btn->down, BTN_LEFT + 1);
248             break;
249         case INPUT_BUTTON_MIDDLE:
250             xenfb_send_key(xenfb, btn->down, BTN_LEFT + 2);
251             break;
252         case INPUT_BUTTON_WHEEL_UP:
253             if (btn->down) {
254                 xenfb->wheel--;
255             }
256             break;
257         case INPUT_BUTTON_WHEEL_DOWN:
258             if (btn->down) {
259                 xenfb->wheel++;
260             }
261             break;
262         default:
263             break;
264         }
265         break;
266 
267     case INPUT_EVENT_KIND_ABS:
268         move = evt->u.abs.data;
269         if (xenfb->raw_pointer_wanted) {
270             xenfb->axis[move->axis] = move->value;
271         } else {
272             con = qemu_console_lookup_by_index(0);
273             if (!con) {
274                 xen_pv_printf(&xenfb->c.xendev, 0, "No QEMU console available");
275                 return;
276             }
277             surface = qemu_console_surface(con);
278             switch (move->axis) {
279             case INPUT_AXIS_X:
280                 scale = surface_width(surface) - 1;
281                 break;
282             case INPUT_AXIS_Y:
283                 scale = surface_height(surface) - 1;
284                 break;
285             default:
286                 scale = 0x8000;
287                 break;
288             }
289             xenfb->axis[move->axis] = move->value * scale / 0x7fff;
290         }
291         break;
292 
293     case INPUT_EVENT_KIND_REL:
294         move = evt->u.rel.data;
295         xenfb->axis[move->axis] += move->value;
296         break;
297 
298     default:
299         break;
300     }
301 }
302 
303 static void xenfb_mouse_sync(DeviceState *dev)
304 {
305     struct XenInput *xenfb = (struct XenInput *)dev;
306 
307     trace_xenfb_mouse_event(xenfb, xenfb->axis[INPUT_AXIS_X],
308                             xenfb->axis[INPUT_AXIS_Y],
309                             xenfb->wheel, 0,
310                             xenfb->abs_pointer_wanted);
311     if (xenfb->abs_pointer_wanted) {
312         xenfb_send_position(xenfb, xenfb->axis[INPUT_AXIS_X],
313                             xenfb->axis[INPUT_AXIS_Y],
314                             xenfb->wheel);
315     } else {
316         xenfb_send_motion(xenfb, xenfb->axis[INPUT_AXIS_X],
317                           xenfb->axis[INPUT_AXIS_Y],
318                           xenfb->wheel);
319         xenfb->axis[INPUT_AXIS_X] = 0;
320         xenfb->axis[INPUT_AXIS_Y] = 0;
321     }
322     xenfb->wheel = 0;
323 }
324 
325 static const QemuInputHandler xenfb_keyboard = {
326     .name  = "Xen PV Keyboard",
327     .mask  = INPUT_EVENT_MASK_KEY,
328     .event = xenfb_key_event,
329 };
330 
331 static const QemuInputHandler xenfb_abs_mouse = {
332     .name  = "Xen PV Mouse",
333     .mask  = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_ABS,
334     .event = xenfb_mouse_event,
335     .sync  = xenfb_mouse_sync,
336 };
337 
338 static const QemuInputHandler xenfb_rel_mouse = {
339     .name  = "Xen PV Mouse",
340     .mask  = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_REL,
341     .event = xenfb_mouse_event,
342     .sync  = xenfb_mouse_sync,
343 };
344 
345 static int input_init(struct XenLegacyDevice *xendev)
346 {
347     xenstore_write_be_int(xendev, "feature-abs-pointer", 1);
348     xenstore_write_be_int(xendev, "feature-raw-pointer", 1);
349     return 0;
350 }
351 
352 static int input_initialise(struct XenLegacyDevice *xendev)
353 {
354     struct XenInput *in = container_of(xendev, struct XenInput, c.xendev);
355     int rc;
356 
357     rc = common_bind(&in->c);
358     if (rc != 0)
359         return rc;
360 
361     return 0;
362 }
363 
364 static void input_connected(struct XenLegacyDevice *xendev)
365 {
366     struct XenInput *in = container_of(xendev, struct XenInput, c.xendev);
367 
368     if (xenstore_read_fe_int(xendev, "request-abs-pointer",
369                              &in->abs_pointer_wanted) == -1) {
370         in->abs_pointer_wanted = 0;
371     }
372     if (xenstore_read_fe_int(xendev, "request-raw-pointer",
373                              &in->raw_pointer_wanted) == -1) {
374         in->raw_pointer_wanted = 0;
375     }
376     if (in->raw_pointer_wanted && in->abs_pointer_wanted == 0) {
377         xen_pv_printf(xendev, 0, "raw pointer set without abs pointer");
378     }
379 
380     if (in->qkbd) {
381         qemu_input_handler_unregister(in->qkbd);
382     }
383     if (in->qmou) {
384         qemu_input_handler_unregister(in->qmou);
385     }
386     trace_xenfb_input_connected(xendev, in->abs_pointer_wanted);
387 
388     in->qkbd = qemu_input_handler_register((DeviceState *)in, &xenfb_keyboard);
389     in->qmou = qemu_input_handler_register((DeviceState *)in,
390                in->abs_pointer_wanted ? &xenfb_abs_mouse : &xenfb_rel_mouse);
391 
392     if (in->raw_pointer_wanted) {
393         qemu_input_handler_activate(in->qkbd);
394         qemu_input_handler_activate(in->qmou);
395     }
396 }
397 
398 static void input_disconnect(struct XenLegacyDevice *xendev)
399 {
400     struct XenInput *in = container_of(xendev, struct XenInput, c.xendev);
401 
402     if (in->qkbd) {
403         qemu_input_handler_unregister(in->qkbd);
404         in->qkbd = NULL;
405     }
406     if (in->qmou) {
407         qemu_input_handler_unregister(in->qmou);
408         in->qmou = NULL;
409     }
410     common_unbind(&in->c);
411 }
412 
413 static void input_event(struct XenLegacyDevice *xendev)
414 {
415     struct XenInput *xenfb = container_of(xendev, struct XenInput, c.xendev);
416     struct xenkbd_page *page = xenfb->c.page;
417 
418     /* We don't understand any keyboard events, so just ignore them. */
419     if (page->out_prod == page->out_cons)
420         return;
421     page->out_cons = page->out_prod;
422     xen_pv_send_notify(&xenfb->c.xendev);
423 }
424 
425 /* -------------------------------------------------------------------- */
426 
427 static void xenfb_copy_mfns(int mode, int count, xen_pfn_t *dst, void *src)
428 {
429     uint32_t *src32 = src;
430     uint64_t *src64 = src;
431     int i;
432 
433     for (i = 0; i < count; i++)
434         dst[i] = (mode == 32) ? src32[i] : src64[i];
435 }
436 
437 static int xenfb_map_fb(struct XenFB *xenfb)
438 {
439     struct xenfb_page *page = xenfb->c.page;
440     char *protocol = xenfb->c.xendev.protocol;
441     int n_fbdirs;
442     xen_pfn_t *pgmfns = NULL;
443     xen_pfn_t *fbmfns = NULL;
444     void *map, *pd;
445     int mode, ret = -1;
446 
447     /* default to native */
448     pd = page->pd;
449     mode = sizeof(unsigned long) * 8;
450 
451     if (!protocol) {
452         /*
453          * Undefined protocol, some guesswork needed.
454          *
455          * Old frontends which don't set the protocol use
456          * one page directory only, thus pd[1] must be zero.
457          * pd[1] of the 32bit struct layout and the lower
458          * 32 bits of pd[0] of the 64bit struct layout have
459          * the same location, so we can check that ...
460          */
461         uint32_t *ptr32 = NULL;
462         uint32_t *ptr64 = NULL;
463 #if defined(__i386__)
464         ptr32 = (void*)page->pd;
465         ptr64 = ((void*)page->pd) + 4;
466 #elif defined(__x86_64__)
467         ptr32 = ((void*)page->pd) - 4;
468         ptr64 = (void*)page->pd;
469 #endif
470         if (ptr32) {
471             if (ptr32[1] == 0) {
472                 mode = 32;
473                 pd   = ptr32;
474             } else {
475                 mode = 64;
476                 pd   = ptr64;
477             }
478         }
479 #if defined(__x86_64__)
480     } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_32) == 0) {
481         /* 64bit dom0, 32bit domU */
482         mode = 32;
483         pd   = ((void*)page->pd) - 4;
484 #elif defined(__i386__)
485     } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_64) == 0) {
486         /* 32bit dom0, 64bit domU */
487         mode = 64;
488         pd   = ((void*)page->pd) + 4;
489 #endif
490     }
491 
492     if (xenfb->pixels) {
493         munmap(xenfb->pixels, xenfb->fbpages * XEN_PAGE_SIZE);
494         xenfb->pixels = NULL;
495     }
496 
497     xenfb->fbpages = DIV_ROUND_UP(xenfb->fb_len, XEN_PAGE_SIZE);
498     n_fbdirs = xenfb->fbpages * mode / 8;
499     n_fbdirs = DIV_ROUND_UP(n_fbdirs, XEN_PAGE_SIZE);
500 
501     pgmfns = g_new0(xen_pfn_t, n_fbdirs);
502     fbmfns = g_new0(xen_pfn_t, xenfb->fbpages);
503 
504     xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd);
505     map = qemu_xen_foreignmem_map(xenfb->c.xendev.dom, NULL, PROT_READ,
506                                   n_fbdirs, pgmfns, NULL);
507     if (map == NULL)
508         goto out;
509     xenfb_copy_mfns(mode, xenfb->fbpages, fbmfns, map);
510     qemu_xen_foreignmem_unmap(map, n_fbdirs);
511 
512     xenfb->pixels = qemu_xen_foreignmem_map(xenfb->c.xendev.dom, NULL,
513                                             PROT_READ, xenfb->fbpages,
514                                             fbmfns, NULL);
515     if (xenfb->pixels == NULL)
516         goto out;
517 
518     ret = 0; /* all is fine */
519 
520 out:
521     g_free(pgmfns);
522     g_free(fbmfns);
523     return ret;
524 }
525 
526 static int xenfb_configure_fb(struct XenFB *xenfb, size_t fb_len_lim,
527                               int width, int height, int depth,
528                               size_t fb_len, int offset, int row_stride)
529 {
530     size_t mfn_sz = sizeof_field(struct xenfb_page, pd[0]);
531     size_t pd_len = sizeof_field(struct xenfb_page, pd) / mfn_sz;
532     size_t fb_pages = pd_len * XEN_PAGE_SIZE / mfn_sz;
533     size_t fb_len_max = fb_pages * XEN_PAGE_SIZE;
534     int max_width, max_height;
535 
536     if (fb_len_lim > fb_len_max) {
537         xen_pv_printf(&xenfb->c.xendev, 0,
538                       "fb size limit %zu exceeds %zu, corrected\n",
539                       fb_len_lim, fb_len_max);
540         fb_len_lim = fb_len_max;
541     }
542     if (fb_len_lim && fb_len > fb_len_lim) {
543         xen_pv_printf(&xenfb->c.xendev, 0,
544                       "frontend fb size %zu limited to %zu\n",
545                       fb_len, fb_len_lim);
546         fb_len = fb_len_lim;
547     }
548     if (depth != 8 && depth != 16 && depth != 24 && depth != 32) {
549         xen_pv_printf(&xenfb->c.xendev, 0,
550                       "can't handle frontend fb depth %d\n",
551                       depth);
552         return -1;
553     }
554     if (row_stride <= 0 || row_stride > fb_len) {
555         xen_pv_printf(&xenfb->c.xendev, 0, "invalid frontend stride %d\n",
556                       row_stride);
557         return -1;
558     }
559     max_width = row_stride / (depth / 8);
560     if (width < 0 || width > max_width) {
561         xen_pv_printf(&xenfb->c.xendev, 0,
562                       "invalid frontend width %d limited to %d\n",
563                       width, max_width);
564         width = max_width;
565     }
566     if (offset < 0 || offset >= fb_len) {
567         xen_pv_printf(&xenfb->c.xendev, 0,
568                       "invalid frontend offset %d (max %zu)\n",
569                       offset, fb_len - 1);
570         return -1;
571     }
572     max_height = (fb_len - offset) / row_stride;
573     if (height < 0 || height > max_height) {
574         xen_pv_printf(&xenfb->c.xendev, 0,
575                       "invalid frontend height %d limited to %d\n",
576                       height, max_height);
577         height = max_height;
578     }
579     xenfb->fb_len = fb_len;
580     xenfb->row_stride = row_stride;
581     xenfb->depth = depth;
582     xenfb->width = width;
583     xenfb->height = height;
584     xenfb->offset = offset;
585     xenfb->up_fullscreen = 1;
586     xenfb->do_resize = 1;
587     xen_pv_printf(&xenfb->c.xendev, 1,
588                   "framebuffer %dx%dx%d offset %d stride %d\n",
589                   width, height, depth, offset, row_stride);
590     return 0;
591 }
592 
593 /* A convenient function for munging pixels between different depths */
594 #define BLT(SRC_T,DST_T,RSB,GSB,BSB,RDB,GDB,BDB)                        \
595     for (line = y ; line < (y+h) ; line++) {                            \
596         SRC_T *src = (SRC_T *)(xenfb->pixels                            \
597                                + xenfb->offset                          \
598                                + (line * xenfb->row_stride)             \
599                                + (x * xenfb->depth / 8));               \
600         DST_T *dst = (DST_T *)(data                                     \
601                                + (line * linesize)                      \
602                                + (x * bpp / 8));                        \
603         int col;                                                        \
604         const int RSS = 32 - (RSB + GSB + BSB);                         \
605         const int GSS = 32 - (GSB + BSB);                               \
606         const int BSS = 32 - (BSB);                                     \
607         const uint32_t RSM = (~0U) << (32 - RSB);                       \
608         const uint32_t GSM = (~0U) << (32 - GSB);                       \
609         const uint32_t BSM = (~0U) << (32 - BSB);                       \
610         const int RDS = 32 - (RDB + GDB + BDB);                         \
611         const int GDS = 32 - (GDB + BDB);                               \
612         const int BDS = 32 - (BDB);                                     \
613         const uint32_t RDM = (~0U) << (32 - RDB);                       \
614         const uint32_t GDM = (~0U) << (32 - GDB);                       \
615         const uint32_t BDM = (~0U) << (32 - BDB);                       \
616         for (col = x ; col < (x+w) ; col++) {                           \
617             uint32_t spix = *src;                                       \
618             *dst = (((spix << RSS) & RSM & RDM) >> RDS) |               \
619                 (((spix << GSS) & GSM & GDM) >> GDS) |                  \
620                 (((spix << BSS) & BSM & BDM) >> BDS);                   \
621             src = (SRC_T *) ((unsigned long) src + xenfb->depth / 8);   \
622             dst = (DST_T *) ((unsigned long) dst + bpp / 8);            \
623         }                                                               \
624     }
625 
626 
627 /*
628  * This copies data from the guest framebuffer region, into QEMU's
629  * displaysurface. qemu uses 16 or 32 bpp.  In case the pv framebuffer
630  * uses something else we must convert and copy, otherwise we can
631  * supply the buffer directly and no thing here.
632  */
633 static void xenfb_guest_copy(struct XenFB *xenfb, int x, int y, int w, int h)
634 {
635     DisplaySurface *surface = qemu_console_surface(xenfb->con);
636     int line, oops = 0;
637     int bpp = surface_bits_per_pixel(surface);
638     int linesize = surface_stride(surface);
639     uint8_t *data = surface_data(surface);
640 
641     if (surface_is_allocated(surface)) {
642         switch (xenfb->depth) {
643         case 8:
644             if (bpp == 16) {
645                 BLT(uint8_t, uint16_t,   3, 3, 2,   5, 6, 5);
646             } else if (bpp == 32) {
647                 BLT(uint8_t, uint32_t,   3, 3, 2,   8, 8, 8);
648             } else {
649                 oops = 1;
650             }
651             break;
652         case 24:
653             if (bpp == 16) {
654                 BLT(uint32_t, uint16_t,  8, 8, 8,   5, 6, 5);
655             } else if (bpp == 32) {
656                 BLT(uint32_t, uint32_t,  8, 8, 8,   8, 8, 8);
657             } else {
658                 oops = 1;
659             }
660             break;
661         default:
662             oops = 1;
663         }
664     }
665     if (oops) /* should not happen */
666         xen_pv_printf(&xenfb->c.xendev, 0, "%s: oops: convert %d -> %d bpp?\n",
667                       __func__, xenfb->depth, bpp);
668 
669     dpy_gfx_update(xenfb->con, x, y, w, h);
670 }
671 
672 #ifdef XENFB_TYPE_REFRESH_PERIOD
673 static int xenfb_queue_full(struct XenFB *xenfb)
674 {
675     struct xenfb_page *page = xenfb->c.page;
676     uint32_t cons, prod;
677 
678     if (!page)
679         return 1;
680 
681     prod = page->in_prod;
682     cons = page->in_cons;
683     return prod - cons == XENFB_IN_RING_LEN;
684 }
685 
686 static void xenfb_send_event(struct XenFB *xenfb, union xenfb_in_event *event)
687 {
688     uint32_t prod;
689     struct xenfb_page *page = xenfb->c.page;
690 
691     prod = page->in_prod;
692     /* caller ensures !xenfb_queue_full() */
693     xen_mb();                   /* ensure ring space available */
694     XENFB_IN_RING_REF(page, prod) = *event;
695     xen_wmb();                  /* ensure ring contents visible */
696     page->in_prod = prod + 1;
697 
698     xen_pv_send_notify(&xenfb->c.xendev);
699 }
700 
701 static void xenfb_send_refresh_period(struct XenFB *xenfb, int period)
702 {
703     union xenfb_in_event event;
704 
705     memset(&event, 0, sizeof(event));
706     event.type = XENFB_TYPE_REFRESH_PERIOD;
707     event.refresh_period.period = period;
708     xenfb_send_event(xenfb, &event);
709 }
710 #endif
711 
712 /*
713  * Periodic update of display.
714  * Also transmit the refresh interval to the frontend.
715  *
716  * Never ever do any qemu display operations
717  * (resize, screen update) outside this function.
718  * Our screen might be inactive.  When asked for
719  * an update we know it is active.
720  */
721 static void xenfb_update(void *opaque)
722 {
723     struct XenFB *xenfb = opaque;
724     DisplaySurface *surface;
725     int i;
726 
727     if (xenfb->c.xendev.be_state != XenbusStateConnected)
728         return;
729 
730     if (!xenfb->feature_update) {
731         /* we don't get update notifications, thus use the
732          * sledge hammer approach ... */
733         xenfb->up_fullscreen = 1;
734     }
735 
736     /* resize if needed */
737     if (xenfb->do_resize) {
738         pixman_format_code_t format;
739 
740         xenfb->do_resize = 0;
741         switch (xenfb->depth) {
742         case 16:
743         case 32:
744             /* console.c supported depth -> buffer can be used directly */
745             format = qemu_default_pixman_format(xenfb->depth, true);
746             surface = qemu_create_displaysurface_from
747                 (xenfb->width, xenfb->height, format,
748                  xenfb->row_stride, xenfb->pixels + xenfb->offset);
749             break;
750         default:
751             /* we must convert stuff */
752             surface = qemu_create_displaysurface(xenfb->width, xenfb->height);
753             break;
754         }
755         dpy_gfx_replace_surface(xenfb->con, surface);
756         xen_pv_printf(&xenfb->c.xendev, 1,
757                       "update: resizing: %dx%d @ %d bpp%s\n",
758                       xenfb->width, xenfb->height, xenfb->depth,
759                       surface_is_allocated(surface)
760                       ? " (allocated)" : " (borrowed)");
761         xenfb->up_fullscreen = 1;
762     }
763 
764     /* run queued updates */
765     if (xenfb->up_fullscreen) {
766         xen_pv_printf(&xenfb->c.xendev, 3, "update: fullscreen\n");
767         xenfb_guest_copy(xenfb, 0, 0, xenfb->width, xenfb->height);
768     } else if (xenfb->up_count) {
769         xen_pv_printf(&xenfb->c.xendev, 3, "update: %d rects\n",
770                       xenfb->up_count);
771         for (i = 0; i < xenfb->up_count; i++)
772             xenfb_guest_copy(xenfb,
773                              xenfb->up_rects[i].x,
774                              xenfb->up_rects[i].y,
775                              xenfb->up_rects[i].w,
776                              xenfb->up_rects[i].h);
777     } else {
778         xen_pv_printf(&xenfb->c.xendev, 3, "update: nothing\n");
779     }
780     xenfb->up_count = 0;
781     xenfb->up_fullscreen = 0;
782 }
783 
784 static void xenfb_ui_info(void *opaque, uint32_t idx, QemuUIInfo *info)
785 {
786     struct XenFB *xenfb = opaque;
787     uint32_t refresh_rate;
788 
789     if (xenfb->feature_update) {
790 #ifdef XENFB_TYPE_REFRESH_PERIOD
791         if (xenfb_queue_full(xenfb)) {
792             return;
793         }
794 
795         refresh_rate = info->refresh_rate;
796         if (!refresh_rate) {
797             refresh_rate = 75;
798         }
799 
800         /* T = 1 / f = 1 [s*Hz] / f = 1000*1000 [ms*mHz] / f */
801         xenfb_send_refresh_period(xenfb, 1000 * 1000 / refresh_rate);
802 #endif
803     }
804 }
805 
806 /* QEMU display state changed, so refresh the framebuffer copy */
807 static void xenfb_invalidate(void *opaque)
808 {
809     struct XenFB *xenfb = opaque;
810     xenfb->up_fullscreen = 1;
811 }
812 
813 static void xenfb_handle_events(struct XenFB *xenfb)
814 {
815     uint32_t prod, cons, out_cons;
816     struct xenfb_page *page = xenfb->c.page;
817 
818     prod = page->out_prod;
819     out_cons = page->out_cons;
820     if (prod - out_cons > XENFB_OUT_RING_LEN) {
821         return;
822     }
823     xen_rmb();          /* ensure we see ring contents up to prod */
824     for (cons = out_cons; cons != prod; cons++) {
825         union xenfb_out_event *event = &XENFB_OUT_RING_REF(page, cons);
826         uint8_t type = event->type;
827         int x, y, w, h;
828 
829         switch (type) {
830         case XENFB_TYPE_UPDATE:
831             if (xenfb->up_count == UP_QUEUE)
832                 xenfb->up_fullscreen = 1;
833             if (xenfb->up_fullscreen)
834                 break;
835             x = MAX(event->update.x, 0);
836             y = MAX(event->update.y, 0);
837             w = MIN(event->update.width, xenfb->width - x);
838             h = MIN(event->update.height, xenfb->height - y);
839             if (w < 0 || h < 0) {
840                 xen_pv_printf(&xenfb->c.xendev, 1, "bogus update ignored\n");
841                 break;
842             }
843             if (x != event->update.x ||
844                 y != event->update.y ||
845                 w != event->update.width ||
846                 h != event->update.height) {
847                 xen_pv_printf(&xenfb->c.xendev, 1, "bogus update clipped\n");
848             }
849             if (w == xenfb->width && h > xenfb->height / 2) {
850                 /* scroll detector: updated more than 50% of the lines,
851                  * don't bother keeping track of the rectangles then */
852                 xenfb->up_fullscreen = 1;
853             } else {
854                 xenfb->up_rects[xenfb->up_count].x = x;
855                 xenfb->up_rects[xenfb->up_count].y = y;
856                 xenfb->up_rects[xenfb->up_count].w = w;
857                 xenfb->up_rects[xenfb->up_count].h = h;
858                 xenfb->up_count++;
859             }
860             break;
861 #ifdef XENFB_TYPE_RESIZE
862         case XENFB_TYPE_RESIZE:
863             if (xenfb_configure_fb(xenfb, xenfb->fb_len,
864                                    event->resize.width,
865                                    event->resize.height,
866                                    event->resize.depth,
867                                    xenfb->fb_len,
868                                    event->resize.offset,
869                                    event->resize.stride) < 0)
870                 break;
871             xenfb_invalidate(xenfb);
872             break;
873 #endif
874         }
875     }
876     xen_mb();           /* ensure we're done with ring contents */
877     page->out_cons = cons;
878 }
879 
880 static int fb_init(struct XenLegacyDevice *xendev)
881 {
882 #ifdef XENFB_TYPE_RESIZE
883     xenstore_write_be_int(xendev, "feature-resize", 1);
884 #endif
885     return 0;
886 }
887 
888 static int fb_initialise(struct XenLegacyDevice *xendev)
889 {
890     struct XenFB *fb = container_of(xendev, struct XenFB, c.xendev);
891     struct xenfb_page *fb_page;
892     int videoram;
893     int rc;
894 
895     if (xenstore_read_fe_int(xendev, "videoram", &videoram) == -1)
896         videoram = 0;
897 
898     rc = common_bind(&fb->c);
899     if (rc != 0)
900         return rc;
901 
902     fb_page = fb->c.page;
903     rc = xenfb_configure_fb(fb, videoram * MiB,
904                             fb_page->width, fb_page->height, fb_page->depth,
905                             fb_page->mem_length, 0, fb_page->line_length);
906     if (rc != 0)
907         return rc;
908 
909     rc = xenfb_map_fb(fb);
910     if (rc != 0)
911         return rc;
912 
913     fb->con = graphic_console_init(NULL, 0, &xenfb_ops, fb);
914 
915     if (xenstore_read_fe_int(xendev, "feature-update", &fb->feature_update) == -1)
916         fb->feature_update = 0;
917     if (fb->feature_update)
918         xenstore_write_be_int(xendev, "request-update", 1);
919 
920     xen_pv_printf(xendev, 1, "feature-update=%d, videoram=%d\n",
921                   fb->feature_update, videoram);
922     return 0;
923 }
924 
925 static void fb_disconnect(struct XenLegacyDevice *xendev)
926 {
927     struct XenFB *fb = container_of(xendev, struct XenFB, c.xendev);
928 
929     /*
930      * FIXME: qemu can't un-init gfx display (yet?).
931      *   Replacing the framebuffer with anonymous shared memory
932      *   instead.  This releases the guest pages and keeps qemu happy.
933      */
934     qemu_xen_foreignmem_unmap(fb->pixels, fb->fbpages);
935     fb->pixels = mmap(fb->pixels, fb->fbpages * XEN_PAGE_SIZE,
936                       PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON,
937                       -1, 0);
938     if (fb->pixels == MAP_FAILED) {
939         xen_pv_printf(xendev, 0,
940                 "Couldn't replace the framebuffer with anonymous memory errno=%d\n",
941                 errno);
942     }
943     common_unbind(&fb->c);
944     fb->feature_update = 0;
945     fb->bug_trigger    = 0;
946 }
947 
948 static void fb_frontend_changed(struct XenLegacyDevice *xendev,
949                                 const char *node)
950 {
951     struct XenFB *fb = container_of(xendev, struct XenFB, c.xendev);
952 
953     /*
954      * Set state to Connected *again* once the frontend switched
955      * to connected.  We must trigger the watch a second time to
956      * workaround a frontend bug.
957      */
958     if (fb->bug_trigger == 0 && strcmp(node, "state") == 0 &&
959         xendev->fe_state == XenbusStateConnected &&
960         xendev->be_state == XenbusStateConnected) {
961         xen_pv_printf(xendev, 2, "re-trigger connected (frontend bug)\n");
962         xen_be_set_state(xendev, XenbusStateConnected);
963         fb->bug_trigger = 1; /* only once */
964     }
965 }
966 
967 static void fb_event(struct XenLegacyDevice *xendev)
968 {
969     struct XenFB *xenfb = container_of(xendev, struct XenFB, c.xendev);
970 
971     xenfb_handle_events(xenfb);
972     xen_pv_send_notify(&xenfb->c.xendev);
973 }
974 
975 /* -------------------------------------------------------------------- */
976 
977 static const struct XenDevOps xen_kbdmouse_ops = {
978     .size       = sizeof(struct XenInput),
979     .init       = input_init,
980     .initialise = input_initialise,
981     .connected  = input_connected,
982     .disconnect = input_disconnect,
983     .event      = input_event,
984 };
985 
986 const struct XenDevOps xen_framebuffer_ops = {
987     .size       = sizeof(struct XenFB),
988     .init       = fb_init,
989     .initialise = fb_initialise,
990     .disconnect = fb_disconnect,
991     .event      = fb_event,
992     .frontend_changed = fb_frontend_changed,
993 };
994 
995 static const GraphicHwOps xenfb_ops = {
996     .invalidate  = xenfb_invalidate,
997     .gfx_update  = xenfb_update,
998     .ui_info     = xenfb_ui_info,
999 };
1000 
1001 static void xen_ui_register_backend(void)
1002 {
1003     xen_be_register("vkbd", &xen_kbdmouse_ops);
1004 
1005     if (vga_interface_type == VGA_XENFB) {
1006         xen_be_register("vfb", &xen_framebuffer_ops);
1007     }
1008 }
1009 xen_backend_init(xen_ui_register_backend);
1010