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