xref: /openbmc/hiomapd/transport_mbox.c (revision 457a6e5f)
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright (C) 2018 IBM Corp.
3 
4 #define _GNU_SOURCE
5 #include <assert.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <getopt.h>
9 #include <limits.h>
10 #include <poll.h>
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <syslog.h>
17 #include <signal.h>
18 #include <sys/ioctl.h>
19 #include <sys/mman.h>
20 #include <sys/stat.h>
21 #include <sys/timerfd.h>
22 #include <sys/types.h>
23 #include <time.h>
24 #include <unistd.h>
25 #include <inttypes.h>
26 
27 #include "mbox.h"
28 #include "common.h"
29 #include "transport_mbox.h"
30 #include "windows.h"
31 #include "lpc.h"
32 
33 /*
34  * write_bmc_event_reg() - Write to the BMC controlled status register (reg 15)
35  * @context:	The mbox context pointer
36  *
37  * Return:	0 on success otherwise negative error code
38  */
39 static int write_bmc_event_reg(struct mbox_context *context)
40 {
41 	int rc;
42 
43 	/* Seek mbox registers */
44 	rc = lseek(context->fds[MBOX_FD].fd, MBOX_BMC_EVENT, SEEK_SET);
45 	if (rc != MBOX_BMC_EVENT) {
46 		MSG_ERR("Couldn't lseek mbox to byte %d: %s\n", MBOX_BMC_EVENT,
47 				strerror(errno));
48 		return -MBOX_R_SYSTEM_ERROR;
49 	}
50 
51 	/* Write to mbox status register */
52 	rc = write(context->fds[MBOX_FD].fd, &context->bmc_events, 1);
53 	if (rc != 1) {
54 		MSG_ERR("Couldn't write to BMC status reg: %s\n",
55 				strerror(errno));
56 		return -MBOX_R_SYSTEM_ERROR;
57 	}
58 
59 	/* Reset to start */
60 	rc = lseek(context->fds[MBOX_FD].fd, 0, SEEK_SET);
61 	if (rc) {
62 		MSG_ERR("Couldn't reset MBOX offset to zero: %s\n",
63 				strerror(errno));
64 		return -MBOX_R_SYSTEM_ERROR;
65 	}
66 
67 	return 0;
68 }
69 
70 /*
71  * set_bmc_events() - Set BMC events
72  * @context:	The mbox context pointer
73  * @bmc_event:	The bits to set
74  * @write_back:	Whether to write back to the register -> will interrupt host
75  *
76  * Return:	0 on success otherwise negative error code
77  */
78 int set_bmc_events(struct mbox_context *context, uint8_t bmc_event,
79 		   bool write_back)
80 {
81 	uint8_t mask = 0x00;
82 
83 	switch (context->version) {
84 	case API_VERSION_1:
85 		mask = BMC_EVENT_V1_MASK;
86 		break;
87 	default:
88 		mask = BMC_EVENT_V2_MASK;
89 		break;
90 	}
91 
92 	context->bmc_events |= (bmc_event & mask);
93 	MSG_DBG("BMC Events set to: 0x%.2x\n", context->bmc_events);
94 
95 	return write_back ? write_bmc_event_reg(context) : 0;
96 }
97 
98 /*
99  * clr_bmc_events() - Clear BMC events
100  * @context:	The mbox context pointer
101  * @bmc_event:	The bits to clear
102  * @write_back:	Whether to write back to the register -> will interrupt host
103  *
104  * Return:	0 on success otherwise negative error code
105  */
106 int clr_bmc_events(struct mbox_context *context, uint8_t bmc_event,
107 		   bool write_back)
108 {
109 	context->bmc_events &= ~bmc_event;
110 	MSG_DBG("BMC Events clear to: 0x%.2x\n", context->bmc_events);
111 
112 	return write_back ? write_bmc_event_reg(context) : 0;
113 }
114 
115 /* Command Handlers */
116 
117 /*
118  * Command: RESET_STATE
119  * Reset the LPC mapping to point back at the flash, or memory in case we're
120  * using a virtual pnor.
121  */
122 int mbox_handle_reset(struct mbox_context *context,
123 			     union mbox_regs *req, struct mbox_msg *resp)
124 {
125 	/* Host requested it -> No BMC Event */
126 	windows_reset_all(context, NO_BMC_EVENT);
127 	return lpc_reset(context);
128 }
129 
130 /*
131  * get_suggested_timeout() - get the suggested timeout value in seconds
132  * @context:	The mbox context pointer
133  *
134  * Return:	Suggested timeout in seconds
135  */
136 static uint16_t get_suggested_timeout(struct mbox_context *context)
137 {
138 	struct window_context *window = windows_find_largest(context);
139 	uint32_t max_size_mb = window ? (window->size >> 20) : 0;
140 	uint16_t ret;
141 
142 	ret = align_up(max_size_mb * FLASH_ACCESS_MS_PER_MB, 1000) / 1000;
143 
144 	MSG_DBG("Suggested Timeout: %us, max window size: %uMB, for %dms/MB\n",
145 		ret, max_size_mb, FLASH_ACCESS_MS_PER_MB);
146 	return ret;
147 }
148 
149 /*
150  * Command: GET_MBOX_INFO
151  * Get the API version, default window size and block size
152  * We also set the LPC mapping to point to the reserved memory region here so
153  * this command must be called before any window manipulation
154  *
155  * V1:
156  * ARGS[0]: API Version
157  *
158  * RESP[0]: API Version
159  * RESP[1:2]: Default read window size (number of blocks)
160  * RESP[3:4]: Default write window size (number of blocks)
161  * RESP[5]: Block size (as shift)
162  *
163  * V2:
164  * ARGS[0]: API Version
165  *
166  * RESP[0]: API Version
167  * RESP[1:2]: Default read window size (number of blocks)
168  * RESP[3:4]: Default write window size (number of blocks)
169  * RESP[5]: Block size (as shift)
170  */
171 int mbox_handle_mbox_info(struct mbox_context *context,
172 				 union mbox_regs *req, struct mbox_msg *resp)
173 {
174 	uint8_t mbox_api_version = req->msg.args[0];
175 	uint8_t old_api_version = context->version;
176 	int rc;
177 
178 	/* Check we support the version requested */
179 	if (mbox_api_version < API_MIN_VERSION)
180 		return -MBOX_R_PARAM_ERROR;
181 
182 	if (mbox_api_version > API_MAX_VERSION)
183 		mbox_api_version = API_MAX_VERSION;
184 
185 	context->version = mbox_api_version;
186 	MSG_INFO("Using Protocol Version: %d\n", context->version);
187 
188 	/*
189 	 * The reset state is currently to have the LPC bus point directly to
190 	 * flash, since we got a mbox_info command we know the host can talk
191 	 * mbox so point the LPC bus mapping to the reserved memory region now
192 	 * so the host can access what we put in it.
193 	 */
194 	rc = lpc_map_memory(context);
195 	if (rc < 0) {
196 		return rc;
197 	}
198 
199 	switch (context->version) {
200 	case API_VERSION_1:
201 		context->block_size_shift = BLOCK_SIZE_SHIFT_V1;
202 		break;
203 	default:
204 		context->block_size_shift = log_2(context->mtd_info.erasesize);
205 		break;
206 	}
207 	MSG_INFO("Block Size: 0x%.8x (shift: %u)\n",
208 		 1 << context->block_size_shift, context->block_size_shift);
209 
210 	/* Now we know the blocksize we can allocate the window dirty_bytemap */
211 	if (mbox_api_version != old_api_version) {
212 		windows_alloc_dirty_bytemap(context);
213 	}
214 	/* Reset if we were V1 since this required exact window mapping */
215 	if (old_api_version == API_VERSION_1) {
216 		/*
217 		 * This will only set the BMC event if there was a current
218 		 * window -> In which case we are better off notifying the
219 		 * host.
220 		 */
221 		windows_reset_all(context, SET_BMC_EVENT);
222 	}
223 
224 	resp->args[0] = mbox_api_version;
225 	if (context->version == API_VERSION_1) {
226 		put_u16(&resp->args[1], context->windows.default_size >>
227 					context->block_size_shift);
228 		put_u16(&resp->args[3], context->windows.default_size >>
229 					context->block_size_shift);
230 	}
231 	if (context->version >= API_VERSION_2) {
232 		resp->args[5] = context->block_size_shift;
233 		put_u16(&resp->args[6], get_suggested_timeout(context));
234 	}
235 
236 	return 0;
237 }
238 
239 /*
240  * Command: GET_FLASH_INFO
241  * Get the flash size and erase granularity
242  *
243  * V1:
244  * RESP[0:3]: Flash Size (bytes)
245  * RESP[4:7]: Erase Size (bytes)
246  * V2:
247  * RESP[0:1]: Flash Size (number of blocks)
248  * RESP[2:3]: Erase Size (number of blocks)
249  */
250 int mbox_handle_flash_info(struct mbox_context *context,
251 				  union mbox_regs *req, struct mbox_msg *resp)
252 {
253 	switch (context->version) {
254 	case API_VERSION_1:
255 		/* Both Sizes in Bytes */
256 		put_u32(&resp->args[0], context->flash_size);
257 		put_u32(&resp->args[4], context->mtd_info.erasesize);
258 		break;
259 	case API_VERSION_2:
260 		/* Both Sizes in Block Size */
261 		put_u16(&resp->args[0],
262 			context->flash_size >> context->block_size_shift);
263 		put_u16(&resp->args[2],
264 			context->mtd_info.erasesize >>
265 					context->block_size_shift);
266 		break;
267 	default:
268 		MSG_ERR("API Version Not Valid - Invalid System State\n");
269 		return -MBOX_R_SYSTEM_ERROR;
270 	}
271 
272 	return 0;
273 }
274 
275 /*
276  * get_lpc_addr_shifted() - Get lpc address of the current window
277  * @context:		The mbox context pointer
278  *
279  * Return:	The lpc address to access that offset shifted by block size
280  */
281 static inline uint16_t get_lpc_addr_shifted(struct mbox_context *context)
282 {
283 	uint32_t lpc_addr, mem_offset;
284 
285 	/* Offset of the current window in the reserved memory region */
286 	mem_offset = context->current->mem - context->mem;
287 	/* Total LPC Address */
288 	lpc_addr = context->lpc_base + mem_offset;
289 
290 	MSG_DBG("LPC address of current window: 0x%.8x\n", lpc_addr);
291 
292 	return lpc_addr >> context->block_size_shift;
293 }
294 
295 /*
296  * Command: CREATE_READ_WINDOW
297  * Opens a read window
298  * First checks if any current window with the requested data, if so we just
299  * point the host to that. Otherwise we read the request data in from flash and
300  * point the host there.
301  *
302  * V1:
303  * ARGS[0:1]: Window Location as Offset into Flash (number of blocks)
304  *
305  * RESP[0:1]: LPC bus address for host to access this window (number of blocks)
306  *
307  * V2:
308  * ARGS[0:1]: Window Location as Offset into Flash (number of blocks)
309  * ARGS[2:3]: Requested window size (number of blocks)
310  *
311  * RESP[0:1]: LPC bus address for host to access this window (number of blocks)
312  * RESP[2:3]: Actual window size that the host can access (number of blocks)
313  */
314 int mbox_handle_read_window(struct mbox_context *context,
315 				   union mbox_regs *req, struct mbox_msg *resp)
316 {
317 	uint32_t flash_offset;
318 	int rc;
319 
320 	/* Close the current window if there is one */
321 	if (context->current) {
322 		/* There is an implicit flush if it was a write window */
323 		if (context->current_is_write) {
324 			rc = mbox_handle_flush_window(context, NULL, NULL);
325 			if (rc < 0) {
326 				MSG_ERR("Couldn't Flush Write Window\n");
327 				return rc;
328 			}
329 		}
330 		windows_close_current(context, NO_BMC_EVENT, FLAGS_NONE);
331 	}
332 
333 	/* Offset the host has requested */
334 	flash_offset = get_u16(&req->msg.args[0]) << context->block_size_shift;
335 	MSG_INFO("Host requested flash @ 0x%.8x\n", flash_offset);
336 	/* Check if we have an existing window */
337 	context->current = windows_search(context, flash_offset,
338 					  context->version == API_VERSION_1);
339 
340 	if (!context->current) { /* No existing window */
341 		MSG_DBG("No existing window which maps that flash offset\n");
342 		rc = windows_create_map(context, &context->current, flash_offset,
343 				       context->version == API_VERSION_1);
344 		if (rc < 0) { /* Unable to map offset */
345 			MSG_ERR("Couldn't create window mapping for offset 0x%.8x\n"
346 				, flash_offset);
347 			return rc;
348 		}
349 	}
350 
351 	MSG_INFO("Window @ %p for size 0x%.8x maps flash offset 0x%.8x\n",
352 		 context->current->mem, context->current->size,
353 		 context->current->flash_offset);
354 
355 	put_u16(&resp->args[0], get_lpc_addr_shifted(context));
356 	if (context->version >= API_VERSION_2) {
357 		put_u16(&resp->args[2], context->current->size >>
358 					context->block_size_shift);
359 		put_u16(&resp->args[4], context->current->flash_offset >>
360 					context->block_size_shift);
361 	}
362 
363 	context->current_is_write = false;
364 
365 	return 0;
366 }
367 
368 /*
369  * Command: CREATE_WRITE_WINDOW
370  * Opens a write window
371  * First checks if any current window with the requested data, if so we just
372  * point the host to that. Otherwise we read the request data in from flash and
373  * point the host there.
374  *
375  * V1:
376  * ARGS[0:1]: Window Location as Offset into Flash (number of blocks)
377  *
378  * RESP[0:1]: LPC bus address for host to access this window (number of blocks)
379  *
380  * V2:
381  * ARGS[0:1]: Window Location as Offset into Flash (number of blocks)
382  * ARGS[2:3]: Requested window size (number of blocks)
383  *
384  * RESP[0:1]: LPC bus address for host to access this window (number of blocks)
385  * RESP[2:3]: Actual window size that was mapped/host can access (n.o. blocks)
386  */
387 int mbox_handle_write_window(struct mbox_context *context,
388 				    union mbox_regs *req, struct mbox_msg *resp)
389 {
390 	int rc;
391 
392 	/*
393 	 * This is very similar to opening a read window (exactly the same
394 	 * for now infact)
395 	 */
396 	rc = mbox_handle_read_window(context, req, resp);
397 	if (rc < 0) {
398 		return rc;
399 	}
400 
401 	context->current_is_write = true;
402 	return rc;
403 }
404 
405 /*
406  * Commands: MARK_WRITE_DIRTY
407  * Marks a portion of the current (write) window dirty, informing the daemon
408  * that is has been written to and thus must be at some point written to the
409  * backing store
410  * These changes aren't written back to the backing store unless flush is then
411  * called or the window closed
412  *
413  * V1:
414  * ARGS[0:1]: Where within flash to start (number of blocks)
415  * ARGS[2:5]: Number to mark dirty (number of bytes)
416  *
417  * V2:
418  * ARGS[0:1]: Where within window to start (number of blocks)
419  * ARGS[2:3]: Number to mark dirty (number of blocks)
420  */
421 int mbox_handle_dirty_window(struct mbox_context *context,
422 				    union mbox_regs *req, struct mbox_msg *resp)
423 {
424 	uint32_t offset, size;
425 	int rc;
426 
427 	if (!(context->current && context->current_is_write)) {
428 		MSG_ERR("Tried to call mark dirty without open write window\n");
429 		return context->version >= API_VERSION_2 ? -MBOX_R_WINDOW_ERROR
430 							 : -MBOX_R_PARAM_ERROR;
431 	}
432 
433 	offset = get_u16(&req->msg.args[0]);
434 
435 	if (context->version >= API_VERSION_2) {
436 		size = get_u16(&req->msg.args[2]);
437 	} else {
438 		uint32_t off;
439 		/* For V1 offset given relative to flash - we want the window */
440 		off = offset - ((context->current->flash_offset) >>
441 				context->block_size_shift);
442 		if (off > offset) { /* Underflow - before current window */
443 			MSG_ERR("Tried to mark dirty before start of window\n");
444 			MSG_ERR("requested offset: 0x%x window start: 0x%x\n",
445 				offset << context->block_size_shift,
446 				context->current->flash_offset);
447 			return -MBOX_R_PARAM_ERROR;
448 		}
449 		offset = off;
450 		size = get_u32(&req->msg.args[2]);
451 		/*
452 		 * We only track dirty at the block level.
453 		 * For protocol V1 we can get away with just marking the whole
454 		 * block dirty.
455 		 */
456 		size = align_up(size, 1 << context->block_size_shift);
457 		size >>= context->block_size_shift;
458 	}
459 
460 	MSG_INFO("Dirty window @ 0x%.8x for 0x%.8x\n",
461 		 offset << context->block_size_shift,
462 		 size << context->block_size_shift);
463 
464 	rc = window_set_bytemap(context, context->current, offset, size,
465 				  WINDOW_DIRTY);
466 	if (rc < 0) {
467 		return (rc == -EACCES) ? -MBOX_R_PARAM_ERROR
468 				       : -MBOX_R_SYSTEM_ERROR;
469 	}
470 
471 	return rc;
472 }
473 
474 /*
475  * Commands: MARK_WRITE_ERASE
476  * Erases a portion of the current window
477  * These changes aren't written back to the backing store unless flush is then
478  * called or the window closed
479  *
480  * V1:
481  * Unimplemented
482  *
483  * V2:
484  * ARGS[0:1]: Where within window to start (number of blocks)
485  * ARGS[2:3]: Number to erase (number of blocks)
486  */
487 int mbox_handle_erase_window(struct mbox_context *context,
488 				    union mbox_regs *req, struct mbox_msg *resp)
489 {
490 	uint32_t offset, size;
491 	int rc;
492 
493 	if (context->version < API_VERSION_2) {
494 		MSG_ERR("Protocol Version invalid for Erase Command\n");
495 		return -MBOX_R_PARAM_ERROR;
496 	}
497 
498 	if (!(context->current && context->current_is_write)) {
499 		MSG_ERR("Tried to call erase without open write window\n");
500 		return -MBOX_R_WINDOW_ERROR;
501 	}
502 
503 	offset = get_u16(&req->msg.args[0]);
504 	size = get_u16(&req->msg.args[2]);
505 
506 	MSG_INFO("Erase window @ 0x%.8x for 0x%.8x\n",
507 		 offset << context->block_size_shift,
508 		 size << context->block_size_shift);
509 
510 	rc = window_set_bytemap(context, context->current, offset, size,
511 				WINDOW_ERASED);
512 	if (rc < 0) {
513 		return (rc == -EACCES) ? -MBOX_R_PARAM_ERROR
514 				       : -MBOX_R_SYSTEM_ERROR;
515 	}
516 
517 	/* Write 0xFF to mem -> This ensures consistency between flash & ram */
518 	memset(context->current->mem + (offset << context->block_size_shift),
519 	       0xFF, size << context->block_size_shift);
520 
521 	return 0;
522 }
523 
524 /*
525  * Command: WRITE_FLUSH
526  * Flushes any dirty or erased blocks in the current window back to the backing
527  * store
528  * NOTE: For V1 this behaves much the same as the dirty command in that it
529  * takes an offset and number of blocks to dirty, then also performs a flush as
530  * part of the same command. For V2 this will only flush blocks already marked
531  * dirty/erased with the appropriate commands and doesn't take any arguments
532  * directly.
533  *
534  * V1:
535  * ARGS[0:1]: Where within window to start (number of blocks)
536  * ARGS[2:5]: Number to mark dirty (number of bytes)
537  *
538  * V2:
539  * NONE
540  */
541 int mbox_handle_flush_window(struct mbox_context *context,
542 				    union mbox_regs *req, struct mbox_msg *resp)
543 {
544 	int rc, i, offset, count;
545 	uint8_t prev;
546 
547 	if (!(context->current && context->current_is_write)) {
548 		MSG_ERR("Tried to call flush without open write window\n");
549 		return context->version >= API_VERSION_2 ? -MBOX_R_WINDOW_ERROR
550 							 : -MBOX_R_PARAM_ERROR;
551 	}
552 
553 	/*
554 	 * For V1 the Flush command acts much the same as the dirty command
555 	 * except with a flush as well. Only do this on an actual flush
556 	 * command not when we call flush because we've implicitly closed a
557 	 * window because we might not have the required args in req.
558 	 */
559 	if (context->version == API_VERSION_1 && req &&
560 			req->msg.command == MBOX_C_WRITE_FLUSH) {
561 		rc = mbox_handle_dirty_window(context, req, NULL);
562 		if (rc < 0) {
563 			return rc;
564 		}
565 	}
566 
567 	offset = 0;
568 	count = 0;
569 	prev = WINDOW_CLEAN;
570 
571 	MSG_INFO("Flush window @ %p for size 0x%.8x which maps flash @ 0x%.8x\n",
572 		 context->current->mem, context->current->size,
573 		 context->current->flash_offset);
574 
575 	/*
576 	 * We look for streaks of the same type and keep a count, when the type
577 	 * (dirty/erased) changes we perform the required action on the backing
578 	 * store and update the current streak-type
579 	 */
580 	for (i = 0; i < (context->current->size >> context->block_size_shift);
581 			i++) {
582 		uint8_t cur = context->current->dirty_bmap[i];
583 		if (cur != WINDOW_CLEAN) {
584 			if (cur == prev) { /* Same as previous block, incrmnt */
585 				count++;
586 			} else if (prev == WINDOW_CLEAN) { /* Start of run */
587 				offset = i;
588 				count++;
589 			} else { /* Change in streak type */
590 				rc = window_flush(context, offset, count,
591 						       prev);
592 				if (rc < 0) {
593 					return rc;
594 				}
595 				offset = i;
596 				count = 1;
597 			}
598 		} else {
599 			if (prev != WINDOW_CLEAN) { /* End of a streak */
600 				rc = window_flush(context, offset, count,
601 						       prev);
602 				if (rc < 0) {
603 					return rc;
604 				}
605 				offset = 0;
606 				count = 0;
607 			}
608 		}
609 		prev = cur;
610 	}
611 
612 	if (prev != WINDOW_CLEAN) { /* Still the last streak to write */
613 		rc = window_flush(context, offset, count, prev);
614 		if (rc < 0) {
615 			return rc;
616 		}
617 	}
618 
619 	/* Clear the dirty bytemap since we have written back all changes */
620 	rc = window_set_bytemap(context, context->current, 0,
621 				  context->current->size >>
622 				  context->block_size_shift,
623 				  WINDOW_CLEAN);
624 	if (rc < 0) {
625 		return (rc == -EACCES) ? -MBOX_R_PARAM_ERROR
626 				       : -MBOX_R_SYSTEM_ERROR;
627 	}
628 
629 	return rc;
630 }
631 
632 /*
633  * Command: CLOSE_WINDOW
634  * Close the current window
635  * NOTE: There is an implicit flush
636  *
637  * V1:
638  * NONE
639  *
640  * V2:
641  * ARGS[0]: FLAGS
642  */
643 int mbox_handle_close_window(struct mbox_context *context,
644 				    union mbox_regs *req, struct mbox_msg *resp)
645 {
646 	uint8_t flags = 0;
647 	int rc;
648 
649 	/* Close the current window if there is one */
650 	if (context->current) {
651 		/* There is an implicit flush if it was a write window */
652 		if (context->current_is_write) {
653 			rc = mbox_handle_flush_window(context, NULL, NULL);
654 			if (rc < 0) {
655 				MSG_ERR("Couldn't Flush Write Window\n");
656 				return rc;
657 			}
658 		}
659 
660 		if (context->version >= API_VERSION_2) {
661 			flags = req->msg.args[0];
662 		}
663 
664 		/* Host asked for it -> Don't set the BMC Event */
665 		windows_close_current(context, NO_BMC_EVENT, flags);
666 	}
667 
668 	return 0;
669 }
670 
671 /*
672  * Command: BMC_EVENT_ACK
673  * Sent by the host to acknowledge BMC events supplied in mailbox register 15
674  *
675  * ARGS[0]: Bitmap of bits to ack (by clearing)
676  */
677 int mbox_handle_ack(struct mbox_context *context, union mbox_regs *req,
678 			   struct mbox_msg *resp)
679 {
680 	uint8_t bmc_events = req->msg.args[0];
681 
682 	return clr_bmc_events(context, (bmc_events & BMC_EVENT_ACK_MASK),
683 			      SET_BMC_EVENT);
684 }
685 
686 /*
687  * check_req_valid() - Check if the given request is a valid mbox request
688  * @context:	The mbox context pointer
689  * @cmd:	The request registers
690  *
691  * Return:	0 if request is valid otherwise negative error code
692  */
693 static int check_req_valid(struct mbox_context *context, union mbox_regs *req)
694 {
695 	uint8_t cmd = req->msg.command;
696 	uint8_t seq = req->msg.seq;
697 
698 	if (cmd > NUM_MBOX_CMDS) {
699 		MSG_ERR("Unknown mbox command: %d\n", cmd);
700 		return -MBOX_R_PARAM_ERROR;
701 	}
702 
703 	if (seq == context->prev_seq && cmd != MBOX_C_GET_MBOX_INFO) {
704 		MSG_ERR("Invalid sequence number: %d, previous: %d\n", seq,
705 			context->prev_seq);
706 		return -MBOX_R_SEQ_ERROR;
707 	}
708 
709 	if (context->state & STATE_SUSPENDED) {
710 		if (cmd != MBOX_C_GET_MBOX_INFO && cmd != MBOX_C_ACK) {
711 			MSG_ERR("Cannot use that cmd while suspended: %d\n",
712 				cmd);
713 			return context->version >= API_VERSION_2 ? -MBOX_R_BUSY
714 						: -MBOX_R_PARAM_ERROR;
715 		}
716 	}
717 
718 	if (!(context->state & MAPS_MEM)) {
719 		if (cmd != MBOX_C_RESET_STATE && cmd != MBOX_C_GET_MBOX_INFO
720 					      && cmd != MBOX_C_ACK) {
721 			MSG_ERR("Must call GET_MBOX_INFO before %d\n", cmd);
722 			return -MBOX_R_PARAM_ERROR;
723 		}
724 	}
725 
726 	return 0;
727 }
728 
729 static const mboxd_mbox_handler mbox_handlers[] = {
730 	mbox_handle_reset,
731 	mbox_handle_mbox_info,
732 	mbox_handle_flash_info,
733 	mbox_handle_read_window,
734 	mbox_handle_close_window,
735 	mbox_handle_write_window,
736 	mbox_handle_dirty_window,
737 	mbox_handle_flush_window,
738 	mbox_handle_ack,
739 	mbox_handle_erase_window
740 };
741 
742 /*
743  * handle_mbox_req() - Handle an incoming mbox command request
744  * @context:	The mbox context pointer
745  * @req:	The mbox request message
746  *
747  * Return:	0 if handled successfully otherwise negative error code
748  */
749 static int handle_mbox_req(struct mbox_context *context, union mbox_regs *req)
750 {
751 	struct mbox_msg resp = {
752 		.command = req->msg.command,
753 		.seq = req->msg.seq,
754 		.args = { 0 },
755 		.response = MBOX_R_SUCCESS
756 	};
757 	int rc = 0, len, i;
758 
759 	MSG_INFO("Received MBOX command: %u\n", req->msg.command);
760 	rc = check_req_valid(context, req);
761 	if (rc < 0) {
762 		resp.response = -rc;
763 	} else {
764 		/* Commands start at 1 so we have to subtract 1 from the cmd */
765 		mboxd_mbox_handler h = context->handlers[req->msg.command - 1];
766 		rc = h(context, req, &resp);
767 		if (rc < 0) {
768 			MSG_ERR("Error handling mbox cmd: %d\n",
769 				req->msg.command);
770 			resp.response = -rc;
771 		}
772 	}
773 
774 	context->prev_seq = req->msg.seq;
775 
776 	MSG_DBG("Writing MBOX response:\n");
777 	MSG_DBG("MBOX cmd: %u\n", resp.command);
778 	MSG_DBG("MBOX seq: %u\n", resp.seq);
779 	for (i = 0; i < MBOX_ARGS_BYTES; i++) {
780 		MSG_DBG("MBOX arg[%d]: 0x%.2x\n", i, resp.args[i]);
781 	}
782 	MSG_INFO("Writing MBOX response: %u\n", resp.response);
783 	len = write(context->fds[MBOX_FD].fd, &resp, sizeof(resp));
784 	if (len < sizeof(resp)) {
785 		MSG_ERR("Didn't write the full response\n");
786 		rc = -errno;
787 	}
788 
789 	return rc;
790 }
791 
792 /*
793  * get_message() - Read an mbox request message from the mbox registers
794  * @context:	The mbox context pointer
795  * @msg:	Where to put the received message
796  *
797  * Return:	0 if read successfully otherwise negative error code
798  */
799 static int get_message(struct mbox_context *context, union mbox_regs *msg)
800 {
801 	int rc, i;
802 
803 	rc = read(context->fds[MBOX_FD].fd, msg, sizeof(msg->raw));
804 	if (rc < 0) {
805 		MSG_ERR("Couldn't read: %s\n", strerror(errno));
806 		return -errno;
807 	} else if (rc < sizeof(msg->raw)) {
808 		MSG_ERR("Short read: %d expecting %zu\n", rc, sizeof(msg->raw));
809 		return -1;
810 	}
811 
812 	MSG_DBG("Received MBOX request:\n");
813 	MSG_DBG("MBOX cmd: %u\n", msg->msg.command);
814 	MSG_DBG("MBOX seq: %u\n", msg->msg.seq);
815 	for (i = 0; i < MBOX_ARGS_BYTES; i++) {
816 		MSG_DBG("MBOX arg[%d]: 0x%.2x\n", i, msg->msg.args[i]);
817 	}
818 
819 	return 0;
820 }
821 
822 /*
823  * dispatch_mbox() - handle an mbox interrupt
824  * @context:	The mbox context pointer
825  *
826  * Return:	0 if handled successfully otherwise negative error code
827  */
828 int dispatch_mbox(struct mbox_context *context)
829 {
830 	int rc = 0;
831 	union mbox_regs req = { 0 };
832 
833 	assert(context);
834 
835 	rc = get_message(context, &req);
836 	if (rc) {
837 		return rc;
838 	}
839 
840 	return handle_mbox_req(context, &req);
841 }
842 
843 int __init_mbox_dev(struct mbox_context *context, const char *path)
844 {
845 	int fd;
846 
847 	context->handlers = mbox_handlers;
848 
849 	/* Open MBOX Device */
850 	fd = open(path, O_RDWR | O_NONBLOCK);
851 	if (fd < 0) {
852 		MSG_ERR("Couldn't open %s with flags O_RDWR: %s\n",
853 			path, strerror(errno));
854 		return -errno;
855 	}
856 	MSG_DBG("Opened mbox dev: %s\n", path);
857 
858 	context->fds[MBOX_FD].fd = fd;
859 
860 	return 0;
861 }
862 
863 int init_mbox_dev(struct mbox_context *context)
864 {
865 	return __init_mbox_dev(context, MBOX_HOST_PATH);
866 }
867 
868 void free_mbox_dev(struct mbox_context *context)
869 {
870 	close(context->fds[MBOX_FD].fd);
871 }
872