xref: /freebsd/stand/common/gfx_fb.c (revision bc5304a006238115291e7568583632889dffbab9)
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 
755 	/*
756 	 * We assume Blt() does work, if not, we will need to build
757 	 * exception list case by case.
758 	 */
759 	if (gop != NULL) {
760 		switch (BltOperation) {
761 		case GfxFbBltVideoFill:
762 			status = gop->Blt(gop, BltBuffer, EfiBltVideoFill,
763 			    SourceX, SourceY, DestinationX, DestinationY,
764 			    Width, Height, Delta);
765 			break;
766 
767 		case GfxFbBltVideoToBltBuffer:
768 			status = gop->Blt(gop, BltBuffer,
769 			    EfiBltVideoToBltBuffer,
770 			    SourceX, SourceY, DestinationX, DestinationY,
771 			    Width, Height, Delta);
772 			break;
773 
774 		case GfxFbBltBufferToVideo:
775 			status = gop->Blt(gop, BltBuffer, EfiBltBufferToVideo,
776 			    SourceX, SourceY, DestinationX, DestinationY,
777 			    Width, Height, Delta);
778 			break;
779 
780 		case GfxFbBltVideoToVideo:
781 			status = gop->Blt(gop, BltBuffer, EfiBltVideoToVideo,
782 			    SourceX, SourceY, DestinationX, DestinationY,
783 			    Width, Height, Delta);
784 			break;
785 
786 		default:
787 			status = EFI_INVALID_PARAMETER;
788 			break;
789 		}
790 
791 		switch (status) {
792 		case EFI_SUCCESS:
793 			rv = 0;
794 			break;
795 
796 		case EFI_INVALID_PARAMETER:
797 			rv = EINVAL;
798 			break;
799 
800 		case EFI_DEVICE_ERROR:
801 		default:
802 			rv = EIO;
803 			break;
804 		}
805 
806 		return (rv);
807 	}
808 #endif
809 
810 	switch (BltOperation) {
811 	case GfxFbBltVideoFill:
812 		rv = gfxfb_blt_fill(BltBuffer, DestinationX, DestinationY,
813 		    Width, Height);
814 		break;
815 
816 	case GfxFbBltVideoToBltBuffer:
817 		rv = gfxfb_blt_video_to_buffer(BltBuffer, SourceX, SourceY,
818 		    DestinationX, DestinationY, Width, Height, Delta);
819 		break;
820 
821 	case GfxFbBltBufferToVideo:
822 		rv = gfxfb_blt_buffer_to_video(BltBuffer, SourceX, SourceY,
823 		    DestinationX, DestinationY, Width, Height, Delta);
824 		break;
825 
826 	case GfxFbBltVideoToVideo:
827 		rv = gfxfb_blt_video_to_video(SourceX, SourceY,
828 		    DestinationX, DestinationY, Width, Height);
829 		break;
830 
831 	default:
832 		rv = EINVAL;
833 		break;
834 	}
835 	return (rv);
836 }
837 
838 void
839 gfx_bitblt_bitmap(teken_gfx_t *state, const uint8_t *glyph,
840     const teken_attr_t *a, uint32_t alpha, bool cursor)
841 {
842 	uint32_t width, height;
843 	uint32_t fgc, bgc, bpl, cc, o;
844 	int bpp, bit, byte;
845 	bool invert = false;
846 
847 	bpp = 4;		/* We only generate BGRA */
848 	width = state->tg_font.vf_width;
849 	height = state->tg_font.vf_height;
850 	bpl = (width + 7) / 8;  /* Bytes per source line. */
851 
852 	fgc = a->ta_fgcolor;
853 	bgc = a->ta_bgcolor;
854 	if (a->ta_format & TF_BOLD)
855 		fgc |= TC_LIGHT;
856 	if (a->ta_format & TF_BLINK)
857 		bgc |= TC_LIGHT;
858 
859 	fgc = gfx_fb_color_map(fgc);
860 	bgc = gfx_fb_color_map(bgc);
861 
862 	if (a->ta_format & TF_REVERSE)
863 		invert = !invert;
864 	if (cursor)
865 		invert = !invert;
866 	if (invert) {
867 		uint32_t tmp;
868 
869 		tmp = fgc;
870 		fgc = bgc;
871 		bgc = tmp;
872 	}
873 
874 	alpha = alpha << 24;
875 	fgc |= alpha;
876 	bgc |= alpha;
877 
878 	for (uint32_t y = 0; y < height; y++) {
879 		for (uint32_t x = 0; x < width; x++) {
880 			byte = y * bpl + x / 8;
881 			bit = 0x80 >> (x % 8);
882 			o = y * width * bpp + x * bpp;
883 			cc = glyph[byte] & bit ? fgc : bgc;
884 
885 			gfx_mem_wr4(state->tg_glyph,
886 			    state->tg_glyph_size, o, cc);
887 		}
888 	}
889 }
890 
891 /*
892  * Draw prepared glyph on terminal point p.
893  */
894 static void
895 gfx_fb_printchar(teken_gfx_t *state, const teken_pos_t *p)
896 {
897 	unsigned x, y, width, height;
898 
899 	width = state->tg_font.vf_width;
900 	height = state->tg_font.vf_height;
901 	x = state->tg_origin.tp_col + p->tp_col * width;
902 	y = state->tg_origin.tp_row + p->tp_row * height;
903 
904 	gfx_fb_cons_display(x, y, width, height, state->tg_glyph);
905 }
906 
907 /*
908  * Store char with its attribute to buffer and put it on screen.
909  */
910 void
911 gfx_fb_putchar(void *arg, const teken_pos_t *p, teken_char_t c,
912     const teken_attr_t *a)
913 {
914 	teken_gfx_t *state = arg;
915 	const uint8_t *glyph;
916 	int idx;
917 
918 	idx = p->tp_col + p->tp_row * state->tg_tp.tp_col;
919 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
920 		return;
921 
922 	/* remove the cursor */
923 	if (state->tg_cursor_visible)
924 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
925 
926 	screen_buffer[idx].c = c;
927 	screen_buffer[idx].a = *a;
928 
929 	glyph = font_lookup(&state->tg_font, c, a);
930 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
931 	gfx_fb_printchar(state, p);
932 
933 	/* display the cursor */
934 	if (state->tg_cursor_visible) {
935 		const teken_pos_t *c;
936 
937 		c = teken_get_cursor(&state->tg_teken);
938 		gfx_fb_cursor_draw(state, c, true);
939 	}
940 }
941 
942 void
943 gfx_fb_fill(void *arg, const teken_rect_t *r, teken_char_t c,
944     const teken_attr_t *a)
945 {
946 	teken_gfx_t *state = arg;
947 	const uint8_t *glyph;
948 	teken_pos_t p;
949 	struct text_pixel *row;
950 
951 	/* remove the cursor */
952 	if (state->tg_cursor_visible)
953 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
954 
955 	glyph = font_lookup(&state->tg_font, c, a);
956 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
957 
958 	for (p.tp_row = r->tr_begin.tp_row; p.tp_row < r->tr_end.tp_row;
959 	    p.tp_row++) {
960 		row = &screen_buffer[p.tp_row * state->tg_tp.tp_col];
961 		for (p.tp_col = r->tr_begin.tp_col;
962 		    p.tp_col < r->tr_end.tp_col; p.tp_col++) {
963 			row[p.tp_col].c = c;
964 			row[p.tp_col].a = *a;
965 			gfx_fb_printchar(state, &p);
966 		}
967 	}
968 
969 	/* display the cursor */
970 	if (state->tg_cursor_visible) {
971 		const teken_pos_t *c;
972 
973 		c = teken_get_cursor(&state->tg_teken);
974 		gfx_fb_cursor_draw(state, c, true);
975 	}
976 }
977 
978 static void
979 gfx_fb_cursor_draw(teken_gfx_t *state, const teken_pos_t *pos, bool on)
980 {
981 	unsigned x, y, width, height;
982 	const uint8_t *glyph;
983 	teken_pos_t p;
984 	int idx;
985 
986 	p = *pos;
987 	if (p.tp_col >= state->tg_tp.tp_col)
988 		p.tp_col = state->tg_tp.tp_col - 1;
989 	if (p.tp_row >= state->tg_tp.tp_row)
990 		p.tp_row = state->tg_tp.tp_row - 1;
991 	idx = p.tp_col + p.tp_row * state->tg_tp.tp_col;
992 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
993 		return;
994 
995 	width = state->tg_font.vf_width;
996 	height = state->tg_font.vf_height;
997 	x = state->tg_origin.tp_col + p.tp_col * width;
998 	y = state->tg_origin.tp_row + p.tp_row * height;
999 
1000 	/*
1001 	 * Save original display content to preserve image data.
1002 	 */
1003 	if (on) {
1004 		if (state->tg_cursor_image == NULL ||
1005 		    state->tg_cursor_size != width * height * 4) {
1006 			free(state->tg_cursor_image);
1007 			state->tg_cursor_size = width * height * 4;
1008 			state->tg_cursor_image = malloc(state->tg_cursor_size);
1009 		}
1010 		if (state->tg_cursor_image != NULL) {
1011 			if (gfxfb_blt(state->tg_cursor_image,
1012 			    GfxFbBltVideoToBltBuffer, x, y, 0, 0,
1013 			    width, height, 0) != 0) {
1014 				free(state->tg_cursor_image);
1015 				state->tg_cursor_image = NULL;
1016 			}
1017 		}
1018 	} else {
1019 		/*
1020 		 * Restore display from tg_cursor_image.
1021 		 * If there is no image, restore char from screen_buffer.
1022 		 */
1023 		if (state->tg_cursor_image != NULL &&
1024 		    gfxfb_blt(state->tg_cursor_image, GfxFbBltBufferToVideo,
1025 		    0, 0, x, y, width, height, 0) == 0) {
1026 			state->tg_cursor = p;
1027 			return;
1028 		}
1029 	}
1030 
1031 	glyph = font_lookup(&state->tg_font, screen_buffer[idx].c,
1032 	    &screen_buffer[idx].a);
1033 	gfx_bitblt_bitmap(state, glyph, &screen_buffer[idx].a, 0xff, on);
1034 	gfx_fb_printchar(state, &p);
1035 
1036 	state->tg_cursor = p;
1037 }
1038 
1039 void
1040 gfx_fb_cursor(void *arg, const teken_pos_t *p)
1041 {
1042 	teken_gfx_t *state = arg;
1043 #if defined(EFI)
1044 	EFI_TPL tpl;
1045 
1046 	tpl = BS->RaiseTPL(TPL_NOTIFY);
1047 #endif
1048 
1049 	/* Switch cursor off in old location and back on in new. */
1050 	if (state->tg_cursor_visible) {
1051 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1052 		gfx_fb_cursor_draw(state, p, true);
1053 	}
1054 #if defined(EFI)
1055 	BS->RestoreTPL(tpl);
1056 #endif
1057 }
1058 
1059 void
1060 gfx_fb_param(void *arg, int cmd, unsigned int value)
1061 {
1062 	teken_gfx_t *state = arg;
1063 	const teken_pos_t *c;
1064 
1065 	switch (cmd) {
1066 	case TP_SETLOCALCURSOR:
1067 		/*
1068 		 * 0 means normal (usually block), 1 means hidden, and
1069 		 * 2 means blinking (always block) for compatibility with
1070 		 * syscons.  We don't support any changes except hiding,
1071 		 * so must map 2 to 0.
1072 		 */
1073 		value = (value == 1) ? 0 : 1;
1074 		/* FALLTHROUGH */
1075 	case TP_SHOWCURSOR:
1076 		c = teken_get_cursor(&state->tg_teken);
1077 		gfx_fb_cursor_draw(state, c, true);
1078 		if (value != 0)
1079 			state->tg_cursor_visible = true;
1080 		else
1081 			state->tg_cursor_visible = false;
1082 		break;
1083 	default:
1084 		/* Not yet implemented */
1085 		break;
1086 	}
1087 }
1088 
1089 bool
1090 is_same_pixel(struct text_pixel *px1, struct text_pixel *px2)
1091 {
1092 	if (px1->c != px2->c)
1093 		return (false);
1094 
1095 	/* Is there image stored? */
1096 	if ((px1->a.ta_format & TF_IMAGE) ||
1097 	    (px2->a.ta_format & TF_IMAGE))
1098 		return (false);
1099 
1100 	if (px1->a.ta_format != px2->a.ta_format)
1101 		return (false);
1102 	if (px1->a.ta_fgcolor != px2->a.ta_fgcolor)
1103 		return (false);
1104 	if (px1->a.ta_bgcolor != px2->a.ta_bgcolor)
1105 		return (false);
1106 
1107 	return (true);
1108 }
1109 
1110 static void
1111 gfx_fb_copy_area(teken_gfx_t *state, const teken_rect_t *s,
1112     const teken_pos_t *d)
1113 {
1114 	uint32_t sx, sy, dx, dy, width, height;
1115 
1116 	width = state->tg_font.vf_width;
1117 	height = state->tg_font.vf_height;
1118 
1119 	sx = state->tg_origin.tp_col + s->tr_begin.tp_col * width;
1120 	sy = state->tg_origin.tp_row + s->tr_begin.tp_row * height;
1121 	dx = state->tg_origin.tp_col + d->tp_col * width;
1122 	dy = state->tg_origin.tp_row + d->tp_row * height;
1123 
1124 	width *= (s->tr_end.tp_col - s->tr_begin.tp_col + 1);
1125 
1126 	(void) gfxfb_blt(NULL, GfxFbBltVideoToVideo, sx, sy, dx, dy,
1127 		    width, height, 0);
1128 }
1129 
1130 static void
1131 gfx_fb_copy_line(teken_gfx_t *state, int ncol, teken_pos_t *s, teken_pos_t *d)
1132 {
1133 	teken_rect_t sr;
1134 	teken_pos_t dp;
1135 	unsigned soffset, doffset;
1136 	bool mark = false;
1137 	int x;
1138 
1139 	soffset = s->tp_col + s->tp_row * state->tg_tp.tp_col;
1140 	doffset = d->tp_col + d->tp_row * state->tg_tp.tp_col;
1141 
1142 	for (x = 0; x < ncol; x++) {
1143 		if (is_same_pixel(&screen_buffer[soffset + x],
1144 		    &screen_buffer[doffset + x])) {
1145 			if (mark) {
1146 				gfx_fb_copy_area(state, &sr, &dp);
1147 				mark = false;
1148 			}
1149 		} else {
1150 			screen_buffer[doffset + x] = screen_buffer[soffset + x];
1151 			if (mark) {
1152 				/* update end point */
1153 				sr.tr_end.tp_col = s->tp_col + x;;
1154 			} else {
1155 				/* set up new rectangle */
1156 				mark = true;
1157 				sr.tr_begin.tp_col = s->tp_col + x;
1158 				sr.tr_begin.tp_row = s->tp_row;
1159 				sr.tr_end.tp_col = s->tp_col + x;
1160 				sr.tr_end.tp_row = s->tp_row;
1161 				dp.tp_col = d->tp_col + x;
1162 				dp.tp_row = d->tp_row;
1163 			}
1164 		}
1165 	}
1166 	if (mark) {
1167 		gfx_fb_copy_area(state, &sr, &dp);
1168 	}
1169 }
1170 
1171 void
1172 gfx_fb_copy(void *arg, const teken_rect_t *r, const teken_pos_t *p)
1173 {
1174 	teken_gfx_t *state = arg;
1175 	unsigned doffset, soffset;
1176 	teken_pos_t d, s;
1177 	int nrow, ncol, y; /* Has to be signed - >= 0 comparison */
1178 
1179 	/*
1180 	 * Copying is a little tricky. We must make sure we do it in
1181 	 * correct order, to make sure we don't overwrite our own data.
1182 	 */
1183 
1184 	nrow = r->tr_end.tp_row - r->tr_begin.tp_row;
1185 	ncol = r->tr_end.tp_col - r->tr_begin.tp_col;
1186 
1187 	if (p->tp_row + nrow > state->tg_tp.tp_row ||
1188 	    p->tp_col + ncol > state->tg_tp.tp_col)
1189 		return;
1190 
1191 	soffset = r->tr_begin.tp_col + r->tr_begin.tp_row * state->tg_tp.tp_col;
1192 	doffset = p->tp_col + p->tp_row * state->tg_tp.tp_col;
1193 
1194 	/* remove the cursor */
1195 	if (state->tg_cursor_visible)
1196 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1197 
1198 	/*
1199 	 * Copy line by line.
1200 	 */
1201 	if (doffset <= soffset) {
1202 		s = r->tr_begin;
1203 		d = *p;
1204 		for (y = 0; y < nrow; y++) {
1205 			s.tp_row = r->tr_begin.tp_row + y;
1206 			d.tp_row = p->tp_row + y;
1207 
1208 			gfx_fb_copy_line(state, ncol, &s, &d);
1209 		}
1210 	} else {
1211 		for (y = nrow - 1; y >= 0; y--) {
1212 			s.tp_row = r->tr_begin.tp_row + y;
1213 			d.tp_row = p->tp_row + y;
1214 
1215 			gfx_fb_copy_line(state, ncol, &s, &d);
1216 		}
1217 	}
1218 
1219 	/* display the cursor */
1220 	if (state->tg_cursor_visible) {
1221 		const teken_pos_t *c;
1222 
1223 		c = teken_get_cursor(&state->tg_teken);
1224 		gfx_fb_cursor_draw(state, c, true);
1225 	}
1226 }
1227 
1228 /*
1229  * Implements alpha blending for RGBA data, could use pixels for arguments,
1230  * but byte stream seems more generic.
1231  * The generic alpha blending is:
1232  * blend = alpha * fg + (1.0 - alpha) * bg.
1233  * Since our alpha is not from range [0..1], we scale appropriately.
1234  */
1235 static uint8_t
1236 alpha_blend(uint8_t fg, uint8_t bg, uint8_t alpha)
1237 {
1238 	uint16_t blend, h, l;
1239 
1240 	/* trivial corner cases */
1241 	if (alpha == 0)
1242 		return (bg);
1243 	if (alpha == 0xFF)
1244 		return (fg);
1245 	blend = (alpha * fg + (0xFF - alpha) * bg);
1246 	/* Division by 0xFF */
1247 	h = blend >> 8;
1248 	l = blend & 0xFF;
1249 	if (h + l >= 0xFF)
1250 		h++;
1251 	return (h);
1252 }
1253 
1254 /*
1255  * Implements alpha blending for RGBA data, could use pixels for arguments,
1256  * but byte stream seems more generic.
1257  * The generic alpha blending is:
1258  * blend = alpha * fg + (1.0 - alpha) * bg.
1259  * Since our alpha is not from range [0..1], we scale appropriately.
1260  */
1261 static void
1262 bitmap_cpy(void *dst, void *src, uint32_t size)
1263 {
1264 #if defined(EFI)
1265 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *ps, *pd;
1266 #else
1267 	struct paletteentry *ps, *pd;
1268 #endif
1269 	uint32_t i;
1270 	uint8_t a;
1271 
1272 	ps = src;
1273 	pd = dst;
1274 
1275 	/*
1276 	 * we only implement alpha blending for depth 32.
1277 	 */
1278 	for (i = 0; i < size; i ++) {
1279 		a = ps[i].Reserved;
1280 		pd[i].Red = alpha_blend(ps[i].Red, pd[i].Red, a);
1281 		pd[i].Green = alpha_blend(ps[i].Green, pd[i].Green, a);
1282 		pd[i].Blue = alpha_blend(ps[i].Blue, pd[i].Blue, a);
1283 		pd[i].Reserved = a;
1284 	}
1285 }
1286 
1287 static void *
1288 allocate_glyphbuffer(uint32_t width, uint32_t height)
1289 {
1290 	size_t size;
1291 
1292 	size = sizeof (*GlyphBuffer) * width * height;
1293 	if (size != GlyphBufferSize) {
1294 		free(GlyphBuffer);
1295 		GlyphBuffer = malloc(size);
1296 		if (GlyphBuffer == NULL)
1297 			return (NULL);
1298 		GlyphBufferSize = size;
1299 	}
1300 	return (GlyphBuffer);
1301 }
1302 
1303 void
1304 gfx_fb_cons_display(uint32_t x, uint32_t y, uint32_t width, uint32_t height,
1305     void *data)
1306 {
1307 #if defined(EFI)
1308 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *buf;
1309 #else
1310 	struct paletteentry *buf;
1311 #endif
1312 	size_t size;
1313 
1314 	size = width * height * sizeof(*buf);
1315 
1316 	/*
1317 	 * Common data to display is glyph, use preallocated
1318 	 * glyph buffer.
1319 	 */
1320         if (gfx_state.tg_glyph_size != GlyphBufferSize)
1321                 (void) allocate_glyphbuffer(width, height);
1322 
1323 	if (size == GlyphBufferSize)
1324 		buf = GlyphBuffer;
1325 	else
1326 		buf = malloc(size);
1327 	if (buf == NULL)
1328 		return;
1329 
1330 	if (gfxfb_blt(buf, GfxFbBltVideoToBltBuffer, x, y, 0, 0,
1331 	    width, height, 0) == 0) {
1332 		bitmap_cpy(buf, data, width * height);
1333 		(void) gfxfb_blt(buf, GfxFbBltBufferToVideo, 0, 0, x, y,
1334 		    width, height, 0);
1335 	}
1336 	if (buf != GlyphBuffer)
1337 		free(buf);
1338 }
1339 
1340 /*
1341  * Public graphics primitives.
1342  */
1343 
1344 static int
1345 isqrt(int num)
1346 {
1347 	int res = 0;
1348 	int bit = 1 << 30;
1349 
1350 	/* "bit" starts at the highest power of four <= the argument. */
1351 	while (bit > num)
1352 		bit >>= 2;
1353 
1354 	while (bit != 0) {
1355 		if (num >= res + bit) {
1356 			num -= res + bit;
1357 			res = (res >> 1) + bit;
1358 		} else {
1359 			res >>= 1;
1360 		}
1361 		bit >>= 2;
1362 	}
1363 	return (res);
1364 }
1365 
1366 static uint32_t
1367 gfx_fb_getcolor(void)
1368 {
1369 	uint32_t c;
1370 	const teken_attr_t *ap;
1371 
1372 	ap = teken_get_curattr(&gfx_state.tg_teken);
1373         if (ap->ta_format & TF_REVERSE) {
1374 		c = ap->ta_bgcolor;
1375 		if (ap->ta_format & TF_BLINK)
1376 			c |= TC_LIGHT;
1377 	} else {
1378 		c = ap->ta_fgcolor;
1379 		if (ap->ta_format & TF_BOLD)
1380 			c |= TC_LIGHT;
1381 	}
1382 
1383 	return (gfx_fb_color_map(c));
1384 }
1385 
1386 /* set pixel in framebuffer using gfx coordinates */
1387 void
1388 gfx_fb_setpixel(uint32_t x, uint32_t y)
1389 {
1390 	uint32_t c;
1391 
1392 	if (gfx_state.tg_fb_type == FB_TEXT)
1393 		return;
1394 
1395 	c = gfx_fb_getcolor();
1396 
1397 	if (x >= gfx_state.tg_fb.fb_width ||
1398 	    y >= gfx_state.tg_fb.fb_height)
1399 		return;
1400 
1401 	gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x, y, 1, 1, 0);
1402 }
1403 
1404 /*
1405  * draw rectangle in framebuffer using gfx coordinates.
1406  */
1407 void
1408 gfx_fb_drawrect(uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2,
1409     uint32_t fill)
1410 {
1411 	uint32_t c;
1412 
1413 	if (gfx_state.tg_fb_type == FB_TEXT)
1414 		return;
1415 
1416 	c = gfx_fb_getcolor();
1417 
1418 	if (fill != 0) {
1419 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1,
1420 		    y2 - y1, 0);
1421 	} else {
1422 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1, 1, 0);
1423 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y2, x2 - x1, 1, 0);
1424 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, 1, y2 - y1, 0);
1425 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x2, y1, 1, y2 - y1, 0);
1426 	}
1427 }
1428 
1429 void
1430 gfx_fb_line(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t wd)
1431 {
1432 	int dx, sx, dy, sy;
1433 	int err, e2, x2, y2, ed, width;
1434 
1435 	if (gfx_state.tg_fb_type == FB_TEXT)
1436 		return;
1437 
1438 	width = wd;
1439 	sx = x0 < x1? 1 : -1;
1440 	sy = y0 < y1? 1 : -1;
1441 	dx = x1 > x0? x1 - x0 : x0 - x1;
1442 	dy = y1 > y0? y1 - y0 : y0 - y1;
1443 	err = dx + dy;
1444 	ed = dx + dy == 0 ? 1: isqrt(dx * dx + dy * dy);
1445 
1446 	for (;;) {
1447 		gfx_fb_setpixel(x0, y0);
1448 		e2 = err;
1449 		x2 = x0;
1450 		if ((e2 << 1) >= -dx) {		/* x step */
1451 			e2 += dy;
1452 			y2 = y0;
1453 			while (e2 < ed * width &&
1454 			    (y1 != (uint32_t)y2 || dx > dy)) {
1455 				y2 += sy;
1456 				gfx_fb_setpixel(x0, y2);
1457 				e2 += dx;
1458 			}
1459 			if (x0 == x1)
1460 				break;
1461 			e2 = err;
1462 			err -= dy;
1463 			x0 += sx;
1464 		}
1465 		if ((e2 << 1) <= dy) {		/* y step */
1466 			e2 = dx-e2;
1467 			while (e2 < ed * width &&
1468 			    (x1 != (uint32_t)x2 || dx < dy)) {
1469 				x2 += sx;
1470 				gfx_fb_setpixel(x2, y0);
1471 				e2 += dy;
1472 			}
1473 			if (y0 == y1)
1474 				break;
1475 			err += dx;
1476 			y0 += sy;
1477 		}
1478 	}
1479 }
1480 
1481 /*
1482  * quadratic Bézier curve limited to gradients without sign change.
1483  */
1484 void
1485 gfx_fb_bezier(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t x2,
1486     uint32_t y2, uint32_t wd)
1487 {
1488 	int sx, sy, xx, yy, xy, width;
1489 	int dx, dy, err, curvature;
1490 	int i;
1491 
1492 	if (gfx_state.tg_fb_type == FB_TEXT)
1493 		return;
1494 
1495 	width = wd;
1496 	sx = x2 - x1;
1497 	sy = y2 - y1;
1498 	xx = x0 - x1;
1499 	yy = y0 - y1;
1500 	curvature = xx*sy - yy*sx;
1501 
1502 	if (sx*sx + sy*sy > xx*xx+yy*yy) {
1503 		x2 = x0;
1504 		x0 = sx + x1;
1505 		y2 = y0;
1506 		y0 = sy + y1;
1507 		curvature = -curvature;
1508 	}
1509 	if (curvature != 0) {
1510 		xx += sx;
1511 		sx = x0 < x2? 1 : -1;
1512 		xx *= sx;
1513 		yy += sy;
1514 		sy = y0 < y2? 1 : -1;
1515 		yy *= sy;
1516 		xy = (xx*yy) << 1;
1517 		xx *= xx;
1518 		yy *= yy;
1519 		if (curvature * sx * sy < 0) {
1520 			xx = -xx;
1521 			yy = -yy;
1522 			xy = -xy;
1523 			curvature = -curvature;
1524 		}
1525 		dx = 4 * sy * curvature * (x1 - x0) + xx - xy;
1526 		dy = 4 * sx * curvature * (y0 - y1) + yy - xy;
1527 		xx += xx;
1528 		yy += yy;
1529 		err = dx + dy + xy;
1530 		do {
1531 			for (i = 0; i <= width; i++)
1532 				gfx_fb_setpixel(x0 + i, y0);
1533 			if (x0 == x2 && y0 == y2)
1534 				return;  /* last pixel -> curve finished */
1535 			y1 = 2 * err < dx;
1536 			if (2 * err > dy) {
1537 				x0 += sx;
1538 				dx -= xy;
1539 				dy += yy;
1540 				err += dy;
1541 			}
1542 			if (y1 != 0) {
1543 				y0 += sy;
1544 				dy -= xy;
1545 				dx += xx;
1546 				err += dx;
1547 			}
1548 		} while (dy < dx); /* gradient negates -> algorithm fails */
1549 	}
1550 	gfx_fb_line(x0, y0, x2, y2, width);
1551 }
1552 
1553 /*
1554  * draw rectangle using terminal coordinates and current foreground color.
1555  */
1556 void
1557 gfx_term_drawrect(uint32_t ux1, uint32_t uy1, uint32_t ux2, uint32_t uy2)
1558 {
1559 	int x1, y1, x2, y2;
1560 	int xshift, yshift;
1561 	int width, i;
1562 	uint32_t vf_width, vf_height;
1563 	teken_rect_t r;
1564 
1565 	if (gfx_state.tg_fb_type == FB_TEXT)
1566 		return;
1567 
1568 	vf_width = gfx_state.tg_font.vf_width;
1569 	vf_height = gfx_state.tg_font.vf_height;
1570 	width = vf_width / 4;			/* line width */
1571 	xshift = (vf_width - width) / 2;
1572 	yshift = (vf_height - width) / 2;
1573 
1574 	/* Shift coordinates */
1575 	if (ux1 != 0)
1576 		ux1--;
1577 	if (uy1 != 0)
1578 		uy1--;
1579 	ux2--;
1580 	uy2--;
1581 
1582 	/* mark area used in terminal */
1583 	r.tr_begin.tp_col = ux1;
1584 	r.tr_begin.tp_row = uy1;
1585 	r.tr_end.tp_col = ux2 + 1;
1586 	r.tr_end.tp_row = uy2 + 1;
1587 
1588 	term_image_display(&gfx_state, &r);
1589 
1590 	/*
1591 	 * Draw horizontal lines width points thick, shifted from outer edge.
1592 	 */
1593 	x1 = (ux1 + 1) * vf_width + gfx_state.tg_origin.tp_col;
1594 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1595 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1596 	gfx_fb_drawrect(x1, y1, x2, y1 + width, 1);
1597 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1598 	y2 += vf_height - yshift - width;
1599 	gfx_fb_drawrect(x1, y2, x2, y2 + width, 1);
1600 
1601 	/*
1602 	 * Draw vertical lines width points thick, shifted from outer edge.
1603 	 */
1604 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1605 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1606 	y1 += vf_height;
1607 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1608 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1609 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1610 	x1 += vf_width - xshift - width;
1611 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1612 
1613 	/* Draw upper left corner. */
1614 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1615 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1616 	y1 += vf_height;
1617 
1618 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1619 	x2 += vf_width;
1620 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1621 	for (i = 0; i <= width; i++)
1622 		gfx_fb_bezier(x1 + i, y1, x1 + i, y2 + i, x2, y2 + i, width-i);
1623 
1624 	/* Draw lower left corner. */
1625 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1626 	x1 += vf_width;
1627 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1628 	y1 += vf_height - yshift;
1629 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1630 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1631 	for (i = 0; i <= width; i++)
1632 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1633 
1634 	/* Draw upper right corner. */
1635 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1636 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1637 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1638 	x2 += vf_width - xshift - width;
1639 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1640 	y2 += vf_height;
1641 	for (i = 0; i <= width; i++)
1642 		gfx_fb_bezier(x1, y1 + i, x2 + i, y1 + i, x2 + i, y2, width-i);
1643 
1644 	/* Draw lower right corner. */
1645 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1646 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1647 	y1 += vf_height - yshift;
1648 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1649 	x2 += vf_width - xshift - width;
1650 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1651 	for (i = 0; i <= width; i++)
1652 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1653 }
1654 
1655 int
1656 gfx_fb_putimage(png_t *png, uint32_t ux1, uint32_t uy1, uint32_t ux2,
1657     uint32_t uy2, uint32_t flags)
1658 {
1659 #if defined(EFI)
1660 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
1661 #else
1662 	struct paletteentry *p;
1663 #endif
1664 	uint8_t *data;
1665 	uint32_t i, j, x, y, fheight, fwidth;
1666 	int rs, gs, bs;
1667 	uint8_t r, g, b, a;
1668 	bool scale = false;
1669 	bool trace = false;
1670 	teken_rect_t rect;
1671 
1672 	trace = (flags & FL_PUTIMAGE_DEBUG) != 0;
1673 
1674 	if (gfx_state.tg_fb_type == FB_TEXT) {
1675 		if (trace)
1676 			printf("Framebuffer not active.\n");
1677 		return (1);
1678 	}
1679 
1680 	if (png->color_type != PNG_TRUECOLOR_ALPHA) {
1681 		if (trace)
1682 			printf("Not truecolor image.\n");
1683 		return (1);
1684 	}
1685 
1686 	if (ux1 > gfx_state.tg_fb.fb_width ||
1687 	    uy1 > gfx_state.tg_fb.fb_height) {
1688 		if (trace)
1689 			printf("Top left coordinate off screen.\n");
1690 		return (1);
1691 	}
1692 
1693 	if (png->width > UINT16_MAX || png->height > UINT16_MAX) {
1694 		if (trace)
1695 			printf("Image too large.\n");
1696 		return (1);
1697 	}
1698 
1699 	if (png->width < 1 || png->height < 1) {
1700 		if (trace)
1701 			printf("Image too small.\n");
1702 		return (1);
1703 	}
1704 
1705 	/*
1706 	 * If 0 was passed for either ux2 or uy2, then calculate the missing
1707 	 * part of the bottom right coordinate.
1708 	 */
1709 	scale = true;
1710 	if (ux2 == 0 && uy2 == 0) {
1711 		/* Both 0, use the native resolution of the image */
1712 		ux2 = ux1 + png->width;
1713 		uy2 = uy1 + png->height;
1714 		scale = false;
1715 	} else if (ux2 == 0) {
1716 		/* Set ux2 from uy2/uy1 to maintain aspect ratio */
1717 		ux2 = ux1 + (png->width * (uy2 - uy1)) / png->height;
1718 	} else if (uy2 == 0) {
1719 		/* Set uy2 from ux2/ux1 to maintain aspect ratio */
1720 		uy2 = uy1 + (png->height * (ux2 - ux1)) / png->width;
1721 	}
1722 
1723 	if (ux2 > gfx_state.tg_fb.fb_width ||
1724 	    uy2 > gfx_state.tg_fb.fb_height) {
1725 		if (trace)
1726 			printf("Bottom right coordinate off screen.\n");
1727 		return (1);
1728 	}
1729 
1730 	fwidth = ux2 - ux1;
1731 	fheight = uy2 - uy1;
1732 
1733 	/*
1734 	 * If the original image dimensions have been passed explicitly,
1735 	 * disable scaling.
1736 	 */
1737 	if (fwidth == png->width && fheight == png->height)
1738 		scale = false;
1739 
1740 	if (ux1 == 0) {
1741 		/*
1742 		 * No top left X co-ordinate (real coordinates start at 1),
1743 		 * place as far right as it will fit.
1744 		 */
1745 		ux2 = gfx_state.tg_fb.fb_width - gfx_state.tg_origin.tp_col;
1746 		ux1 = ux2 - fwidth;
1747 	}
1748 
1749 	if (uy1 == 0) {
1750 		/*
1751 		 * No top left Y co-ordinate (real coordinates start at 1),
1752 		 * place as far down as it will fit.
1753 		 */
1754 		uy2 = gfx_state.tg_fb.fb_height - gfx_state.tg_origin.tp_row;
1755 		uy1 = uy2 - fheight;
1756 	}
1757 
1758 	if (ux1 >= ux2 || uy1 >= uy2) {
1759 		if (trace)
1760 			printf("Image dimensions reversed.\n");
1761 		return (1);
1762 	}
1763 
1764 	if (fwidth < 2 || fheight < 2) {
1765 		if (trace)
1766 			printf("Target area too small\n");
1767 		return (1);
1768 	}
1769 
1770 	if (trace)
1771 		printf("Image %ux%u -> %ux%u @%ux%u\n",
1772 		    png->width, png->height, fwidth, fheight, ux1, uy1);
1773 
1774 	rect.tr_begin.tp_col = ux1 / gfx_state.tg_font.vf_width;
1775 	rect.tr_begin.tp_row = uy1 / gfx_state.tg_font.vf_height;
1776 	rect.tr_end.tp_col = (ux1 + fwidth) / gfx_state.tg_font.vf_width;
1777 	rect.tr_end.tp_row = (uy1 + fheight) / gfx_state.tg_font.vf_height;
1778 
1779 	/*
1780 	 * mark area used in terminal
1781 	 */
1782 	if (!(flags & FL_PUTIMAGE_NOSCROLL))
1783 		term_image_display(&gfx_state, &rect);
1784 
1785 	if ((flags & FL_PUTIMAGE_BORDER))
1786 		gfx_fb_drawrect(ux1, uy1, ux2, uy2, 0);
1787 
1788 	data = malloc(fwidth * fheight * sizeof(*p));
1789 	p = (void *)data;
1790 	if (data == NULL) {
1791 		if (trace)
1792 			printf("Out of memory.\n");
1793 		return (1);
1794 	}
1795 
1796 	/*
1797 	 * Build image for our framebuffer.
1798 	 */
1799 
1800 	/* Helper to calculate the pixel index from the source png */
1801 #define	GETPIXEL(xx, yy)	(((yy) * png->width + (xx)) * png->bpp)
1802 
1803 	/*
1804 	 * For each of the x and y directions, calculate the number of pixels
1805 	 * in the source image that correspond to a single pixel in the target.
1806 	 * Use fixed-point arithmetic with 16-bits for each of the integer and
1807 	 * fractional parts.
1808 	 */
1809 	const uint32_t wcstep = ((png->width - 1) << 16) / (fwidth - 1);
1810 	const uint32_t hcstep = ((png->height - 1) << 16) / (fheight - 1);
1811 
1812 	rs = 8 - (fls(gfx_state.tg_fb.fb_mask_red) -
1813 	    ffs(gfx_state.tg_fb.fb_mask_red) + 1);
1814 	gs = 8 - (fls(gfx_state.tg_fb.fb_mask_green) -
1815 	    ffs(gfx_state.tg_fb.fb_mask_green) + 1);
1816 	bs = 8 - (fls(gfx_state.tg_fb.fb_mask_blue) -
1817 	    ffs(gfx_state.tg_fb.fb_mask_blue) + 1);
1818 
1819 	uint32_t hc = 0;
1820 	for (y = 0; y < fheight; y++) {
1821 		uint32_t hc2 = (hc >> 9) & 0x7f;
1822 		uint32_t hc1 = 0x80 - hc2;
1823 
1824 		uint32_t offset_y = hc >> 16;
1825 		uint32_t offset_y1 = offset_y + 1;
1826 
1827 		uint32_t wc = 0;
1828 		for (x = 0; x < fwidth; x++) {
1829 			uint32_t wc2 = (wc >> 9) & 0x7f;
1830 			uint32_t wc1 = 0x80 - wc2;
1831 
1832 			uint32_t offset_x = wc >> 16;
1833 			uint32_t offset_x1 = offset_x + 1;
1834 
1835 			/* Target pixel index */
1836 			j = y * fwidth + x;
1837 
1838 			if (!scale) {
1839 				i = GETPIXEL(x, y);
1840 				r = png->image[i];
1841 				g = png->image[i + 1];
1842 				b = png->image[i + 2];
1843 				a = png->image[i + 3];
1844 			} else {
1845 				uint8_t pixel[4];
1846 
1847 				uint32_t p00 = GETPIXEL(offset_x, offset_y);
1848 				uint32_t p01 = GETPIXEL(offset_x, offset_y1);
1849 				uint32_t p10 = GETPIXEL(offset_x1, offset_y);
1850 				uint32_t p11 = GETPIXEL(offset_x1, offset_y1);
1851 
1852 				/*
1853 				 * Given a 2x2 array of pixels in the source
1854 				 * image, combine them to produce a single
1855 				 * value for the pixel in the target image.
1856 				 * Each column of pixels is combined using
1857 				 * a weighted average where the top and bottom
1858 				 * pixels contribute hc1 and hc2 respectively.
1859 				 * The calculation for bottom pixel pB and
1860 				 * top pixel pT is:
1861 				 *   (pT * hc1 + pB * hc2) / (hc1 + hc2)
1862 				 * Once the values are determined for the two
1863 				 * columns of pixels, then the columns are
1864 				 * averaged together in the same way but using
1865 				 * wc1 and wc2 for the weightings.
1866 				 *
1867 				 * Since hc1 and hc2 are chosen so that
1868 				 * hc1 + hc2 == 128 (and same for wc1 + wc2),
1869 				 * the >> 14 below is a quick way to divide by
1870 				 * (hc1 + hc2) * (wc1 + wc2)
1871 				 */
1872 				for (i = 0; i < 4; i++)
1873 					pixel[i] = (
1874 					    (png->image[p00 + i] * hc1 +
1875 					    png->image[p01 + i] * hc2) * wc1 +
1876 					    (png->image[p10 + i] * hc1 +
1877 					    png->image[p11 + i] * hc2) * wc2)
1878 					    >> 14;
1879 
1880 				r = pixel[0];
1881 				g = pixel[1];
1882 				b = pixel[2];
1883 				a = pixel[3];
1884 			}
1885 
1886 			if (trace)
1887 				printf("r/g/b: %x/%x/%x\n", r, g, b);
1888 			/*
1889 			 * Rough colorspace reduction for 15/16 bit colors.
1890 			 */
1891 			p[j].Red = r >> rs;
1892                         p[j].Green = g >> gs;
1893                         p[j].Blue = b >> bs;
1894                         p[j].Reserved = a;
1895 
1896 			wc += wcstep;
1897 		}
1898 		hc += hcstep;
1899 	}
1900 
1901 	gfx_fb_cons_display(ux1, uy1, fwidth, fheight, data);
1902 	free(data);
1903 	return (0);
1904 }
1905 
1906 /*
1907  * Reset font flags to FONT_AUTO.
1908  */
1909 void
1910 reset_font_flags(void)
1911 {
1912 	struct fontlist *fl;
1913 
1914 	STAILQ_FOREACH(fl, &fonts, font_next) {
1915 		fl->font_flags = FONT_AUTO;
1916 	}
1917 }
1918 
1919 /* Return  w^2 + h^2 or 0, if the dimensions are unknown */
1920 static unsigned
1921 edid_diagonal_squared(void)
1922 {
1923 	unsigned w, h;
1924 
1925 	if (edid_info == NULL)
1926 		return (0);
1927 
1928 	w = edid_info->display.max_horizontal_image_size;
1929 	h = edid_info->display.max_vertical_image_size;
1930 
1931 	/* If either one is 0, we have aspect ratio, not size */
1932 	if (w == 0 || h == 0)
1933 		return (0);
1934 
1935 	/*
1936 	 * some monitors encode the aspect ratio instead of the physical size.
1937 	 */
1938 	if ((w == 16 && h == 9) || (w == 16 && h == 10) ||
1939 	    (w == 4 && h == 3) || (w == 5 && h == 4))
1940 		return (0);
1941 
1942 	/*
1943 	 * translate cm to inch, note we scale by 100 here.
1944 	 */
1945 	w = w * 100 / 254;
1946 	h = h * 100 / 254;
1947 
1948 	/* Return w^2 + h^2 */
1949 	return (w * w + h * h);
1950 }
1951 
1952 /*
1953  * calculate pixels per inch.
1954  */
1955 static unsigned
1956 gfx_get_ppi(void)
1957 {
1958 	unsigned dp, di;
1959 
1960 	di = edid_diagonal_squared();
1961 	if (di == 0)
1962 		return (0);
1963 
1964 	dp = gfx_state.tg_fb.fb_width *
1965 	    gfx_state.tg_fb.fb_width +
1966 	    gfx_state.tg_fb.fb_height *
1967 	    gfx_state.tg_fb.fb_height;
1968 
1969 	return (isqrt(dp / di));
1970 }
1971 
1972 /*
1973  * Calculate font size from density independent pixels (dp):
1974  * ((16dp * ppi) / 160) * display_factor.
1975  * Here we are using fixed constants: 1dp == 160 ppi and
1976  * display_factor 2.
1977  *
1978  * We are rounding font size up and are searching for font which is
1979  * not smaller than calculated size value.
1980  */
1981 static vt_font_bitmap_data_t *
1982 gfx_get_font(void)
1983 {
1984 	unsigned ppi, size;
1985 	vt_font_bitmap_data_t *font = NULL;
1986 	struct fontlist *fl, *next;
1987 
1988 	/* Text mode is not supported here. */
1989 	if (gfx_state.tg_fb_type == FB_TEXT)
1990 		return (NULL);
1991 
1992 	ppi = gfx_get_ppi();
1993 	if (ppi == 0)
1994 		return (NULL);
1995 
1996 	/*
1997 	 * We will search for 16dp font.
1998 	 * We are using scale up by 10 for roundup.
1999 	 */
2000 	size = (16 * ppi * 10) / 160;
2001 	/* Apply display factor 2.  */
2002 	size = roundup(size * 2, 10) / 10;
2003 
2004 	STAILQ_FOREACH(fl, &fonts, font_next) {
2005 		next = STAILQ_NEXT(fl, font_next);
2006 
2007 		/*
2008 		 * If this is last font or, if next font is smaller,
2009 		 * we have our font. Make sure, it actually is loaded.
2010 		 */
2011 		if (next == NULL || next->font_data->vfbd_height < size) {
2012 			font = fl->font_data;
2013 			if (font->vfbd_font == NULL ||
2014 			    fl->font_flags == FONT_RELOAD) {
2015 				if (fl->font_load != NULL &&
2016 				    fl->font_name != NULL)
2017 					font = fl->font_load(fl->font_name);
2018 			}
2019 			break;
2020 		}
2021 	}
2022 
2023 	return (font);
2024 }
2025 
2026 static vt_font_bitmap_data_t *
2027 set_font(teken_unit_t *rows, teken_unit_t *cols, teken_unit_t h, teken_unit_t w)
2028 {
2029 	vt_font_bitmap_data_t *font = NULL;
2030 	struct fontlist *fl;
2031 	unsigned height = h;
2032 	unsigned width = w;
2033 
2034 	/*
2035 	 * First check for manually loaded font.
2036 	 */
2037 	STAILQ_FOREACH(fl, &fonts, font_next) {
2038 		if (fl->font_flags == FONT_MANUAL) {
2039 			font = fl->font_data;
2040 			if (font->vfbd_font == NULL && fl->font_load != NULL &&
2041 			    fl->font_name != NULL) {
2042 				font = fl->font_load(fl->font_name);
2043 			}
2044 			if (font == NULL || font->vfbd_font == NULL)
2045 				font = NULL;
2046 			break;
2047 		}
2048 	}
2049 
2050 	if (font == NULL)
2051 		font = gfx_get_font();
2052 
2053 	if (font != NULL) {
2054 		*rows = height / font->vfbd_height;
2055 		*cols = width / font->vfbd_width;
2056 		return (font);
2057 	}
2058 
2059 	/*
2060 	 * Find best font for these dimensions, or use default.
2061 	 * If height >= VT_FB_MAX_HEIGHT and width >= VT_FB_MAX_WIDTH,
2062 	 * do not use smaller font than our DEFAULT_FONT_DATA.
2063 	 */
2064 	STAILQ_FOREACH(fl, &fonts, font_next) {
2065 		font = fl->font_data;
2066 		if ((*rows * font->vfbd_height <= height &&
2067 		    *cols * font->vfbd_width <= width) ||
2068 		    (height >= VT_FB_MAX_HEIGHT &&
2069 		    width >= VT_FB_MAX_WIDTH &&
2070 		    font->vfbd_height == DEFAULT_FONT_DATA.vfbd_height &&
2071 		    font->vfbd_width == DEFAULT_FONT_DATA.vfbd_width)) {
2072 			if (font->vfbd_font == NULL ||
2073 			    fl->font_flags == FONT_RELOAD) {
2074 				if (fl->font_load != NULL &&
2075 				    fl->font_name != NULL) {
2076 					font = fl->font_load(fl->font_name);
2077 				}
2078 				if (font == NULL)
2079 					continue;
2080 			}
2081 			*rows = height / font->vfbd_height;
2082 			*cols = width / font->vfbd_width;
2083 			break;
2084 		}
2085 		font = NULL;
2086 	}
2087 
2088 	if (font == NULL) {
2089 		/*
2090 		 * We have fonts sorted smallest last, try it before
2091 		 * falling back to builtin.
2092 		 */
2093 		fl = STAILQ_LAST(&fonts, fontlist, font_next);
2094 		if (fl != NULL && fl->font_load != NULL &&
2095 		    fl->font_name != NULL) {
2096 			font = fl->font_load(fl->font_name);
2097 		}
2098 		if (font == NULL)
2099 			font = &DEFAULT_FONT_DATA;
2100 
2101 		*rows = height / font->vfbd_height;
2102 		*cols = width / font->vfbd_width;
2103 	}
2104 
2105 	return (font);
2106 }
2107 
2108 static void
2109 cons_clear(void)
2110 {
2111 	char clear[] = { '\033', 'c' };
2112 
2113 	/* Reset terminal */
2114 	teken_input(&gfx_state.tg_teken, clear, sizeof(clear));
2115 	gfx_state.tg_functions->tf_param(&gfx_state, TP_SHOWCURSOR, 0);
2116 }
2117 
2118 void
2119 setup_font(teken_gfx_t *state, teken_unit_t height, teken_unit_t width)
2120 {
2121 	vt_font_bitmap_data_t *font_data;
2122 	teken_pos_t *tp = &state->tg_tp;
2123 	char env[8];
2124 	int i;
2125 
2126 	/*
2127 	 * set_font() will select a appropriate sized font for
2128 	 * the number of rows and columns selected.  If we don't
2129 	 * have a font that will fit, then it will use the
2130 	 * default builtin font and adjust the rows and columns
2131 	 * to fit on the screen.
2132 	 */
2133 	font_data = set_font(&tp->tp_row, &tp->tp_col, height, width);
2134 
2135         if (font_data == NULL)
2136 		panic("out of memory");
2137 
2138 	for (i = 0; i < VFNT_MAPS; i++) {
2139 		state->tg_font.vf_map[i] =
2140 		    font_data->vfbd_font->vf_map[i];
2141 		state->tg_font.vf_map_count[i] =
2142 		    font_data->vfbd_font->vf_map_count[i];
2143 	}
2144 
2145 	state->tg_font.vf_bytes = font_data->vfbd_font->vf_bytes;
2146 	state->tg_font.vf_height = font_data->vfbd_font->vf_height;
2147 	state->tg_font.vf_width = font_data->vfbd_font->vf_width;
2148 
2149 	snprintf(env, sizeof (env), "%ux%u",
2150 	    state->tg_font.vf_width, state->tg_font.vf_height);
2151 	env_setenv("screen.font", EV_VOLATILE | EV_NOHOOK,
2152 	    env, font_set, env_nounset);
2153 }
2154 
2155 /* Binary search for the glyph. Return 0 if not found. */
2156 static uint16_t
2157 font_bisearch(const vfnt_map_t *map, uint32_t len, teken_char_t src)
2158 {
2159 	unsigned min, mid, max;
2160 
2161 	min = 0;
2162 	max = len - 1;
2163 
2164 	/* Empty font map. */
2165 	if (len == 0)
2166 		return (0);
2167 	/* Character below minimal entry. */
2168 	if (src < map[0].vfm_src)
2169 		return (0);
2170 	/* Optimization: ASCII characters occur very often. */
2171 	if (src <= map[0].vfm_src + map[0].vfm_len)
2172 		return (src - map[0].vfm_src + map[0].vfm_dst);
2173 	/* Character above maximum entry. */
2174 	if (src > map[max].vfm_src + map[max].vfm_len)
2175 		return (0);
2176 
2177 	/* Binary search. */
2178 	while (max >= min) {
2179 		mid = (min + max) / 2;
2180 		if (src < map[mid].vfm_src)
2181 			max = mid - 1;
2182 		else if (src > map[mid].vfm_src + map[mid].vfm_len)
2183 			min = mid + 1;
2184 		else
2185 			return (src - map[mid].vfm_src + map[mid].vfm_dst);
2186 	}
2187 
2188 	return (0);
2189 }
2190 
2191 /*
2192  * Return glyph bitmap. If glyph is not found, we will return bitmap
2193  * for the first (offset 0) glyph.
2194  */
2195 uint8_t *
2196 font_lookup(const struct vt_font *vf, teken_char_t c, const teken_attr_t *a)
2197 {
2198 	uint16_t dst;
2199 	size_t stride;
2200 
2201 	/* Substitute bold with normal if not found. */
2202 	if (a->ta_format & TF_BOLD) {
2203 		dst = font_bisearch(vf->vf_map[VFNT_MAP_BOLD],
2204 		    vf->vf_map_count[VFNT_MAP_BOLD], c);
2205 		if (dst != 0)
2206 			goto found;
2207 	}
2208 	dst = font_bisearch(vf->vf_map[VFNT_MAP_NORMAL],
2209 	    vf->vf_map_count[VFNT_MAP_NORMAL], c);
2210 
2211 found:
2212 	stride = howmany(vf->vf_width, 8) * vf->vf_height;
2213 	return (&vf->vf_bytes[dst * stride]);
2214 }
2215 
2216 static int
2217 load_mapping(int fd, struct vt_font *fp, int n)
2218 {
2219 	size_t i, size;
2220 	ssize_t rv;
2221 	vfnt_map_t *mp;
2222 
2223 	if (fp->vf_map_count[n] == 0)
2224 		return (0);
2225 
2226 	size = fp->vf_map_count[n] * sizeof(*mp);
2227 	mp = malloc(size);
2228 	if (mp == NULL)
2229 		return (ENOMEM);
2230 	fp->vf_map[n] = mp;
2231 
2232 	rv = read(fd, mp, size);
2233 	if (rv < 0 || (size_t)rv != size) {
2234 		free(fp->vf_map[n]);
2235 		fp->vf_map[n] = NULL;
2236 		return (EIO);
2237 	}
2238 
2239 	for (i = 0; i < fp->vf_map_count[n]; i++) {
2240 		mp[i].vfm_src = be32toh(mp[i].vfm_src);
2241 		mp[i].vfm_dst = be16toh(mp[i].vfm_dst);
2242 		mp[i].vfm_len = be16toh(mp[i].vfm_len);
2243 	}
2244 	return (0);
2245 }
2246 
2247 static int
2248 builtin_mapping(struct vt_font *fp, int n)
2249 {
2250 	size_t size;
2251 	struct vfnt_map *mp;
2252 
2253 	if (n >= VFNT_MAPS)
2254 		return (EINVAL);
2255 
2256 	if (fp->vf_map_count[n] == 0)
2257 		return (0);
2258 
2259 	size = fp->vf_map_count[n] * sizeof(*mp);
2260 	mp = malloc(size);
2261 	if (mp == NULL)
2262 		return (ENOMEM);
2263 	fp->vf_map[n] = mp;
2264 
2265 	memcpy(mp, DEFAULT_FONT_DATA.vfbd_font->vf_map[n], size);
2266 	return (0);
2267 }
2268 
2269 /*
2270  * Load font from builtin or from file.
2271  * We do need special case for builtin because the builtin font glyphs
2272  * are compressed and we do need to uncompress them.
2273  * Having single load_font() for both cases will help us to simplify
2274  * font switch handling.
2275  */
2276 static vt_font_bitmap_data_t *
2277 load_font(char *path)
2278 {
2279 	int fd, i;
2280 	uint32_t glyphs;
2281 	struct font_header fh;
2282 	struct fontlist *fl;
2283 	vt_font_bitmap_data_t *bp;
2284 	struct vt_font *fp;
2285 	size_t size;
2286 	ssize_t rv;
2287 
2288 	/* Get our entry from the font list. */
2289 	STAILQ_FOREACH(fl, &fonts, font_next) {
2290 		if (strcmp(fl->font_name, path) == 0)
2291 			break;
2292 	}
2293 	if (fl == NULL)
2294 		return (NULL);	/* Should not happen. */
2295 
2296 	bp = fl->font_data;
2297 	if (bp->vfbd_font != NULL && fl->font_flags != FONT_RELOAD)
2298 		return (bp);
2299 
2300 	fd = -1;
2301 	/*
2302 	 * Special case for builtin font.
2303 	 * Builtin font is the very first font we load, we do not have
2304 	 * previous loads to be released.
2305 	 */
2306 	if (fl->font_flags == FONT_BUILTIN) {
2307 		if ((fp = calloc(1, sizeof(struct vt_font))) == NULL)
2308 			return (NULL);
2309 
2310 		fp->vf_width = DEFAULT_FONT_DATA.vfbd_width;
2311 		fp->vf_height = DEFAULT_FONT_DATA.vfbd_height;
2312 
2313 		fp->vf_bytes = malloc(DEFAULT_FONT_DATA.vfbd_uncompressed_size);
2314 		if (fp->vf_bytes == NULL) {
2315 			free(fp);
2316 			return (NULL);
2317 		}
2318 
2319 		bp->vfbd_uncompressed_size =
2320 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size;
2321 		bp->vfbd_compressed_size =
2322 		    DEFAULT_FONT_DATA.vfbd_compressed_size;
2323 
2324 		if (lz4_decompress(DEFAULT_FONT_DATA.vfbd_compressed_data,
2325 		    fp->vf_bytes,
2326 		    DEFAULT_FONT_DATA.vfbd_compressed_size,
2327 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size, 0) != 0) {
2328 			free(fp->vf_bytes);
2329 			free(fp);
2330 			return (NULL);
2331 		}
2332 
2333 		for (i = 0; i < VFNT_MAPS; i++) {
2334 			fp->vf_map_count[i] =
2335 			    DEFAULT_FONT_DATA.vfbd_font->vf_map_count[i];
2336 			if (builtin_mapping(fp, i) != 0)
2337 				goto free_done;
2338 		}
2339 
2340 		bp->vfbd_font = fp;
2341 		return (bp);
2342 	}
2343 
2344 	fd = open(path, O_RDONLY);
2345 	if (fd < 0)
2346 		return (NULL);
2347 
2348 	size = sizeof(fh);
2349 	rv = read(fd, &fh, size);
2350 	if (rv < 0 || (size_t)rv != size) {
2351 		bp = NULL;
2352 		goto done;
2353 	}
2354 	if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC, sizeof(fh.fh_magic)) != 0) {
2355 		bp = NULL;
2356 		goto done;
2357 	}
2358 	if ((fp = calloc(1, sizeof(struct vt_font))) == NULL) {
2359 		bp = NULL;
2360 		goto done;
2361 	}
2362 	for (i = 0; i < VFNT_MAPS; i++)
2363 		fp->vf_map_count[i] = be32toh(fh.fh_map_count[i]);
2364 
2365 	glyphs = be32toh(fh.fh_glyph_count);
2366 	fp->vf_width = fh.fh_width;
2367 	fp->vf_height = fh.fh_height;
2368 
2369 	size = howmany(fp->vf_width, 8) * fp->vf_height * glyphs;
2370 	bp->vfbd_uncompressed_size = size;
2371 	if ((fp->vf_bytes = malloc(size)) == NULL)
2372 		goto free_done;
2373 
2374 	rv = read(fd, fp->vf_bytes, size);
2375 	if (rv < 0 || (size_t)rv != size)
2376 		goto free_done;
2377 	for (i = 0; i < VFNT_MAPS; i++) {
2378 		if (load_mapping(fd, fp, i) != 0)
2379 			goto free_done;
2380 	}
2381 
2382 	/*
2383 	 * Reset builtin flag now as we have full font loaded.
2384 	 */
2385 	if (fl->font_flags == FONT_BUILTIN)
2386 		fl->font_flags = FONT_AUTO;
2387 
2388 	/*
2389 	 * Release previously loaded entries. We can do this now, as
2390 	 * the new font is loaded. Note, there can be no console
2391 	 * output till the new font is in place and teken is notified.
2392 	 * We do need to keep fl->font_data for glyph dimensions.
2393 	 */
2394 	STAILQ_FOREACH(fl, &fonts, font_next) {
2395 		if (fl->font_data->vfbd_font == NULL)
2396 			continue;
2397 
2398 		for (i = 0; i < VFNT_MAPS; i++)
2399 			free(fl->font_data->vfbd_font->vf_map[i]);
2400 		free(fl->font_data->vfbd_font->vf_bytes);
2401 		free(fl->font_data->vfbd_font);
2402 		fl->font_data->vfbd_font = NULL;
2403 	}
2404 
2405 	bp->vfbd_font = fp;
2406 	bp->vfbd_compressed_size = 0;
2407 
2408 done:
2409 	if (fd != -1)
2410 		close(fd);
2411 	return (bp);
2412 
2413 free_done:
2414 	for (i = 0; i < VFNT_MAPS; i++)
2415 		free(fp->vf_map[i]);
2416 	free(fp->vf_bytes);
2417 	free(fp);
2418 	bp = NULL;
2419 	goto done;
2420 }
2421 
2422 struct name_entry {
2423 	char			*n_name;
2424 	SLIST_ENTRY(name_entry)	n_entry;
2425 };
2426 
2427 SLIST_HEAD(name_list, name_entry);
2428 
2429 /* Read font names from index file. */
2430 static struct name_list *
2431 read_list(char *fonts)
2432 {
2433 	struct name_list *nl;
2434 	struct name_entry *np;
2435 	char *dir, *ptr;
2436 	char buf[PATH_MAX];
2437 	int fd, len;
2438 
2439 	TSENTER();
2440 
2441 	dir = strdup(fonts);
2442 	if (dir == NULL)
2443 		return (NULL);
2444 
2445 	ptr = strrchr(dir, '/');
2446 	*ptr = '\0';
2447 
2448 	fd = open(fonts, O_RDONLY);
2449 	if (fd < 0)
2450 		return (NULL);
2451 
2452 	nl = malloc(sizeof(*nl));
2453 	if (nl == NULL) {
2454 		close(fd);
2455 		return (nl);
2456 	}
2457 
2458 	SLIST_INIT(nl);
2459 	while ((len = fgetstr(buf, sizeof (buf), fd)) >= 0) {
2460 		if (*buf == '#' || *buf == '\0')
2461 			continue;
2462 
2463 		if (bcmp(buf, "MENU", 4) == 0)
2464 			continue;
2465 
2466 		if (bcmp(buf, "FONT", 4) == 0)
2467 			continue;
2468 
2469 		ptr = strchr(buf, ':');
2470 		if (ptr == NULL)
2471 			continue;
2472 		else
2473 			*ptr = '\0';
2474 
2475 		np = malloc(sizeof(*np));
2476 		if (np == NULL) {
2477 			close(fd);
2478 			return (nl);	/* return what we have */
2479 		}
2480 		if (asprintf(&np->n_name, "%s/%s", dir, buf) < 0) {
2481 			free(np);
2482 			close(fd);
2483 			return (nl);    /* return what we have */
2484 		}
2485 		SLIST_INSERT_HEAD(nl, np, n_entry);
2486 	}
2487 	close(fd);
2488 	TSEXIT();
2489 	return (nl);
2490 }
2491 
2492 /*
2493  * Read the font properties and insert new entry into the list.
2494  * The font list is built in descending order.
2495  */
2496 static bool
2497 insert_font(char *name, FONT_FLAGS flags)
2498 {
2499 	struct font_header fh;
2500 	struct fontlist *fp, *previous, *entry, *next;
2501 	size_t size;
2502 	ssize_t rv;
2503 	int fd;
2504 	char *font_name;
2505 
2506 	TSENTER();
2507 
2508 	font_name = NULL;
2509 	if (flags == FONT_BUILTIN) {
2510 		/*
2511 		 * We only install builtin font once, while setting up
2512 		 * initial console. Since this will happen very early,
2513 		 * we assume asprintf will not fail. Once we have access to
2514 		 * files, the builtin font will be replaced by font loaded
2515 		 * from file.
2516 		 */
2517 		if (!STAILQ_EMPTY(&fonts))
2518 			return (false);
2519 
2520 		fh.fh_width = DEFAULT_FONT_DATA.vfbd_width;
2521 		fh.fh_height = DEFAULT_FONT_DATA.vfbd_height;
2522 
2523 		(void) asprintf(&font_name, "%dx%d",
2524 		    DEFAULT_FONT_DATA.vfbd_width,
2525 		    DEFAULT_FONT_DATA.vfbd_height);
2526 	} else {
2527 		fd = open(name, O_RDONLY);
2528 		if (fd < 0)
2529 			return (false);
2530 		rv = read(fd, &fh, sizeof(fh));
2531 		close(fd);
2532 		if (rv < 0 || (size_t)rv != sizeof(fh))
2533 			return (false);
2534 
2535 		if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC,
2536 		    sizeof(fh.fh_magic)) != 0)
2537 			return (false);
2538 		font_name = strdup(name);
2539 	}
2540 
2541 	if (font_name == NULL)
2542 		return (false);
2543 
2544 	/*
2545 	 * If we have an entry with the same glyph dimensions, replace
2546 	 * the file name and mark us. We only support unique dimensions.
2547 	 */
2548 	STAILQ_FOREACH(entry, &fonts, font_next) {
2549 		if (fh.fh_width == entry->font_data->vfbd_width &&
2550 		    fh.fh_height == entry->font_data->vfbd_height) {
2551 			free(entry->font_name);
2552 			entry->font_name = font_name;
2553 			entry->font_flags = FONT_RELOAD;
2554 			TSEXIT();
2555 			return (true);
2556 		}
2557 	}
2558 
2559 	fp = calloc(sizeof(*fp), 1);
2560 	if (fp == NULL) {
2561 		free(font_name);
2562 		return (false);
2563 	}
2564 	fp->font_data = calloc(sizeof(*fp->font_data), 1);
2565 	if (fp->font_data == NULL) {
2566 		free(font_name);
2567 		free(fp);
2568 		return (false);
2569 	}
2570 	fp->font_name = font_name;
2571 	fp->font_flags = flags;
2572 	fp->font_load = load_font;
2573 	fp->font_data->vfbd_width = fh.fh_width;
2574 	fp->font_data->vfbd_height = fh.fh_height;
2575 
2576 	if (STAILQ_EMPTY(&fonts)) {
2577 		STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2578 		TSEXIT();
2579 		return (true);
2580 	}
2581 
2582 	previous = NULL;
2583 	size = fp->font_data->vfbd_width * fp->font_data->vfbd_height;
2584 
2585 	STAILQ_FOREACH(entry, &fonts, font_next) {
2586 		vt_font_bitmap_data_t *bd;
2587 
2588 		bd = entry->font_data;
2589 		/* Should fp be inserted before the entry? */
2590 		if (size > bd->vfbd_width * bd->vfbd_height) {
2591 			if (previous == NULL) {
2592 				STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2593 			} else {
2594 				STAILQ_INSERT_AFTER(&fonts, previous, fp,
2595 				    font_next);
2596 			}
2597 			TSEXIT();
2598 			return (true);
2599 		}
2600 		next = STAILQ_NEXT(entry, font_next);
2601 		if (next == NULL ||
2602 		    size > next->font_data->vfbd_width *
2603 		    next->font_data->vfbd_height) {
2604 			STAILQ_INSERT_AFTER(&fonts, entry, fp, font_next);
2605 			TSEXIT();
2606 			return (true);
2607 		}
2608 		previous = entry;
2609 	}
2610 	TSEXIT();
2611 	return (true);
2612 }
2613 
2614 static int
2615 font_set(struct env_var *ev __unused, int flags __unused, const void *value)
2616 {
2617 	struct fontlist *fl;
2618 	char *eptr;
2619 	unsigned long x = 0, y = 0;
2620 
2621 	/*
2622 	 * Attempt to extract values from "XxY" string. In case of error,
2623 	 * we have unmaching glyph dimensions and will just output the
2624 	 * available values.
2625 	 */
2626 	if (value != NULL) {
2627 		x = strtoul(value, &eptr, 10);
2628 		if (*eptr == 'x')
2629 			y = strtoul(eptr + 1, &eptr, 10);
2630 	}
2631 	STAILQ_FOREACH(fl, &fonts, font_next) {
2632 		if (fl->font_data->vfbd_width == x &&
2633 		    fl->font_data->vfbd_height == y)
2634 			break;
2635 	}
2636 	if (fl != NULL) {
2637 		/* Reset any FONT_MANUAL flag. */
2638 		reset_font_flags();
2639 
2640 		/* Mark this font manually loaded */
2641 		fl->font_flags = FONT_MANUAL;
2642 		cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2643 		return (CMD_OK);
2644 	}
2645 
2646 	printf("Available fonts:\n");
2647 	STAILQ_FOREACH(fl, &fonts, font_next) {
2648 		printf("    %dx%d\n", fl->font_data->vfbd_width,
2649 		    fl->font_data->vfbd_height);
2650 	}
2651 	return (CMD_OK);
2652 }
2653 
2654 void
2655 bios_text_font(bool use_vga_font)
2656 {
2657 	if (use_vga_font)
2658 		(void) insert_font(VGA_8X16_FONT, FONT_MANUAL);
2659 	else
2660 		(void) insert_font(DEFAULT_8X16_FONT, FONT_MANUAL);
2661 }
2662 
2663 void
2664 autoload_font(bool bios)
2665 {
2666 	struct name_list *nl;
2667 	struct name_entry *np;
2668 
2669 	TSENTER();
2670 
2671 	nl = read_list("/boot/fonts/INDEX.fonts");
2672 	if (nl == NULL)
2673 		return;
2674 
2675 	while (!SLIST_EMPTY(nl)) {
2676 		np = SLIST_FIRST(nl);
2677 		SLIST_REMOVE_HEAD(nl, n_entry);
2678 		if (insert_font(np->n_name, FONT_AUTO) == false)
2679 			printf("failed to add font: %s\n", np->n_name);
2680 		free(np->n_name);
2681 		free(np);
2682 	}
2683 
2684 	/*
2685 	 * If vga text mode was requested, load vga.font (8x16 bold) font.
2686 	 */
2687 	if (bios) {
2688 		bios_text_font(true);
2689 	}
2690 
2691 	(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2692 
2693 	TSEXIT();
2694 }
2695 
2696 COMMAND_SET(load_font, "loadfont", "load console font from file", command_font);
2697 
2698 static int
2699 command_font(int argc, char *argv[])
2700 {
2701 	int i, c, rc;
2702 	struct fontlist *fl;
2703 	vt_font_bitmap_data_t *bd;
2704 	bool list;
2705 
2706 	list = false;
2707 	optind = 1;
2708 	optreset = 1;
2709 	rc = CMD_OK;
2710 
2711 	while ((c = getopt(argc, argv, "l")) != -1) {
2712 		switch (c) {
2713 		case 'l':
2714 			list = true;
2715 			break;
2716 		case '?':
2717 		default:
2718 			return (CMD_ERROR);
2719 		}
2720 	}
2721 
2722 	argc -= optind;
2723 	argv += optind;
2724 
2725 	if (argc > 1 || (list && argc != 0)) {
2726 		printf("Usage: loadfont [-l] | [file.fnt]\n");
2727 		return (CMD_ERROR);
2728 	}
2729 
2730 	if (list) {
2731 		STAILQ_FOREACH(fl, &fonts, font_next) {
2732 			printf("font %s: %dx%d%s\n", fl->font_name,
2733 			    fl->font_data->vfbd_width,
2734 			    fl->font_data->vfbd_height,
2735 			    fl->font_data->vfbd_font == NULL? "" : " loaded");
2736 		}
2737 		return (CMD_OK);
2738 	}
2739 
2740 	/* Clear scren */
2741 	cons_clear();
2742 
2743 	if (argc == 1) {
2744 		char *name = argv[0];
2745 
2746 		if (insert_font(name, FONT_MANUAL) == false) {
2747 			printf("loadfont error: failed to load: %s\n", name);
2748 			return (CMD_ERROR);
2749 		}
2750 
2751 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2752 		return (CMD_OK);
2753 	}
2754 
2755 	if (argc == 0) {
2756 		/*
2757 		 * Walk entire font list, release any loaded font, and set
2758 		 * autoload flag. The font list does have at least the builtin
2759 		 * default font.
2760 		 */
2761 		STAILQ_FOREACH(fl, &fonts, font_next) {
2762 			if (fl->font_data->vfbd_font != NULL) {
2763 
2764 				bd = fl->font_data;
2765 				/*
2766 				 * Note the setup_font() is releasing
2767 				 * font bytes.
2768 				 */
2769 				for (i = 0; i < VFNT_MAPS; i++)
2770 					free(bd->vfbd_font->vf_map[i]);
2771 				free(fl->font_data->vfbd_font);
2772 				fl->font_data->vfbd_font = NULL;
2773 				fl->font_data->vfbd_uncompressed_size = 0;
2774 				fl->font_flags = FONT_AUTO;
2775 			}
2776 		}
2777 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2778 	}
2779 	return (rc);
2780 }
2781 
2782 bool
2783 gfx_get_edid_resolution(struct vesa_edid_info *edid, edid_res_list_t *res)
2784 {
2785 	struct resolution *rp, *p;
2786 
2787 	/*
2788 	 * Walk detailed timings tables (4).
2789 	 */
2790 	if ((edid->display.supported_features
2791 	    & EDID_FEATURE_PREFERRED_TIMING_MODE) != 0) {
2792 		/* Walk detailed timing descriptors (4) */
2793 		for (int i = 0; i < DET_TIMINGS; i++) {
2794 			/*
2795 			 * Reserved value 0 is not used for display decriptor.
2796 			 */
2797 			if (edid->detailed_timings[i].pixel_clock == 0)
2798 				continue;
2799 			if ((rp = malloc(sizeof(*rp))) == NULL)
2800 				continue;
2801 			rp->width = GET_EDID_INFO_WIDTH(edid, i);
2802 			rp->height = GET_EDID_INFO_HEIGHT(edid, i);
2803 			if (rp->width > 0 && rp->width <= EDID_MAX_PIXELS &&
2804 			    rp->height > 0 && rp->height <= EDID_MAX_LINES)
2805 				TAILQ_INSERT_TAIL(res, rp, next);
2806 			else
2807 				free(rp);
2808 		}
2809 	}
2810 
2811 	/*
2812 	 * Walk standard timings list (8).
2813 	 */
2814 	for (int i = 0; i < STD_TIMINGS; i++) {
2815 		/* Is this field unused? */
2816 		if (edid->standard_timings[i] == 0x0101)
2817 			continue;
2818 
2819 		if ((rp = malloc(sizeof(*rp))) == NULL)
2820 			continue;
2821 
2822 		rp->width = HSIZE(edid->standard_timings[i]);
2823 		switch (RATIO(edid->standard_timings[i])) {
2824 		case RATIO1_1:
2825 			rp->height = HSIZE(edid->standard_timings[i]);
2826 			if (edid->header.version > 1 ||
2827 			    edid->header.revision > 2) {
2828 				rp->height = rp->height * 10 / 16;
2829 			}
2830 			break;
2831 		case RATIO4_3:
2832 			rp->height = HSIZE(edid->standard_timings[i]) * 3 / 4;
2833 			break;
2834 		case RATIO5_4:
2835 			rp->height = HSIZE(edid->standard_timings[i]) * 4 / 5;
2836 			break;
2837 		case RATIO16_9:
2838 			rp->height = HSIZE(edid->standard_timings[i]) * 9 / 16;
2839 			break;
2840 		}
2841 
2842 		/*
2843 		 * Create resolution list in decreasing order, except keep
2844 		 * first entry (preferred timing mode).
2845 		 */
2846 		TAILQ_FOREACH(p, res, next) {
2847 			if (p->width * p->height < rp->width * rp->height) {
2848 				/* Keep preferred mode first */
2849 				if (TAILQ_FIRST(res) == p)
2850 					TAILQ_INSERT_AFTER(res, p, rp, next);
2851 				else
2852 					TAILQ_INSERT_BEFORE(p, rp, next);
2853 				break;
2854 			}
2855 			if (TAILQ_NEXT(p, next) == NULL) {
2856 				TAILQ_INSERT_TAIL(res, rp, next);
2857 				break;
2858 			}
2859 		}
2860 	}
2861 	return (!TAILQ_EMPTY(res));
2862 }
2863