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