1 /*
2  * Chromium OS cros_ec driver - sandbox emulation
3  *
4  * Copyright (c) 2013 The Chromium OS Authors.
5  *
6  * SPDX-License-Identifier:	GPL-2.0+
7  */
8 
9 #include <common.h>
10 #include <cros_ec.h>
11 #include <dm.h>
12 #include <ec_commands.h>
13 #include <errno.h>
14 #include <hash.h>
15 #include <malloc.h>
16 #include <os.h>
17 #include <u-boot/sha256.h>
18 #include <spi.h>
19 #include <asm/state.h>
20 #include <asm/sdl.h>
21 #include <linux/input.h>
22 
23 /*
24  * Ultimately it shold be possible to connect an Chrome OS EC emulation
25  * to U-Boot and remove all of this code. But this provides a test
26  * environment for bringing up chromeos_sandbox and demonstrating its
27  * utility.
28  *
29  * This emulation includes the following:
30  *
31  * 1. Emulation of the keyboard, by converting keypresses received from SDL
32  * into key scan data, passed back from the EC as key scan messages. The
33  * key layout is read from the device tree.
34  *
35  * 2. Emulation of vboot context - so this can be read/written as required.
36  *
37  * 3. Save/restore of EC state, so that the vboot context, flash memory
38  * contents and current image can be preserved across boots. This is important
39  * since the EC is supposed to continue running even if the AP resets.
40  *
41  * 4. Some event support, in particular allowing Escape to be pressed on boot
42  * to enter recovery mode. The EC passes this to U-Boot through the normal
43  * event message.
44  *
45  * 5. Flash read/write/erase support, so that software sync works. The
46  * protect messages are supported but no protection is implemented.
47  *
48  * 6. Hashing of the EC image, again to support software sync.
49  *
50  * Other features can be added, although a better path is probably to link
51  * the EC image in with U-Boot (Vic has demonstrated a prototype for this).
52  */
53 
54 DECLARE_GLOBAL_DATA_PTR;
55 
56 #define KEYBOARD_ROWS	8
57 #define KEYBOARD_COLS	13
58 
59 /* A single entry of the key matrix */
60 struct ec_keymatrix_entry {
61 	int row;	/* key matrix row */
62 	int col;	/* key matrix column */
63 	int keycode;	/* corresponding linux key code */
64 };
65 
66 /**
67  * struct ec_state - Information about the EC state
68  *
69  * @vbnv_context: Vboot context data stored by EC
70  * @ec_config: FDT config information about the EC (e.g. flashmap)
71  * @flash_data: Contents of flash memory
72  * @flash_data_len: Size of flash memory
73  * @current_image: Current image the EC is running
74  * @matrix_count: Number of keys to decode in matrix
75  * @matrix: Information about keyboard matrix
76  * @keyscan: Current keyscan information (bit set for each row/column pressed)
77  * @recovery_req: Keyboard recovery requested
78  */
79 struct ec_state {
80 	uint8_t vbnv_context[EC_VBNV_BLOCK_SIZE];
81 	struct fdt_cros_ec ec_config;
82 	uint8_t *flash_data;
83 	int flash_data_len;
84 	enum ec_current_image current_image;
85 	int matrix_count;
86 	struct ec_keymatrix_entry *matrix;	/* the key matrix info */
87 	uint8_t keyscan[KEYBOARD_COLS];
88 	bool recovery_req;
89 } s_state, *g_state;
90 
91 /**
92  * cros_ec_read_state() - read the sandbox EC state from the state file
93  *
94  * If data is available, then blob and node will provide access to it. If
95  * not this function sets up an empty EC.
96  *
97  * @param blob: Pointer to device tree blob, or NULL if no data to read
98  * @param node: Node offset to read from
99  */
100 static int cros_ec_read_state(const void *blob, int node)
101 {
102 	struct ec_state *ec = &s_state;
103 	const char *prop;
104 	int len;
105 
106 	/* Set everything to defaults */
107 	ec->current_image = EC_IMAGE_RO;
108 	if (!blob)
109 		return 0;
110 
111 	/* Read the data if available */
112 	ec->current_image = fdtdec_get_int(blob, node, "current-image",
113 					   EC_IMAGE_RO);
114 	prop = fdt_getprop(blob, node, "vbnv-context", &len);
115 	if (prop && len == sizeof(ec->vbnv_context))
116 		memcpy(ec->vbnv_context, prop, len);
117 
118 	prop = fdt_getprop(blob, node, "flash-data", &len);
119 	if (prop) {
120 		ec->flash_data_len = len;
121 		ec->flash_data = os_malloc(len);
122 		if (!ec->flash_data)
123 			return -ENOMEM;
124 		memcpy(ec->flash_data, prop, len);
125 		debug("%s: Loaded EC flash data size %#x\n", __func__, len);
126 	}
127 
128 	return 0;
129 }
130 
131 /**
132  * cros_ec_write_state() - Write out our state to the state file
133  *
134  * The caller will ensure that there is a node ready for the state. The node
135  * may already contain the old state, in which case it is overridden.
136  *
137  * @param blob: Device tree blob holding state
138  * @param node: Node to write our state into
139  */
140 static int cros_ec_write_state(void *blob, int node)
141 {
142 	struct ec_state *ec = g_state;
143 
144 	/* We are guaranteed enough space to write basic properties */
145 	fdt_setprop_u32(blob, node, "current-image", ec->current_image);
146 	fdt_setprop(blob, node, "vbnv-context", ec->vbnv_context,
147 		    sizeof(ec->vbnv_context));
148 	return state_setprop(node, "flash-data", ec->flash_data,
149 			     ec->ec_config.flash.length);
150 }
151 
152 SANDBOX_STATE_IO(cros_ec, "google,cros-ec", cros_ec_read_state,
153 		 cros_ec_write_state);
154 
155 /**
156  * Return the number of bytes used in the specified image.
157  *
158  * This is the actual size of code+data in the image, as opposed to the
159  * amount of space reserved in flash for that image. This code is similar to
160  * that used by the real EC code base.
161  *
162  * @param ec	Current emulated EC state
163  * @param entry	Flash map entry containing the image to check
164  * @return actual image size in bytes, 0 if the image contains no content or
165  * error.
166  */
167 static int get_image_used(struct ec_state *ec, struct fmap_entry *entry)
168 {
169 	int size;
170 
171 	/*
172 	 * Scan backwards looking for 0xea byte, which is by definition the
173 	 * last byte of the image.  See ec.lds.S for how this is inserted at
174 	 * the end of the image.
175 	 */
176 	for (size = entry->length - 1;
177 	     size > 0 && ec->flash_data[entry->offset + size] != 0xea;
178 	     size--)
179 		;
180 
181 	return size ? size + 1 : 0;  /* 0xea byte IS part of the image */
182 }
183 
184 /**
185  * Read the key matrix from the device tree
186  *
187  * Keymap entries in the fdt take the form of 0xRRCCKKKK where
188  * RR=Row CC=Column KKKK=Key Code
189  *
190  * @param ec	Current emulated EC state
191  * @param blob	Device tree blob containing keyscan information
192  * @param node	Keyboard node of device tree containing keyscan information
193  * @return 0 if ok, -1 on error
194  */
195 static int keyscan_read_fdt_matrix(struct ec_state *ec, const void *blob,
196 				   int node)
197 {
198 	const u32 *cell;
199 	int upto;
200 	int len;
201 
202 	cell = fdt_getprop(blob, node, "linux,keymap", &len);
203 	ec->matrix_count = len / 4;
204 	ec->matrix = calloc(ec->matrix_count, sizeof(*ec->matrix));
205 	if (!ec->matrix) {
206 		debug("%s: Out of memory for key matrix\n", __func__);
207 		return -1;
208 	}
209 
210 	/* Now read the data */
211 	for (upto = 0; upto < ec->matrix_count; upto++) {
212 		struct ec_keymatrix_entry *matrix = &ec->matrix[upto];
213 		u32 word;
214 
215 		word = fdt32_to_cpu(*cell++);
216 		matrix->row = word >> 24;
217 		matrix->col = (word >> 16) & 0xff;
218 		matrix->keycode = word & 0xffff;
219 
220 		/* Hard-code some sanity limits for now */
221 		if (matrix->row >= KEYBOARD_ROWS ||
222 		    matrix->col >= KEYBOARD_COLS) {
223 			debug("%s: Matrix pos out of range (%d,%d)\n",
224 			      __func__, matrix->row, matrix->col);
225 			return -1;
226 		}
227 	}
228 
229 	if (upto != ec->matrix_count) {
230 		debug("%s: Read mismatch from key matrix\n", __func__);
231 		return -1;
232 	}
233 
234 	return 0;
235 }
236 
237 /**
238  * Return the next keyscan message contents
239  *
240  * @param ec	Current emulated EC state
241  * @param scan	Place to put keyscan bytes for the keyscan message (must hold
242  *		enough space for a full keyscan)
243  * @return number of bytes of valid scan data
244  */
245 static int cros_ec_keyscan(struct ec_state *ec, uint8_t *scan)
246 {
247 	const struct ec_keymatrix_entry *matrix;
248 	int bytes = KEYBOARD_COLS;
249 	int key[8];	/* allow up to 8 keys to be pressed at once */
250 	int count;
251 	int i;
252 
253 	memset(ec->keyscan, '\0', bytes);
254 	count = sandbox_sdl_scan_keys(key, ARRAY_SIZE(key));
255 
256 	/* Look up keycode in matrix */
257 	for (i = 0, matrix = ec->matrix; i < ec->matrix_count; i++, matrix++) {
258 		bool found;
259 		int j;
260 
261 		for (found = false, j = 0; j < count; j++) {
262 			if (matrix->keycode == key[j])
263 				found = true;
264 		}
265 
266 		if (found) {
267 			debug("%d: %d,%d\n", matrix->keycode, matrix->row,
268 			      matrix->col);
269 			ec->keyscan[matrix->col] |= 1 << matrix->row;
270 		}
271 	}
272 
273 	memcpy(scan, ec->keyscan, bytes);
274 	return bytes;
275 }
276 
277 /**
278  * Process an emulated EC command
279  *
280  * @param ec		Current emulated EC state
281  * @param req_hdr	Pointer to request header
282  * @param req_data	Pointer to body of request
283  * @param resp_hdr	Pointer to place to put response header
284  * @param resp_data	Pointer to place to put response data, if any
285  * @return length of response data, or 0 for no response data, or -1 on error
286  */
287 static int process_cmd(struct ec_state *ec,
288 		       struct ec_host_request *req_hdr, const void *req_data,
289 		       struct ec_host_response *resp_hdr, void *resp_data)
290 {
291 	int len;
292 
293 	/* TODO(sjg@chromium.org): Check checksums */
294 	debug("EC command %#0x\n", req_hdr->command);
295 
296 	switch (req_hdr->command) {
297 	case EC_CMD_HELLO: {
298 		const struct ec_params_hello *req = req_data;
299 		struct ec_response_hello *resp = resp_data;
300 
301 		resp->out_data = req->in_data + 0x01020304;
302 		len = sizeof(*resp);
303 		break;
304 	}
305 	case EC_CMD_GET_VERSION: {
306 		struct ec_response_get_version *resp = resp_data;
307 
308 		strcpy(resp->version_string_ro, "sandbox_ro");
309 		strcpy(resp->version_string_rw, "sandbox_rw");
310 		resp->current_image = ec->current_image;
311 		debug("Current image %d\n", resp->current_image);
312 		len = sizeof(*resp);
313 		break;
314 	}
315 	case EC_CMD_VBNV_CONTEXT: {
316 		const struct ec_params_vbnvcontext *req = req_data;
317 		struct ec_response_vbnvcontext *resp = resp_data;
318 
319 		switch (req->op) {
320 		case EC_VBNV_CONTEXT_OP_READ:
321 			memcpy(resp->block, ec->vbnv_context,
322 			       sizeof(resp->block));
323 			len = sizeof(*resp);
324 			break;
325 		case EC_VBNV_CONTEXT_OP_WRITE:
326 			memcpy(ec->vbnv_context, resp->block,
327 			       sizeof(resp->block));
328 			len = 0;
329 			break;
330 		default:
331 			printf("   ** Unknown vbnv_context command %#02x\n",
332 			       req->op);
333 			return -1;
334 		}
335 		break;
336 	}
337 	case EC_CMD_REBOOT_EC: {
338 		const struct ec_params_reboot_ec *req = req_data;
339 
340 		printf("Request reboot type %d\n", req->cmd);
341 		switch (req->cmd) {
342 		case EC_REBOOT_DISABLE_JUMP:
343 			len = 0;
344 			break;
345 		case EC_REBOOT_JUMP_RW:
346 			ec->current_image = EC_IMAGE_RW;
347 			len = 0;
348 			break;
349 		default:
350 			puts("   ** Unknown type");
351 			return -1;
352 		}
353 		break;
354 	}
355 	case EC_CMD_HOST_EVENT_GET_B: {
356 		struct ec_response_host_event_mask *resp = resp_data;
357 
358 		resp->mask = 0;
359 		if (ec->recovery_req) {
360 			resp->mask |= EC_HOST_EVENT_MASK(
361 					EC_HOST_EVENT_KEYBOARD_RECOVERY);
362 		}
363 
364 		len = sizeof(*resp);
365 		break;
366 	}
367 	case EC_CMD_VBOOT_HASH: {
368 		const struct ec_params_vboot_hash *req = req_data;
369 		struct ec_response_vboot_hash *resp = resp_data;
370 		struct fmap_entry *entry;
371 		int ret, size;
372 
373 		entry = &ec->ec_config.region[EC_FLASH_REGION_RW];
374 
375 		switch (req->cmd) {
376 		case EC_VBOOT_HASH_RECALC:
377 		case EC_VBOOT_HASH_GET:
378 			size = SHA256_SUM_LEN;
379 			len = get_image_used(ec, entry);
380 			ret = hash_block("sha256",
381 					 ec->flash_data + entry->offset,
382 					 len, resp->hash_digest, &size);
383 			if (ret) {
384 				printf("   ** hash_block() failed\n");
385 				return -1;
386 			}
387 			resp->status = EC_VBOOT_HASH_STATUS_DONE;
388 			resp->hash_type = EC_VBOOT_HASH_TYPE_SHA256;
389 			resp->digest_size = size;
390 			resp->reserved0 = 0;
391 			resp->offset = entry->offset;
392 			resp->size = len;
393 			len = sizeof(*resp);
394 			break;
395 		default:
396 			printf("   ** EC_CMD_VBOOT_HASH: Unknown command %d\n",
397 			       req->cmd);
398 			return -1;
399 		}
400 		break;
401 	}
402 	case EC_CMD_FLASH_PROTECT: {
403 		const struct ec_params_flash_protect *req = req_data;
404 		struct ec_response_flash_protect *resp = resp_data;
405 		uint32_t expect = EC_FLASH_PROTECT_ALL_NOW |
406 				EC_FLASH_PROTECT_ALL_AT_BOOT;
407 
408 		printf("mask=%#x, flags=%#x\n", req->mask, req->flags);
409 		if (req->flags == expect || req->flags == 0) {
410 			resp->flags = req->flags ? EC_FLASH_PROTECT_ALL_NOW :
411 								0;
412 			resp->valid_flags = EC_FLASH_PROTECT_ALL_NOW;
413 			resp->writable_flags = 0;
414 			len = sizeof(*resp);
415 		} else {
416 			puts("   ** unexpected flash protect request\n");
417 			return -1;
418 		}
419 		break;
420 	}
421 	case EC_CMD_FLASH_REGION_INFO: {
422 		const struct ec_params_flash_region_info *req = req_data;
423 		struct ec_response_flash_region_info *resp = resp_data;
424 		struct fmap_entry *entry;
425 
426 		switch (req->region) {
427 		case EC_FLASH_REGION_RO:
428 		case EC_FLASH_REGION_RW:
429 		case EC_FLASH_REGION_WP_RO:
430 			entry = &ec->ec_config.region[req->region];
431 			resp->offset = entry->offset;
432 			resp->size = entry->length;
433 			len = sizeof(*resp);
434 			printf("EC flash region %d: offset=%#x, size=%#x\n",
435 			       req->region, resp->offset, resp->size);
436 			break;
437 		default:
438 			printf("** Unknown flash region %d\n", req->region);
439 			return -1;
440 		}
441 		break;
442 	}
443 	case EC_CMD_FLASH_ERASE: {
444 		const struct ec_params_flash_erase *req = req_data;
445 
446 		memset(ec->flash_data + req->offset,
447 		       ec->ec_config.flash_erase_value,
448 		       req->size);
449 		len = 0;
450 		break;
451 	}
452 	case EC_CMD_FLASH_WRITE: {
453 		const struct ec_params_flash_write *req = req_data;
454 
455 		memcpy(ec->flash_data + req->offset, req + 1, req->size);
456 		len = 0;
457 		break;
458 	}
459 	case EC_CMD_MKBP_STATE:
460 		len = cros_ec_keyscan(ec, resp_data);
461 		break;
462 	case EC_CMD_ENTERING_MODE:
463 		len = 0;
464 		break;
465 	default:
466 		printf("   ** Unknown EC command %#02x\n", req_hdr->command);
467 		return -1;
468 	}
469 
470 	return len;
471 }
472 
473 int cros_ec_sandbox_packet(struct udevice *udev, int out_bytes, int in_bytes)
474 {
475 	struct cros_ec_dev *dev = dev_get_uclass_priv(udev);
476 	struct ec_state *ec = dev_get_priv(dev->dev);
477 	struct ec_host_request *req_hdr = (struct ec_host_request *)dev->dout;
478 	const void *req_data = req_hdr + 1;
479 	struct ec_host_response *resp_hdr = (struct ec_host_response *)dev->din;
480 	void *resp_data = resp_hdr + 1;
481 	int len;
482 
483 	len = process_cmd(ec, req_hdr, req_data, resp_hdr, resp_data);
484 	if (len < 0)
485 		return len;
486 
487 	resp_hdr->struct_version = 3;
488 	resp_hdr->result = EC_RES_SUCCESS;
489 	resp_hdr->data_len = len;
490 	resp_hdr->reserved = 0;
491 	len += sizeof(*resp_hdr);
492 	resp_hdr->checksum = 0;
493 	resp_hdr->checksum = (uint8_t)
494 		-cros_ec_calc_checksum((const uint8_t *)resp_hdr, len);
495 
496 	return in_bytes;
497 }
498 
499 void cros_ec_check_keyboard(struct cros_ec_dev *dev)
500 {
501 	struct ec_state *ec = dev_get_priv(dev->dev);
502 	ulong start;
503 
504 	printf("Press keys for EC to detect on reset (ESC=recovery)...");
505 	start = get_timer(0);
506 	while (get_timer(start) < 1000)
507 		;
508 	putc('\n');
509 	if (!sandbox_sdl_key_pressed(KEY_ESC)) {
510 		ec->recovery_req = true;
511 		printf("   - EC requests recovery\n");
512 	}
513 }
514 
515 int cros_ec_probe(struct udevice *dev)
516 {
517 	struct ec_state *ec = dev->priv;
518 	struct cros_ec_dev *cdev = dev->uclass_priv;
519 	const void *blob = gd->fdt_blob;
520 	struct udevice *keyb_dev;
521 	int node;
522 	int err;
523 
524 	memcpy(ec, &s_state, sizeof(*ec));
525 	err = cros_ec_decode_ec_flash(blob, dev_of_offset(dev), &ec->ec_config);
526 	if (err)
527 		return err;
528 
529 	node = -1;
530 	for (device_find_first_child(dev, &keyb_dev);
531 	     keyb_dev;
532 	     device_find_next_child(&keyb_dev)) {
533 		if (device_get_uclass_id(keyb_dev) == UCLASS_KEYBOARD) {
534 			node = dev_of_offset(keyb_dev);
535 			break;
536 		}
537 	}
538 	if (node < 0) {
539 		debug("%s: No cros_ec keyboard found\n", __func__);
540 	} else if (keyscan_read_fdt_matrix(ec, blob, node)) {
541 		debug("%s: Could not read key matrix\n", __func__);
542 		return -1;
543 	}
544 
545 	/* If we loaded EC data, check that the length matches */
546 	if (ec->flash_data &&
547 	    ec->flash_data_len != ec->ec_config.flash.length) {
548 		printf("EC data length is %x, expected %x, discarding data\n",
549 		       ec->flash_data_len, ec->ec_config.flash.length);
550 		os_free(ec->flash_data);
551 		ec->flash_data = NULL;
552 	}
553 
554 	/* Otherwise allocate the memory */
555 	if (!ec->flash_data) {
556 		ec->flash_data_len = ec->ec_config.flash.length;
557 		ec->flash_data = os_malloc(ec->flash_data_len);
558 		if (!ec->flash_data)
559 			return -ENOMEM;
560 	}
561 
562 	cdev->dev = dev;
563 	g_state = ec;
564 	return cros_ec_register(dev);
565 }
566 
567 struct dm_cros_ec_ops cros_ec_ops = {
568 	.packet = cros_ec_sandbox_packet,
569 };
570 
571 static const struct udevice_id cros_ec_ids[] = {
572 	{ .compatible = "google,cros-ec-sandbox" },
573 	{ }
574 };
575 
576 U_BOOT_DRIVER(cros_ec_sandbox) = {
577 	.name		= "cros_ec_sandbox",
578 	.id		= UCLASS_CROS_EC,
579 	.of_match	= cros_ec_ids,
580 	.probe		= cros_ec_probe,
581 	.priv_auto_alloc_size = sizeof(struct ec_state),
582 	.ops		= &cros_ec_ops,
583 };
584