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