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