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