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