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