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