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