xref: /linux/kernel/liveupdate/luo_file.c (revision b20624608f350c5dadd74577629e90715d351e2c)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright (c) 2025, Google LLC.
5  * Pasha Tatashin <pasha.tatashin@soleen.com>
6  */
7 
8 /**
9  * DOC: LUO File Descriptors
10  *
11  * LUO provides the infrastructure to preserve specific, stateful file
12  * descriptors across a kexec-based live update. The primary goal is to allow
13  * workloads, such as virtual machines using vfio, memfd, or iommufd, to
14  * retain access to their essential resources without interruption.
15  *
16  * The framework is built around a callback-based handler model and a well-
17  * defined lifecycle for each preserved file.
18  *
19  * Handler Registration:
20  * Kernel modules responsible for a specific file type (e.g., memfd, vfio)
21  * register a &struct liveupdate_file_handler. This handler provides a set of
22  * callbacks that LUO invokes at different stages of the update process, most
23  * notably:
24  *
25  *   - can_preserve(): A lightweight check to determine if the handler is
26  *     compatible with a given 'struct file'.
27  *   - preserve(): The heavyweight operation that saves the file's state and
28  *     returns an opaque u64 handle. This is typically performed while the
29  *     workload is still active to minimize the downtime during the
30  *     actual reboot transition.
31  *   - unpreserve(): Cleans up any resources allocated by .preserve(), called
32  *     if the preservation process is aborted before the reboot (i.e. session is
33  *     closed).
34  *   - freeze(): A final pre-reboot opportunity to prepare the state for kexec.
35  *     We are already in reboot syscall, and therefore userspace cannot mutate
36  *     the file anymore.
37  *   - unfreeze(): Undoes the actions of .freeze(), called if the live update
38  *     is aborted after the freeze phase.
39  *   - retrieve(): Reconstructs the file in the new kernel from the preserved
40  *     handle.
41  *   - finish(): Performs final check and cleanup in the new kernel. After
42  *     succesul finish call, LUO gives up ownership to this file.
43  *
44  * File Preservation Lifecycle happy path:
45  *
46  * 1. Preserve (Normal Operation): A userspace agent preserves files one by one
47  *    via an ioctl. For each file, luo_preserve_file() finds a compatible
48  *    handler, calls its .preserve() operation, and creates an internal &struct
49  *    luo_file to track the live state.
50  *
51  * 2. Freeze (Pre-Reboot): Just before the kexec, luo_file_freeze() is called.
52  *    It iterates through all preserved files, calls their respective .freeze()
53  *    operation, and serializes their final metadata (compatible string, token,
54  *    and data handle) into a contiguous memory block for KHO.
55  *
56  * 3. Deserialize: After kexec, luo_file_deserialize() runs when session gets
57  *    deserialized (which is when /dev/liveupdate is first opened). It reads the
58  *    serialized data from the KHO memory region and reconstructs the in-memory
59  *    list of &struct luo_file instances for the new kernel, linking them to
60  *    their corresponding handlers.
61  *
62  * 4. Retrieve (New Kernel - Userspace Ready): The userspace agent can now
63  *    restore file descriptors by providing a token. luo_retrieve_file()
64  *    searches for the matching token, calls the handler's .retrieve() op to
65  *    re-create the 'struct file', and returns a new FD. Files can be
66  *    retrieved in ANY order.
67  *
68  * 5. Finish (New Kernel - Cleanup): Once a session retrival is complete,
69  *    luo_file_finish() is called. It iterates through all files, invokes their
70  *    .finish() operations for final cleanup, and releases all associated kernel
71  *    resources.
72  *
73  * File Preservation Lifecycle unhappy paths:
74  *
75  * 1. Abort Before Reboot: If the userspace agent aborts the live update
76  *    process before calling reboot (e.g., by closing the session file
77  *    descriptor), the session's release handler calls
78  *    luo_file_unpreserve_files(). This invokes the .unpreserve() callback on
79  *    all preserved files, ensuring all allocated resources are cleaned up and
80  *    returning the system to a clean state.
81  *
82  * 2. Freeze Failure: During the reboot() syscall, if any handler's .freeze()
83  *    op fails, the .unfreeze() op is invoked on all previously *successful*
84  *    freezes to roll back their state. The reboot() syscall then returns an
85  *    error to userspace, canceling the live update.
86  *
87  * 3. Finish Failure: In the new kernel, if a handler's .finish() op fails,
88  *    the luo_file_finish() operation is aborted. LUO retains ownership of
89  *    all files within that session, including those that were not yet
90  *    processed. The userspace agent can attempt to call the finish operation
91  *    again later. If the issue cannot be resolved, these resources will be held
92  *    by LUO until the next live update cycle, at which point they will be
93  *    discarded.
94  */
95 
96 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
97 
98 #include <linux/cleanup.h>
99 #include <linux/compiler.h>
100 #include <linux/err.h>
101 #include <linux/errno.h>
102 #include <linux/file.h>
103 #include <linux/fs.h>
104 #include <linux/io.h>
105 #include <linux/kexec_handover.h>
106 #include <linux/kho/abi/luo.h>
107 #include <linux/liveupdate.h>
108 #include <linux/module.h>
109 #include <linux/sizes.h>
110 #include <linux/slab.h>
111 #include <linux/string.h>
112 #include "luo_internal.h"
113 
114 static LIST_HEAD(luo_file_handler_list);
115 
116 /* 2 4K pages, give space for 128 files per file_set */
117 #define LUO_FILE_PGCNT		2ul
118 #define LUO_FILE_MAX							\
119 	((LUO_FILE_PGCNT << PAGE_SHIFT) / sizeof(struct luo_file_ser))
120 
121 /**
122  * struct luo_file - Represents a single preserved file instance.
123  * @fh:            Pointer to the &struct liveupdate_file_handler that manages
124  *                 this type of file.
125  * @file:          Pointer to the kernel's &struct file that is being preserved.
126  *                 This is NULL in the new kernel until the file is successfully
127  *                 retrieved.
128  * @serialized_data: The opaque u64 handle to the serialized state of the file.
129  *                 This handle is passed back to the handler's .freeze(),
130  *                 .retrieve(), and .finish() callbacks, allowing it to track
131  *                 and update its serialized state across phases.
132  * @private_data:  Pointer to the private data for the file used to hold runtime
133  *                 state that is not preserved. Set by the handler's .preserve()
134  *                 callback, and must be freed in the handler's .unpreserve()
135  *                 callback.
136  * @retrieved:     A flag indicating whether a user/kernel in the new kernel has
137  *                 successfully called retrieve() on this file. This prevents
138  *                 multiple retrieval attempts.
139  * @mutex:         A mutex that protects the fields of this specific instance
140  *                 (e.g., @retrieved, @file), ensuring that operations like
141  *                 retrieving or finishing a file are atomic.
142  * @list:          The list_head linking this instance into its parent
143  *                 file_set's list of preserved files.
144  * @token:         The user-provided unique token used to identify this file.
145  *
146  * This structure is the core in-kernel representation of a single file being
147  * managed through a live update. An instance is created by luo_preserve_file()
148  * to link a 'struct file' to its corresponding handler, a user-provided token,
149  * and the serialized state handle returned by the handler's .preserve()
150  * operation.
151  *
152  * These instances are tracked in a per-file_set list. The @serialized_data
153  * field, which holds a handle to the file's serialized state, may be updated
154  * during the .freeze() callback before being serialized for the next kernel.
155  * After reboot, these structures are recreated by luo_file_deserialize() and
156  * are finally cleaned up by luo_file_finish().
157  */
158 struct luo_file {
159 	struct liveupdate_file_handler *fh;
160 	struct file *file;
161 	u64 serialized_data;
162 	void *private_data;
163 	bool retrieved;
164 	struct mutex mutex;
165 	struct list_head list;
166 	u64 token;
167 };
168 
luo_alloc_files_mem(struct luo_file_set * file_set)169 static int luo_alloc_files_mem(struct luo_file_set *file_set)
170 {
171 	size_t size;
172 	void *mem;
173 
174 	if (file_set->files)
175 		return 0;
176 
177 	WARN_ON_ONCE(file_set->count);
178 
179 	size = LUO_FILE_PGCNT << PAGE_SHIFT;
180 	mem = kho_alloc_preserve(size);
181 	if (IS_ERR(mem))
182 		return PTR_ERR(mem);
183 
184 	file_set->files = mem;
185 
186 	return 0;
187 }
188 
luo_free_files_mem(struct luo_file_set * file_set)189 static void luo_free_files_mem(struct luo_file_set *file_set)
190 {
191 	/* If file_set has files, no need to free preservation memory */
192 	if (file_set->count)
193 		return;
194 
195 	if (!file_set->files)
196 		return;
197 
198 	kho_unpreserve_free(file_set->files);
199 	file_set->files = NULL;
200 }
201 
luo_token_is_used(struct luo_file_set * file_set,u64 token)202 static bool luo_token_is_used(struct luo_file_set *file_set, u64 token)
203 {
204 	struct luo_file *iter;
205 
206 	list_for_each_entry(iter, &file_set->files_list, list) {
207 		if (iter->token == token)
208 			return true;
209 	}
210 
211 	return false;
212 }
213 
214 /**
215  * luo_preserve_file - Initiate the preservation of a file descriptor.
216  * @file_set: The file_set to which the preserved file will be added.
217  * @token:    A unique, user-provided identifier for the file.
218  * @fd:       The file descriptor to be preserved.
219  *
220  * This function orchestrates the first phase of preserving a file. Upon entry,
221  * it takes a reference to the 'struct file' via fget(), effectively making LUO
222  * a co-owner of the file. This reference is held until the file is either
223  * unpreserved or successfully finished in the next kernel, preventing the file
224  * from being prematurely destroyed.
225  *
226  * This function orchestrates the first phase of preserving a file. It performs
227  * the following steps:
228  *
229  * 1. Validates that the @token is not already in use within the file_set.
230  * 2. Ensures the file_set's memory for files serialization is allocated
231  *    (allocates if needed).
232  * 3. Iterates through registered handlers, calling can_preserve() to find one
233  *    compatible with the given @fd.
234  * 4. Calls the handler's .preserve() operation, which saves the file's state
235  *    and returns an opaque private data handle.
236  * 5. Adds the new instance to the file_set's internal list.
237  *
238  * On success, LUO takes a reference to the 'struct file' and considers it
239  * under its management until it is unpreserved or finished.
240  *
241  * In case of any failure, all intermediate allocations (file reference, memory
242  * for the 'luo_file' struct, etc.) are cleaned up before returning an error.
243  *
244  * Context: Can be called from an ioctl handler during normal system operation.
245  * Return: 0 on success. Returns a negative errno on failure:
246  *         -EEXIST if the token is already used.
247  *         -EBADF if the file descriptor is invalid.
248  *         -ENOSPC if the file_set is full.
249  *         -ENOENT if no compatible handler is found.
250  *         -ENOMEM on memory allocation failure.
251  *         Other erros might be returned by .preserve().
252  */
luo_preserve_file(struct luo_file_set * file_set,u64 token,int fd)253 int luo_preserve_file(struct luo_file_set *file_set, u64 token, int fd)
254 {
255 	struct liveupdate_file_op_args args = {0};
256 	struct liveupdate_file_handler *fh;
257 	struct luo_file *luo_file;
258 	struct file *file;
259 	int err;
260 
261 	if (luo_token_is_used(file_set, token))
262 		return -EEXIST;
263 
264 	if (file_set->count == LUO_FILE_MAX)
265 		return -ENOSPC;
266 
267 	file = fget(fd);
268 	if (!file)
269 		return -EBADF;
270 
271 	err = luo_alloc_files_mem(file_set);
272 	if (err)
273 		goto  err_fput;
274 
275 	err = -ENOENT;
276 	luo_list_for_each_private(fh, &luo_file_handler_list, list) {
277 		if (fh->ops->can_preserve(fh, file)) {
278 			err = 0;
279 			break;
280 		}
281 	}
282 
283 	/* err is still -ENOENT if no handler was found */
284 	if (err)
285 		goto err_free_files_mem;
286 
287 	luo_file = kzalloc(sizeof(*luo_file), GFP_KERNEL);
288 	if (!luo_file) {
289 		err = -ENOMEM;
290 		goto err_free_files_mem;
291 	}
292 
293 	luo_file->file = file;
294 	luo_file->fh = fh;
295 	luo_file->token = token;
296 	luo_file->retrieved = false;
297 	mutex_init(&luo_file->mutex);
298 
299 	args.handler = fh;
300 	args.file = file;
301 	err = fh->ops->preserve(&args);
302 	if (err)
303 		goto err_kfree;
304 
305 	luo_file->serialized_data = args.serialized_data;
306 	luo_file->private_data = args.private_data;
307 	list_add_tail(&luo_file->list, &file_set->files_list);
308 	file_set->count++;
309 
310 	return 0;
311 
312 err_kfree:
313 	kfree(luo_file);
314 err_free_files_mem:
315 	luo_free_files_mem(file_set);
316 err_fput:
317 	fput(file);
318 
319 	return err;
320 }
321 
322 /**
323  * luo_file_unpreserve_files - Unpreserves all files from a file_set.
324  * @file_set: The files to be cleaned up.
325  *
326  * This function serves as the primary cleanup path for a file_set. It is
327  * invoked when the userspace agent closes the file_set's file descriptor.
328  *
329  * For each file, it performs the following cleanup actions:
330  *   1. Calls the handler's .unpreserve() callback to allow the handler to
331  *      release any resources it allocated.
332  *   2. Removes the file from the file_set's internal tracking list.
333  *   3. Releases the reference to the 'struct file' that was taken by
334  *      luo_preserve_file() via fput(), returning ownership.
335  *   4. Frees the memory associated with the internal 'struct luo_file'.
336  *
337  * After all individual files are unpreserved, it frees the contiguous memory
338  * block that was allocated to hold their serialization data.
339  */
luo_file_unpreserve_files(struct luo_file_set * file_set)340 void luo_file_unpreserve_files(struct luo_file_set *file_set)
341 {
342 	struct luo_file *luo_file;
343 
344 	while (!list_empty(&file_set->files_list)) {
345 		struct liveupdate_file_op_args args = {0};
346 
347 		luo_file = list_last_entry(&file_set->files_list,
348 					   struct luo_file, list);
349 
350 		args.handler = luo_file->fh;
351 		args.file = luo_file->file;
352 		args.serialized_data = luo_file->serialized_data;
353 		args.private_data = luo_file->private_data;
354 		luo_file->fh->ops->unpreserve(&args);
355 
356 		list_del(&luo_file->list);
357 		file_set->count--;
358 
359 		fput(luo_file->file);
360 		mutex_destroy(&luo_file->mutex);
361 		kfree(luo_file);
362 	}
363 
364 	luo_free_files_mem(file_set);
365 }
366 
luo_file_freeze_one(struct luo_file_set * file_set,struct luo_file * luo_file)367 static int luo_file_freeze_one(struct luo_file_set *file_set,
368 			       struct luo_file *luo_file)
369 {
370 	int err = 0;
371 
372 	guard(mutex)(&luo_file->mutex);
373 
374 	if (luo_file->fh->ops->freeze) {
375 		struct liveupdate_file_op_args args = {0};
376 
377 		args.handler = luo_file->fh;
378 		args.file = luo_file->file;
379 		args.serialized_data = luo_file->serialized_data;
380 		args.private_data = luo_file->private_data;
381 
382 		err = luo_file->fh->ops->freeze(&args);
383 		if (!err)
384 			luo_file->serialized_data = args.serialized_data;
385 	}
386 
387 	return err;
388 }
389 
luo_file_unfreeze_one(struct luo_file_set * file_set,struct luo_file * luo_file)390 static void luo_file_unfreeze_one(struct luo_file_set *file_set,
391 				  struct luo_file *luo_file)
392 {
393 	guard(mutex)(&luo_file->mutex);
394 
395 	if (luo_file->fh->ops->unfreeze) {
396 		struct liveupdate_file_op_args args = {0};
397 
398 		args.handler = luo_file->fh;
399 		args.file = luo_file->file;
400 		args.serialized_data = luo_file->serialized_data;
401 		args.private_data = luo_file->private_data;
402 
403 		luo_file->fh->ops->unfreeze(&args);
404 	}
405 }
406 
__luo_file_unfreeze(struct luo_file_set * file_set,struct luo_file * failed_entry)407 static void __luo_file_unfreeze(struct luo_file_set *file_set,
408 				struct luo_file *failed_entry)
409 {
410 	struct list_head *files_list = &file_set->files_list;
411 	struct luo_file *luo_file;
412 
413 	list_for_each_entry(luo_file, files_list, list) {
414 		if (luo_file == failed_entry)
415 			break;
416 
417 		luo_file_unfreeze_one(file_set, luo_file);
418 	}
419 
420 	memset(file_set->files, 0, LUO_FILE_PGCNT << PAGE_SHIFT);
421 }
422 
423 /**
424  * luo_file_freeze - Freezes all preserved files and serializes their metadata.
425  * @file_set:     The file_set whose files are to be frozen.
426  * @file_set_ser: Where to put the serialized file_set.
427  *
428  * This function is called from the reboot() syscall path, just before the
429  * kernel transitions to the new image via kexec. Its purpose is to perform the
430  * final preparation and serialization of all preserved files in the file_set.
431  *
432  * It iterates through each preserved file in FIFO order (the order of
433  * preservation) and performs two main actions:
434  *
435  * 1. Freezes the File: It calls the handler's .freeze() callback for each
436  *    file. This gives the handler a final opportunity to quiesce the device or
437  *    prepare its state for the upcoming reboot. The handler may update its
438  *    private data handle during this step.
439  *
440  * 2. Serializes Metadata: After a successful freeze, it copies the final file
441  *    metadata—the handler's compatible string, the user token, and the final
442  *    private data handle—into the pre-allocated contiguous memory buffer
443  *    (file_set->files) that will be handed over to the next kernel via KHO.
444  *
445  * Error Handling (Rollback):
446  * This function is atomic. If any handler's .freeze() operation fails, the
447  * entire live update is aborted. The __luo_file_unfreeze() helper is
448  * immediately called to invoke the .unfreeze() op on all files that were
449  * successfully frozen before the point of failure, rolling them back to a
450  * running state. The function then returns an error, causing the reboot()
451  * syscall to fail.
452  *
453  * Context: Called only from the liveupdate_reboot() path.
454  * Return: 0 on success, or a negative errno on failure.
455  */
luo_file_freeze(struct luo_file_set * file_set,struct luo_file_set_ser * file_set_ser)456 int luo_file_freeze(struct luo_file_set *file_set,
457 		    struct luo_file_set_ser *file_set_ser)
458 {
459 	struct luo_file_ser *file_ser = file_set->files;
460 	struct luo_file *luo_file;
461 	int err;
462 	int i;
463 
464 	if (!file_set->count)
465 		return 0;
466 
467 	if (WARN_ON(!file_ser))
468 		return -EINVAL;
469 
470 	i = 0;
471 	list_for_each_entry(luo_file, &file_set->files_list, list) {
472 		err = luo_file_freeze_one(file_set, luo_file);
473 		if (err < 0) {
474 			pr_warn("Freeze failed for token[%#0llx] handler[%s] err[%pe]\n",
475 				luo_file->token, luo_file->fh->compatible,
476 				ERR_PTR(err));
477 			goto err_unfreeze;
478 		}
479 
480 		strscpy(file_ser[i].compatible, luo_file->fh->compatible,
481 			sizeof(file_ser[i].compatible));
482 		file_ser[i].data = luo_file->serialized_data;
483 		file_ser[i].token = luo_file->token;
484 		i++;
485 	}
486 
487 	file_set_ser->count = file_set->count;
488 	if (file_set->files)
489 		file_set_ser->files = virt_to_phys(file_set->files);
490 
491 	return 0;
492 
493 err_unfreeze:
494 	__luo_file_unfreeze(file_set, luo_file);
495 
496 	return err;
497 }
498 
499 /**
500  * luo_file_unfreeze - Unfreezes all files in a file_set and clear serialization
501  * @file_set:     The file_set whose files are to be unfrozen.
502  * @file_set_ser: Serialized file_set.
503  *
504  * This function rolls back the state of all files in a file_set after the
505  * freeze phase has begun but must be aborted. It is the counterpart to
506  * luo_file_freeze().
507  *
508  * It invokes the __luo_file_unfreeze() helper with a NULL argument, which
509  * signals the helper to iterate through all files in the file_set and call
510  * their respective .unfreeze() handler callbacks.
511  *
512  * Context: This is called when the live update is aborted during
513  *          the reboot() syscall, after luo_file_freeze() has been called.
514  */
luo_file_unfreeze(struct luo_file_set * file_set,struct luo_file_set_ser * file_set_ser)515 void luo_file_unfreeze(struct luo_file_set *file_set,
516 		       struct luo_file_set_ser *file_set_ser)
517 {
518 	if (!file_set->count)
519 		return;
520 
521 	__luo_file_unfreeze(file_set, NULL);
522 	memset(file_set_ser, 0, sizeof(*file_set_ser));
523 }
524 
525 /**
526  * luo_retrieve_file - Restores a preserved file from a file_set by its token.
527  * @file_set: The file_set from which to retrieve the file.
528  * @token:    The unique token identifying the file to be restored.
529  * @filep:    Output parameter; on success, this is populated with a pointer
530  *            to the newly retrieved 'struct file'.
531  *
532  * This function is the primary mechanism for recreating a file in the new
533  * kernel after a live update. It searches the file_set's list of deserialized
534  * files for an entry matching the provided @token.
535  *
536  * The operation is idempotent: if a file has already been successfully
537  * retrieved, this function will simply return a pointer to the existing
538  * 'struct file' and report success without re-executing the retrieve
539  * operation. This is handled by checking the 'retrieved' flag under a lock.
540  *
541  * File retrieval can happen in any order; it is not bound by the order of
542  * preservation.
543  *
544  * Context: Can be called from an ioctl or other in-kernel code in the new
545  *          kernel.
546  * Return: 0 on success. Returns a negative errno on failure:
547  *         -ENOENT if no file with the matching token is found.
548  *         Any error code returned by the handler's .retrieve() op.
549  */
luo_retrieve_file(struct luo_file_set * file_set,u64 token,struct file ** filep)550 int luo_retrieve_file(struct luo_file_set *file_set, u64 token,
551 		      struct file **filep)
552 {
553 	struct liveupdate_file_op_args args = {0};
554 	struct luo_file *luo_file;
555 	bool found = false;
556 	int err;
557 
558 	if (list_empty(&file_set->files_list))
559 		return -ENOENT;
560 
561 	list_for_each_entry(luo_file, &file_set->files_list, list) {
562 		if (luo_file->token == token) {
563 			found = true;
564 			break;
565 		}
566 	}
567 
568 	if (!found)
569 		return -ENOENT;
570 
571 	guard(mutex)(&luo_file->mutex);
572 	if (luo_file->retrieved) {
573 		/*
574 		 * Someone is asking for this file again, so get a reference
575 		 * for them.
576 		 */
577 		get_file(luo_file->file);
578 		*filep = luo_file->file;
579 		return 0;
580 	}
581 
582 	args.handler = luo_file->fh;
583 	args.serialized_data = luo_file->serialized_data;
584 	err = luo_file->fh->ops->retrieve(&args);
585 	if (!err) {
586 		luo_file->file = args.file;
587 
588 		/* Get reference so we can keep this file in LUO until finish */
589 		get_file(luo_file->file);
590 		*filep = luo_file->file;
591 		luo_file->retrieved = true;
592 	}
593 
594 	return err;
595 }
596 
luo_file_can_finish_one(struct luo_file_set * file_set,struct luo_file * luo_file)597 static int luo_file_can_finish_one(struct luo_file_set *file_set,
598 				   struct luo_file *luo_file)
599 {
600 	bool can_finish = true;
601 
602 	guard(mutex)(&luo_file->mutex);
603 
604 	if (luo_file->fh->ops->can_finish) {
605 		struct liveupdate_file_op_args args = {0};
606 
607 		args.handler = luo_file->fh;
608 		args.file = luo_file->file;
609 		args.serialized_data = luo_file->serialized_data;
610 		args.retrieved = luo_file->retrieved;
611 		can_finish = luo_file->fh->ops->can_finish(&args);
612 	}
613 
614 	return can_finish ? 0 : -EBUSY;
615 }
616 
luo_file_finish_one(struct luo_file_set * file_set,struct luo_file * luo_file)617 static void luo_file_finish_one(struct luo_file_set *file_set,
618 				struct luo_file *luo_file)
619 {
620 	struct liveupdate_file_op_args args = {0};
621 
622 	guard(mutex)(&luo_file->mutex);
623 
624 	args.handler = luo_file->fh;
625 	args.file = luo_file->file;
626 	args.serialized_data = luo_file->serialized_data;
627 	args.retrieved = luo_file->retrieved;
628 
629 	luo_file->fh->ops->finish(&args);
630 }
631 
632 /**
633  * luo_file_finish - Completes the lifecycle for all files in a file_set.
634  * @file_set: The file_set to be finalized.
635  *
636  * This function orchestrates the final teardown of a live update file_set in
637  * the new kernel. It should be called after all necessary files have been
638  * retrieved and the userspace agent is ready to release the preserved state.
639  *
640  * The function iterates through all tracked files. For each file, it performs
641  * the following sequence of cleanup actions:
642  *
643  * 1. If file is not yet retrieved, retrieves it, and calls can_finish() on
644  *    every file in the file_set. If all can_finish return true, continue to
645  *    finish.
646  * 2. Calls the handler's .finish() callback (via luo_file_finish_one) to
647  *    allow for final resource cleanup within the handler.
648  * 3. Releases LUO's ownership reference on the 'struct file' via fput(). This
649  *    is the counterpart to the get_file() call in luo_retrieve_file().
650  * 4. Removes the 'struct luo_file' from the file_set's internal list.
651  * 5. Frees the memory for the 'struct luo_file' instance itself.
652  *
653  * After successfully finishing all individual files, it frees the
654  * contiguous memory block that was used to transfer the serialized metadata
655  * from the previous kernel.
656  *
657  * Error Handling (Atomic Failure):
658  * This operation is atomic. If any handler's .can_finish() op fails, the entire
659  * function aborts immediately and returns an error.
660  *
661  * Context: Can be called from an ioctl handler in the new kernel.
662  * Return: 0 on success, or a negative errno on failure.
663  */
luo_file_finish(struct luo_file_set * file_set)664 int luo_file_finish(struct luo_file_set *file_set)
665 {
666 	struct list_head *files_list = &file_set->files_list;
667 	struct luo_file *luo_file;
668 	int err;
669 
670 	if (!file_set->count)
671 		return 0;
672 
673 	list_for_each_entry(luo_file, files_list, list) {
674 		err = luo_file_can_finish_one(file_set, luo_file);
675 		if (err)
676 			return err;
677 	}
678 
679 	while (!list_empty(&file_set->files_list)) {
680 		luo_file = list_last_entry(&file_set->files_list,
681 					   struct luo_file, list);
682 
683 		luo_file_finish_one(file_set, luo_file);
684 
685 		if (luo_file->file)
686 			fput(luo_file->file);
687 		list_del(&luo_file->list);
688 		file_set->count--;
689 		mutex_destroy(&luo_file->mutex);
690 		kfree(luo_file);
691 	}
692 
693 	if (file_set->files) {
694 		kho_restore_free(file_set->files);
695 		file_set->files = NULL;
696 	}
697 
698 	return 0;
699 }
700 
701 /**
702  * luo_file_deserialize - Reconstructs the list of preserved files in the new kernel.
703  * @file_set:     The incoming file_set to fill with deserialized data.
704  * @file_set_ser: Serialized KHO file_set data from the previous kernel.
705  *
706  * This function is called during the early boot process of the new kernel. It
707  * takes the raw, contiguous memory block of 'struct luo_file_ser' entries,
708  * provided by the previous kernel, and transforms it back into a live,
709  * in-memory linked list of 'struct luo_file' instances.
710  *
711  * For each serialized entry, it performs the following steps:
712  *   1. Reads the 'compatible' string.
713  *   2. Searches the global list of registered file handlers for one that
714  *      matches the compatible string.
715  *   3. Allocates a new 'struct luo_file'.
716  *   4. Populates the new structure with the deserialized data (token, private
717  *      data handle) and links it to the found handler. The 'file' pointer is
718  *      initialized to NULL, as the file has not been retrieved yet.
719  *   5. Adds the new 'struct luo_file' to the file_set's files_list.
720  *
721  * This prepares the file_set for userspace, which can later call
722  * luo_retrieve_file() to restore the actual file descriptors.
723  *
724  * Context: Called from session deserialization.
725  */
luo_file_deserialize(struct luo_file_set * file_set,struct luo_file_set_ser * file_set_ser)726 int luo_file_deserialize(struct luo_file_set *file_set,
727 			 struct luo_file_set_ser *file_set_ser)
728 {
729 	struct luo_file_ser *file_ser;
730 	u64 i;
731 
732 	if (!file_set_ser->files) {
733 		WARN_ON(file_set_ser->count);
734 		return 0;
735 	}
736 
737 	file_set->count = file_set_ser->count;
738 	file_set->files = phys_to_virt(file_set_ser->files);
739 
740 	/*
741 	 * Note on error handling:
742 	 *
743 	 * If deserialization fails (e.g., allocation failure or corrupt data),
744 	 * we intentionally skip cleanup of files that were already restored.
745 	 *
746 	 * A partial failure leaves the preserved state inconsistent.
747 	 * Implementing a safe "undo" to unwind complex dependencies (sessions,
748 	 * files, hardware state) is error-prone and provides little value, as
749 	 * the system is effectively in a broken state.
750 	 *
751 	 * We treat these resources as leaked. The expected recovery path is for
752 	 * userspace to detect the failure and trigger a reboot, which will
753 	 * reliably reset devices and reclaim memory.
754 	 */
755 	file_ser = file_set->files;
756 	for (i = 0; i < file_set->count; i++) {
757 		struct liveupdate_file_handler *fh;
758 		bool handler_found = false;
759 		struct luo_file *luo_file;
760 
761 		luo_list_for_each_private(fh, &luo_file_handler_list, list) {
762 			if (!strcmp(fh->compatible, file_ser[i].compatible)) {
763 				handler_found = true;
764 				break;
765 			}
766 		}
767 
768 		if (!handler_found) {
769 			pr_warn("No registered handler for compatible '%s'\n",
770 				file_ser[i].compatible);
771 			return -ENOENT;
772 		}
773 
774 		luo_file = kzalloc(sizeof(*luo_file), GFP_KERNEL);
775 		if (!luo_file)
776 			return -ENOMEM;
777 
778 		luo_file->fh = fh;
779 		luo_file->file = NULL;
780 		luo_file->serialized_data = file_ser[i].data;
781 		luo_file->token = file_ser[i].token;
782 		luo_file->retrieved = false;
783 		mutex_init(&luo_file->mutex);
784 		list_add_tail(&luo_file->list, &file_set->files_list);
785 	}
786 
787 	return 0;
788 }
789 
luo_file_set_init(struct luo_file_set * file_set)790 void luo_file_set_init(struct luo_file_set *file_set)
791 {
792 	INIT_LIST_HEAD(&file_set->files_list);
793 }
794 
luo_file_set_destroy(struct luo_file_set * file_set)795 void luo_file_set_destroy(struct luo_file_set *file_set)
796 {
797 	WARN_ON(file_set->count);
798 	WARN_ON(!list_empty(&file_set->files_list));
799 }
800 
801 /**
802  * liveupdate_register_file_handler - Register a file handler with LUO.
803  * @fh: Pointer to a caller-allocated &struct liveupdate_file_handler.
804  * The caller must initialize this structure, including a unique
805  * 'compatible' string and a valid 'fh' callbacks. This function adds the
806  * handler to the global list of supported file handlers.
807  *
808  * Context: Typically called during module initialization for file types that
809  * support live update preservation.
810  *
811  * Return: 0 on success. Negative errno on failure.
812  */
liveupdate_register_file_handler(struct liveupdate_file_handler * fh)813 int liveupdate_register_file_handler(struct liveupdate_file_handler *fh)
814 {
815 	struct liveupdate_file_handler *fh_iter;
816 	int err;
817 
818 	if (!liveupdate_enabled())
819 		return -EOPNOTSUPP;
820 
821 	/* Sanity check that all required callbacks are set */
822 	if (!fh->ops->preserve || !fh->ops->unpreserve || !fh->ops->retrieve ||
823 	    !fh->ops->finish || !fh->ops->can_preserve) {
824 		return -EINVAL;
825 	}
826 
827 	/*
828 	 * Ensure the system is quiescent (no active sessions).
829 	 * This prevents registering new handlers while sessions are active or
830 	 * while deserialization is in progress.
831 	 */
832 	if (!luo_session_quiesce())
833 		return -EBUSY;
834 
835 	/* Check for duplicate compatible strings */
836 	luo_list_for_each_private(fh_iter, &luo_file_handler_list, list) {
837 		if (!strcmp(fh_iter->compatible, fh->compatible)) {
838 			pr_err("File handler registration failed: Compatible string '%s' already registered.\n",
839 			       fh->compatible);
840 			err = -EEXIST;
841 			goto err_resume;
842 		}
843 	}
844 
845 	/* Pin the module implementing the handler */
846 	if (!try_module_get(fh->ops->owner)) {
847 		err = -EAGAIN;
848 		goto err_resume;
849 	}
850 
851 	INIT_LIST_HEAD(&ACCESS_PRIVATE(fh, list));
852 	list_add_tail(&ACCESS_PRIVATE(fh, list), &luo_file_handler_list);
853 	luo_session_resume();
854 
855 	return 0;
856 
857 err_resume:
858 	luo_session_resume();
859 	return err;
860 }
861 
862 /**
863  * liveupdate_unregister_file_handler - Unregister a liveupdate file handler
864  * @fh: The file handler to unregister
865  *
866  * Unregisters the file handler from the liveupdate core. This function
867  * reverses the operations of liveupdate_register_file_handler().
868  *
869  * It ensures safe removal by checking that:
870  * No live update session is currently in progress.
871  *
872  * If the unregistration fails, the internal test state is reverted.
873  *
874  * Return: 0 Success. -EOPNOTSUPP when live update is not enabled. -EBUSY A live
875  * update is in progress, can't quiesce live update.
876  */
liveupdate_unregister_file_handler(struct liveupdate_file_handler * fh)877 int liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)
878 {
879 	if (!liveupdate_enabled())
880 		return -EOPNOTSUPP;
881 
882 	if (!luo_session_quiesce())
883 		return -EBUSY;
884 
885 	list_del(&ACCESS_PRIVATE(fh, list));
886 	module_put(fh->ops->owner);
887 	luo_session_resume();
888 
889 	return 0;
890 }
891