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