xref: /freebsd/stand/efi/loader/framebuffer.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*-
2  * Copyright (c) 2013 The FreeBSD Foundation
3  *
4  * This software was developed by Benno Rice under sponsorship from
5  * the FreeBSD Foundation.
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <bootstrap.h>
32 #include <sys/endian.h>
33 #include <sys/param.h>
34 #include <stand.h>
35 
36 #include <efi.h>
37 #include <efilib.h>
38 #include <efiuga.h>
39 #include <efipciio.h>
40 #include <Protocol/EdidActive.h>
41 #include <Protocol/EdidDiscovered.h>
42 #include <machine/metadata.h>
43 
44 #include "bootstrap.h"
45 #include "framebuffer.h"
46 
47 static EFI_GUID conout_guid = EFI_CONSOLE_OUT_DEVICE_GUID;
48 EFI_GUID gop_guid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
49 static EFI_GUID pciio_guid = EFI_PCI_IO_PROTOCOL_GUID;
50 static EFI_GUID uga_guid = EFI_UGA_DRAW_PROTOCOL_GUID;
51 static EFI_GUID active_edid_guid = EFI_EDID_ACTIVE_PROTOCOL_GUID;
52 static EFI_GUID discovered_edid_guid = EFI_EDID_DISCOVERED_PROTOCOL_GUID;
53 static EFI_HANDLE gop_handle;
54 
55 /* Cached EDID. */
56 struct vesa_edid_info *edid_info = NULL;
57 
58 static EFI_GRAPHICS_OUTPUT *gop;
59 static EFI_UGA_DRAW_PROTOCOL *uga;
60 
61 static struct named_resolution {
62 	const char *name;
63 	const char *alias;
64 	unsigned int width;
65 	unsigned int height;
66 } resolutions[] = {
67 	{
68 		.name = "480p",
69 		.width = 640,
70 		.height = 480,
71 	},
72 	{
73 		.name = "720p",
74 		.width = 1280,
75 		.height = 720,
76 	},
77 	{
78 		.name = "1080p",
79 		.width = 1920,
80 		.height = 1080,
81 	},
82 	{
83 		.name = "2160p",
84 		.alias = "4k",
85 		.width = 3840,
86 		.height = 2160,
87 	},
88 	{
89 		.name = "5k",
90 		.width = 5120,
91 		.height = 2880,
92 	}
93 };
94 
95 static u_int
96 efifb_color_depth(struct efi_fb *efifb)
97 {
98 	uint32_t mask;
99 	u_int depth;
100 
101 	mask = efifb->fb_mask_red | efifb->fb_mask_green |
102 	    efifb->fb_mask_blue | efifb->fb_mask_reserved;
103 	if (mask == 0)
104 		return (0);
105 	for (depth = 1; mask != 1; depth++)
106 		mask >>= 1;
107 	return (depth);
108 }
109 
110 static int
111 efifb_mask_from_pixfmt(struct efi_fb *efifb, EFI_GRAPHICS_PIXEL_FORMAT pixfmt,
112     EFI_PIXEL_BITMASK *pixinfo)
113 {
114 	int result;
115 
116 	result = 0;
117 	switch (pixfmt) {
118 	case PixelRedGreenBlueReserved8BitPerColor:
119 	case PixelBltOnly:
120 		efifb->fb_mask_red = 0x000000ff;
121 		efifb->fb_mask_green = 0x0000ff00;
122 		efifb->fb_mask_blue = 0x00ff0000;
123 		efifb->fb_mask_reserved = 0xff000000;
124 		break;
125 	case PixelBlueGreenRedReserved8BitPerColor:
126 		efifb->fb_mask_red = 0x00ff0000;
127 		efifb->fb_mask_green = 0x0000ff00;
128 		efifb->fb_mask_blue = 0x000000ff;
129 		efifb->fb_mask_reserved = 0xff000000;
130 		break;
131 	case PixelBitMask:
132 		efifb->fb_mask_red = pixinfo->RedMask;
133 		efifb->fb_mask_green = pixinfo->GreenMask;
134 		efifb->fb_mask_blue = pixinfo->BlueMask;
135 		efifb->fb_mask_reserved = pixinfo->ReservedMask;
136 		break;
137 	default:
138 		result = 1;
139 		break;
140 	}
141 	return (result);
142 }
143 
144 static int
145 efifb_from_gop(struct efi_fb *efifb, EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *mode,
146     EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info)
147 {
148 	int result;
149 
150 	efifb->fb_addr = mode->FrameBufferBase;
151 	efifb->fb_size = mode->FrameBufferSize;
152 	efifb->fb_height = info->VerticalResolution;
153 	efifb->fb_width = info->HorizontalResolution;
154 	efifb->fb_stride = info->PixelsPerScanLine;
155 	result = efifb_mask_from_pixfmt(efifb, info->PixelFormat,
156 	    &info->PixelInformation);
157 	return (result);
158 }
159 
160 static ssize_t
161 efifb_uga_find_pixel(EFI_UGA_DRAW_PROTOCOL *uga, u_int line,
162     EFI_PCI_IO_PROTOCOL *pciio, uint64_t addr, uint64_t size)
163 {
164 	EFI_UGA_PIXEL pix0, pix1;
165 	uint8_t *data1, *data2;
166 	size_t count, maxcount = 1024;
167 	ssize_t ofs;
168 	EFI_STATUS status;
169 	u_int idx;
170 
171 	status = uga->Blt(uga, &pix0, EfiUgaVideoToBltBuffer,
172 	    0, line, 0, 0, 1, 1, 0);
173 	if (EFI_ERROR(status)) {
174 		printf("UGA BLT operation failed (video->buffer)");
175 		return (-1);
176 	}
177 	pix1.Red = ~pix0.Red;
178 	pix1.Green = ~pix0.Green;
179 	pix1.Blue = ~pix0.Blue;
180 	pix1.Reserved = 0;
181 
182 	data1 = calloc(maxcount, 2);
183 	if (data1 == NULL) {
184 		printf("Unable to allocate memory");
185 		return (-1);
186 	}
187 	data2 = data1 + maxcount;
188 
189 	ofs = 0;
190 	while (size > 0) {
191 		count = min(size, maxcount);
192 
193 		status = pciio->Mem.Read(pciio, EfiPciIoWidthUint32,
194 		    EFI_PCI_IO_PASS_THROUGH_BAR, addr + ofs, count >> 2,
195 		    data1);
196 		if (EFI_ERROR(status)) {
197 			printf("Error reading frame buffer (before)");
198 			goto fail;
199 		}
200 		status = uga->Blt(uga, &pix1, EfiUgaBltBufferToVideo,
201 		    0, 0, 0, line, 1, 1, 0);
202 		if (EFI_ERROR(status)) {
203 			printf("UGA BLT operation failed (modify)");
204 			goto fail;
205 		}
206 		status = pciio->Mem.Read(pciio, EfiPciIoWidthUint32,
207 		    EFI_PCI_IO_PASS_THROUGH_BAR, addr + ofs, count >> 2,
208 		    data2);
209 		if (EFI_ERROR(status)) {
210 			printf("Error reading frame buffer (after)");
211 			goto fail;
212 		}
213 		status = uga->Blt(uga, &pix0, EfiUgaBltBufferToVideo,
214 		    0, 0, 0, line, 1, 1, 0);
215 		if (EFI_ERROR(status)) {
216 			printf("UGA BLT operation failed (restore)");
217 			goto fail;
218 		}
219 		for (idx = 0; idx < count; idx++) {
220 			if (data1[idx] != data2[idx]) {
221 				free(data1);
222 				return (ofs + (idx & ~3));
223 			}
224 		}
225 		ofs += count;
226 		size -= count;
227 	}
228 	printf("No change detected in frame buffer");
229 
230  fail:
231 	printf(" -- error %lu\n", EFI_ERROR_CODE(status));
232 	free(data1);
233 	return (-1);
234 }
235 
236 static EFI_PCI_IO_PROTOCOL *
237 efifb_uga_get_pciio(void)
238 {
239 	EFI_PCI_IO_PROTOCOL *pciio;
240 	EFI_HANDLE *buf, *hp;
241 	EFI_STATUS status;
242 	UINTN bufsz;
243 
244 	/* Get all handles that support the UGA protocol. */
245 	bufsz = 0;
246 	status = BS->LocateHandle(ByProtocol, &uga_guid, NULL, &bufsz, NULL);
247 	if (status != EFI_BUFFER_TOO_SMALL)
248 		return (NULL);
249 	buf = malloc(bufsz);
250 	status = BS->LocateHandle(ByProtocol, &uga_guid, NULL, &bufsz, buf);
251 	if (status != EFI_SUCCESS) {
252 		free(buf);
253 		return (NULL);
254 	}
255 	bufsz /= sizeof(EFI_HANDLE);
256 
257 	/* Get the PCI I/O interface of the first handle that supports it. */
258 	pciio = NULL;
259 	for (hp = buf; hp < buf + bufsz; hp++) {
260 		status = OpenProtocolByHandle(*hp, &pciio_guid,
261 		    (void **)&pciio);
262 		if (status == EFI_SUCCESS) {
263 			free(buf);
264 			return (pciio);
265 		}
266 	}
267 	free(buf);
268 	return (NULL);
269 }
270 
271 static EFI_STATUS
272 efifb_uga_locate_framebuffer(EFI_PCI_IO_PROTOCOL *pciio, uint64_t *addrp,
273     uint64_t *sizep)
274 {
275 	uint8_t *resattr;
276 	uint64_t addr, size;
277 	EFI_STATUS status;
278 	u_int bar;
279 
280 	if (pciio == NULL)
281 		return (EFI_DEVICE_ERROR);
282 
283 	/* Attempt to get the frame buffer address (imprecise). */
284 	*addrp = 0;
285 	*sizep = 0;
286 	for (bar = 0; bar < 6; bar++) {
287 		status = pciio->GetBarAttributes(pciio, bar, NULL,
288 		    (void **)&resattr);
289 		if (status != EFI_SUCCESS)
290 			continue;
291 		/* XXX magic offsets and constants. */
292 		if (resattr[0] == 0x87 && resattr[3] == 0) {
293 			/* 32-bit address space descriptor (MEMIO) */
294 			addr = le32dec(resattr + 10);
295 			size = le32dec(resattr + 22);
296 		} else if (resattr[0] == 0x8a && resattr[3] == 0) {
297 			/* 64-bit address space descriptor (MEMIO) */
298 			addr = le64dec(resattr + 14);
299 			size = le64dec(resattr + 38);
300 		} else {
301 			addr = 0;
302 			size = 0;
303 		}
304 		BS->FreePool(resattr);
305 		if (addr == 0 || size == 0)
306 			continue;
307 
308 		/* We assume the largest BAR is the frame buffer. */
309 		if (size > *sizep) {
310 			*addrp = addr;
311 			*sizep = size;
312 		}
313 	}
314 	return ((*addrp == 0 || *sizep == 0) ? EFI_DEVICE_ERROR : 0);
315 }
316 
317 static int
318 efifb_from_uga(struct efi_fb *efifb)
319 {
320 	EFI_PCI_IO_PROTOCOL *pciio;
321 	char *ev, *p;
322 	EFI_STATUS status;
323 	ssize_t offset;
324 	uint64_t fbaddr;
325 	uint32_t horiz, vert, stride;
326 	uint32_t np, depth, refresh;
327 
328 	status = uga->GetMode(uga, &horiz, &vert, &depth, &refresh);
329 	if (EFI_ERROR(status))
330 		return (1);
331 	efifb->fb_height = vert;
332 	efifb->fb_width = horiz;
333 	/* Paranoia... */
334 	if (efifb->fb_height == 0 || efifb->fb_width == 0)
335 		return (1);
336 
337 	/* The color masks are fixed AFAICT. */
338 	efifb_mask_from_pixfmt(efifb, PixelBlueGreenRedReserved8BitPerColor,
339 	    NULL);
340 
341 	/* pciio can be NULL on return! */
342 	pciio = efifb_uga_get_pciio();
343 
344 	/* Try to find the frame buffer. */
345 	status = efifb_uga_locate_framebuffer(pciio, &efifb->fb_addr,
346 	    &efifb->fb_size);
347 	if (EFI_ERROR(status)) {
348 		efifb->fb_addr = 0;
349 		efifb->fb_size = 0;
350 	}
351 
352 	/*
353 	 * There's no reliable way to detect the frame buffer or the
354 	 * offset within the frame buffer of the visible region, nor
355 	 * the stride. Our only option is to look at the system and
356 	 * fill in the blanks based on that. Luckily, UGA was mostly
357 	 * only used on Apple hardware.
358 	 */
359 	offset = -1;
360 	ev = getenv("smbios.system.maker");
361 	if (ev != NULL && !strcmp(ev, "Apple Inc.")) {
362 		ev = getenv("smbios.system.product");
363 		if (ev != NULL && !strcmp(ev, "iMac7,1")) {
364 			/* These are the expected values we should have. */
365 			horiz = 1680;
366 			vert = 1050;
367 			fbaddr = 0xc0000000;
368 			/* These are the missing bits. */
369 			offset = 0x10000;
370 			stride = 1728;
371 		} else if (ev != NULL && !strcmp(ev, "MacBook3,1")) {
372 			/* These are the expected values we should have. */
373 			horiz = 1280;
374 			vert = 800;
375 			fbaddr = 0xc0000000;
376 			/* These are the missing bits. */
377 			offset = 0x0;
378 			stride = 2048;
379 		}
380 	}
381 
382 	/*
383 	 * If this is hardware we know, make sure that it looks familiar
384 	 * before we accept our hardcoded values.
385 	 */
386 	if (offset >= 0 && efifb->fb_width == horiz &&
387 	    efifb->fb_height == vert && efifb->fb_addr == fbaddr) {
388 		efifb->fb_addr += offset;
389 		efifb->fb_size -= offset;
390 		efifb->fb_stride = stride;
391 		return (0);
392 	} else if (offset >= 0) {
393 		printf("Hardware make/model known, but graphics not "
394 		    "as expected.\n");
395 		printf("Console may not work!\n");
396 	}
397 
398 	/*
399 	 * The stride is equal or larger to the width. Often it's the
400 	 * next larger power of two. We'll start with that...
401 	 */
402 	efifb->fb_stride = efifb->fb_width;
403 	do {
404 		np = efifb->fb_stride & (efifb->fb_stride - 1);
405 		if (np) {
406 			efifb->fb_stride |= (np - 1);
407 			efifb->fb_stride++;
408 		}
409 	} while (np);
410 
411 	ev = getenv("hw.efifb.address");
412 	if (ev == NULL) {
413 		if (efifb->fb_addr == 0) {
414 			printf("Please set hw.efifb.address and "
415 			    "hw.efifb.stride.\n");
416 			return (1);
417 		}
418 
419 		/*
420 		 * The visible part of the frame buffer may not start at
421 		 * offset 0, so try to detect it. Note that we may not
422 		 * always be able to read from the frame buffer, which
423 		 * means that we may not be able to detect anything. In
424 		 * that case, we would take a long time scanning for a
425 		 * pixel change in the frame buffer, which would have it
426 		 * appear that we're hanging, so we limit the scan to
427 		 * 1/256th of the frame buffer. This number is mostly
428 		 * based on PR 202730 and the fact that on a MacBoook,
429 		 * where we can't read from the frame buffer the offset
430 		 * of the visible region is 0. In short: we want to scan
431 		 * enough to handle all adapters that have an offset
432 		 * larger than 0 and we want to scan as little as we can
433 		 * to not appear to hang when we can't read from the
434 		 * frame buffer.
435 		 */
436 		offset = efifb_uga_find_pixel(uga, 0, pciio, efifb->fb_addr,
437 		    efifb->fb_size >> 8);
438 		if (offset == -1) {
439 			printf("Unable to reliably detect frame buffer.\n");
440 		} else if (offset > 0) {
441 			efifb->fb_addr += offset;
442 			efifb->fb_size -= offset;
443 		}
444 	} else {
445 		offset = 0;
446 		efifb->fb_size = efifb->fb_height * efifb->fb_stride * 4;
447 		efifb->fb_addr = strtoul(ev, &p, 0);
448 		if (*p != '\0')
449 			return (1);
450 	}
451 
452 	ev = getenv("hw.efifb.stride");
453 	if (ev == NULL) {
454 		if (pciio != NULL && offset != -1) {
455 			/* Determine the stride. */
456 			offset = efifb_uga_find_pixel(uga, 1, pciio,
457 			    efifb->fb_addr, horiz * 8);
458 			if (offset != -1)
459 				efifb->fb_stride = offset >> 2;
460 		} else {
461 			printf("Unable to reliably detect the stride.\n");
462 		}
463 	} else {
464 		efifb->fb_stride = strtoul(ev, &p, 0);
465 		if (*p != '\0')
466 			return (1);
467 	}
468 
469 	/*
470 	 * We finalized on the stride, so recalculate the size of the
471 	 * frame buffer.
472 	 */
473 	efifb->fb_size = efifb->fb_height * efifb->fb_stride * 4;
474 	return (0);
475 }
476 
477 /*
478  * Fetch EDID info. Caller must free the buffer.
479  */
480 static struct vesa_edid_info *
481 efifb_gop_get_edid(EFI_HANDLE h)
482 {
483 	const uint8_t magic[] = EDID_MAGIC;
484 	EFI_EDID_ACTIVE_PROTOCOL *edid;
485 	struct vesa_edid_info *edid_infop;
486 	EFI_GUID *guid;
487 	EFI_STATUS status;
488 	size_t size;
489 
490 	guid = &active_edid_guid;
491 	status = BS->OpenProtocol(h, guid, (void **)&edid, IH, NULL,
492 	    EFI_OPEN_PROTOCOL_GET_PROTOCOL);
493 	if (status != EFI_SUCCESS ||
494 	    edid->SizeOfEdid == 0) {
495 		guid = &discovered_edid_guid;
496 		status = BS->OpenProtocol(h, guid, (void **)&edid, IH, NULL,
497 		    EFI_OPEN_PROTOCOL_GET_PROTOCOL);
498 		if (status != EFI_SUCCESS ||
499 		    edid->SizeOfEdid == 0)
500 			return (NULL);
501 	}
502 
503 	size = MAX(sizeof(*edid_infop), edid->SizeOfEdid);
504 
505 	edid_infop = calloc(1, size);
506 	if (edid_infop == NULL)
507 		return (NULL);
508 
509 	memcpy(edid_infop, edid->Edid, edid->SizeOfEdid);
510 
511 	/* Validate EDID */
512 	if (memcmp(edid_infop, magic, sizeof (magic)) != 0)
513 		goto error;
514 
515 	if (edid_infop->header.version != 1)
516 		goto error;
517 
518 	return (edid_infop);
519 error:
520 	free(edid_infop);
521 	return (NULL);
522 }
523 
524 static bool
525 efifb_get_edid(edid_res_list_t *res)
526 {
527 	bool rv = false;
528 
529 	if (edid_info == NULL)
530 		edid_info = efifb_gop_get_edid(gop_handle);
531 
532 	if (edid_info != NULL)
533 		rv = gfx_get_edid_resolution(edid_info, res);
534 
535 	return (rv);
536 }
537 
538 int
539 efi_find_framebuffer(teken_gfx_t *gfx_state)
540 {
541 	EFI_HANDLE *hlist;
542 	UINTN nhandles, i, hsize;
543 	struct efi_fb efifb;
544 	EFI_STATUS status;
545 	int rv;
546 
547 	gfx_state->tg_fb_type = FB_TEXT;
548 
549 	hsize = 0;
550 	hlist = NULL;
551 	status = BS->LocateHandle(ByProtocol, &gop_guid, NULL, &hsize, hlist);
552 	if (status == EFI_BUFFER_TOO_SMALL) {
553 		hlist = malloc(hsize);
554 		if (hlist == NULL)
555 			return (ENOMEM);
556 		status = BS->LocateHandle(ByProtocol, &gop_guid, NULL, &hsize,
557 		    hlist);
558 		if (EFI_ERROR(status))
559 			free(hlist);
560 	}
561 	if (EFI_ERROR(status))
562 		return (efi_status_to_errno(status));
563 
564 	nhandles = hsize / sizeof(*hlist);
565 
566 	/*
567 	 * Search for ConOut protocol, if not found, use first handle.
568 	 */
569 	gop_handle = NULL;
570 	for (i = 0; i < nhandles; i++) {
571 		EFI_GRAPHICS_OUTPUT *tgop;
572 		void *dummy;
573 
574 		status = OpenProtocolByHandle(hlist[i], &gop_guid, (void **)&tgop);
575 		if (status != EFI_SUCCESS)
576 			continue;
577 
578 		if (tgop->Mode->Info->PixelFormat == PixelBltOnly ||
579 		    tgop->Mode->Info->PixelFormat >= PixelFormatMax)
580 			continue;
581 
582 		status = OpenProtocolByHandle(hlist[i], &conout_guid, &dummy);
583 		if (status == EFI_SUCCESS) {
584 			gop_handle = hlist[i];
585 			gop = tgop;
586 			break;
587 		} else if (gop_handle == NULL) {
588 			gop_handle = hlist[i];
589 			gop = tgop;
590 		}
591 	}
592 
593 	free(hlist);
594 
595 	if (gop_handle != NULL) {
596 		gfx_state->tg_fb_type = FB_GOP;
597 		gfx_state->tg_private = gop;
598 		if (edid_info == NULL)
599 			edid_info = efifb_gop_get_edid(gop_handle);
600 	} else {
601 		status = BS->LocateProtocol(&uga_guid, NULL, (VOID **)&uga);
602 		if (status == EFI_SUCCESS) {
603 			gfx_state->tg_fb_type = FB_UGA;
604 			gfx_state->tg_private = uga;
605 		} else {
606 			return (1);
607 		}
608 	}
609 
610 	switch (gfx_state->tg_fb_type) {
611 	case FB_GOP:
612 		rv = efifb_from_gop(&efifb, gop->Mode, gop->Mode->Info);
613 		break;
614 
615 	case FB_UGA:
616 		rv = efifb_from_uga(&efifb);
617 		break;
618 
619 	default:
620 		return (1);
621 	}
622 
623 	gfx_state->tg_fb.fb_addr = efifb.fb_addr;
624 	gfx_state->tg_fb.fb_size = efifb.fb_size;
625 	gfx_state->tg_fb.fb_height = efifb.fb_height;
626 	gfx_state->tg_fb.fb_width = efifb.fb_width;
627 	gfx_state->tg_fb.fb_stride = efifb.fb_stride;
628 	gfx_state->tg_fb.fb_mask_red = efifb.fb_mask_red;
629 	gfx_state->tg_fb.fb_mask_green = efifb.fb_mask_green;
630 	gfx_state->tg_fb.fb_mask_blue = efifb.fb_mask_blue;
631 	gfx_state->tg_fb.fb_mask_reserved = efifb.fb_mask_reserved;
632 
633 	gfx_state->tg_fb.fb_bpp = fls(efifb.fb_mask_red | efifb.fb_mask_green |
634 	    efifb.fb_mask_blue | efifb.fb_mask_reserved);
635 
636 	if (gfx_state->tg_shadow_fb != NULL)
637 		BS->FreePages((EFI_PHYSICAL_ADDRESS)gfx_state->tg_shadow_fb,
638 		    gfx_state->tg_shadow_sz);
639 	gfx_state->tg_shadow_sz =
640 	    EFI_SIZE_TO_PAGES(efifb.fb_height * efifb.fb_width *
641 	    sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
642 	status = BS->AllocatePages(AllocateMaxAddress, EfiLoaderData,
643 	    gfx_state->tg_shadow_sz,
644 	    (EFI_PHYSICAL_ADDRESS *)&gfx_state->tg_shadow_fb);
645 	if (status != EFI_SUCCESS)
646 		gfx_state->tg_shadow_fb = NULL;
647 
648 	return (0);
649 }
650 
651 static void
652 print_efifb(int mode, struct efi_fb *efifb, int verbose)
653 {
654 	u_int depth;
655 
656 	if (mode >= 0)
657 		printf("mode %d: ", mode);
658 	depth = efifb_color_depth(efifb);
659 	printf("%ux%ux%u, stride=%u", efifb->fb_width, efifb->fb_height,
660 	    depth, efifb->fb_stride);
661 	if (verbose) {
662 		printf("\n    frame buffer: address=%jx, size=%jx",
663 		    (uintmax_t)efifb->fb_addr, (uintmax_t)efifb->fb_size);
664 		printf("\n    color mask: R=%08x, G=%08x, B=%08x\n",
665 		    efifb->fb_mask_red, efifb->fb_mask_green,
666 		    efifb->fb_mask_blue);
667 	}
668 }
669 
670 static bool
671 efi_resolution_compare(struct named_resolution *res, const char *cmp)
672 {
673 
674 	if (strcasecmp(res->name, cmp) == 0)
675 		return (true);
676 	if (res->alias != NULL && strcasecmp(res->alias, cmp) == 0)
677 		return (true);
678 	return (false);
679 }
680 
681 
682 static void
683 efi_get_max_resolution(int *width, int *height)
684 {
685 	struct named_resolution *res;
686 	char *maxres;
687 	char *height_start, *width_start;
688 	int idx;
689 
690 	*width = *height = 0;
691 	maxres = getenv("efi_max_resolution");
692 	/* No max_resolution set? Bail out; choose highest resolution */
693 	if (maxres == NULL)
694 		return;
695 	/* See if it matches one of our known resolutions */
696 	for (idx = 0; idx < nitems(resolutions); ++idx) {
697 		res = &resolutions[idx];
698 		if (efi_resolution_compare(res, maxres)) {
699 			*width = res->width;
700 			*height = res->height;
701 			return;
702 		}
703 	}
704 	/* Not a known resolution, try to parse it; make a copy we can modify */
705 	maxres = strdup(maxres);
706 	if (maxres == NULL)
707 		return;
708 	height_start = strchr(maxres, 'x');
709 	if (height_start == NULL) {
710 		free(maxres);
711 		return;
712 	}
713 	width_start = maxres;
714 	*height_start++ = 0;
715 	/* Errors from this will effectively mean "no max" */
716 	*width = (int)strtol(width_start, NULL, 0);
717 	*height = (int)strtol(height_start, NULL, 0);
718 	free(maxres);
719 }
720 
721 static int
722 gop_autoresize(void)
723 {
724 	struct efi_fb efifb;
725 	EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info;
726 	EFI_STATUS status;
727 	UINTN infosz;
728 	UINT32 best_mode, currdim, maxdim, mode;
729 	int height, max_height, max_width, width;
730 
731 	best_mode = maxdim = 0;
732 	efi_get_max_resolution(&max_width, &max_height);
733 	for (mode = 0; mode < gop->Mode->MaxMode; mode++) {
734 		status = gop->QueryMode(gop, mode, &infosz, &info);
735 		if (EFI_ERROR(status))
736 			continue;
737 		efifb_from_gop(&efifb, gop->Mode, info);
738 		width = info->HorizontalResolution;
739 		height = info->VerticalResolution;
740 		currdim = width * height;
741 		if (currdim > maxdim) {
742 			if ((max_width != 0 && width > max_width) ||
743 			    (max_height != 0 && height > max_height))
744 				continue;
745 			maxdim = currdim;
746 			best_mode = mode;
747 		}
748 	}
749 
750 	if (maxdim != 0) {
751 		status = gop->SetMode(gop, best_mode);
752 		if (EFI_ERROR(status)) {
753 			snprintf(command_errbuf, sizeof(command_errbuf),
754 			    "gop_autoresize: Unable to set mode to %u (error=%lu)",
755 			    mode, EFI_ERROR_CODE(status));
756 			return (CMD_ERROR);
757 		}
758 		(void) cons_update_mode(true);
759 	}
760 	return (CMD_OK);
761 }
762 
763 static int
764 text_autoresize()
765 {
766 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
767 	EFI_STATUS status;
768 	UINTN i, max_dim, best_mode, cols, rows;
769 
770 	conout = ST->ConOut;
771 	max_dim = best_mode = 0;
772 	for (i = 0; i < conout->Mode->MaxMode; i++) {
773 		status = conout->QueryMode(conout, i, &cols, &rows);
774 		if (EFI_ERROR(status))
775 			continue;
776 		if (cols * rows > max_dim) {
777 			max_dim = cols * rows;
778 			best_mode = i;
779 		}
780 	}
781 	if (max_dim > 0)
782 		conout->SetMode(conout, best_mode);
783 	(void) cons_update_mode(true);
784 	return (CMD_OK);
785 }
786 
787 static int
788 uga_autoresize(void)
789 {
790 
791 	return (text_autoresize());
792 }
793 
794 COMMAND_SET(efi_autoresize, "efi-autoresizecons", "EFI Auto-resize Console", command_autoresize);
795 
796 static int
797 command_autoresize(int argc, char *argv[])
798 {
799 	char *textmode;
800 
801 	textmode = getenv("hw.vga.textmode");
802 	/* If it's set and non-zero, we'll select a console mode instead */
803 	if (textmode != NULL && strcmp(textmode, "0") != 0)
804 		return (text_autoresize());
805 
806 	if (gop != NULL)
807 		return (gop_autoresize());
808 
809 	if (uga != NULL)
810 		return (uga_autoresize());
811 
812 	snprintf(command_errbuf, sizeof(command_errbuf),
813 	    "%s: Neither Graphics Output Protocol nor Universal Graphics Adapter present",
814 	    argv[0]);
815 
816 	/*
817 	 * Default to text_autoresize if we have neither GOP or UGA.  This won't
818 	 * give us the most ideal resolution, but it will at least leave us
819 	 * functional rather than failing the boot for an objectively bad
820 	 * reason.
821 	 */
822 	return (text_autoresize());
823 }
824 
825 COMMAND_SET(gop, "gop", "graphics output protocol", command_gop);
826 
827 static int
828 command_gop(int argc, char *argv[])
829 {
830 	struct efi_fb efifb;
831 	EFI_STATUS status;
832 	u_int mode;
833 
834 	if (gop == NULL) {
835 		snprintf(command_errbuf, sizeof(command_errbuf),
836 		    "%s: Graphics Output Protocol not present", argv[0]);
837 		return (CMD_ERROR);
838 	}
839 
840 	if (argc < 2)
841 		goto usage;
842 
843 	if (!strcmp(argv[1], "set")) {
844 		char *cp;
845 
846 		if (argc != 3)
847 			goto usage;
848 		mode = strtol(argv[2], &cp, 0);
849 		if (cp[0] != '\0') {
850 			sprintf(command_errbuf, "mode is an integer");
851 			return (CMD_ERROR);
852 		}
853 		status = gop->SetMode(gop, mode);
854 		if (EFI_ERROR(status)) {
855 			snprintf(command_errbuf, sizeof(command_errbuf),
856 			    "%s: Unable to set mode to %u (error=%lu)",
857 			    argv[0], mode, EFI_ERROR_CODE(status));
858 			return (CMD_ERROR);
859 		}
860 		(void) cons_update_mode(true);
861 	} else if (strcmp(argv[1], "off") == 0) {
862 		(void) cons_update_mode(false);
863 	} else if (strcmp(argv[1], "get") == 0) {
864 		edid_res_list_t res;
865 
866 		if (argc != 2)
867 			goto usage;
868 		TAILQ_INIT(&res);
869 		efifb_from_gop(&efifb, gop->Mode, gop->Mode->Info);
870 		if (efifb_get_edid(&res)) {
871 			struct resolution *rp;
872 
873 			printf("EDID");
874 			while ((rp = TAILQ_FIRST(&res)) != NULL) {
875 				printf(" %dx%d", rp->width, rp->height);
876 				TAILQ_REMOVE(&res, rp, next);
877 				free(rp);
878 			}
879 			printf("\n");
880 		} else {
881 			printf("no EDID information\n");
882 		}
883 		print_efifb(gop->Mode->Mode, &efifb, 1);
884 		printf("\n");
885 	} else if (!strcmp(argv[1], "list")) {
886 		EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info;
887 		UINTN infosz;
888 
889 		if (argc != 2)
890 			goto usage;
891 
892 		pager_open();
893 		for (mode = 0; mode < gop->Mode->MaxMode; mode++) {
894 			status = gop->QueryMode(gop, mode, &infosz, &info);
895 			if (EFI_ERROR(status))
896 				continue;
897 			efifb_from_gop(&efifb, gop->Mode, info);
898 			print_efifb(mode, &efifb, 0);
899 			if (pager_output("\n"))
900 				break;
901 		}
902 		pager_close();
903 	}
904 	return (CMD_OK);
905 
906  usage:
907 	snprintf(command_errbuf, sizeof(command_errbuf),
908 	    "usage: %s [list | get | set <mode> | off]", argv[0]);
909 	return (CMD_ERROR);
910 }
911 
912 COMMAND_SET(uga, "uga", "universal graphics adapter", command_uga);
913 
914 static int
915 command_uga(int argc, char *argv[])
916 {
917 	struct efi_fb efifb;
918 
919 	if (uga == NULL) {
920 		snprintf(command_errbuf, sizeof(command_errbuf),
921 		    "%s: UGA Protocol not present", argv[0]);
922 		return (CMD_ERROR);
923 	}
924 
925 	if (argc != 1)
926 		goto usage;
927 
928 	if (efifb_from_uga(&efifb) != CMD_OK) {
929 		snprintf(command_errbuf, sizeof(command_errbuf),
930 		    "%s: Unable to get UGA information", argv[0]);
931 		return (CMD_ERROR);
932 	}
933 
934 	print_efifb(-1, &efifb, 1);
935 	printf("\n");
936 	return (CMD_OK);
937 
938  usage:
939 	snprintf(command_errbuf, sizeof(command_errbuf), "usage: %s", argv[0]);
940 	return (CMD_ERROR);
941 }
942