xref: /freebsd/stand/common/gfx_fb.c (revision 32da2f23ae4d18888d34682b0ddb49ec80c0bb26)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 2020 Toomas Soome
5  * Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
6  * Copyright 2020 RackTop Systems, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * The workhorse here is gfxfb_blt(). It is implemented to mimic UEFI
32  * GOP Blt, and allows us to fill the rectangle on screen, copy
33  * rectangle from video to buffer and buffer to video and video to video.
34  * Such implementation does allow us to have almost identical implementation
35  * for both BIOS VBE and UEFI.
36  *
37  * ALL pixel data is assumed to be 32-bit BGRA (byte order Blue, Green, Red,
38  * Alpha) format, this allows us to only handle RGB data and not to worry
39  * about mixing RGB with indexed colors.
40  * Data exchange between memory buffer and video will translate BGRA
41  * and native format as following:
42  *
43  * 32-bit to/from 32-bit is trivial case.
44  * 32-bit to/from 24-bit is also simple - we just drop the alpha channel.
45  * 32-bit to/from 16-bit is more complicated, because we nee to handle
46  * data loss from 32-bit to 16-bit. While reading/writing from/to video, we
47  * need to apply masks of 16-bit color components. This will preserve
48  * colors for terminal text. For 32-bit truecolor PMG images, we need to
49  * translate 32-bit colors to 15/16 bit colors and this means data loss.
50  * There are different algorithms how to perform such color space reduction,
51  * we are currently using bitwise right shift to reduce color space and so far
52  * this technique seems to be sufficient (see also gfx_fb_putimage(), the
53  * end of for loop).
54  * 32-bit to/from 8-bit is the most troublesome because 8-bit colors are
55  * indexed. From video, we do get color indexes, and we do translate
56  * color index values to RGB. To write to video, we again need to translate
57  * RGB to color index. Additionally, we need to translate between VGA and
58  * console colors.
59  *
60  * Our internal color data is represented using BGRA format. But the hardware
61  * used indexed colors for 8-bit colors (0-255) and for this mode we do
62  * need to perform translation to/from BGRA and index values.
63  *
64  *                   - paletteentry RGB <-> index -
65  * BGRA BUFFER <----/                              \ - VIDEO
66  *                  \                              /
67  *                   -  RGB (16/24/32)            -
68  *
69  * To perform index to RGB translation, we use palette table generated
70  * from when we set up 8-bit mode video. We cannot read palette data from
71  * the hardware, because not all hardware supports reading it.
72  *
73  * BGRA to index is implemented in rgb_to_color_index() by searching
74  * palette array for closest match of RBG values.
75  *
76  * Note: In 8-bit mode, We do store first 16 colors to palette registers
77  * in VGA color order, this serves two purposes; firstly,
78  * if palette update is not supported, we still have correct 16 colors.
79  * Secondly, the kernel does get correct 16 colors when some other boot
80  * loader is used. However, the palette map for 8-bit colors is using
81  * console color ordering - this does allow us to skip translation
82  * from VGA colors to console colors, while we are reading RGB data.
83  */
84 
85 #include <sys/param.h>
86 #include <assert.h>
87 #include <stand.h>
88 #include <teken.h>
89 #include <gfx_fb.h>
90 #include <sys/font.h>
91 #include <sys/splash.h>
92 #include <sys/linker.h>
93 #include <sys/module.h>
94 #include <sys/stdint.h>
95 #include <sys/endian.h>
96 #include <pnglite.h>
97 #include <bootstrap.h>
98 #include <lz4.h>
99 #if defined(EFI)
100 #include <efi.h>
101 #include <efilib.h>
102 #include <Protocol/GraphicsOutput.h>
103 #else
104 #include <vbe.h>
105 #endif
106 
107 #include "modinfo.h"
108 
109 /* VGA text mode does use bold font. */
110 #if !defined(VGA_8X16_FONT)
111 #define	VGA_8X16_FONT		"/boot/fonts/8x16b.fnt"
112 #endif
113 #if !defined(DEFAULT_8X16_FONT)
114 #define	DEFAULT_8X16_FONT	"/boot/fonts/8x16.fnt"
115 #endif
116 
117 /*
118  * Must be sorted by font size in descending order
119  */
120 font_list_t fonts = STAILQ_HEAD_INITIALIZER(fonts);
121 
122 #define	DEFAULT_FONT_DATA	font_data_8x16
123 extern vt_font_bitmap_data_t	font_data_8x16;
124 teken_gfx_t gfx_state = { 0 };
125 
126 static struct {
127 	unsigned char r;	/* Red percentage value. */
128 	unsigned char g;	/* Green percentage value. */
129 	unsigned char b;	/* Blue percentage value. */
130 } color_def[NCOLORS] = {
131 	{0,	0,	0},	/* black */
132 	{50,	0,	0},	/* dark red */
133 	{0,	50,	0},	/* dark green */
134 	{77,	63,	0},	/* dark yellow */
135 	{20,	40,	64},	/* dark blue */
136 	{50,	0,	50},	/* dark magenta */
137 	{0,	50,	50},	/* dark cyan */
138 	{75,	75,	75},	/* light gray */
139 
140 	{18,	20,	21},	/* dark gray */
141 	{100,	0,	0},	/* light red */
142 	{0,	100,	0},	/* light green */
143 	{100,	100,	0},	/* light yellow */
144 	{45,	62,	81},	/* light blue */
145 	{100,	0,	100},	/* light magenta */
146 	{0,	100,	100},	/* light cyan */
147 	{100,	100,	100},	/* white */
148 };
149 uint32_t cmap[NCMAP];
150 
151 /*
152  * Between console's palette and VGA's one:
153  *  - blue and red are swapped (1 <-> 4)
154  *  - yellow and cyan are swapped (3 <-> 6)
155  */
156 const int cons_to_vga_colors[NCOLORS] = {
157 	0,  4,  2,  6,  1,  5,  3,  7,
158 	8, 12, 10, 14,  9, 13, 11, 15
159 };
160 
161 static const int vga_to_cons_colors[NCOLORS] = {
162 	0,  1,  2,  3,  4,  5,  6,  7,
163 	8,  9, 10, 11,  12, 13, 14, 15
164 };
165 
166 /*
167  * It is reported very slow console draw in some systems.
168  * in order to exclude buggy gop->Blt(), we want option
169  * to use direct draw to framebuffer and avoid gop->Blt.
170  * Can be toggled with "gop" command.
171  */
172 bool ignore_gop_blt = false;
173 
174 struct text_pixel *screen_buffer;
175 #if defined(EFI)
176 static EFI_GRAPHICS_OUTPUT_BLT_PIXEL *GlyphBuffer;
177 #else
178 static struct paletteentry *GlyphBuffer;
179 #endif
180 static size_t GlyphBufferSize;
181 
182 static bool insert_font(char *, FONT_FLAGS);
183 static int font_set(struct env_var *, int, const void *);
184 static void * allocate_glyphbuffer(uint32_t, uint32_t);
185 static void gfx_fb_cursor_draw(teken_gfx_t *, const teken_pos_t *, bool);
186 
187 /*
188  * Initialize gfx framework.
189  */
190 void
191 gfx_framework_init(void)
192 {
193 	/*
194 	 * Setup font list to have builtin font.
195 	 */
196 	(void) insert_font(NULL, FONT_BUILTIN);
197 	gfx_interp_ref();	/* Draw in the gfx interpreter for this thing */
198 }
199 
200 static uint8_t *
201 gfx_get_fb_address(void)
202 {
203 	return (ptov((uint32_t)gfx_state.tg_fb.fb_addr));
204 }
205 
206 /*
207  * Utility function to parse gfx mode line strings.
208  */
209 bool
210 gfx_parse_mode_str(char *str, int *x, int *y, int *depth)
211 {
212 	char *p, *end;
213 
214 	errno = 0;
215 	p = str;
216 	*x = strtoul(p, &end, 0);
217 	if (*x == 0 || errno != 0)
218 		return (false);
219 	if (*end != 'x')
220 		return (false);
221 	p = end + 1;
222 	*y = strtoul(p, &end, 0);
223 	if (*y == 0 || errno != 0)
224 		return (false);
225 	if (*end != 'x') {
226 		*depth = -1;    /* auto select */
227 	} else {
228 		p = end + 1;
229 		*depth = strtoul(p, &end, 0);
230 		if (*depth == 0 || errno != 0 || *end != '\0')
231 			return (false);
232 	}
233 
234 	return (true);
235 }
236 
237 /*
238  * Returns true if we set the color from pre-existing environment, false if
239  * just used existing defaults.
240  */
241 static bool
242 gfx_fb_evalcolor(const char *envname, teken_color_t *cattr,
243     ev_sethook_t sethook, ev_unsethook_t unsethook)
244 {
245 	const char *ptr;
246 	char env[10];
247 	int eflags = EV_VOLATILE | EV_NOKENV;
248 	bool from_env = false;
249 
250 	ptr = getenv(envname);
251 	if (ptr != NULL) {
252 		*cattr = strtol(ptr, NULL, 10);
253 
254 		/*
255 		 * If we can't unset the value, then it's probably hooked
256 		 * properly and we can just carry on.  Otherwise, we want to
257 		 * reinitialize it so that we can hook it for the console that
258 		 * we're resetting defaults for.
259 		 */
260 		if (unsetenv(envname) != 0)
261 			return (true);
262 		from_env = true;
263 
264 		/*
265 		 * If we're carrying over an existing value, we *do* want that
266 		 * to propagate to the kenv.
267 		 */
268 		eflags &= ~EV_NOKENV;
269 	}
270 
271 	snprintf(env, sizeof(env), "%d", *cattr);
272 	env_setenv(envname, eflags, env, sethook, unsethook);
273 
274 	return (from_env);
275 }
276 
277 void
278 gfx_fb_setcolors(teken_attr_t *attr, ev_sethook_t sethook,
279      ev_unsethook_t unsethook)
280 {
281 	bool need_setattr = false;
282 
283 	/*
284 	 * On first run, we setup an environment hook to process any color
285 	 * changes.  If the env is already set, we pick up fg and bg color
286 	 * values from the environment.
287 	 */
288 	if (gfx_fb_evalcolor("teken.fg_color", &attr->ta_fgcolor,
289 	    sethook, unsethook))
290 		need_setattr = true;
291 	if (gfx_fb_evalcolor("teken.bg_color", &attr->ta_bgcolor,
292 	    sethook, unsethook))
293 		need_setattr = true;
294 
295 	if (need_setattr)
296 		teken_set_defattr(&gfx_state.tg_teken, attr);
297 }
298 
299 static uint32_t
300 rgb_color_map(uint8_t index, uint32_t rmax, int roffset,
301     uint32_t gmax, int goffset, uint32_t bmax, int boffset)
302 {
303 	uint32_t color, code, gray, level;
304 
305 	if (index < NCOLORS) {
306 #define	CF(_f, _i) ((_f ## max * color_def[(_i)]._f / 100) << _f ## offset)
307 		return (CF(r, index) | CF(g, index) | CF(b, index));
308 #undef  CF
309         }
310 
311 #define	CF(_f, _c) ((_f ## max & _c) << _f ## offset)
312         /* 6x6x6 color cube */
313         if (index > 15 && index < 232) {
314                 uint32_t red, green, blue;
315 
316                 for (red = 0; red < 6; red++) {
317                         for (green = 0; green < 6; green++) {
318                                 for (blue = 0; blue < 6; blue++) {
319                                         code = 16 + (red * 36) +
320                                             (green * 6) + blue;
321                                         if (code != index)
322                                                 continue;
323                                         red = red ? (red * 40 + 55) : 0;
324                                         green = green ? (green * 40 + 55) : 0;
325                                         blue = blue ? (blue * 40 + 55) : 0;
326                                         color = CF(r, red);
327 					color |= CF(g, green);
328 					color |= CF(b, blue);
329 					return (color);
330                                 }
331                         }
332                 }
333         }
334 
335         /* colors 232-255 are a grayscale ramp */
336         for (gray = 0; gray < 24; gray++) {
337                 level = (gray * 10) + 8;
338                 code = 232 + gray;
339                 if (code == index)
340                         break;
341         }
342         return (CF(r, level) | CF(g, level) | CF(b, level));
343 #undef  CF
344 }
345 
346 /*
347  * Support for color mapping.
348  * For 8, 24 and 32 bit depth, use mask size 8.
349  * 15/16 bit depth needs to use mask size from mode,
350  * or we will lose color information from 32-bit to 15/16 bit translation.
351  */
352 uint32_t
353 gfx_fb_color_map(uint8_t index)
354 {
355 	int rmask, gmask, bmask;
356 	int roff, goff, boff, bpp;
357 
358 	roff = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
359         goff = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
360         boff = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
361 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
362 
363 	if (bpp == 2)
364 		rmask = gfx_state.tg_fb.fb_mask_red >> roff;
365 	else
366 		rmask = 0xff;
367 
368 	if (bpp == 2)
369 		gmask = gfx_state.tg_fb.fb_mask_green >> goff;
370 	else
371 		gmask = 0xff;
372 
373 	if (bpp == 2)
374 		bmask = gfx_state.tg_fb.fb_mask_blue >> boff;
375 	else
376 		bmask = 0xff;
377 
378 	return (rgb_color_map(index, rmask, 16, gmask, 8, bmask, 0));
379 }
380 
381 /*
382  * Get indexed color from RGB. This function is used to write data to video
383  * memory when the adapter is set to use indexed colors.
384  * Since UEFI does only support 32-bit colors, we do not implement it for
385  * UEFI because there is no need for it and we do not have palette array
386  * for UEFI.
387  */
388 static uint8_t
389 rgb_to_color_index(uint8_t r, uint8_t g, uint8_t b)
390 {
391 #if !defined(EFI)
392 	uint32_t color, best, dist, k;
393 	int diff;
394 
395 	color = 0;
396 	best = 255 * 255 * 255;
397 	for (k = 0; k < NCMAP; k++) {
398 		diff = r - pe8[k].Red;
399 		dist = diff * diff;
400 		diff = g - pe8[k].Green;
401 		dist += diff * diff;
402 		diff = b - pe8[k].Blue;
403 		dist += diff * diff;
404 
405 		/* Exact match, exit the loop */
406 		if (dist == 0)
407 			break;
408 
409 		if (dist < best) {
410 			color = k;
411 			best = dist;
412 		}
413 	}
414 	if (k == NCMAP)
415 		k = color;
416 	return (k);
417 #else
418 	(void) r;
419 	(void) g;
420 	(void) b;
421 	return (0);
422 #endif
423 }
424 
425 int
426 generate_cons_palette(uint32_t *palette, int format,
427     uint32_t rmax, int roffset, uint32_t gmax, int goffset,
428     uint32_t bmax, int boffset)
429 {
430 	int i;
431 
432 	switch (format) {
433 	case COLOR_FORMAT_VGA:
434 		for (i = 0; i < NCOLORS; i++)
435 			palette[i] = cons_to_vga_colors[i];
436 		for (; i < NCMAP; i++)
437 			palette[i] = i;
438 		break;
439 	case COLOR_FORMAT_RGB:
440 		for (i = 0; i < NCMAP; i++)
441 			palette[i] = rgb_color_map(i, rmax, roffset,
442 			    gmax, goffset, bmax, boffset);
443 		break;
444 	default:
445 		return (ENODEV);
446 	}
447 
448 	return (0);
449 }
450 
451 static void
452 gfx_mem_wr1(uint8_t *base, size_t size, uint32_t o, uint8_t v)
453 {
454 
455 	if (o >= size)
456 		return;
457 	*(uint8_t *)(base + o) = v;
458 }
459 
460 static void
461 gfx_mem_wr2(uint8_t *base, size_t size, uint32_t o, uint16_t v)
462 {
463 
464 	if (o >= size)
465 		return;
466 	*(uint16_t *)(base + o) = v;
467 }
468 
469 static void
470 gfx_mem_wr4(uint8_t *base, size_t size, uint32_t o, uint32_t v)
471 {
472 
473 	if (o >= size)
474 		return;
475 	*(uint32_t *)(base + o) = v;
476 }
477 
478 static int gfxfb_blt_fill(void *BltBuffer,
479     uint32_t DestinationX, uint32_t DestinationY,
480     uint32_t Width, uint32_t Height)
481 {
482 #if defined(EFI)
483 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
484 #else
485 	struct paletteentry *p;
486 #endif
487 	uint32_t data, bpp, pitch, y, x;
488 	int roff, goff, boff;
489 	size_t size;
490 	off_t off;
491 	uint8_t *destination;
492 
493 	if (BltBuffer == NULL)
494 		return (EINVAL);
495 
496 	if (DestinationY + Height > gfx_state.tg_fb.fb_height)
497 		return (EINVAL);
498 
499 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
500 		return (EINVAL);
501 
502 	if (Width == 0 || Height == 0)
503 		return (EINVAL);
504 
505 	p = BltBuffer;
506 	roff = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
507 	goff = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
508 	boff = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
509 
510 	if (gfx_state.tg_fb.fb_bpp == 8) {
511 		data = rgb_to_color_index(p->Red, p->Green, p->Blue);
512 	} else {
513 		data = (p->Red &
514 		    (gfx_state.tg_fb.fb_mask_red >> roff)) << roff;
515 		data |= (p->Green &
516 		    (gfx_state.tg_fb.fb_mask_green >> goff)) << goff;
517 		data |= (p->Blue &
518 		    (gfx_state.tg_fb.fb_mask_blue >> boff)) << boff;
519 	}
520 
521 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
522 	pitch = gfx_state.tg_fb.fb_stride * bpp;
523 	destination = gfx_get_fb_address();
524 	size = gfx_state.tg_fb.fb_size;
525 
526 	for (y = DestinationY; y < Height + DestinationY; y++) {
527 		off = y * pitch + DestinationX * bpp;
528 		for (x = 0; x < Width; x++) {
529 			switch (bpp) {
530 			case 1:
531 				gfx_mem_wr1(destination, size, off,
532 				    (data < NCOLORS) ?
533 				    cons_to_vga_colors[data] : data);
534 				break;
535 			case 2:
536 				gfx_mem_wr2(destination, size, off, data);
537 				break;
538 			case 3:
539 				gfx_mem_wr1(destination, size, off,
540 				    (data >> 16) & 0xff);
541 				gfx_mem_wr1(destination, size, off + 1,
542 				    (data >> 8) & 0xff);
543 				gfx_mem_wr1(destination, size, off + 2,
544 				    data & 0xff);
545 				break;
546 			case 4:
547 				gfx_mem_wr4(destination, size, off, data);
548 				break;
549 			default:
550 				return (EINVAL);
551 			}
552 			off += bpp;
553 		}
554 	}
555 
556 	return (0);
557 }
558 
559 static int
560 gfxfb_blt_video_to_buffer(void *BltBuffer, uint32_t SourceX, uint32_t SourceY,
561     uint32_t DestinationX, uint32_t DestinationY,
562     uint32_t Width, uint32_t Height, uint32_t Delta)
563 {
564 #if defined(EFI)
565 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
566 #else
567 	struct paletteentry *p;
568 #endif
569 	uint32_t x, sy, dy;
570 	uint32_t bpp, pitch, copybytes;
571 	off_t off;
572 	uint8_t *source, *destination, *sb;
573 	uint8_t rm, rp, gm, gp, bm, bp;
574 	bool bgra;
575 
576 	if (BltBuffer == NULL)
577 		return (EINVAL);
578 
579 	if (SourceY + Height >
580 	    gfx_state.tg_fb.fb_height)
581 		return (EINVAL);
582 
583 	if (SourceX + Width > gfx_state.tg_fb.fb_width)
584 		return (EINVAL);
585 
586 	if (Width == 0 || Height == 0)
587 		return (EINVAL);
588 
589 	if (Delta == 0)
590 		Delta = Width * sizeof (*p);
591 
592 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
593 	pitch = gfx_state.tg_fb.fb_stride * bpp;
594 
595 	copybytes = Width * bpp;
596 
597 	rp = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
598 	gp = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
599 	bp = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
600 	rm = gfx_state.tg_fb.fb_mask_red >> rp;
601 	gm = gfx_state.tg_fb.fb_mask_green >> gp;
602 	bm = gfx_state.tg_fb.fb_mask_blue >> bp;
603 
604 	/* If FB pixel format is BGRA, we can use direct copy. */
605 	bgra = bpp == 4 &&
606 	    ffs(rm) - 1 == 8 && rp == 16 &&
607 	    ffs(gm) - 1 == 8 && gp == 8 &&
608 	    ffs(bm) - 1 == 8 && bp == 0;
609 
610 	for (sy = SourceY, dy = DestinationY; dy < Height + DestinationY;
611 	    sy++, dy++) {
612 		off = sy * pitch + SourceX * bpp;
613 		source = gfx_get_fb_address() + off;
614 		destination = (uint8_t *)BltBuffer + dy * Delta +
615 		    DestinationX * sizeof (*p);
616 
617 		if (bgra) {
618 			bcopy(source, destination, copybytes);
619 		} else {
620 			for (x = 0; x < Width; x++) {
621 				uint32_t c = 0;
622 
623 				p = (void *)(destination + x * sizeof (*p));
624 				sb = source + x * bpp;
625 				switch (bpp) {
626 				case 1:
627 					c = *sb;
628 					break;
629 				case 2:
630 					c = *(uint16_t *)sb;
631 					break;
632 				case 3:
633 					c = sb[0] << 16 | sb[1] << 8 | sb[2];
634 					break;
635 				case 4:
636 					c = *(uint32_t *)sb;
637 					break;
638 				default:
639 					return (EINVAL);
640 				}
641 
642 				if (bpp == 1) {
643 					*(uint32_t *)p = gfx_fb_color_map(
644 					    (c < 16) ?
645 					    vga_to_cons_colors[c] : c);
646 				} else {
647 					p->Red = (c >> rp) & rm;
648 					p->Green = (c >> gp) & gm;
649 					p->Blue = (c >> bp) & bm;
650 					p->Reserved = 0;
651 				}
652 			}
653 		}
654 	}
655 
656 	return (0);
657 }
658 
659 static int
660 gfxfb_blt_buffer_to_video(void *BltBuffer, uint32_t SourceX, uint32_t SourceY,
661     uint32_t DestinationX, uint32_t DestinationY,
662     uint32_t Width, uint32_t Height, uint32_t Delta)
663 {
664 #if defined(EFI)
665 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
666 #else
667 	struct paletteentry *p;
668 #endif
669 	uint32_t x, sy, dy;
670 	uint32_t bpp, pitch, copybytes;
671 	off_t off;
672 	uint8_t *source, *destination;
673 	uint8_t rm, rp, gm, gp, bm, bp;
674 	bool bgra;
675 
676 	if (BltBuffer == NULL)
677 		return (EINVAL);
678 
679 	if (DestinationY + Height >
680 	    gfx_state.tg_fb.fb_height)
681 		return (EINVAL);
682 
683 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
684 		return (EINVAL);
685 
686 	if (Width == 0 || Height == 0)
687 		return (EINVAL);
688 
689 	if (Delta == 0)
690 		Delta = Width * sizeof (*p);
691 
692 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
693 	pitch = gfx_state.tg_fb.fb_stride * bpp;
694 
695 	copybytes = Width * bpp;
696 
697 	rp = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
698 	gp = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
699 	bp = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
700 	rm = gfx_state.tg_fb.fb_mask_red >> rp;
701 	gm = gfx_state.tg_fb.fb_mask_green >> gp;
702 	bm = gfx_state.tg_fb.fb_mask_blue >> bp;
703 
704 	/* If FB pixel format is BGRA, we can use direct copy. */
705 	bgra = bpp == 4 &&
706 	    ffs(rm) - 1 == 8 && rp == 16 &&
707 	    ffs(gm) - 1 == 8 && gp == 8 &&
708 	    ffs(bm) - 1 == 8 && bp == 0;
709 
710 	for (sy = SourceY, dy = DestinationY; sy < Height + SourceY;
711 	    sy++, dy++) {
712 		off = dy * pitch + DestinationX * bpp;
713 		destination = gfx_get_fb_address() + off;
714 
715 		if (bgra) {
716 			source = (uint8_t *)BltBuffer + sy * Delta +
717 			    SourceX * sizeof (*p);
718 			bcopy(source, destination, copybytes);
719 		} else {
720 			for (x = 0; x < Width; x++) {
721 				uint32_t c;
722 
723 				p = (void *)((uint8_t *)BltBuffer +
724 				    sy * Delta +
725 				    (SourceX + x) * sizeof (*p));
726 				if (bpp == 1) {
727 					c = rgb_to_color_index(p->Red,
728 					    p->Green, p->Blue);
729 				} else {
730 					c = (p->Red & rm) << rp |
731 					    (p->Green & gm) << gp |
732 					    (p->Blue & bm) << bp;
733 				}
734 				off = x * bpp;
735 				switch (bpp) {
736 				case 1:
737 					gfx_mem_wr1(destination, copybytes,
738 					    off, (c < 16) ?
739 					    cons_to_vga_colors[c] : c);
740 					break;
741 				case 2:
742 					gfx_mem_wr2(destination, copybytes,
743 					    off, c);
744 					break;
745 				case 3:
746 					gfx_mem_wr1(destination, copybytes,
747 					    off, (c >> 16) & 0xff);
748 					gfx_mem_wr1(destination, copybytes,
749 					    off + 1, (c >> 8) & 0xff);
750 					gfx_mem_wr1(destination, copybytes,
751 					    off + 2, c & 0xff);
752 					break;
753 				case 4:
754 					gfx_mem_wr4(destination, copybytes,
755 					    x * bpp, c);
756 					break;
757 				default:
758 					return (EINVAL);
759 				}
760 			}
761 		}
762 	}
763 
764 	return (0);
765 }
766 
767 static int
768 gfxfb_blt_video_to_video(uint32_t SourceX, uint32_t SourceY,
769     uint32_t DestinationX, uint32_t DestinationY,
770     uint32_t Width, uint32_t Height)
771 {
772 	uint32_t bpp, copybytes;
773 	int pitch;
774 	uint8_t *source, *destination;
775 	off_t off;
776 
777 	if (SourceY + Height >
778 	    gfx_state.tg_fb.fb_height)
779 		return (EINVAL);
780 
781 	if (SourceX + Width > gfx_state.tg_fb.fb_width)
782 		return (EINVAL);
783 
784 	if (DestinationY + Height >
785 	    gfx_state.tg_fb.fb_height)
786 		return (EINVAL);
787 
788 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
789 		return (EINVAL);
790 
791 	if (Width == 0 || Height == 0)
792 		return (EINVAL);
793 
794 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
795 	pitch = gfx_state.tg_fb.fb_stride * bpp;
796 
797 	copybytes = Width * bpp;
798 
799 	off = SourceY * pitch + SourceX * bpp;
800 	source = gfx_get_fb_address() + off;
801 	off = DestinationY * pitch + DestinationX * bpp;
802 	destination = gfx_get_fb_address() + off;
803 
804 	if ((uintptr_t)destination > (uintptr_t)source) {
805 		source += Height * pitch;
806 		destination += Height * pitch;
807 		pitch = -pitch;
808 	}
809 
810 	while (Height-- > 0) {
811 		bcopy(source, destination, copybytes);
812 		source += pitch;
813 		destination += pitch;
814 	}
815 
816 	return (0);
817 }
818 
819 static void
820 gfx_shadow_mark_dirty(uint32_t x, uint32_t y, uint32_t w, uint32_t h)
821 {
822 	if (gfx_state.tg_dirty) {
823 		if (x < gfx_state.tg_dirty_x1)
824 			gfx_state.tg_dirty_x1 = x;
825 		if (y < gfx_state.tg_dirty_y1)
826 			gfx_state.tg_dirty_y1 = y;
827 		if (x + w > gfx_state.tg_dirty_x2)
828 			gfx_state.tg_dirty_x2 = x + w;
829 		if (y + h > gfx_state.tg_dirty_y2)
830 			gfx_state.tg_dirty_y2 = y + h;
831 	} else {
832 		gfx_state.tg_dirty = true;
833 		gfx_state.tg_dirty_x1 = x;
834 		gfx_state.tg_dirty_y1 = y;
835 		gfx_state.tg_dirty_x2 = x + w;
836 		gfx_state.tg_dirty_y2 = y + h;
837 	}
838 }
839 
840 static void
841 gfxfb_shadow_fill(uint32_t *BltBuffer,
842     uint32_t DestinationX, uint32_t DestinationY,
843     uint32_t Width, uint32_t Height)
844 {
845 	uint32_t fbX, fbY;
846 
847 	if (gfx_state.tg_shadow_fb == NULL)
848 		return;
849 
850 	fbX = gfx_state.tg_fb.fb_width;
851 	fbY = gfx_state.tg_fb.fb_height;
852 
853 	if (BltBuffer == NULL)
854 		return;
855 
856 	if (DestinationX + Width > fbX)
857 		Width = fbX - DestinationX;
858 
859 	if (DestinationY + Height > fbY)
860 		Height = fbY - DestinationY;
861 
862 	uint32_t y2 = Height + DestinationY;
863 	for (uint32_t y1 = DestinationY; y1 < y2; y1++) {
864 		uint32_t off = y1 * fbX + DestinationX;
865 
866 		for (uint32_t x = 0; x < Width; x++) {
867 			gfx_state.tg_shadow_fb[off + x] = *BltBuffer;
868 		}
869 	}
870 
871 	gfx_shadow_mark_dirty(DestinationX, DestinationY, Width, Height);
872 }
873 
874 /*
875  * Write a pixel buffer into the shadow framebuffer.
876  */
877 static void
878 gfxfb_shadow_buf_write(void *BltBuffer, uint32_t SourceX, uint32_t SourceY,
879     uint32_t DestinationX, uint32_t DestinationY,
880     uint32_t Width, uint32_t Height, uint32_t Delta)
881 {
882 	uint32_t fbW = gfx_state.tg_fb.fb_width;
883 	uint32_t sy, dy;
884 
885 	if (Delta == 0)
886 		Delta = Width * sizeof(*gfx_state.tg_shadow_fb);
887 
888 	for (sy = SourceY, dy = DestinationY; sy < SourceY + Height; sy++, dy++) {
889 		uint32_t *src = (uint32_t *)((uint8_t *)BltBuffer + sy * Delta) +
890 		    SourceX;
891 		uint32_t *dst = gfx_state.tg_shadow_fb + dy * fbW + DestinationX;
892 
893 		bcopy(src, dst, Width * sizeof(*gfx_state.tg_shadow_fb));
894 	}
895 
896 	gfx_shadow_mark_dirty(DestinationX, DestinationY, Width, Height);
897 }
898 
899 /*
900  * Copy a region within the shadow framebuffer.
901  */
902 static void
903 gfxfb_shadow_vid_to_vid(uint32_t SourceX, uint32_t SourceY,
904     uint32_t DestinationX, uint32_t DestinationY,
905     uint32_t Width, uint32_t Height)
906 {
907 	uint32_t fbW = gfx_state.tg_fb.fb_width;
908 	uint32_t h = Height;
909 	int step = 1;
910 	uint32_t sy = SourceY, dy = DestinationY;
911 
912 	if (dy * fbW + DestinationX > sy * fbW + SourceX) {
913 		sy += Height - 1;
914 		dy += Height - 1;
915 		step = -1;
916 	}
917 
918 	while (Height-- > 0) {
919 		bcopy(gfx_state.tg_shadow_fb + sy * fbW + SourceX,
920 		    gfx_state.tg_shadow_fb + dy * fbW + DestinationX,
921 		    Width * sizeof(*gfx_state.tg_shadow_fb));
922 		sy += step;
923 		dy += step;
924 	}
925 
926 	gfx_shadow_mark_dirty(DestinationX, DestinationY, Width, h);
927 }
928 
929 int
930 gfxfb_blt(void *BltBuffer, GFXFB_BLT_OPERATION BltOperation,
931     uint32_t SourceX, uint32_t SourceY,
932     uint32_t DestinationX, uint32_t DestinationY,
933     uint32_t Width, uint32_t Height, uint32_t Delta)
934 {
935 	int rv;
936 
937 	/*
938 	 * When a shadow framebuffer is present, redirect write operations into
939 	 * it regardless of the underlying display backend (EFI GOP or direct
940 	 * framebuffer).  The real video is updated in bulk by gfx_fb_flush()
941 	 * once a logical output operation is complete.
942 	 *
943 	 * Reads (VideoToBltBuffer) are intentionally NOT redirected to shadow:
944 	 * the shadow only contains pixels that have been explicitly written
945 	 * through it, so unwritten regions (e.g. firmware content already on
946 	 * screen at boot) would return stale or uninitialised data.  Instead,
947 	 * flush any pending shadow writes to video first so the
948 	 * backend-specific read below always sees the current framebuffer
949 	 * contents.
950 	 */
951 	if (gfx_state.tg_shadow_fb != NULL &&
952 	    BltOperation == GfxFbBltVideoToBltBuffer)
953 		gfx_fb_flush();
954 
955 	if (gfx_state.tg_shadow_fb != NULL &&
956 	    BltOperation != GfxFbBltVideoToBltBuffer) {
957 		switch (BltOperation) {
958 		case GfxFbBltVideoFill:
959 			gfxfb_shadow_fill(BltBuffer, DestinationX, DestinationY,
960 			    Width, Height);
961 			break;
962 
963 		case GfxFbBltBufferToVideo:
964 			gfxfb_shadow_buf_write(BltBuffer, SourceX, SourceY,
965 			    DestinationX, DestinationY, Width, Height, Delta);
966 			break;
967 
968 		case GfxFbBltVideoToVideo:
969 			gfxfb_shadow_vid_to_vid(SourceX, SourceY,
970 			    DestinationX, DestinationY, Width, Height);
971 			break;
972 
973 		default:
974 			return (EINVAL);
975 		}
976 		return (0);
977 	}
978 
979 #if defined(EFI)
980 	EFI_STATUS status;
981 	EFI_GRAPHICS_OUTPUT_PROTOCOL *gop;
982 	EFI_TPL tpl;
983 
984 	/*
985 	 * We assume Blt() does work, if not, we will need to build exception
986 	 * list case by case. We only have boot services during part of our
987 	 * exectution. Once terminate boot services, these operations cannot be
988 	 * done as they are provided by protocols that disappear when exit
989 	 * boot services.
990 	 */
991 	if (gfx_state.tg_fb_type == FB_GOP && !ignore_gop_blt &&
992 	    boot_services_active) {
993 		assert(gfx_state.tg_private != NULL);
994 		gop = gfx_state.tg_private;
995 		tpl = BS->RaiseTPL(TPL_NOTIFY);
996 		switch (BltOperation) {
997 		case GfxFbBltVideoFill:
998 			status = gop->Blt(gop, BltBuffer, EfiBltVideoFill,
999 			    SourceX, SourceY, DestinationX, DestinationY,
1000 			    Width, Height, Delta);
1001 			break;
1002 
1003 		case GfxFbBltVideoToBltBuffer:
1004 			status = gop->Blt(gop, BltBuffer,
1005 			    EfiBltVideoToBltBuffer,
1006 			    SourceX, SourceY, DestinationX, DestinationY,
1007 			    Width, Height, Delta);
1008 			break;
1009 
1010 		case GfxFbBltBufferToVideo:
1011 			status = gop->Blt(gop, BltBuffer, EfiBltBufferToVideo,
1012 			    SourceX, SourceY, DestinationX, DestinationY,
1013 			    Width, Height, Delta);
1014 			break;
1015 
1016 		case GfxFbBltVideoToVideo:
1017 			status = gop->Blt(gop, BltBuffer, EfiBltVideoToVideo,
1018 			    SourceX, SourceY, DestinationX, DestinationY,
1019 			    Width, Height, Delta);
1020 			break;
1021 
1022 		default:
1023 			status = EFI_INVALID_PARAMETER;
1024 			break;
1025 		}
1026 
1027 		switch (status) {
1028 		case EFI_SUCCESS:
1029 			rv = 0;
1030 			break;
1031 
1032 		case EFI_INVALID_PARAMETER:
1033 			rv = EINVAL;
1034 			break;
1035 
1036 		case EFI_DEVICE_ERROR:
1037 		default:
1038 			rv = EIO;
1039 			break;
1040 		}
1041 
1042 		BS->RestoreTPL(tpl);
1043 		return (rv);
1044 	}
1045 #endif
1046 
1047 	switch (BltOperation) {
1048 	case GfxFbBltVideoFill:
1049 		rv = gfxfb_blt_fill(BltBuffer, DestinationX, DestinationY,
1050 		    Width, Height);
1051 		break;
1052 
1053 	case GfxFbBltVideoToBltBuffer:
1054 		rv = gfxfb_blt_video_to_buffer(BltBuffer, SourceX, SourceY,
1055 		    DestinationX, DestinationY, Width, Height, Delta);
1056 		break;
1057 
1058 	case GfxFbBltBufferToVideo:
1059 		rv = gfxfb_blt_buffer_to_video(BltBuffer, SourceX, SourceY,
1060 		    DestinationX, DestinationY, Width, Height, Delta);
1061 		break;
1062 
1063 	case GfxFbBltVideoToVideo:
1064 		rv = gfxfb_blt_video_to_video(SourceX, SourceY,
1065 		    DestinationX, DestinationY, Width, Height);
1066 		break;
1067 
1068 	default:
1069 		rv = EINVAL;
1070 		break;
1071 	}
1072 	return (rv);
1073 }
1074 
1075 /*
1076  * Flush the dirty region of the shadow framebuffer to the real framebuffer.
1077  * Must be called after each logical output operation when shadow fb is in use.
1078  */
1079 void
1080 gfx_fb_flush(void)
1081 {
1082 	uint32_t x, y, w, h, pitch;
1083 
1084 	if (gfx_state.tg_shadow_fb == NULL || !gfx_state.tg_dirty ||
1085 	    gfx_state.tg_fb_type == FB_TEXT)
1086 		return;
1087 
1088 	x = gfx_state.tg_dirty_x1;
1089 	y = gfx_state.tg_dirty_y1;
1090 	pitch = gfx_state.tg_fb.fb_width;
1091 
1092 	if (x >= pitch || y >= gfx_state.tg_fb.fb_height)
1093 		goto done;
1094 
1095 	w = gfx_state.tg_dirty_x2 - x;
1096 	h = gfx_state.tg_dirty_y2 - y;
1097 
1098 	if (x + w > pitch)
1099 		w = pitch - x;
1100 	if (y + h > gfx_state.tg_fb.fb_height)
1101 		h = gfx_state.tg_fb.fb_height - y;
1102 
1103 #if defined(EFI)
1104 	if (gfx_state.tg_fb_type == FB_GOP && !ignore_gop_blt &&
1105 	    boot_services_active) {
1106 		EFI_GRAPHICS_OUTPUT_PROTOCOL *gop = gfx_state.tg_private;
1107 		EFI_TPL tpl;
1108 
1109 		assert(gop != NULL);
1110 		tpl = BS->RaiseTPL(TPL_NOTIFY);
1111 		(void) gop->Blt(gop,
1112 		    (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *)gfx_state.tg_shadow_fb,
1113 		    EfiBltBufferToVideo, x, y, x, y, w, h,
1114 		    pitch * sizeof(*gfx_state.tg_shadow_fb));
1115 		BS->RestoreTPL(tpl);
1116 		goto done;
1117 	}
1118 #endif
1119 	(void) gfxfb_blt_buffer_to_video(gfx_state.tg_shadow_fb,
1120 	    x, y, x, y, w, h, pitch * sizeof(*gfx_state.tg_shadow_fb));
1121 
1122 done:
1123 	gfx_state.tg_dirty = false;
1124 }
1125 
1126 void
1127 gfx_bitblt_bitmap(teken_gfx_t *state, const uint8_t *glyph,
1128     const teken_attr_t *a, uint32_t alpha, bool cursor)
1129 {
1130 	uint32_t width, height;
1131 	uint32_t fgc, bgc, bpl, cc, o;
1132 	int bpp, bit, byte;
1133 	bool invert = false;
1134 
1135 	bpp = 4;		/* We only generate BGRA */
1136 	width = state->tg_font.vf_width;
1137 	height = state->tg_font.vf_height;
1138 	bpl = (width + 7) / 8;  /* Bytes per source line. */
1139 
1140 	fgc = a->ta_fgcolor;
1141 	bgc = a->ta_bgcolor;
1142 	if (a->ta_format & TF_BOLD)
1143 		fgc |= TC_LIGHT;
1144 	if (a->ta_format & TF_BLINK)
1145 		bgc |= TC_LIGHT;
1146 
1147 	fgc = gfx_fb_color_map(fgc);
1148 	bgc = gfx_fb_color_map(bgc);
1149 
1150 	if (a->ta_format & TF_REVERSE)
1151 		invert = !invert;
1152 	if (cursor)
1153 		invert = !invert;
1154 	if (invert) {
1155 		uint32_t tmp;
1156 
1157 		tmp = fgc;
1158 		fgc = bgc;
1159 		bgc = tmp;
1160 	}
1161 
1162 	alpha = alpha << 24;
1163 	fgc |= alpha;
1164 	bgc |= alpha;
1165 
1166 	for (uint32_t y = 0; y < height; y++) {
1167 		for (uint32_t x = 0; x < width; x++) {
1168 			byte = y * bpl + x / 8;
1169 			bit = 0x80 >> (x % 8);
1170 			o = y * width * bpp + x * bpp;
1171 			cc = glyph[byte] & bit ? fgc : bgc;
1172 
1173 			gfx_mem_wr4(state->tg_glyph,
1174 			    state->tg_glyph_size, o, cc);
1175 		}
1176 	}
1177 }
1178 
1179 /*
1180  * Draw prepared glyph on terminal point p.
1181  */
1182 static void
1183 gfx_fb_printchar(teken_gfx_t *state, const teken_pos_t *p)
1184 {
1185 	unsigned x, y, width, height;
1186 
1187 	width = state->tg_font.vf_width;
1188 	height = state->tg_font.vf_height;
1189 	x = state->tg_origin.tp_col + p->tp_col * width;
1190 	y = state->tg_origin.tp_row + p->tp_row * height;
1191 
1192 	gfx_fb_cons_display(x, y, width, height, state->tg_glyph);
1193 }
1194 
1195 /*
1196  * Store char with its attribute to buffer and put it on screen.
1197  */
1198 void
1199 gfx_fb_putchar(void *arg, const teken_pos_t *p, teken_char_t c,
1200     const teken_attr_t *a)
1201 {
1202 	teken_gfx_t *state = arg;
1203 	const uint8_t *glyph;
1204 	int idx;
1205 
1206 	idx = p->tp_col + p->tp_row * state->tg_tp.tp_col;
1207 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
1208 		return;
1209 
1210 	/* remove the cursor */
1211 	if (state->tg_cursor_visible)
1212 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1213 
1214 	screen_buffer[idx].c = c;
1215 	screen_buffer[idx].a = *a;
1216 
1217 	glyph = font_lookup(&state->tg_font, c, a);
1218 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
1219 	gfx_fb_printchar(state, p);
1220 
1221 	/* display the cursor */
1222 	if (state->tg_cursor_visible) {
1223 		const teken_pos_t *c;
1224 
1225 		c = teken_get_cursor(&state->tg_teken);
1226 		gfx_fb_cursor_draw(state, c, true);
1227 	}
1228 
1229 	gfx_fb_flush();
1230 }
1231 
1232 void
1233 gfx_fb_fill(void *arg, const teken_rect_t *r, teken_char_t c,
1234     const teken_attr_t *a)
1235 {
1236 	teken_gfx_t *state = arg;
1237 	const uint8_t *glyph;
1238 	teken_pos_t p;
1239 	struct text_pixel *row;
1240 
1241 	TSENTER();
1242 
1243 	/* remove the cursor */
1244 	if (state->tg_cursor_visible)
1245 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1246 
1247 	glyph = font_lookup(&state->tg_font, c, a);
1248 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
1249 
1250 	for (p.tp_row = r->tr_begin.tp_row; p.tp_row < r->tr_end.tp_row;
1251 	    p.tp_row++) {
1252 		row = &screen_buffer[p.tp_row * state->tg_tp.tp_col];
1253 		for (p.tp_col = r->tr_begin.tp_col;
1254 		    p.tp_col < r->tr_end.tp_col; p.tp_col++) {
1255 			row[p.tp_col].c = c;
1256 			row[p.tp_col].a = *a;
1257 			gfx_fb_printchar(state, &p);
1258 		}
1259 	}
1260 
1261 	/* display the cursor */
1262 	if (state->tg_cursor_visible) {
1263 		const teken_pos_t *c;
1264 
1265 		c = teken_get_cursor(&state->tg_teken);
1266 		gfx_fb_cursor_draw(state, c, true);
1267 	}
1268 
1269 	gfx_fb_flush();
1270 	TSEXIT();
1271 }
1272 
1273 static void
1274 gfx_fb_cursor_draw(teken_gfx_t *state, const teken_pos_t *pos, bool on)
1275 {
1276 	const uint8_t *glyph;
1277 	teken_pos_t p;
1278 	int idx;
1279 
1280 	p = *pos;
1281 	if (p.tp_col >= state->tg_tp.tp_col)
1282 		p.tp_col = state->tg_tp.tp_col - 1;
1283 	if (p.tp_row >= state->tg_tp.tp_row)
1284 		p.tp_row = state->tg_tp.tp_row - 1;
1285 	idx = p.tp_col + p.tp_row * state->tg_tp.tp_col;
1286 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
1287 		return;
1288 
1289 	glyph = font_lookup(&state->tg_font, screen_buffer[idx].c,
1290 	    &screen_buffer[idx].a);
1291 	gfx_bitblt_bitmap(state, glyph, &screen_buffer[idx].a, 0xff, on);
1292 	gfx_fb_printchar(state, &p);
1293 
1294 	state->tg_cursor = p;
1295 }
1296 
1297 void
1298 gfx_fb_cursor(void *arg, const teken_pos_t *p)
1299 {
1300 	teken_gfx_t *state = arg;
1301 
1302 	/* Switch cursor off in old location and back on in new. */
1303 	if (state->tg_cursor_visible) {
1304 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1305 		gfx_fb_cursor_draw(state, p, true);
1306 		gfx_fb_flush();
1307 	}
1308 }
1309 
1310 void
1311 gfx_fb_param(void *arg, int cmd, unsigned int value)
1312 {
1313 	teken_gfx_t *state = arg;
1314 	const teken_pos_t *c;
1315 
1316 	switch (cmd) {
1317 	case TP_SETLOCALCURSOR:
1318 		/*
1319 		 * 0 means normal (usually block), 1 means hidden, and
1320 		 * 2 means blinking (always block) for compatibility with
1321 		 * syscons.  We don't support any changes except hiding,
1322 		 * so must map 2 to 0.
1323 		 */
1324 		value = (value == 1) ? 0 : 1;
1325 		/* FALLTHROUGH */
1326 	case TP_SHOWCURSOR:
1327 		c = teken_get_cursor(&state->tg_teken);
1328 		gfx_fb_cursor_draw(state, c, true);
1329 		if (value != 0)
1330 			state->tg_cursor_visible = true;
1331 		else
1332 			state->tg_cursor_visible = false;
1333 		gfx_fb_flush();
1334 		break;
1335 	default:
1336 		/* Not yet implemented */
1337 		break;
1338 	}
1339 }
1340 
1341 bool
1342 is_same_pixel(struct text_pixel *px1, struct text_pixel *px2)
1343 {
1344 	if (px1->c != px2->c)
1345 		return (false);
1346 
1347 	/* Is there image stored? */
1348 	if ((px1->a.ta_format & TF_IMAGE) ||
1349 	    (px2->a.ta_format & TF_IMAGE))
1350 		return (false);
1351 
1352 	if (px1->a.ta_format != px2->a.ta_format)
1353 		return (false);
1354 	if (px1->a.ta_fgcolor != px2->a.ta_fgcolor)
1355 		return (false);
1356 	if (px1->a.ta_bgcolor != px2->a.ta_bgcolor)
1357 		return (false);
1358 
1359 	return (true);
1360 }
1361 
1362 static void
1363 gfx_fb_copy_area(teken_gfx_t *state, const teken_rect_t *s,
1364     const teken_pos_t *d)
1365 {
1366 	uint32_t sx, sy, dx, dy, width, height;
1367 	uint32_t pitch, bytes;
1368 	int step;
1369 
1370 	width = state->tg_font.vf_width;
1371 	height = state->tg_font.vf_height;
1372 
1373 	sx = s->tr_begin.tp_col * width;
1374 	sy = s->tr_begin.tp_row * height;
1375 	dx = d->tp_col * width;
1376 	dy = d->tp_row * height;
1377 
1378 	width *= (s->tr_end.tp_col - s->tr_begin.tp_col + 1);
1379 
1380 	/*
1381 	 * With no shadow fb, use video to video copy directly.
1382 	 */
1383 	if (state->tg_shadow_fb == NULL) {
1384 		(void) gfxfb_blt(NULL, GfxFbBltVideoToVideo,
1385 		    sx + state->tg_origin.tp_col,
1386 		    sy + state->tg_origin.tp_row,
1387 		    dx + state->tg_origin.tp_col,
1388 		    dy + state->tg_origin.tp_row,
1389 		    width, height, 0);
1390 		return;
1391 	}
1392 
1393 	/*
1394 	 * With shadow fb, copy within shadow only.  Every region that could
1395 	 * be the source of a copy was previously drawn through the shadow, so
1396 	 * reading from it here is always valid.  Mark the destination dirty so
1397 	 * gfx_fb_flush() will push it to the real framebuffer.
1398 	 */
1399 	step = 1;
1400 	pitch = state->tg_fb.fb_width;
1401 	bytes = width * sizeof (*state->tg_shadow_fb);
1402 
1403 	uint32_t dst_x = dx + state->tg_origin.tp_col;
1404 	uint32_t dst_y = dy + state->tg_origin.tp_row;
1405 	uint32_t dst_h = height;
1406 
1407 	/*
1408 	 * To handle overlapping areas, set up reverse copy here.
1409 	 */
1410 	if (dy * pitch + dx > sy * pitch + sx) {
1411 		sy += height;
1412 		dy += height;
1413 		step = -step;
1414 	}
1415 
1416 	while (height-- > 0) {
1417 		uint32_t *source = &state->tg_shadow_fb[sy * pitch + sx];
1418 		uint32_t *destination = &state->tg_shadow_fb[dy * pitch + dx];
1419 
1420 		bcopy(source, destination, bytes);
1421 		sy += step;
1422 		dy += step;
1423 	}
1424 
1425 	gfx_shadow_mark_dirty(dst_x, dst_y, width, dst_h);
1426 }
1427 
1428 static void
1429 gfx_fb_copy_line(teken_gfx_t *state, int ncol, teken_pos_t *s, teken_pos_t *d)
1430 {
1431 	teken_rect_t sr;
1432 	teken_pos_t dp;
1433 	unsigned soffset, doffset;
1434 	bool mark = false;
1435 	int x;
1436 
1437 	soffset = s->tp_col + s->tp_row * state->tg_tp.tp_col;
1438 	doffset = d->tp_col + d->tp_row * state->tg_tp.tp_col;
1439 
1440 	for (x = 0; x < ncol; x++) {
1441 		if (is_same_pixel(&screen_buffer[soffset + x],
1442 		    &screen_buffer[doffset + x])) {
1443 			if (mark) {
1444 				gfx_fb_copy_area(state, &sr, &dp);
1445 				mark = false;
1446 			}
1447 		} else {
1448 			screen_buffer[doffset + x] = screen_buffer[soffset + x];
1449 			if (mark) {
1450 				/* update end point */
1451 				sr.tr_end.tp_col = s->tp_col + x;
1452 			} else {
1453 				/* set up new rectangle */
1454 				mark = true;
1455 				sr.tr_begin.tp_col = s->tp_col + x;
1456 				sr.tr_begin.tp_row = s->tp_row;
1457 				sr.tr_end.tp_col = s->tp_col + x;
1458 				sr.tr_end.tp_row = s->tp_row;
1459 				dp.tp_col = d->tp_col + x;
1460 				dp.tp_row = d->tp_row;
1461 			}
1462 		}
1463 	}
1464 	if (mark) {
1465 		gfx_fb_copy_area(state, &sr, &dp);
1466 	}
1467 }
1468 
1469 void
1470 gfx_fb_copy(void *arg, const teken_rect_t *r, const teken_pos_t *p)
1471 {
1472 	teken_gfx_t *state = arg;
1473 	unsigned doffset, soffset;
1474 	teken_pos_t d, s;
1475 	int nrow, ncol, y; /* Has to be signed - >= 0 comparison */
1476 
1477 	/*
1478 	 * Copying is a little tricky. We must make sure we do it in
1479 	 * correct order, to make sure we don't overwrite our own data.
1480 	 */
1481 
1482 	nrow = r->tr_end.tp_row - r->tr_begin.tp_row;
1483 	ncol = r->tr_end.tp_col - r->tr_begin.tp_col;
1484 
1485 	if (p->tp_row + nrow > state->tg_tp.tp_row ||
1486 	    p->tp_col + ncol > state->tg_tp.tp_col)
1487 		return;
1488 
1489 	soffset = r->tr_begin.tp_col + r->tr_begin.tp_row * state->tg_tp.tp_col;
1490 	doffset = p->tp_col + p->tp_row * state->tg_tp.tp_col;
1491 
1492 	/* remove the cursor */
1493 	if (state->tg_cursor_visible)
1494 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1495 
1496 	/*
1497 	 * Copy line by line.
1498 	 */
1499 	if (doffset <= soffset) {
1500 		s = r->tr_begin;
1501 		d = *p;
1502 		for (y = 0; y < nrow; y++) {
1503 			s.tp_row = r->tr_begin.tp_row + y;
1504 			d.tp_row = p->tp_row + y;
1505 
1506 			gfx_fb_copy_line(state, ncol, &s, &d);
1507 		}
1508 	} else {
1509 		for (y = nrow - 1; y >= 0; y--) {
1510 			s.tp_row = r->tr_begin.tp_row + y;
1511 			d.tp_row = p->tp_row + y;
1512 
1513 			gfx_fb_copy_line(state, ncol, &s, &d);
1514 		}
1515 	}
1516 
1517 	/* display the cursor */
1518 	if (state->tg_cursor_visible) {
1519 		const teken_pos_t *c;
1520 
1521 		c = teken_get_cursor(&state->tg_teken);
1522 		gfx_fb_cursor_draw(state, c, true);
1523 	}
1524 
1525 	gfx_fb_flush();
1526 }
1527 
1528 /*
1529  * Implements alpha blending for RGBA data, could use pixels for arguments,
1530  * but byte stream seems more generic.
1531  * The generic alpha blending is:
1532  * blend = alpha * fg + (1.0 - alpha) * bg.
1533  * Since our alpha is not from range [0..1], we scale appropriately.
1534  */
1535 static uint8_t
1536 alpha_blend(uint8_t fg, uint8_t bg, uint8_t alpha)
1537 {
1538 	uint16_t blend, h, l;
1539 
1540 	/* trivial corner cases */
1541 	if (alpha == 0)
1542 		return (bg);
1543 	if (alpha == 0xFF)
1544 		return (fg);
1545 	blend = (alpha * fg + (0xFF - alpha) * bg);
1546 	/* Division by 0xFF */
1547 	h = blend >> 8;
1548 	l = blend & 0xFF;
1549 	if (h + l >= 0xFF)
1550 		h++;
1551 	return (h);
1552 }
1553 
1554 /*
1555  * Implements alpha blending for RGBA data, could use pixels for arguments,
1556  * but byte stream seems more generic.
1557  * The generic alpha blending is:
1558  * blend = alpha * fg + (1.0 - alpha) * bg.
1559  * Since our alpha is not from range [0..1], we scale appropriately.
1560  */
1561 static void
1562 bitmap_cpy(void *dst, void *src, uint32_t size)
1563 {
1564 #if defined(EFI)
1565 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *ps, *pd;
1566 #else
1567 	struct paletteentry *ps, *pd;
1568 #endif
1569 	uint32_t i;
1570 	uint8_t a;
1571 
1572 	ps = src;
1573 	pd = dst;
1574 
1575 	/*
1576 	 * we only implement alpha blending for depth 32.
1577 	 */
1578 	for (i = 0; i < size; i ++) {
1579 		a = ps[i].Reserved;
1580 		pd[i].Red = alpha_blend(ps[i].Red, pd[i].Red, a);
1581 		pd[i].Green = alpha_blend(ps[i].Green, pd[i].Green, a);
1582 		pd[i].Blue = alpha_blend(ps[i].Blue, pd[i].Blue, a);
1583 		pd[i].Reserved = a;
1584 	}
1585 }
1586 
1587 static void *
1588 allocate_glyphbuffer(uint32_t width, uint32_t height)
1589 {
1590 	size_t size;
1591 
1592 	size = sizeof (*GlyphBuffer) * width * height;
1593 	if (size != GlyphBufferSize) {
1594 		free(GlyphBuffer);
1595 		GlyphBuffer = malloc(size);
1596 		if (GlyphBuffer == NULL)
1597 			return (NULL);
1598 		GlyphBufferSize = size;
1599 	}
1600 	return (GlyphBuffer);
1601 }
1602 
1603 void
1604 gfx_fb_cons_display(uint32_t x, uint32_t y, uint32_t width, uint32_t height,
1605     void *data)
1606 {
1607 #if defined(EFI)
1608 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *buf, *p;
1609 #else
1610 	struct paletteentry *buf, *p;
1611 #endif
1612 	size_t size;
1613 
1614 	/*
1615 	 * If we do have shadow fb, render into it only.  The caller is
1616 	 * responsible for flushing the dirty region to the real framebuffer
1617 	 * via gfx_fb_flush() once a logical output operation is complete.
1618 	 */
1619 	if (gfx_state.tg_shadow_fb != NULL) {
1620 		uint32_t pitch = gfx_state.tg_fb.fb_width;
1621 		uint32_t sy = y - gfx_state.tg_origin.tp_row;
1622 		uint32_t sx = x - gfx_state.tg_origin.tp_col;
1623 
1624 		p = data;
1625 		for (uint32_t row = 0; row < height; row++) {
1626 			buf = (void *)(gfx_state.tg_shadow_fb +
1627 			    (sy + row) * pitch + sx);
1628 			bitmap_cpy(buf, &p[row * width], width);
1629 		}
1630 		gfx_shadow_mark_dirty(x, y, width, height);
1631 		return;
1632 	}
1633 
1634 	/*
1635 	 * Common data to display is glyph, use preallocated
1636 	 * glyph buffer.
1637 	 */
1638         if (gfx_state.tg_glyph_size != GlyphBufferSize)
1639                 (void) allocate_glyphbuffer(width, height);
1640 
1641 	size = width * height * sizeof(*buf);
1642 	if (size == GlyphBufferSize)
1643 		buf = GlyphBuffer;
1644 	else
1645 		buf = malloc(size);
1646 	if (buf == NULL)
1647 		return;
1648 
1649 	if (gfxfb_blt(buf, GfxFbBltVideoToBltBuffer, x, y, 0, 0,
1650 	    width, height, 0) == 0) {
1651 		bitmap_cpy(buf, data, width * height);
1652 		(void) gfxfb_blt(buf, GfxFbBltBufferToVideo, 0, 0, x, y,
1653 		    width, height, 0);
1654 	}
1655 	if (buf != GlyphBuffer)
1656 		free(buf);
1657 }
1658 
1659 /*
1660  * Public graphics primitives.
1661  */
1662 
1663 static int
1664 isqrt(int num)
1665 {
1666 	int res = 0;
1667 	int bit = 1 << 30;
1668 
1669 	/* "bit" starts at the highest power of four <= the argument. */
1670 	while (bit > num)
1671 		bit >>= 2;
1672 
1673 	while (bit != 0) {
1674 		if (num >= res + bit) {
1675 			num -= res + bit;
1676 			res = (res >> 1) + bit;
1677 		} else {
1678 			res >>= 1;
1679 		}
1680 		bit >>= 2;
1681 	}
1682 	return (res);
1683 }
1684 
1685 static uint32_t
1686 gfx_fb_getcolor(void)
1687 {
1688 	uint32_t c;
1689 	const teken_attr_t *ap;
1690 
1691 	ap = teken_get_curattr(&gfx_state.tg_teken);
1692         if (ap->ta_format & TF_REVERSE) {
1693 		c = ap->ta_bgcolor;
1694 		if (ap->ta_format & TF_BLINK)
1695 			c |= TC_LIGHT;
1696 	} else {
1697 		c = ap->ta_fgcolor;
1698 		if (ap->ta_format & TF_BOLD)
1699 			c |= TC_LIGHT;
1700 	}
1701 
1702 	return (gfx_fb_color_map(c));
1703 }
1704 
1705 /* set pixel in framebuffer using gfx coordinates */
1706 void
1707 gfx_fb_setpixel(uint32_t x, uint32_t y)
1708 {
1709 	uint32_t c;
1710 
1711 	if (gfx_state.tg_fb_type == FB_TEXT)
1712 		return;
1713 
1714 	c = gfx_fb_getcolor();
1715 
1716 	if (x >= gfx_state.tg_fb.fb_width ||
1717 	    y >= gfx_state.tg_fb.fb_height)
1718 		return;
1719 
1720 	gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x, y, 1, 1, 0);
1721 }
1722 
1723 /*
1724  * draw rectangle in framebuffer using gfx coordinates.
1725  */
1726 void
1727 gfx_fb_drawrect(uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2,
1728     uint32_t fill)
1729 {
1730 	uint32_t c;
1731 
1732 	if (gfx_state.tg_fb_type == FB_TEXT)
1733 		return;
1734 
1735 	c = gfx_fb_getcolor();
1736 
1737 	if (fill != 0) {
1738 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1,
1739 		    y2 - y1, 0);
1740 	} else {
1741 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1, 1, 0);
1742 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y2, x2 - x1, 1, 0);
1743 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, 1, y2 - y1, 0);
1744 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x2, y1, 1, y2 - y1, 0);
1745 	}
1746 	gfx_fb_flush();
1747 }
1748 
1749 void
1750 gfx_fb_line(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t wd)
1751 {
1752 	int dx, sx, dy, sy;
1753 	int err, e2, x2, y2, ed, width;
1754 
1755 	if (gfx_state.tg_fb_type == FB_TEXT)
1756 		return;
1757 
1758 	width = wd;
1759 	sx = x0 < x1? 1 : -1;
1760 	sy = y0 < y1? 1 : -1;
1761 	dx = x1 > x0? x1 - x0 : x0 - x1;
1762 	dy = y1 > y0? y1 - y0 : y0 - y1;
1763 	err = dx + dy;
1764 	ed = dx + dy == 0 ? 1: isqrt(dx * dx + dy * dy);
1765 
1766 	for (;;) {
1767 		gfx_fb_setpixel(x0, y0);
1768 		e2 = err;
1769 		x2 = x0;
1770 		if ((e2 << 1) >= -dx) {		/* x step */
1771 			e2 += dy;
1772 			y2 = y0;
1773 			while (e2 < ed * width &&
1774 			    (y1 != (uint32_t)y2 || dx > dy)) {
1775 				y2 += sy;
1776 				gfx_fb_setpixel(x0, y2);
1777 				e2 += dx;
1778 			}
1779 			if (x0 == x1)
1780 				break;
1781 			e2 = err;
1782 			err -= dy;
1783 			x0 += sx;
1784 		}
1785 		if ((e2 << 1) <= dy) {		/* y step */
1786 			e2 = dx-e2;
1787 			while (e2 < ed * width &&
1788 			    (x1 != (uint32_t)x2 || dx < dy)) {
1789 				x2 += sx;
1790 				gfx_fb_setpixel(x2, y0);
1791 				e2 += dy;
1792 			}
1793 			if (y0 == y1)
1794 				break;
1795 			err += dx;
1796 			y0 += sy;
1797 		}
1798 	}
1799 	gfx_fb_flush();
1800 }
1801 
1802 /*
1803  * quadratic Bézier curve limited to gradients without sign change.
1804  */
1805 void
1806 gfx_fb_bezier(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t x2,
1807     uint32_t y2, uint32_t wd)
1808 {
1809 	int sx, sy, xx, yy, xy, width;
1810 	int dx, dy, err, curvature;
1811 	int i;
1812 
1813 	if (gfx_state.tg_fb_type == FB_TEXT)
1814 		return;
1815 
1816 	width = wd;
1817 	sx = x2 - x1;
1818 	sy = y2 - y1;
1819 	xx = x0 - x1;
1820 	yy = y0 - y1;
1821 	curvature = xx*sy - yy*sx;
1822 
1823 	if (sx*sx + sy*sy > xx*xx+yy*yy) {
1824 		x2 = x0;
1825 		x0 = sx + x1;
1826 		y2 = y0;
1827 		y0 = sy + y1;
1828 		curvature = -curvature;
1829 	}
1830 	if (curvature != 0) {
1831 		xx += sx;
1832 		sx = x0 < x2? 1 : -1;
1833 		xx *= sx;
1834 		yy += sy;
1835 		sy = y0 < y2? 1 : -1;
1836 		yy *= sy;
1837 		xy = (xx*yy) << 1;
1838 		xx *= xx;
1839 		yy *= yy;
1840 		if (curvature * sx * sy < 0) {
1841 			xx = -xx;
1842 			yy = -yy;
1843 			xy = -xy;
1844 			curvature = -curvature;
1845 		}
1846 		dx = 4 * sy * curvature * (x1 - x0) + xx - xy;
1847 		dy = 4 * sx * curvature * (y0 - y1) + yy - xy;
1848 		xx += xx;
1849 		yy += yy;
1850 		err = dx + dy + xy;
1851 		do {
1852 			for (i = 0; i <= width; i++)
1853 				gfx_fb_setpixel(x0 + i, y0);
1854 			if (x0 == x2 && y0 == y2)
1855 				return;  /* last pixel -> curve finished */
1856 			y1 = 2 * err < dx;
1857 			if (2 * err > dy) {
1858 				x0 += sx;
1859 				dx -= xy;
1860 				dy += yy;
1861 				err += dy;
1862 			}
1863 			if (y1 != 0) {
1864 				y0 += sy;
1865 				dy -= xy;
1866 				dx += xx;
1867 				err += dx;
1868 			}
1869 		} while (dy < dx); /* gradient negates -> algorithm fails */
1870 	}
1871 	gfx_fb_line(x0, y0, x2, y2, width);
1872 	gfx_fb_flush();
1873 }
1874 
1875 /*
1876  * draw rectangle using terminal coordinates and current foreground color.
1877  */
1878 void
1879 gfx_term_drawrect(uint32_t ux1, uint32_t uy1, uint32_t ux2, uint32_t uy2)
1880 {
1881 	int x1, y1, x2, y2;
1882 	int xshift, yshift;
1883 	int width, i;
1884 	uint32_t vf_width, vf_height;
1885 	teken_rect_t r;
1886 
1887 	if (gfx_state.tg_fb_type == FB_TEXT)
1888 		return;
1889 
1890 	vf_width = gfx_state.tg_font.vf_width;
1891 	vf_height = gfx_state.tg_font.vf_height;
1892 	width = vf_width / 4;			/* line width */
1893 	xshift = (vf_width - width) / 2;
1894 	yshift = (vf_height - width) / 2;
1895 
1896 	/* Shift coordinates */
1897 	if (ux1 != 0)
1898 		ux1--;
1899 	if (uy1 != 0)
1900 		uy1--;
1901 	ux2--;
1902 	uy2--;
1903 
1904 	/* mark area used in terminal */
1905 	r.tr_begin.tp_col = ux1;
1906 	r.tr_begin.tp_row = uy1;
1907 	r.tr_end.tp_col = ux2 + 1;
1908 	r.tr_end.tp_row = uy2 + 1;
1909 
1910 	term_image_display(&gfx_state, &r);
1911 
1912 	/*
1913 	 * Draw horizontal lines width points thick, shifted from outer edge.
1914 	 */
1915 	x1 = (ux1 + 1) * vf_width + gfx_state.tg_origin.tp_col;
1916 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1917 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1918 	gfx_fb_drawrect(x1, y1, x2, y1 + width, 1);
1919 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1920 	y2 += vf_height - yshift - width;
1921 	gfx_fb_drawrect(x1, y2, x2, y2 + width, 1);
1922 
1923 	/*
1924 	 * Draw vertical lines width points thick, shifted from outer edge.
1925 	 */
1926 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1927 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1928 	y1 += vf_height;
1929 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1930 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1931 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1932 	x1 += vf_width - xshift - width;
1933 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1934 
1935 	/* Draw upper left corner. */
1936 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1937 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1938 	y1 += vf_height;
1939 
1940 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1941 	x2 += vf_width;
1942 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1943 	for (i = 0; i <= width; i++)
1944 		gfx_fb_bezier(x1 + i, y1, x1 + i, y2 + i, x2, y2 + i, width-i);
1945 
1946 	/* Draw lower left corner. */
1947 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1948 	x1 += vf_width;
1949 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1950 	y1 += vf_height - yshift;
1951 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1952 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1953 	for (i = 0; i <= width; i++)
1954 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1955 
1956 	/* Draw upper right corner. */
1957 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1958 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1959 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1960 	x2 += vf_width - xshift - width;
1961 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1962 	y2 += vf_height;
1963 	for (i = 0; i <= width; i++)
1964 		gfx_fb_bezier(x1, y1 + i, x2 + i, y1 + i, x2 + i, y2, width-i);
1965 
1966 	/* Draw lower right corner. */
1967 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1968 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1969 	y1 += vf_height - yshift;
1970 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1971 	x2 += vf_width - xshift - width;
1972 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1973 	for (i = 0; i <= width; i++)
1974 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1975 }
1976 
1977 int
1978 gfx_fb_putimage(png_t *png, uint32_t ux1, uint32_t uy1, uint32_t ux2,
1979     uint32_t uy2, uint32_t flags)
1980 {
1981 #if defined(EFI)
1982 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
1983 #else
1984 	struct paletteentry *p;
1985 #endif
1986 	uint8_t *data;
1987 	uint32_t i, j, x, y, fheight, fwidth;
1988 	int rs, gs, bs;
1989 	uint8_t r, g, b, a;
1990 	bool scale = false;
1991 	bool trace = false;
1992 	teken_rect_t rect;
1993 
1994 	trace = (flags & FL_PUTIMAGE_DEBUG) != 0;
1995 
1996 	if (gfx_state.tg_fb_type == FB_TEXT) {
1997 		if (trace)
1998 			printf("Framebuffer not active.\n");
1999 		return (1);
2000 	}
2001 
2002 	if (png->color_type != PNG_TRUECOLOR_ALPHA) {
2003 		if (trace)
2004 			printf("Not truecolor image.\n");
2005 		return (1);
2006 	}
2007 
2008 	if (ux1 > gfx_state.tg_fb.fb_width ||
2009 	    uy1 > gfx_state.tg_fb.fb_height) {
2010 		if (trace)
2011 			printf("Top left coordinate off screen.\n");
2012 		return (1);
2013 	}
2014 
2015 	if (png->width > UINT16_MAX || png->height > UINT16_MAX) {
2016 		if (trace)
2017 			printf("Image too large.\n");
2018 		return (1);
2019 	}
2020 
2021 	if (png->width < 1 || png->height < 1) {
2022 		if (trace)
2023 			printf("Image too small.\n");
2024 		return (1);
2025 	}
2026 
2027 	/*
2028 	 * If 0 was passed for either ux2 or uy2, then calculate the missing
2029 	 * part of the bottom right coordinate.
2030 	 */
2031 	scale = true;
2032 	if (ux2 == 0 && uy2 == 0) {
2033 		/* Both 0, use the native resolution of the image */
2034 		ux2 = ux1 + png->width;
2035 		uy2 = uy1 + png->height;
2036 		scale = false;
2037 	} else if (ux2 == 0) {
2038 		/* Set ux2 from uy2/uy1 to maintain aspect ratio */
2039 		ux2 = ux1 + (png->width * (uy2 - uy1)) / png->height;
2040 	} else if (uy2 == 0) {
2041 		/* Set uy2 from ux2/ux1 to maintain aspect ratio */
2042 		uy2 = uy1 + (png->height * (ux2 - ux1)) / png->width;
2043 	}
2044 
2045 	if (ux2 > gfx_state.tg_fb.fb_width ||
2046 	    uy2 > gfx_state.tg_fb.fb_height) {
2047 		if (trace)
2048 			printf("Bottom right coordinate off screen.\n");
2049 		return (1);
2050 	}
2051 
2052 	fwidth = ux2 - ux1;
2053 	fheight = uy2 - uy1;
2054 
2055 	/*
2056 	 * If the original image dimensions have been passed explicitly,
2057 	 * disable scaling.
2058 	 */
2059 	if (fwidth == png->width && fheight == png->height)
2060 		scale = false;
2061 
2062 	if (ux1 == 0) {
2063 		/*
2064 		 * No top left X co-ordinate (real coordinates start at 1),
2065 		 * place as far right as it will fit.
2066 		 */
2067 		ux2 = gfx_state.tg_fb.fb_width - gfx_state.tg_origin.tp_col;
2068 		ux1 = ux2 - fwidth;
2069 	}
2070 
2071 	if (uy1 == 0) {
2072 		/*
2073 		 * No top left Y co-ordinate (real coordinates start at 1),
2074 		 * place as far down as it will fit.
2075 		 */
2076 		uy2 = gfx_state.tg_fb.fb_height - gfx_state.tg_origin.tp_row;
2077 		uy1 = uy2 - fheight;
2078 	}
2079 
2080 	if (ux1 >= ux2 || uy1 >= uy2) {
2081 		if (trace)
2082 			printf("Image dimensions reversed.\n");
2083 		return (1);
2084 	}
2085 
2086 	if (fwidth < 2 || fheight < 2) {
2087 		if (trace)
2088 			printf("Target area too small\n");
2089 		return (1);
2090 	}
2091 
2092 	if (trace)
2093 		printf("Image %ux%u -> %ux%u @%ux%u\n",
2094 		    png->width, png->height, fwidth, fheight, ux1, uy1);
2095 
2096 	rect.tr_begin.tp_col = ux1 / gfx_state.tg_font.vf_width;
2097 	rect.tr_begin.tp_row = uy1 / gfx_state.tg_font.vf_height;
2098 	rect.tr_end.tp_col = (ux1 + fwidth) / gfx_state.tg_font.vf_width;
2099 	rect.tr_end.tp_row = (uy1 + fheight) / gfx_state.tg_font.vf_height;
2100 
2101 	/*
2102 	 * mark area used in terminal
2103 	 */
2104 	if (!(flags & FL_PUTIMAGE_NOSCROLL))
2105 		term_image_display(&gfx_state, &rect);
2106 
2107 	if ((flags & FL_PUTIMAGE_BORDER))
2108 		gfx_fb_drawrect(ux1, uy1, ux2, uy2, 0);
2109 
2110 	data = malloc(fwidth * fheight * sizeof(*p));
2111 	p = (void *)data;
2112 	if (data == NULL) {
2113 		if (trace)
2114 			printf("Out of memory.\n");
2115 		return (1);
2116 	}
2117 
2118 	/*
2119 	 * Build image for our framebuffer.
2120 	 */
2121 
2122 	/* Helper to calculate the pixel index from the source png */
2123 #define	GETPIXEL(xx, yy)	(((yy) * png->width + (xx)) * png->bpp)
2124 
2125 	/*
2126 	 * For each of the x and y directions, calculate the number of pixels
2127 	 * in the source image that correspond to a single pixel in the target.
2128 	 * Use fixed-point arithmetic with 16-bits for each of the integer and
2129 	 * fractional parts.
2130 	 */
2131 	const uint32_t wcstep = ((png->width - 1) << 16) / (fwidth - 1);
2132 	const uint32_t hcstep = ((png->height - 1) << 16) / (fheight - 1);
2133 
2134 	rs = 8 - (fls(gfx_state.tg_fb.fb_mask_red) -
2135 	    ffs(gfx_state.tg_fb.fb_mask_red) + 1);
2136 	gs = 8 - (fls(gfx_state.tg_fb.fb_mask_green) -
2137 	    ffs(gfx_state.tg_fb.fb_mask_green) + 1);
2138 	bs = 8 - (fls(gfx_state.tg_fb.fb_mask_blue) -
2139 	    ffs(gfx_state.tg_fb.fb_mask_blue) + 1);
2140 
2141 	uint32_t hc = 0;
2142 	for (y = 0; y < fheight; y++) {
2143 		uint32_t hc2 = (hc >> 9) & 0x7f;
2144 		uint32_t hc1 = 0x80 - hc2;
2145 
2146 		uint32_t offset_y = hc >> 16;
2147 		uint32_t offset_y1 = offset_y + 1;
2148 
2149 		uint32_t wc = 0;
2150 		for (x = 0; x < fwidth; x++) {
2151 			uint32_t wc2 = (wc >> 9) & 0x7f;
2152 			uint32_t wc1 = 0x80 - wc2;
2153 
2154 			uint32_t offset_x = wc >> 16;
2155 			uint32_t offset_x1 = offset_x + 1;
2156 
2157 			/* Target pixel index */
2158 			j = y * fwidth + x;
2159 
2160 			if (!scale) {
2161 				i = GETPIXEL(x, y);
2162 				r = png->image[i];
2163 				g = png->image[i + 1];
2164 				b = png->image[i + 2];
2165 				a = png->image[i + 3];
2166 			} else {
2167 				uint8_t pixel[4];
2168 
2169 				uint32_t p00 = GETPIXEL(offset_x, offset_y);
2170 				uint32_t p01 = GETPIXEL(offset_x, offset_y1);
2171 				uint32_t p10 = GETPIXEL(offset_x1, offset_y);
2172 				uint32_t p11 = GETPIXEL(offset_x1, offset_y1);
2173 
2174 				/*
2175 				 * Given a 2x2 array of pixels in the source
2176 				 * image, combine them to produce a single
2177 				 * value for the pixel in the target image.
2178 				 * Each column of pixels is combined using
2179 				 * a weighted average where the top and bottom
2180 				 * pixels contribute hc1 and hc2 respectively.
2181 				 * The calculation for bottom pixel pB and
2182 				 * top pixel pT is:
2183 				 *   (pT * hc1 + pB * hc2) / (hc1 + hc2)
2184 				 * Once the values are determined for the two
2185 				 * columns of pixels, then the columns are
2186 				 * averaged together in the same way but using
2187 				 * wc1 and wc2 for the weightings.
2188 				 *
2189 				 * Since hc1 and hc2 are chosen so that
2190 				 * hc1 + hc2 == 128 (and same for wc1 + wc2),
2191 				 * the >> 14 below is a quick way to divide by
2192 				 * (hc1 + hc2) * (wc1 + wc2)
2193 				 */
2194 				for (i = 0; i < 4; i++)
2195 					pixel[i] = (
2196 					    (png->image[p00 + i] * hc1 +
2197 					    png->image[p01 + i] * hc2) * wc1 +
2198 					    (png->image[p10 + i] * hc1 +
2199 					    png->image[p11 + i] * hc2) * wc2)
2200 					    >> 14;
2201 
2202 				r = pixel[0];
2203 				g = pixel[1];
2204 				b = pixel[2];
2205 				a = pixel[3];
2206 			}
2207 
2208 			if (trace)
2209 				printf("r/g/b: %x/%x/%x\n", r, g, b);
2210 			/*
2211 			 * Rough colorspace reduction for 15/16 bit colors.
2212 			 */
2213 			p[j].Red = r >> rs;
2214                         p[j].Green = g >> gs;
2215                         p[j].Blue = b >> bs;
2216                         p[j].Reserved = a;
2217 
2218 			wc += wcstep;
2219 		}
2220 		hc += hcstep;
2221 	}
2222 
2223 	gfx_fb_cons_display(ux1, uy1, fwidth, fheight, data);
2224 	free(data);
2225 	gfx_fb_flush();
2226 	return (0);
2227 }
2228 
2229 /*
2230  * Reset font flags to FONT_AUTO.
2231  */
2232 void
2233 reset_font_flags(void)
2234 {
2235 	struct fontlist *fl;
2236 
2237 	STAILQ_FOREACH(fl, &fonts, font_next) {
2238 		fl->font_flags = FONT_AUTO;
2239 	}
2240 }
2241 
2242 /* Return  w^2 + h^2 or 0, if the dimensions are unknown */
2243 static unsigned
2244 edid_diagonal_squared(void)
2245 {
2246 	unsigned w, h;
2247 
2248 	if (edid_info == NULL)
2249 		return (0);
2250 
2251 	w = edid_info->display.max_horizontal_image_size;
2252 	h = edid_info->display.max_vertical_image_size;
2253 
2254 	/* If either one is 0, we have aspect ratio, not size */
2255 	if (w == 0 || h == 0)
2256 		return (0);
2257 
2258 	/*
2259 	 * some monitors encode the aspect ratio instead of the physical size.
2260 	 */
2261 	if ((w == 16 && h == 9) || (w == 16 && h == 10) ||
2262 	    (w == 4 && h == 3) || (w == 5 && h == 4))
2263 		return (0);
2264 
2265 	/*
2266 	 * translate cm to inch, note we scale by 100 here.
2267 	 */
2268 	w = w * 100 / 254;
2269 	h = h * 100 / 254;
2270 
2271 	/* Return w^2 + h^2 */
2272 	return (w * w + h * h);
2273 }
2274 
2275 /*
2276  * calculate pixels per inch.
2277  */
2278 static unsigned
2279 gfx_get_ppi(void)
2280 {
2281 	unsigned dp, di;
2282 
2283 	di = edid_diagonal_squared();
2284 	if (di == 0)
2285 		return (0);
2286 
2287 	dp = gfx_state.tg_fb.fb_width *
2288 	    gfx_state.tg_fb.fb_width +
2289 	    gfx_state.tg_fb.fb_height *
2290 	    gfx_state.tg_fb.fb_height;
2291 
2292 	return (isqrt(dp / di));
2293 }
2294 
2295 /*
2296  * Calculate font size from density independent pixels (dp):
2297  * ((16dp * ppi) / 160) * display_factor.
2298  * Here we are using fixed constants: 1dp == 160 ppi and
2299  * display_factor 2.
2300  *
2301  * We are rounding font size up and are searching for font which is
2302  * not smaller than calculated size value.
2303  */
2304 static vt_font_bitmap_data_t *
2305 gfx_get_font(teken_unit_t rows, teken_unit_t cols, teken_unit_t height,
2306     teken_unit_t width)
2307 {
2308 	unsigned ppi, size;
2309 	vt_font_bitmap_data_t *font = NULL;
2310 	struct fontlist *fl, *next;
2311 
2312 	/* Text mode is not supported here. */
2313 	if (gfx_state.tg_fb_type == FB_TEXT)
2314 		return (NULL);
2315 
2316 	ppi = gfx_get_ppi();
2317 	if (ppi == 0)
2318 		return (NULL);
2319 
2320 	/*
2321 	 * We will search for 16dp font.
2322 	 * We are using scale up by 10 for roundup.
2323 	 */
2324 	size = (16 * ppi * 10) / 160;
2325 	/* Apply display factor 2.  */
2326 	size = roundup(size * 2, 10) / 10;
2327 
2328 	STAILQ_FOREACH(fl, &fonts, font_next) {
2329 		/*
2330 		 * Skip too large fonts.
2331 		 */
2332 		font = fl->font_data;
2333 		if (height / font->vfbd_height < rows ||
2334 		    width / font->vfbd_width < cols)
2335 			continue;
2336 
2337 		next = STAILQ_NEXT(fl, font_next);
2338 
2339 		/*
2340 		 * If this is last font or, if next font is smaller,
2341 		 * we have our font. Make sure, it actually is loaded.
2342 		 */
2343 		if (next == NULL || next->font_data->vfbd_height < size) {
2344 			if (font->vfbd_font == NULL ||
2345 			    fl->font_flags == FONT_RELOAD) {
2346 				if (fl->font_load != NULL &&
2347 				    fl->font_name != NULL)
2348 					font = fl->font_load(fl->font_name);
2349 			}
2350 			break;
2351 		}
2352 		font = NULL;
2353 	}
2354 
2355 	return (font);
2356 }
2357 
2358 static vt_font_bitmap_data_t *
2359 set_font(teken_unit_t *rows, teken_unit_t *cols, teken_unit_t h, teken_unit_t w)
2360 {
2361 	vt_font_bitmap_data_t *font = NULL;
2362 	struct fontlist *fl;
2363 	unsigned height = h;
2364 	unsigned width = w;
2365 
2366 	/*
2367 	 * First check for manually loaded font.
2368 	 */
2369 	STAILQ_FOREACH(fl, &fonts, font_next) {
2370 		if (fl->font_flags == FONT_MANUAL) {
2371 			font = fl->font_data;
2372 			if (font->vfbd_font == NULL && fl->font_load != NULL &&
2373 			    fl->font_name != NULL) {
2374 				font = fl->font_load(fl->font_name);
2375 			}
2376 			if (font == NULL || font->vfbd_font == NULL)
2377 				font = NULL;
2378 			break;
2379 		}
2380 	}
2381 
2382 	if (font == NULL)
2383 		font = gfx_get_font(*rows, *cols, h, w);
2384 
2385 	if (font != NULL) {
2386 		*rows = height / font->vfbd_height;
2387 		*cols = width / font->vfbd_width;
2388 		return (font);
2389 	}
2390 
2391 	/*
2392 	 * Find best font for these dimensions, or use default.
2393 	 * If height >= VT_FB_MAX_HEIGHT and width >= VT_FB_MAX_WIDTH,
2394 	 * do not use smaller font than our DEFAULT_FONT_DATA.
2395 	 */
2396 	STAILQ_FOREACH(fl, &fonts, font_next) {
2397 		font = fl->font_data;
2398 		if ((*rows * font->vfbd_height <= height &&
2399 		    *cols * font->vfbd_width <= width) ||
2400 		    (height >= VT_FB_MAX_HEIGHT &&
2401 		    width >= VT_FB_MAX_WIDTH &&
2402 		    font->vfbd_height == DEFAULT_FONT_DATA.vfbd_height &&
2403 		    font->vfbd_width == DEFAULT_FONT_DATA.vfbd_width)) {
2404 			if (font->vfbd_font == NULL ||
2405 			    fl->font_flags == FONT_RELOAD) {
2406 				if (fl->font_load != NULL &&
2407 				    fl->font_name != NULL) {
2408 					font = fl->font_load(fl->font_name);
2409 				}
2410 				if (font == NULL)
2411 					continue;
2412 			}
2413 			*rows = height / font->vfbd_height;
2414 			*cols = width / font->vfbd_width;
2415 			break;
2416 		}
2417 		font = NULL;
2418 	}
2419 
2420 	if (font == NULL) {
2421 		/*
2422 		 * We have fonts sorted smallest last, try it before
2423 		 * falling back to builtin.
2424 		 */
2425 		fl = STAILQ_LAST(&fonts, fontlist, font_next);
2426 		if (fl != NULL && fl->font_load != NULL &&
2427 		    fl->font_name != NULL) {
2428 			font = fl->font_load(fl->font_name);
2429 		}
2430 		if (font == NULL)
2431 			font = &DEFAULT_FONT_DATA;
2432 
2433 		*rows = height / font->vfbd_height;
2434 		*cols = width / font->vfbd_width;
2435 	}
2436 
2437 	return (font);
2438 }
2439 
2440 static void
2441 cons_clear(void)
2442 {
2443 	char clear[] = { '\033', 'c' };
2444 
2445 	/* Reset terminal */
2446 	teken_input(&gfx_state.tg_teken, clear, sizeof(clear));
2447 	gfx_state.tg_functions->tf_param(&gfx_state, TP_SHOWCURSOR, 0);
2448 }
2449 
2450 void
2451 setup_font(teken_gfx_t *state, teken_unit_t height, teken_unit_t width)
2452 {
2453 	vt_font_bitmap_data_t *font_data;
2454 	teken_pos_t *tp = &state->tg_tp;
2455 	char env[8];
2456 	int i;
2457 
2458 	/*
2459 	 * set_font() will select a appropriate sized font for
2460 	 * the number of rows and columns selected.  If we don't
2461 	 * have a font that will fit, then it will use the
2462 	 * default builtin font and adjust the rows and columns
2463 	 * to fit on the screen.
2464 	 */
2465 	font_data = set_font(&tp->tp_row, &tp->tp_col, height, width);
2466 
2467         if (font_data == NULL)
2468 		panic("out of memory");
2469 
2470 	for (i = 0; i < VFNT_MAPS; i++) {
2471 		state->tg_font.vf_map[i] =
2472 		    font_data->vfbd_font->vf_map[i];
2473 		state->tg_font.vf_map_count[i] =
2474 		    font_data->vfbd_font->vf_map_count[i];
2475 	}
2476 
2477 	state->tg_font.vf_bytes = font_data->vfbd_font->vf_bytes;
2478 	state->tg_font.vf_height = font_data->vfbd_font->vf_height;
2479 	state->tg_font.vf_width = font_data->vfbd_font->vf_width;
2480 
2481 	snprintf(env, sizeof (env), "%ux%u",
2482 	    state->tg_font.vf_width, state->tg_font.vf_height);
2483 	env_setenv("screen.font", EV_VOLATILE | EV_NOHOOK,
2484 	    env, font_set, env_nounset);
2485 }
2486 
2487 /* Binary search for the glyph. Return 0 if not found. */
2488 static uint16_t
2489 font_bisearch(const vfnt_map_t *map, uint32_t len, teken_char_t src)
2490 {
2491 	unsigned min, mid, max;
2492 
2493 	min = 0;
2494 	max = len - 1;
2495 
2496 	/* Empty font map. */
2497 	if (len == 0)
2498 		return (0);
2499 	/* Character below minimal entry. */
2500 	if (src < map[0].vfm_src)
2501 		return (0);
2502 	/* Optimization: ASCII characters occur very often. */
2503 	if (src <= map[0].vfm_src + map[0].vfm_len)
2504 		return (src - map[0].vfm_src + map[0].vfm_dst);
2505 	/* Character above maximum entry. */
2506 	if (src > map[max].vfm_src + map[max].vfm_len)
2507 		return (0);
2508 
2509 	/* Binary search. */
2510 	while (max >= min) {
2511 		mid = (min + max) / 2;
2512 		if (src < map[mid].vfm_src)
2513 			max = mid - 1;
2514 		else if (src > map[mid].vfm_src + map[mid].vfm_len)
2515 			min = mid + 1;
2516 		else
2517 			return (src - map[mid].vfm_src + map[mid].vfm_dst);
2518 	}
2519 
2520 	return (0);
2521 }
2522 
2523 /*
2524  * Return glyph bitmap. If glyph is not found, we will return bitmap
2525  * for the first (offset 0) glyph.
2526  */
2527 uint8_t *
2528 font_lookup(const struct vt_font *vf, teken_char_t c, const teken_attr_t *a)
2529 {
2530 	uint16_t dst;
2531 	size_t stride;
2532 
2533 	/* Substitute bold with normal if not found. */
2534 	if (a->ta_format & TF_BOLD) {
2535 		dst = font_bisearch(vf->vf_map[VFNT_MAP_BOLD],
2536 		    vf->vf_map_count[VFNT_MAP_BOLD], c);
2537 		if (dst != 0)
2538 			goto found;
2539 	}
2540 	dst = font_bisearch(vf->vf_map[VFNT_MAP_NORMAL],
2541 	    vf->vf_map_count[VFNT_MAP_NORMAL], c);
2542 
2543 found:
2544 	stride = howmany(vf->vf_width, 8) * vf->vf_height;
2545 	return (&vf->vf_bytes[dst * stride]);
2546 }
2547 
2548 static int
2549 load_mapping(int fd, struct vt_font *fp, int n)
2550 {
2551 	size_t i, size;
2552 	ssize_t rv;
2553 	vfnt_map_t *mp;
2554 
2555 	if (fp->vf_map_count[n] == 0)
2556 		return (0);
2557 
2558 	size = fp->vf_map_count[n] * sizeof(*mp);
2559 	mp = malloc(size);
2560 	if (mp == NULL)
2561 		return (ENOMEM);
2562 	fp->vf_map[n] = mp;
2563 
2564 	rv = read(fd, mp, size);
2565 	if (rv < 0 || (size_t)rv != size) {
2566 		free(fp->vf_map[n]);
2567 		fp->vf_map[n] = NULL;
2568 		return (EIO);
2569 	}
2570 
2571 	for (i = 0; i < fp->vf_map_count[n]; i++) {
2572 		mp[i].vfm_src = be32toh(mp[i].vfm_src);
2573 		mp[i].vfm_dst = be16toh(mp[i].vfm_dst);
2574 		mp[i].vfm_len = be16toh(mp[i].vfm_len);
2575 	}
2576 	return (0);
2577 }
2578 
2579 static int
2580 builtin_mapping(struct vt_font *fp, int n)
2581 {
2582 	size_t size;
2583 	struct vfnt_map *mp;
2584 
2585 	if (n >= VFNT_MAPS)
2586 		return (EINVAL);
2587 
2588 	if (fp->vf_map_count[n] == 0)
2589 		return (0);
2590 
2591 	size = fp->vf_map_count[n] * sizeof(*mp);
2592 	mp = malloc(size);
2593 	if (mp == NULL)
2594 		return (ENOMEM);
2595 	fp->vf_map[n] = mp;
2596 
2597 	memcpy(mp, DEFAULT_FONT_DATA.vfbd_font->vf_map[n], size);
2598 	return (0);
2599 }
2600 
2601 /*
2602  * Load font from builtin or from file.
2603  * We do need special case for builtin because the builtin font glyphs
2604  * are compressed and we do need to uncompress them.
2605  * Having single load_font() for both cases will help us to simplify
2606  * font switch handling.
2607  */
2608 static vt_font_bitmap_data_t *
2609 load_font(char *path)
2610 {
2611 	int fd, i;
2612 	uint32_t glyphs;
2613 	struct font_header fh;
2614 	struct fontlist *fl;
2615 	vt_font_bitmap_data_t *bp;
2616 	struct vt_font *fp;
2617 	size_t size;
2618 	ssize_t rv;
2619 
2620 	/* Get our entry from the font list. */
2621 	STAILQ_FOREACH(fl, &fonts, font_next) {
2622 		if (strcmp(fl->font_name, path) == 0)
2623 			break;
2624 	}
2625 	if (fl == NULL)
2626 		return (NULL);	/* Should not happen. */
2627 
2628 	bp = fl->font_data;
2629 	if (bp->vfbd_font != NULL && fl->font_flags != FONT_RELOAD)
2630 		return (bp);
2631 
2632 	fd = -1;
2633 	/*
2634 	 * Special case for builtin font.
2635 	 * Builtin font is the very first font we load, we do not have
2636 	 * previous loads to be released.
2637 	 */
2638 	if (fl->font_flags == FONT_BUILTIN) {
2639 		if ((fp = calloc(1, sizeof(struct vt_font))) == NULL)
2640 			return (NULL);
2641 
2642 		fp->vf_width = DEFAULT_FONT_DATA.vfbd_width;
2643 		fp->vf_height = DEFAULT_FONT_DATA.vfbd_height;
2644 
2645 		fp->vf_bytes = malloc(DEFAULT_FONT_DATA.vfbd_uncompressed_size);
2646 		if (fp->vf_bytes == NULL) {
2647 			free(fp);
2648 			return (NULL);
2649 		}
2650 
2651 		bp->vfbd_uncompressed_size =
2652 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size;
2653 		bp->vfbd_compressed_size =
2654 		    DEFAULT_FONT_DATA.vfbd_compressed_size;
2655 
2656 		if (lz4_decompress(DEFAULT_FONT_DATA.vfbd_compressed_data,
2657 		    fp->vf_bytes,
2658 		    DEFAULT_FONT_DATA.vfbd_compressed_size,
2659 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size, 0) != 0) {
2660 			free(fp->vf_bytes);
2661 			free(fp);
2662 			return (NULL);
2663 		}
2664 
2665 		for (i = 0; i < VFNT_MAPS; i++) {
2666 			fp->vf_map_count[i] =
2667 			    DEFAULT_FONT_DATA.vfbd_font->vf_map_count[i];
2668 			if (builtin_mapping(fp, i) != 0)
2669 				goto free_done;
2670 		}
2671 
2672 		bp->vfbd_font = fp;
2673 		return (bp);
2674 	}
2675 
2676 	fd = open(path, O_RDONLY);
2677 	if (fd < 0)
2678 		return (NULL);
2679 
2680 	size = sizeof(fh);
2681 	rv = read(fd, &fh, size);
2682 	if (rv < 0 || (size_t)rv != size) {
2683 		bp = NULL;
2684 		goto done;
2685 	}
2686 	if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC, sizeof(fh.fh_magic)) != 0) {
2687 		bp = NULL;
2688 		goto done;
2689 	}
2690 	if ((fp = calloc(1, sizeof(struct vt_font))) == NULL) {
2691 		bp = NULL;
2692 		goto done;
2693 	}
2694 	for (i = 0; i < VFNT_MAPS; i++)
2695 		fp->vf_map_count[i] = be32toh(fh.fh_map_count[i]);
2696 
2697 	glyphs = be32toh(fh.fh_glyph_count);
2698 	fp->vf_width = fh.fh_width;
2699 	fp->vf_height = fh.fh_height;
2700 
2701 	size = howmany(fp->vf_width, 8) * fp->vf_height * glyphs;
2702 	bp->vfbd_uncompressed_size = size;
2703 	if ((fp->vf_bytes = malloc(size)) == NULL)
2704 		goto free_done;
2705 
2706 	rv = read(fd, fp->vf_bytes, size);
2707 	if (rv < 0 || (size_t)rv != size)
2708 		goto free_done;
2709 	for (i = 0; i < VFNT_MAPS; i++) {
2710 		if (load_mapping(fd, fp, i) != 0)
2711 			goto free_done;
2712 	}
2713 
2714 	/*
2715 	 * Reset builtin flag now as we have full font loaded.
2716 	 */
2717 	if (fl->font_flags == FONT_BUILTIN)
2718 		fl->font_flags = FONT_AUTO;
2719 
2720 	/*
2721 	 * Release previously loaded entries. We can do this now, as
2722 	 * the new font is loaded. Note, there can be no console
2723 	 * output till the new font is in place and teken is notified.
2724 	 * We do need to keep fl->font_data for glyph dimensions.
2725 	 */
2726 	STAILQ_FOREACH(fl, &fonts, font_next) {
2727 		if (fl->font_data->vfbd_font == NULL)
2728 			continue;
2729 
2730 		for (i = 0; i < VFNT_MAPS; i++)
2731 			free(fl->font_data->vfbd_font->vf_map[i]);
2732 		free(fl->font_data->vfbd_font->vf_bytes);
2733 		free(fl->font_data->vfbd_font);
2734 		fl->font_data->vfbd_font = NULL;
2735 	}
2736 
2737 	bp->vfbd_font = fp;
2738 	bp->vfbd_compressed_size = 0;
2739 
2740 done:
2741 	if (fd != -1)
2742 		close(fd);
2743 	return (bp);
2744 
2745 free_done:
2746 	for (i = 0; i < VFNT_MAPS; i++)
2747 		free(fp->vf_map[i]);
2748 	free(fp->vf_bytes);
2749 	free(fp);
2750 	bp = NULL;
2751 	goto done;
2752 }
2753 
2754 struct name_entry {
2755 	char			*n_name;
2756 	SLIST_ENTRY(name_entry)	n_entry;
2757 };
2758 
2759 SLIST_HEAD(name_list, name_entry);
2760 
2761 /* Read font names from index file. */
2762 static struct name_list *
2763 read_list(char *fonts)
2764 {
2765 	struct name_list *nl;
2766 	struct name_entry *np;
2767 	char *dir, *ptr;
2768 	char buf[PATH_MAX];
2769 	int fd, len;
2770 
2771 	TSENTER();
2772 
2773 	dir = strdup(fonts);
2774 	if (dir == NULL)
2775 		return (NULL);
2776 
2777 	ptr = strrchr(dir, '/');
2778 	*ptr = '\0';
2779 
2780 	fd = open(fonts, O_RDONLY);
2781 	if (fd < 0)
2782 		return (NULL);
2783 
2784 	nl = malloc(sizeof(*nl));
2785 	if (nl == NULL) {
2786 		close(fd);
2787 		return (nl);
2788 	}
2789 
2790 	SLIST_INIT(nl);
2791 	while ((len = fgetstr(buf, sizeof (buf), fd)) >= 0) {
2792 		if (*buf == '#' || *buf == '\0')
2793 			continue;
2794 
2795 		if (bcmp(buf, "MENU", 4) == 0)
2796 			continue;
2797 
2798 		if (bcmp(buf, "FONT", 4) == 0)
2799 			continue;
2800 
2801 		ptr = strchr(buf, ':');
2802 		if (ptr == NULL)
2803 			continue;
2804 		else
2805 			*ptr = '\0';
2806 
2807 		np = malloc(sizeof(*np));
2808 		if (np == NULL) {
2809 			close(fd);
2810 			return (nl);	/* return what we have */
2811 		}
2812 		if (asprintf(&np->n_name, "%s/%s", dir, buf) < 0) {
2813 			free(np);
2814 			close(fd);
2815 			return (nl);    /* return what we have */
2816 		}
2817 		SLIST_INSERT_HEAD(nl, np, n_entry);
2818 	}
2819 	close(fd);
2820 	TSEXIT();
2821 	return (nl);
2822 }
2823 
2824 /*
2825  * Read the font properties and insert new entry into the list.
2826  * The font list is built in descending order.
2827  */
2828 static bool
2829 insert_font(char *name, FONT_FLAGS flags)
2830 {
2831 	struct font_header fh;
2832 	struct fontlist *fp, *previous, *entry, *next;
2833 	size_t size;
2834 	ssize_t rv;
2835 	int fd;
2836 	char *font_name;
2837 
2838 	TSENTER();
2839 
2840 	font_name = NULL;
2841 	if (flags == FONT_BUILTIN) {
2842 		/*
2843 		 * We only install builtin font once, while setting up
2844 		 * initial console. Since this will happen very early,
2845 		 * we assume asprintf will not fail. Once we have access to
2846 		 * files, the builtin font will be replaced by font loaded
2847 		 * from file.
2848 		 */
2849 		if (!STAILQ_EMPTY(&fonts))
2850 			return (false);
2851 
2852 		fh.fh_width = DEFAULT_FONT_DATA.vfbd_width;
2853 		fh.fh_height = DEFAULT_FONT_DATA.vfbd_height;
2854 
2855 		(void) asprintf(&font_name, "%dx%d",
2856 		    DEFAULT_FONT_DATA.vfbd_width,
2857 		    DEFAULT_FONT_DATA.vfbd_height);
2858 	} else {
2859 		fd = open(name, O_RDONLY);
2860 		if (fd < 0)
2861 			return (false);
2862 		rv = read(fd, &fh, sizeof(fh));
2863 		close(fd);
2864 		if (rv < 0 || (size_t)rv != sizeof(fh))
2865 			return (false);
2866 
2867 		if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC,
2868 		    sizeof(fh.fh_magic)) != 0)
2869 			return (false);
2870 		font_name = strdup(name);
2871 	}
2872 
2873 	if (font_name == NULL)
2874 		return (false);
2875 
2876 	/*
2877 	 * If we have an entry with the same glyph dimensions, replace
2878 	 * the file name and mark us. We only support unique dimensions.
2879 	 */
2880 	STAILQ_FOREACH(entry, &fonts, font_next) {
2881 		if (fh.fh_width == entry->font_data->vfbd_width &&
2882 		    fh.fh_height == entry->font_data->vfbd_height) {
2883 			free(entry->font_name);
2884 			entry->font_name = font_name;
2885 			entry->font_flags = FONT_RELOAD;
2886 			TSEXIT();
2887 			return (true);
2888 		}
2889 	}
2890 
2891 	fp = calloc(sizeof(*fp), 1);
2892 	if (fp == NULL) {
2893 		free(font_name);
2894 		return (false);
2895 	}
2896 	fp->font_data = calloc(sizeof(*fp->font_data), 1);
2897 	if (fp->font_data == NULL) {
2898 		free(font_name);
2899 		free(fp);
2900 		return (false);
2901 	}
2902 	fp->font_name = font_name;
2903 	fp->font_flags = flags;
2904 	fp->font_load = load_font;
2905 	fp->font_data->vfbd_width = fh.fh_width;
2906 	fp->font_data->vfbd_height = fh.fh_height;
2907 
2908 	if (STAILQ_EMPTY(&fonts)) {
2909 		STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2910 		TSEXIT();
2911 		return (true);
2912 	}
2913 
2914 	previous = NULL;
2915 	size = fp->font_data->vfbd_width * fp->font_data->vfbd_height;
2916 
2917 	STAILQ_FOREACH(entry, &fonts, font_next) {
2918 		vt_font_bitmap_data_t *bd;
2919 
2920 		bd = entry->font_data;
2921 		/* Should fp be inserted before the entry? */
2922 		if (size > bd->vfbd_width * bd->vfbd_height) {
2923 			if (previous == NULL) {
2924 				STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2925 			} else {
2926 				STAILQ_INSERT_AFTER(&fonts, previous, fp,
2927 				    font_next);
2928 			}
2929 			TSEXIT();
2930 			return (true);
2931 		}
2932 		next = STAILQ_NEXT(entry, font_next);
2933 		if (next == NULL ||
2934 		    size > next->font_data->vfbd_width *
2935 		    next->font_data->vfbd_height) {
2936 			STAILQ_INSERT_AFTER(&fonts, entry, fp, font_next);
2937 			TSEXIT();
2938 			return (true);
2939 		}
2940 		previous = entry;
2941 	}
2942 	TSEXIT();
2943 	return (true);
2944 }
2945 
2946 static int
2947 font_set(struct env_var *ev __unused, int flags __unused, const void *value)
2948 {
2949 	struct fontlist *fl;
2950 	char *eptr;
2951 	unsigned long x = 0, y = 0;
2952 
2953 	/*
2954 	 * Attempt to extract values from "XxY" string. In case of error,
2955 	 * we have unmaching glyph dimensions and will just output the
2956 	 * available values.
2957 	 */
2958 	if (value != NULL) {
2959 		x = strtoul(value, &eptr, 10);
2960 		if (*eptr == 'x')
2961 			y = strtoul(eptr + 1, &eptr, 10);
2962 	}
2963 	STAILQ_FOREACH(fl, &fonts, font_next) {
2964 		if (fl->font_data->vfbd_width == x &&
2965 		    fl->font_data->vfbd_height == y)
2966 			break;
2967 	}
2968 	if (fl != NULL) {
2969 		/* Reset any FONT_MANUAL flag. */
2970 		reset_font_flags();
2971 
2972 		/* Mark this font manually loaded */
2973 		fl->font_flags = FONT_MANUAL;
2974 		cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2975 		return (CMD_OK);
2976 	}
2977 
2978 	printf("Available fonts:\n");
2979 	STAILQ_FOREACH(fl, &fonts, font_next) {
2980 		printf("    %dx%d\n", fl->font_data->vfbd_width,
2981 		    fl->font_data->vfbd_height);
2982 	}
2983 	return (CMD_OK);
2984 }
2985 
2986 void
2987 bios_text_font(bool use_vga_font)
2988 {
2989 	if (use_vga_font)
2990 		(void) insert_font(VGA_8X16_FONT, FONT_MANUAL);
2991 	else
2992 		(void) insert_font(DEFAULT_8X16_FONT, FONT_MANUAL);
2993 }
2994 
2995 void
2996 autoload_font(bool bios)
2997 {
2998 	struct name_list *nl;
2999 	struct name_entry *np;
3000 
3001 	TSENTER();
3002 
3003 	nl = read_list("/boot/fonts/INDEX.fonts");
3004 	if (nl == NULL)
3005 		return;
3006 
3007 	while (!SLIST_EMPTY(nl)) {
3008 		np = SLIST_FIRST(nl);
3009 		SLIST_REMOVE_HEAD(nl, n_entry);
3010 		if (insert_font(np->n_name, FONT_AUTO) == false)
3011 			printf("failed to add font: %s\n", np->n_name);
3012 		free(np->n_name);
3013 		free(np);
3014 	}
3015 
3016 	/*
3017 	 * If vga text mode was requested, load vga.font (8x16 bold) font.
3018 	 */
3019 	if (bios) {
3020 		bios_text_font(true);
3021 	}
3022 
3023 	(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
3024 
3025 	TSEXIT();
3026 }
3027 
3028 COMMAND_SET(load_font, "loadfont", "load console font from file", command_font);
3029 
3030 static int
3031 command_font(int argc, char *argv[])
3032 {
3033 	int i, c, rc;
3034 	struct fontlist *fl;
3035 	vt_font_bitmap_data_t *bd;
3036 	bool list;
3037 
3038 	list = false;
3039 	optind = 1;
3040 	optreset = 1;
3041 	rc = CMD_OK;
3042 
3043 	while ((c = getopt(argc, argv, "l")) != -1) {
3044 		switch (c) {
3045 		case 'l':
3046 			list = true;
3047 			break;
3048 		case '?':
3049 		default:
3050 			return (CMD_ERROR);
3051 		}
3052 	}
3053 
3054 	argc -= optind;
3055 	argv += optind;
3056 
3057 	if (argc > 1 || (list && argc != 0)) {
3058 		printf("Usage: loadfont [-l] | [file.fnt]\n");
3059 		return (CMD_ERROR);
3060 	}
3061 
3062 	if (list) {
3063 		STAILQ_FOREACH(fl, &fonts, font_next) {
3064 			printf("font %s: %dx%d%s\n", fl->font_name,
3065 			    fl->font_data->vfbd_width,
3066 			    fl->font_data->vfbd_height,
3067 			    fl->font_data->vfbd_font == NULL? "" : " loaded");
3068 		}
3069 		return (CMD_OK);
3070 	}
3071 
3072 	/* Clear scren */
3073 	cons_clear();
3074 
3075 	if (argc == 1) {
3076 		char *name = argv[0];
3077 
3078 		if (insert_font(name, FONT_MANUAL) == false) {
3079 			printf("loadfont error: failed to load: %s\n", name);
3080 			return (CMD_ERROR);
3081 		}
3082 
3083 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
3084 		return (CMD_OK);
3085 	}
3086 
3087 	if (argc == 0) {
3088 		/*
3089 		 * Walk entire font list, release any loaded font, and set
3090 		 * autoload flag. The font list does have at least the builtin
3091 		 * default font.
3092 		 */
3093 		STAILQ_FOREACH(fl, &fonts, font_next) {
3094 			if (fl->font_data->vfbd_font != NULL) {
3095 
3096 				bd = fl->font_data;
3097 				/*
3098 				 * Note the setup_font() is releasing
3099 				 * font bytes.
3100 				 */
3101 				for (i = 0; i < VFNT_MAPS; i++)
3102 					free(bd->vfbd_font->vf_map[i]);
3103 				free(fl->font_data->vfbd_font);
3104 				fl->font_data->vfbd_font = NULL;
3105 				fl->font_data->vfbd_uncompressed_size = 0;
3106 				fl->font_flags = FONT_AUTO;
3107 			}
3108 		}
3109 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
3110 	}
3111 	return (rc);
3112 }
3113 
3114 bool
3115 gfx_get_edid_resolution(struct vesa_edid_info *edid, edid_res_list_t *res)
3116 {
3117 	struct resolution *rp, *p;
3118 
3119 	/*
3120 	 * Walk detailed timings tables (4).
3121 	 */
3122 	if ((edid->display.supported_features
3123 	    & EDID_FEATURE_PREFERRED_TIMING_MODE) != 0) {
3124 		/* Walk detailed timing descriptors (4) */
3125 		for (int i = 0; i < DET_TIMINGS; i++) {
3126 			/*
3127 			 * Reserved value 0 is not used for display descriptor.
3128 			 */
3129 			if (edid->detailed_timings[i].pixel_clock == 0)
3130 				continue;
3131 			if ((rp = malloc(sizeof(*rp))) == NULL)
3132 				continue;
3133 			rp->width = GET_EDID_INFO_WIDTH(edid, i);
3134 			rp->height = GET_EDID_INFO_HEIGHT(edid, i);
3135 			if (rp->width > 0 && rp->width <= EDID_MAX_PIXELS &&
3136 			    rp->height > 0 && rp->height <= EDID_MAX_LINES)
3137 				TAILQ_INSERT_TAIL(res, rp, next);
3138 			else
3139 				free(rp);
3140 		}
3141 	}
3142 
3143 	/*
3144 	 * Walk standard timings list (8).
3145 	 */
3146 	for (int i = 0; i < STD_TIMINGS; i++) {
3147 		/* Is this field unused? */
3148 		if (edid->standard_timings[i] == 0x0101)
3149 			continue;
3150 
3151 		if ((rp = malloc(sizeof(*rp))) == NULL)
3152 			continue;
3153 
3154 		rp->width = HSIZE(edid->standard_timings[i]);
3155 		switch (RATIO(edid->standard_timings[i])) {
3156 		case RATIO1_1:
3157 			rp->height = HSIZE(edid->standard_timings[i]);
3158 			if (edid->header.version > 1 ||
3159 			    edid->header.revision > 2) {
3160 				rp->height = rp->height * 10 / 16;
3161 			}
3162 			break;
3163 		case RATIO4_3:
3164 			rp->height = HSIZE(edid->standard_timings[i]) * 3 / 4;
3165 			break;
3166 		case RATIO5_4:
3167 			rp->height = HSIZE(edid->standard_timings[i]) * 4 / 5;
3168 			break;
3169 		case RATIO16_9:
3170 			rp->height = HSIZE(edid->standard_timings[i]) * 9 / 16;
3171 			break;
3172 		}
3173 
3174 		/*
3175 		 * Create resolution list in decreasing order, except keep
3176 		 * first entry (preferred timing mode).
3177 		 */
3178 		TAILQ_FOREACH(p, res, next) {
3179 			if (p->width * p->height < rp->width * rp->height) {
3180 				/* Keep preferred mode first */
3181 				if (TAILQ_FIRST(res) == p)
3182 					TAILQ_INSERT_AFTER(res, p, rp, next);
3183 				else
3184 					TAILQ_INSERT_BEFORE(p, rp, next);
3185 				break;
3186 			}
3187 			if (TAILQ_NEXT(p, next) == NULL) {
3188 				TAILQ_INSERT_TAIL(res, rp, next);
3189 				break;
3190 			}
3191 		}
3192 	}
3193 	return (!TAILQ_EMPTY(res));
3194 }
3195 
3196 vm_offset_t
3197 build_font_module(vm_offset_t addr)
3198 {
3199 	vt_font_bitmap_data_t *bd;
3200 	struct vt_font *fd;
3201 	struct preloaded_file *fp;
3202 	size_t size;
3203 	uint32_t checksum;
3204 	int i;
3205 	struct font_info fi;
3206 	struct fontlist *fl;
3207 	uint64_t fontp;
3208 
3209 	if (STAILQ_EMPTY(&fonts))
3210 		return (addr);
3211 
3212 	/* We can't load first */
3213 	if ((file_findfile(NULL, NULL)) == NULL) {
3214 		printf("Can not load font module: %s\n",
3215 		    "the kernel is not loaded");
3216 		return (addr);
3217 	}
3218 
3219 	/* helper pointers */
3220 	bd = NULL;
3221 	STAILQ_FOREACH(fl, &fonts, font_next) {
3222 		if (gfx_state.tg_font.vf_width == fl->font_data->vfbd_width &&
3223 		    gfx_state.tg_font.vf_height == fl->font_data->vfbd_height) {
3224 			/*
3225 			 * Kernel does have better built in font.
3226 			 */
3227 			if (fl->font_flags == FONT_BUILTIN)
3228 				return (addr);
3229 
3230 			bd = fl->font_data;
3231 			break;
3232 		}
3233 	}
3234 	if (bd == NULL)
3235 		return (addr);
3236 	fd = bd->vfbd_font;
3237 
3238 	fi.fi_width = fd->vf_width;
3239 	checksum = fi.fi_width;
3240 	fi.fi_height = fd->vf_height;
3241 	checksum += fi.fi_height;
3242 	fi.fi_bitmap_size = bd->vfbd_uncompressed_size;
3243 	checksum += fi.fi_bitmap_size;
3244 
3245 	size = roundup2(sizeof (struct font_info), 8);
3246 	for (i = 0; i < VFNT_MAPS; i++) {
3247 		fi.fi_map_count[i] = fd->vf_map_count[i];
3248 		checksum += fi.fi_map_count[i];
3249 		size += fd->vf_map_count[i] * sizeof (struct vfnt_map);
3250 		size += roundup2(size, 8);
3251 	}
3252 	size += bd->vfbd_uncompressed_size;
3253 
3254 	fi.fi_checksum = -checksum;
3255 
3256 	fp = file_findfile(NULL, md_kerntype);
3257 	if (fp == NULL)
3258 		panic("can't find kernel file");
3259 
3260 	fontp = addr;
3261 	addr += archsw.arch_copyin(&fi, addr, sizeof (struct font_info));
3262 	addr = roundup2(addr, 8);
3263 
3264 	/* Copy maps. */
3265 	for (i = 0; i < VFNT_MAPS; i++) {
3266 		if (fd->vf_map_count[i] != 0) {
3267 			addr += archsw.arch_copyin(fd->vf_map[i], addr,
3268 			    fd->vf_map_count[i] * sizeof (struct vfnt_map));
3269 			addr = roundup2(addr, 8);
3270 		}
3271 	}
3272 
3273 	/* Copy the bitmap. */
3274 	addr += archsw.arch_copyin(fd->vf_bytes, addr, fi.fi_bitmap_size);
3275 
3276 	/* Looks OK so far; populate control structure */
3277 	file_addmetadata(fp, MODINFOMD_FONT, sizeof(fontp), &fontp);
3278 	return (addr);
3279 }
3280 
3281 vm_offset_t
3282 build_splash_module(vm_offset_t addr, int type)
3283 {
3284 	struct preloaded_file *fp;
3285 	struct splash_info si;
3286 	const char *splash;
3287 	png_t png;
3288 	uint64_t splashp;
3289 	int error;
3290 
3291 	/* We can't load first */
3292 	if ((file_findfile(NULL, NULL)) == NULL) {
3293 		printf("Can not load splash module: %s\n",
3294 		    "the kernel is not loaded");
3295 		return (addr);
3296 	}
3297 
3298 	fp = file_findfile(NULL, md_kerntype);
3299 	if (fp == NULL)
3300 		panic("can't find kernel file");
3301 
3302 	if (type == SPLASH_STARTUP)
3303 		splash = getenv("splash");
3304 	if (type == SPLASH_SHUTDOWN)
3305 		splash = getenv("shutdown_splash");
3306 
3307 	if (splash == NULL)
3308 		return (addr);
3309 
3310 	/* Parse png */
3311 	if ((error = png_open(&png, splash)) != PNG_NO_ERROR) {
3312 		return (addr);
3313 	}
3314 
3315 	si.si_width = png.width;
3316 	si.si_height = png.height;
3317 	si.si_depth = png.bpp;
3318 	splashp = addr;
3319 	addr += archsw.arch_copyin(&si, addr, sizeof (struct splash_info));
3320 	addr = roundup2(addr, 8);
3321 
3322 	/* Copy the bitmap. */
3323 	addr += archsw.arch_copyin(png.image, addr, png.png_datalen);
3324 
3325 	if (type == SPLASH_STARTUP) {
3326 		printf("Loading splash ok\n");
3327 		file_addmetadata(fp, MODINFOMD_SPLASH,
3328 		    sizeof(splashp), &splashp);
3329 	}
3330 	if (type == SPLASH_SHUTDOWN) {
3331 		printf("Loading shutdown splash ok\n");
3332 		file_addmetadata(fp, MODINFOMD_SHTDWNSPLASH,
3333 		    sizeof(splashp), &splashp);
3334 	}
3335 	return (addr);
3336 }
3337