xref: /openbmc/phosphor-mboxd/mboxd_windows.c (revision c29172e1734012af7a9b97c5170b9da6a571e343)
1 /*
2  * Mailbox Daemon Window Helpers
3  *
4  * Copyright 2016 IBM
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19 
20 #define _GNU_SOURCE
21 #include <assert.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <getopt.h>
25 #include <limits.h>
26 #include <poll.h>
27 #include <stdbool.h>
28 #include <stdint.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <syslog.h>
33 #include <signal.h>
34 #include <sys/ioctl.h>
35 #include <sys/mman.h>
36 #include <sys/stat.h>
37 #include <sys/timerfd.h>
38 #include <sys/types.h>
39 #include <time.h>
40 #include <unistd.h>
41 #include <inttypes.h>
42 #include <mtd/mtd-abi.h>
43 
44 #include "mbox.h"
45 #include "common.h"
46 #include "mboxd_msg.h"
47 #include "mboxd_windows.h"
48 #include "mboxd_flash.h"
49 
50 /* Initialisation Functions */
51 
52 /*
53  * init_window_state() - Initialise a new window to a known state
54  * @window:	The window to initialise
55  * @size:	The size of the window
56  */
57 static void init_window_state(struct window_context *window, uint32_t size)
58 {
59 	window->mem = NULL;
60 	window->flash_offset = FLASH_OFFSET_UNINIT;
61 	window->size = size;
62 	window->dirty_bmap = NULL;
63 	window->age = 0;
64 }
65 
66 /*
67  * init_window_mem() - Divide the reserved memory region among the windows
68  * @context:	The mbox context pointer
69  *
70  * Return:	0 on success otherwise negative error code
71  */
72 static int init_window_mem(struct mbox_context *context)
73 {
74 	void *mem_location = context->mem;
75 	int i;
76 
77 	/*
78 	 * Carve up the reserved memory region and allocate it to each of the
79 	 * windows. The windows are placed one after the other in ascending
80 	 * order, so the first window will be first in memory and so on. We
81 	 * shouldn't have allocated more windows than we have memory, but if we
82 	 * did we will error out here
83 	 */
84 	for (i = 0; i < context->windows.num; i++) {
85 		context->windows.window[i].mem = mem_location;
86 		mem_location += context->windows.window[i].size;
87 		if (mem_location > (context->mem + context->mem_size)) {
88 			/* Tried to allocate window past the end of memory */
89 			MSG_ERR("Total size of windows exceeds reserved mem\n");
90 			MSG_ERR("Try smaller or fewer windows\n");
91 			MSG_ERR("Mem size: 0x%.8x\n", context->mem_size);
92 			return -1;
93 		}
94 	}
95 
96 	return 0;
97 }
98 /*
99  * init_windows() - Initalise the window cache
100  * @context:    The mbox context pointer
101  *
102  * Return:      0 on success otherwise negative
103  */
104 int init_windows(struct mbox_context *context)
105 {
106 	int i;
107 
108 	/* Check if window size and number set - otherwise set to default */
109 	if (!context->windows.default_size) {
110 		/* Default to 1MB windows */
111 		context->windows.default_size = 1 << 20;
112 	}
113 	MSG_OUT("Window size: 0x%.8x\n", context->windows.default_size);
114 	if (!context->windows.num) {
115 		/* Use the entire reserved memory region by default */
116 		context->windows.num = context->mem_size /
117 				       context->windows.default_size;
118 	}
119 	MSG_OUT("Number of Windows: %d\n", context->windows.num);
120 
121 	context->windows.window = calloc(context->windows.num,
122 					 sizeof(*context->windows.window));
123 	if (!context->windows.window) {
124 		MSG_ERR("Memory allocation failed\n");
125 		return -1;
126 	}
127 
128 	for (i = 0; i < context->windows.num; i++) {
129 		init_window_state(&context->windows.window[i],
130 				  context->windows.default_size);
131 	}
132 
133 	return init_window_mem(context);
134 }
135 
136 /*
137  * free_windows() - Free the window cache
138  * @context:	The mbox context pointer
139  */
140 void free_windows(struct mbox_context *context)
141 {
142 	int i;
143 
144 	/* Check window cache has actually been allocated */
145 	if (context->windows.window) {
146 		for (i = 0; i < context->windows.num; i++) {
147 			free(context->windows.window[i].dirty_bmap);
148 		}
149 		free(context->windows.window);
150 	}
151 }
152 
153 /* Write from Window Functions */
154 
155 /*
156  * write_from_window_v1() - Handle writing when erase and block size differ
157  * @context:		The mbox context pointer
158  * @offset_bytes:	The offset in the current window to write from (bytes)
159  * @count_bytes:	Number of bytes to write
160  *
161  * Handle a write_from_window for dirty memory when block_size is less than the
162  * flash erase size
163  * This requires us to be a bit careful because we might have to erase more
164  * than we want to write which could result in data loss if we don't have the
165  * entire portion of flash to be erased already saved in memory (for us to
166  * write back after the erase)
167  *
168  * Return:	0 on success otherwise negative error code
169  */
170 int write_from_window_v1(struct mbox_context *context,
171 			 uint32_t offset_bytes, uint32_t count_bytes)
172 {
173 	int rc;
174 	uint32_t flash_offset;
175 	struct window_context low_mem = { 0 }, high_mem = { 0 };
176 
177 	/* Find where in phys flash this is based on the window.flash_offset */
178 	flash_offset = context->current->flash_offset + offset_bytes;
179 
180 	/*
181 	 * low_mem.flash_offset = erase boundary below where we're writing
182 	 * low_mem.size = size from low_mem.flash_offset to where we're writing
183 	 *
184 	 * high_mem.flash_offset = end of where we're writing
185 	 * high_mem.size = size from end of where we're writing to next erase
186 	 * 		   boundary
187 	 */
188 	low_mem.flash_offset = align_down(flash_offset,
189 					  context->mtd_info.erasesize);
190 	low_mem.size = flash_offset - low_mem.flash_offset;
191 	high_mem.flash_offset = flash_offset + count_bytes;
192 	high_mem.size = align_up(high_mem.flash_offset,
193 				 context->mtd_info.erasesize) -
194 			high_mem.flash_offset;
195 
196 	/*
197 	 * Check if we already have a copy of the required flash areas in
198 	 * memory as part of the existing window
199 	 */
200 	if (low_mem.flash_offset < context->current->flash_offset) {
201 		/* Before the start of our current window */
202 		low_mem.mem = malloc(low_mem.size);
203 		if (!low_mem.mem) {
204 			MSG_ERR("Unable to allocate memory\n");
205 			return -MBOX_R_SYSTEM_ERROR;
206 		}
207 		rc = copy_flash(context, low_mem.flash_offset,
208 				low_mem.mem, low_mem.size);
209 		if (rc < 0) {
210 			goto out;
211 		}
212 	}
213 	if ((high_mem.flash_offset + high_mem.size) >
214 	    (context->current->flash_offset + context->current->size)) {
215 		/* After the end of our current window */
216 		high_mem.mem = malloc(high_mem.size);
217 		if (!high_mem.mem) {
218 			MSG_ERR("Unable to allocate memory\n");
219 			rc = -MBOX_R_SYSTEM_ERROR;
220 			goto out;
221 		}
222 		rc = copy_flash(context, high_mem.flash_offset,
223 				high_mem.mem, high_mem.size);
224 		if (rc < 0) {
225 			goto out;
226 		}
227 	}
228 
229 	/*
230 	 * We need to erase the flash from low_mem.flash_offset->
231 	 * high_mem.flash_offset + high_mem.size
232 	 */
233 	rc = erase_flash(context, low_mem.flash_offset,
234 			 (high_mem.flash_offset - low_mem.flash_offset) +
235 			 high_mem.size);
236 	if (rc < 0) {
237 		MSG_ERR("Couldn't erase flash\n");
238 		goto out;
239 	}
240 
241 	/* Write back over the erased area */
242 	if (low_mem.mem) {
243 		/* Exceed window at the start */
244 		rc = write_flash(context, low_mem.flash_offset, low_mem.mem,
245 				 low_mem.size);
246 		if (rc < 0) {
247 			goto out;
248 		}
249 	}
250 	rc = write_flash(context, flash_offset,
251 			 context->current->mem + offset_bytes, count_bytes);
252 	if (rc < 0) {
253 		goto out;
254 	}
255 	/*
256 	 * We still need to write the last little bit that we erased - it's
257 	 * either in the current window or the high_mem window.
258 	 */
259 	if (high_mem.mem) {
260 		/* Exceed window at the end */
261 		rc = write_flash(context, high_mem.flash_offset, high_mem.mem,
262 				 high_mem.size);
263 		if (rc < 0) {
264 			goto out;
265 		}
266 	} else {
267 		/* Write from the current window - it's atleast that big */
268 		rc = write_flash(context, high_mem.flash_offset,
269 				 context->current->mem + offset_bytes +
270 				 count_bytes, high_mem.size);
271 		if (rc < 0) {
272 			goto out;
273 		}
274 	}
275 
276 out:
277 	free(low_mem.mem);
278 	free(high_mem.mem);
279 	return rc;
280 }
281 
282 /*
283  * write_from_window() - Write back to the flash from the current window
284  * @context:		The mbox context pointer
285  * @offset_bytes:	The offset in the current window to write from (blocks)
286  * @count_bytes:	Number of blocks to write
287  * @type:		Whether this is an erase & write or just an erase
288  *
289  * Return:	0 on success otherwise negative error code
290  */
291 int write_from_window(struct mbox_context *context, uint32_t offset,
292 		      uint32_t count, uint8_t type)
293 {
294 	int rc;
295 	uint32_t flash_offset, count_bytes = count << context->block_size_shift;
296 	uint32_t offset_bytes = offset << context->block_size_shift;
297 
298 	switch (type) {
299 	case WINDOW_ERASED: /* >= V2 ONLY -> block_size == erasesize */
300 		flash_offset = context->current->flash_offset + offset_bytes;
301 		rc = erase_flash(context, flash_offset, count_bytes);
302 		if (rc < 0) {
303 			MSG_ERR("Couldn't erase flash\n");
304 			return rc;
305 		}
306 		break;
307 	case WINDOW_DIRTY:
308 		/*
309 		 * For protocol V1, block_size may be smaller than erase size
310 		 * so we have a special function to make sure that we do this
311 		 * correctly without losing data.
312 		 */
313 		if (log_2(context->mtd_info.erasesize) !=
314 						context->block_size_shift) {
315 			return write_from_window_v1(context, offset_bytes,
316 						    count_bytes);
317 		}
318 		flash_offset = context->current->flash_offset + offset_bytes;
319 
320 		/* Erase the flash */
321 		rc = erase_flash(context, flash_offset, count_bytes);
322 		if (rc < 0) {
323 			return rc;
324 		}
325 
326 		/* Write to the erased flash */
327 		rc = write_flash(context, flash_offset,
328 				 context->current->mem + offset_bytes,
329 				 count_bytes);
330 		if (rc < 0) {
331 			return rc;
332 		}
333 
334 		break;
335 	default:
336 		/* We shouldn't be able to get here */
337 		MSG_ERR("Write from window with invalid type: %d\n", type);
338 		return -MBOX_R_SYSTEM_ERROR;
339 	}
340 
341 	return 0;
342 }
343 
344 /* Window Management Functions */
345 
346 /*
347  * alloc_window_dirty_bytemap() - (re)allocate all the window dirty bytemaps
348  * @context:		The mbox context pointer
349  */
350 void alloc_window_dirty_bytemap(struct mbox_context *context)
351 {
352 	struct window_context *cur;
353 	int i;
354 
355 	for (i = 0; i < context->windows.num; i++) {
356 		cur = &context->windows.window[i];
357 		/* There may already be one allocated */
358 		free(cur->dirty_bmap);
359 		/* Allocate the new one */
360 		cur->dirty_bmap = calloc((cur->size >>
361 					  context->block_size_shift),
362 					 sizeof(*cur->dirty_bmap));
363 	}
364 }
365 
366 /*
367  * set_window_bytemap() - Set the window bytemap
368  * @context:	The mbox context pointer
369  * @cur:	The window to set the bytemap of
370  * @offset:	Where in the window to set the bytemap (blocks)
371  * @size:	The number of blocks to set
372  * @val:	The value to set the bytemap to
373  *
374  * Return:	0 on success otherwise negative error code
375  */
376 int set_window_bytemap(struct mbox_context *context, struct window_context *cur,
377 		       uint32_t offset, uint32_t size, uint8_t val)
378 {
379 	if (offset + size > (cur->size >> context->block_size_shift)) {
380 		MSG_ERR("Tried to set window bytemap past end of window\n");
381 		MSG_ERR("Requested offset: 0x%x size: 0x%x window size: 0x%x\n",
382 			offset << context->block_size_shift,
383 			size << context->block_size_shift,
384 			cur->size << context->block_size_shift);
385 		return -MBOX_R_PARAM_ERROR;
386 	}
387 
388 	memset(cur->dirty_bmap + offset, val, size);
389 	return 0;
390 }
391 
392 /*
393  * close_current_window() - Close the current (active) window
394  * @context:   		The mbox context pointer
395  * @set_bmc_event:	Whether to set the bmc event bit
396  * @flags:		Flags as defined for a close command in the protocol
397  *
398  * This closes the current window. If the host has requested the current window
399  * be closed then we don't need to set the bmc event bit
400  * (set_bmc_event == false), otherwise if the current window has been closed
401  * without the host requesting it the bmc event bit must be set to indicate this
402  * to the host (set_bmc_event == true).
403  */
404 void close_current_window(struct mbox_context *context, bool set_bmc_event,
405 			  uint8_t flags)
406 {
407 	if (set_bmc_event) {
408 		set_bmc_events(context, BMC_EVENT_WINDOW_RESET, SET_BMC_EVENT);
409 	}
410 
411 	if (flags & FLAGS_SHORT_LIFETIME) {
412 		context->current->age = 0;
413 	}
414 
415 	context->current->size = context->windows.default_size;
416 	context->current = NULL;
417 	context->current_is_write = false;
418 }
419 
420 /*
421  * reset_window() - Reset a window context to a well defined default state
422  * @context:   	The mbox context pointer
423  * @window:	The window to reset
424  */
425 void reset_window(struct mbox_context *context, struct window_context *window)
426 {
427 	window->flash_offset = FLASH_OFFSET_UNINIT;
428 	window->size = context->windows.default_size;
429 	if (window->dirty_bmap) { /* Might not have been allocated */
430 		set_window_bytemap(context, window, 0,
431 				   window->size >> context->block_size_shift,
432 				   WINDOW_CLEAN);
433 	}
434 	window->age = 0;
435 }
436 
437 /*
438  * reset_all_windows() - Reset all windows to a well defined default state
439  * @context:		The mbox context pointer
440  * @set_bmc_event:	If any state change should be indicated to the host
441  */
442 void reset_all_windows(struct mbox_context *context, bool set_bmc_event)
443 {
444 	int i;
445 
446 	/* We might have an open window which needs closing */
447 	if (context->current) {
448 		close_current_window(context, set_bmc_event, FLAGS_NONE);
449 	}
450 	for (i = 0; i < context->windows.num; i++) {
451 		reset_window(context, &context->windows.window[i]);
452 	}
453 
454 	context->windows.max_age = 0;
455 }
456 
457 /*
458  * find_oldest_window() - Find the oldest (Least Recently Used) window
459  * @context:		The mbox context pointer
460  *
461  * Return:	Pointer to the least recently used window
462  */
463 struct window_context *find_oldest_window(struct mbox_context *context)
464 {
465 	struct window_context *oldest = NULL, *cur;
466 	uint32_t min_age = context->windows.max_age + 1;
467 	int i;
468 
469 	for (i = 0; i < context->windows.num; i++) {
470 		cur = &context->windows.window[i];
471 
472 		if (cur->age < min_age) {
473 			min_age = cur->age;
474 			oldest = cur;
475 		}
476 	}
477 
478 	return oldest;
479 }
480 
481 /*
482  * search_windows() - Search the window cache for a window containing offset
483  * @context:	The mbox context pointer
484  * @offset:	Absolute flash offset to search for (bytes)
485  * @exact:	If the window must exactly map the requested offset
486  *
487  * This will search the cache of windows for one containing the requested
488  * offset. For V1 of the protocol windows must exactly map the offset since we
489  * can't tell the host how much of its request we actually mapped and it will
490  * thus assume it can access window->size from the offset we give it.
491  *
492  * Return:	Pointer to a window containing the requested offset otherwise
493  *		NULL
494  */
495 struct window_context *search_windows(struct mbox_context *context,
496 				      uint32_t offset, bool exact)
497 {
498 	struct window_context *cur;
499 	int i;
500 
501 	for (i = 0; i < context->windows.num; i++) {
502 		cur = &context->windows.window[i];
503 		if (cur->flash_offset == FLASH_OFFSET_UNINIT) {
504 			/* Uninitialised Window */
505 			if (offset == FLASH_OFFSET_UNINIT) {
506 				return cur;
507 			}
508 			continue;
509 		}
510 		if ((offset >= cur->flash_offset) &&
511 		    (offset < (cur->flash_offset + cur->size))) {
512 			if (exact && (cur->flash_offset != offset)) {
513 				continue;
514 			}
515 			/* This window contains the requested offset */
516 			cur->age = ++(context->windows.max_age);
517 			return cur;
518 		}
519 	}
520 
521 	return NULL;
522 }
523 
524 /*
525  * create_map_window() - Create a window mapping which maps the requested offset
526  * @context:		The mbox context pointer
527  * @this_window:	A pointer to update to the "new" window
528  * @offset:		Absolute flash offset to create a mapping for (bytes)
529  * @exact:		If the window must exactly map the requested offset
530  *
531  * This is used to create a window mapping for the requested offset when there
532  * is no existing window in the cache which satisfies the offset. This involves
533  * choosing an existing window from the window cache to evict so we can use it
534  * to store the flash contents from the requested offset, we then point the
535  * caller to that window since it now maps their request.
536  *
537  * Return:	0 on success otherwise negative error code
538  */
539 int create_map_window(struct mbox_context *context,
540 		      struct window_context **this_window, uint32_t offset,
541 		      bool exact)
542 {
543 	struct window_context *cur = NULL;
544 	int rc;
545 
546 
547 	/* Search for an uninitialised window, use this before evicting */
548 	cur = search_windows(context, FLASH_OFFSET_UNINIT, true);
549 
550 	/* No uninitialised window found, we need to choose one to "evict" */
551 	if (!cur) {
552 		cur = find_oldest_window(context);
553 	}
554 
555 	if (!exact) {
556 		/*
557 		 * It would be nice to align the offsets which we map to window
558 		 * size, this will help prevent overlap which would be an
559 		 * inefficient use of our reserved memory area (we would like
560 		 * to "cache" as much of the acutal flash as possible in
561 		 * memory). If we're protocol V1 however we must ensure the
562 		 * offset requested is exactly mapped.
563 		 */
564 		offset &= ~(cur->size - 1);
565 	}
566 
567 	if ((offset + cur->size) > context->flash_size) {
568 		/*
569 		 * There is V1 skiboot implementations out there which don't
570 		 * mask offset with window size, meaning when we have
571 		 * window size == flash size we will never allow the host to
572 		 * open a window except at 0x0, which isn't always where the
573 		 * host requests it. Thus we have to ignore this check and just
574 		 * hope the host doesn't access past the end of the window
575 		 * (which it shouldn't) for V1 implementations to get around
576 		 * this.
577 		 */
578 		if (context->version == API_VERSION_1) {
579 			cur->size = align_down(context->flash_size - offset,
580 					       1 << context->block_size_shift);
581 		} else {
582 			/* Trying to read past the end of flash */
583 			MSG_ERR("Tried to open read window past flash limit\n");
584 			return -MBOX_R_PARAM_ERROR;
585 		}
586 	}
587 
588 	/* Copy from flash into the window buffer */
589 	rc = copy_flash(context, offset, cur->mem, cur->size);
590 	if (rc < 0) {
591 		/* We don't know how much we've copied -> better reset window */
592 		reset_window(context, cur);
593 		return rc;
594 	}
595 
596 	/*
597 	 * Since for V1 windows aren't constrained to start at multiples of
598 	 * window size it's possible that something already maps this offset.
599 	 * Reset any windows which map this offset to avoid coherency problems.
600 	 * We just have to check for anything which maps the start or the end
601 	 * of the window since all windows are the same size so another window
602 	 * cannot map just the middle of this window.
603 	 */
604 	if (context->version == API_VERSION_1) {
605 		uint32_t i;
606 
607 		for (i = offset; i < (offset + cur->size); i += (cur->size - 1)) {
608 			struct window_context *tmp = NULL;
609 			do {
610 				tmp = search_windows(context, i, false);
611 				if (tmp) {
612 					reset_window(context, tmp);
613 				}
614 			} while (tmp);
615 		}
616 	}
617 
618 	/* Clear the bytemap of the window just loaded -> we know it's clean */
619 	set_window_bytemap(context, cur, 0,
620 			   cur->size >> context->block_size_shift,
621 			   WINDOW_CLEAN);
622 
623 	/* Update so we know what's in the window */
624 	cur->flash_offset = offset;
625 	cur->age = ++(context->windows.max_age);
626 	*this_window = cur;
627 
628 	return 0;
629 }
630