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