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