• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2019 Google LLC
4  */
5 #include <linux/crc32.h>
6 #include <linux/file.h>
7 #include <linux/fsverity.h>
8 #include <linux/gfp.h>
9 #include <linux/kobject.h>
10 #include <linux/ktime.h>
11 #include <linux/lz4.h>
12 #include <linux/mm.h>
13 #include <linux/namei.h>
14 #include <linux/pagemap.h>
15 #include <linux/slab.h>
16 #include <linux/types.h>
17 #include <linux/workqueue.h>
18 
19 #include "data_mgmt.h"
20 #include "format.h"
21 #include "integrity.h"
22 #include "sysfs.h"
23 #include "verity.h"
24 
25 static int incfs_scan_metadata_chain(struct data_file *df);
26 
log_wake_up_all(struct work_struct * work)27 static void log_wake_up_all(struct work_struct *work)
28 {
29 	struct delayed_work *dw = container_of(work, struct delayed_work, work);
30 	struct read_log *rl = container_of(dw, struct read_log, ml_wakeup_work);
31 	wake_up_all(&rl->ml_notif_wq);
32 }
33 
zstd_free_workspace(struct work_struct * work)34 static void zstd_free_workspace(struct work_struct *work)
35 {
36 	struct delayed_work *dw = container_of(work, struct delayed_work, work);
37 	struct mount_info *mi =
38 		container_of(dw, struct mount_info, mi_zstd_cleanup_work);
39 
40 	mutex_lock(&mi->mi_zstd_workspace_mutex);
41 	kvfree(mi->mi_zstd_workspace);
42 	mi->mi_zstd_workspace = NULL;
43 	mi->mi_zstd_stream = NULL;
44 	mutex_unlock(&mi->mi_zstd_workspace_mutex);
45 }
46 
incfs_alloc_mount_info(struct super_block * sb,struct mount_options * options,struct path * backing_dir_path)47 struct mount_info *incfs_alloc_mount_info(struct super_block *sb,
48 					  struct mount_options *options,
49 					  struct path *backing_dir_path)
50 {
51 	struct mount_info *mi = NULL;
52 	int error = 0;
53 	struct incfs_sysfs_node *node;
54 
55 	mi = kzalloc(sizeof(*mi), GFP_NOFS);
56 	if (!mi)
57 		return ERR_PTR(-ENOMEM);
58 
59 	mi->mi_sb = sb;
60 	mi->mi_backing_dir_path = *backing_dir_path;
61 	mi->mi_owner = get_current_cred();
62 	path_get(&mi->mi_backing_dir_path);
63 	mutex_init(&mi->mi_dir_struct_mutex);
64 	init_waitqueue_head(&mi->mi_pending_reads_notif_wq);
65 	init_waitqueue_head(&mi->mi_log.ml_notif_wq);
66 	init_waitqueue_head(&mi->mi_blocks_written_notif_wq);
67 	atomic_set(&mi->mi_blocks_written, 0);
68 	INIT_DELAYED_WORK(&mi->mi_log.ml_wakeup_work, log_wake_up_all);
69 	spin_lock_init(&mi->mi_log.rl_lock);
70 	spin_lock_init(&mi->pending_read_lock);
71 	INIT_LIST_HEAD(&mi->mi_reads_list_head);
72 	spin_lock_init(&mi->mi_per_uid_read_timeouts_lock);
73 	mutex_init(&mi->mi_zstd_workspace_mutex);
74 	INIT_DELAYED_WORK(&mi->mi_zstd_cleanup_work, zstd_free_workspace);
75 	mutex_init(&mi->mi_le_mutex);
76 
77 	node = incfs_add_sysfs_node(options->sysfs_name, mi);
78 	if (IS_ERR(node)) {
79 		error = PTR_ERR(node);
80 		goto err;
81 	}
82 	mi->mi_sysfs_node = node;
83 
84 	error = incfs_realloc_mount_info(mi, options);
85 	if (error)
86 		goto err;
87 
88 	return mi;
89 
90 err:
91 	incfs_free_mount_info(mi);
92 	return ERR_PTR(error);
93 }
94 
incfs_realloc_mount_info(struct mount_info * mi,struct mount_options * options)95 int incfs_realloc_mount_info(struct mount_info *mi,
96 			     struct mount_options *options)
97 {
98 	void *new_buffer = NULL;
99 	void *old_buffer;
100 	size_t new_buffer_size = 0;
101 
102 	if (options->read_log_pages != mi->mi_options.read_log_pages) {
103 		struct read_log_state log_state;
104 		/*
105 		 * Even though having two buffers allocated at once isn't
106 		 * usually good, allocating a multipage buffer under a spinlock
107 		 * is even worse, so let's optimize for the shorter lock
108 		 * duration. It's not end of the world if we fail to increase
109 		 * the buffer size anyway.
110 		 */
111 		if (options->read_log_pages > 0) {
112 			new_buffer_size = PAGE_SIZE * options->read_log_pages;
113 			new_buffer = kzalloc(new_buffer_size, GFP_NOFS);
114 			if (!new_buffer)
115 				return -ENOMEM;
116 		}
117 
118 		spin_lock(&mi->mi_log.rl_lock);
119 		old_buffer = mi->mi_log.rl_ring_buf;
120 		mi->mi_log.rl_ring_buf = new_buffer;
121 		mi->mi_log.rl_size = new_buffer_size;
122 		log_state = (struct read_log_state){
123 			.generation_id = mi->mi_log.rl_head.generation_id + 1,
124 		};
125 		mi->mi_log.rl_head = log_state;
126 		mi->mi_log.rl_tail = log_state;
127 		spin_unlock(&mi->mi_log.rl_lock);
128 
129 		kfree(old_buffer);
130 	}
131 
132 	if (options->sysfs_name && !mi->mi_sysfs_node)
133 		mi->mi_sysfs_node = incfs_add_sysfs_node(options->sysfs_name,
134 							 mi);
135 	else if (!options->sysfs_name && mi->mi_sysfs_node) {
136 		incfs_free_sysfs_node(mi->mi_sysfs_node);
137 		mi->mi_sysfs_node = NULL;
138 	} else if (options->sysfs_name &&
139 		strcmp(options->sysfs_name,
140 		       kobject_name(&mi->mi_sysfs_node->isn_sysfs_node))) {
141 		incfs_free_sysfs_node(mi->mi_sysfs_node);
142 		mi->mi_sysfs_node = incfs_add_sysfs_node(options->sysfs_name,
143 							 mi);
144 	}
145 
146 	if (IS_ERR(mi->mi_sysfs_node)) {
147 		int err = PTR_ERR(mi->mi_sysfs_node);
148 
149 		mi->mi_sysfs_node = NULL;
150 		return err;
151 	}
152 
153 	mi->mi_options = *options;
154 	return 0;
155 }
156 
incfs_free_mount_info(struct mount_info * mi)157 void incfs_free_mount_info(struct mount_info *mi)
158 {
159 	int i;
160 	if (!mi)
161 		return;
162 
163 	flush_delayed_work(&mi->mi_log.ml_wakeup_work);
164 	flush_delayed_work(&mi->mi_zstd_cleanup_work);
165 
166 	dput(mi->mi_index_dir);
167 	dput(mi->mi_incomplete_dir);
168 	path_put(&mi->mi_backing_dir_path);
169 	mutex_destroy(&mi->mi_dir_struct_mutex);
170 	mutex_destroy(&mi->mi_zstd_workspace_mutex);
171 	put_cred(mi->mi_owner);
172 	kfree(mi->mi_log.rl_ring_buf);
173 	for (i = 0; i < ARRAY_SIZE(mi->pseudo_file_xattr); ++i)
174 		kfree(mi->pseudo_file_xattr[i].data);
175 	kfree(mi->mi_per_uid_read_timeouts);
176 	incfs_free_sysfs_node(mi->mi_sysfs_node);
177 	kfree(mi);
178 }
179 
data_file_segment_init(struct data_file_segment * segment)180 static void data_file_segment_init(struct data_file_segment *segment)
181 {
182 	init_waitqueue_head(&segment->new_data_arrival_wq);
183 	init_rwsem(&segment->rwsem);
184 	INIT_LIST_HEAD(&segment->reads_list_head);
185 }
186 
file_id_to_str(incfs_uuid_t id)187 char *file_id_to_str(incfs_uuid_t id)
188 {
189 	char *result = kmalloc(1 + sizeof(id.bytes) * 2, GFP_NOFS);
190 	char *end;
191 
192 	if (!result)
193 		return NULL;
194 
195 	end = bin2hex(result, id.bytes, sizeof(id.bytes));
196 	*end = 0;
197 	return result;
198 }
199 
incfs_lookup_dentry(struct dentry * parent,const char * name)200 struct dentry *incfs_lookup_dentry(struct dentry *parent, const char *name)
201 {
202 	struct inode *inode;
203 	struct dentry *result = NULL;
204 
205 	if (!parent)
206 		return ERR_PTR(-EFAULT);
207 
208 	inode = d_inode(parent);
209 	inode_lock_nested(inode, I_MUTEX_PARENT);
210 	result = lookup_one_len(name, parent, strlen(name));
211 	inode_unlock(inode);
212 
213 	if (IS_ERR(result))
214 		pr_warn("%s err:%ld\n", __func__, PTR_ERR(result));
215 
216 	return result;
217 }
218 
handle_mapped_file(struct mount_info * mi,struct data_file * df)219 static struct data_file *handle_mapped_file(struct mount_info *mi,
220 					    struct data_file *df)
221 {
222 	char *file_id_str;
223 	struct dentry *index_file_dentry;
224 	struct path path;
225 	struct file *bf;
226 	struct data_file *result = NULL;
227 	const struct cred *old_cred;
228 
229 	file_id_str = file_id_to_str(df->df_id);
230 	if (!file_id_str)
231 		return ERR_PTR(-ENOENT);
232 
233 	index_file_dentry = incfs_lookup_dentry(mi->mi_index_dir,
234 						file_id_str);
235 	kfree(file_id_str);
236 	if (!index_file_dentry)
237 		return ERR_PTR(-ENOENT);
238 	if (IS_ERR(index_file_dentry))
239 		return (struct data_file *)index_file_dentry;
240 	if (!d_really_is_positive(index_file_dentry)) {
241 		result = ERR_PTR(-ENOENT);
242 		goto out;
243 	}
244 
245 	path = (struct path) {
246 		.mnt = mi->mi_backing_dir_path.mnt,
247 		.dentry = index_file_dentry
248 	};
249 
250 	old_cred = override_creds(mi->mi_owner);
251 	bf = dentry_open(&path, O_RDWR | O_NOATIME | O_LARGEFILE,
252 			 current_cred());
253 	revert_creds(old_cred);
254 
255 	if (IS_ERR(bf)) {
256 		result = (struct data_file *)bf;
257 		goto out;
258 	}
259 
260 	result = incfs_open_data_file(mi, bf);
261 	fput(bf);
262 	if (IS_ERR(result))
263 		goto out;
264 
265 	result->df_mapped_offset = df->df_metadata_off;
266 
267 out:
268 	dput(index_file_dentry);
269 	return result;
270 }
271 
incfs_open_data_file(struct mount_info * mi,struct file * bf)272 struct data_file *incfs_open_data_file(struct mount_info *mi, struct file *bf)
273 {
274 	struct data_file *df = NULL;
275 	struct backing_file_context *bfc = NULL;
276 	int md_records;
277 	u64 size;
278 	int error = 0;
279 	int i;
280 
281 	if (!bf || !mi)
282 		return ERR_PTR(-EFAULT);
283 
284 	if (!S_ISREG(bf->f_inode->i_mode))
285 		return ERR_PTR(-EBADF);
286 
287 	bfc = incfs_alloc_bfc(mi, bf);
288 	if (IS_ERR(bfc))
289 		return ERR_CAST(bfc);
290 
291 	df = kzalloc(sizeof(*df), GFP_NOFS);
292 	if (!df) {
293 		error = -ENOMEM;
294 		goto out;
295 	}
296 
297 	mutex_init(&df->df_enable_verity);
298 
299 	df->df_backing_file_context = bfc;
300 	df->df_mount_info = mi;
301 	for (i = 0; i < ARRAY_SIZE(df->df_segments); i++)
302 		data_file_segment_init(&df->df_segments[i]);
303 
304 	error = incfs_read_file_header(bfc, &df->df_metadata_off, &df->df_id,
305 				       &size, &df->df_header_flags);
306 
307 	if (error)
308 		goto out;
309 
310 	df->df_size = size;
311 	if (size > 0)
312 		df->df_data_block_count = get_blocks_count_for_size(size);
313 
314 	if (df->df_header_flags & INCFS_FILE_MAPPED) {
315 		struct data_file *mapped_df = handle_mapped_file(mi, df);
316 
317 		incfs_free_data_file(df);
318 		return mapped_df;
319 	}
320 
321 	md_records = incfs_scan_metadata_chain(df);
322 	if (md_records < 0)
323 		error = md_records;
324 
325 out:
326 	if (error) {
327 		incfs_free_bfc(bfc);
328 		if (df)
329 			df->df_backing_file_context = NULL;
330 		incfs_free_data_file(df);
331 		return ERR_PTR(error);
332 	}
333 	return df;
334 }
335 
incfs_free_data_file(struct data_file * df)336 void incfs_free_data_file(struct data_file *df)
337 {
338 	u32 data_blocks_written, hash_blocks_written;
339 
340 	if (!df)
341 		return;
342 
343 	data_blocks_written = atomic_read(&df->df_data_blocks_written);
344 	hash_blocks_written = atomic_read(&df->df_hash_blocks_written);
345 
346 	if (data_blocks_written != df->df_initial_data_blocks_written ||
347 	    hash_blocks_written != df->df_initial_hash_blocks_written) {
348 		struct backing_file_context *bfc = df->df_backing_file_context;
349 		int error = -1;
350 
351 		if (bfc && !mutex_lock_interruptible(&bfc->bc_mutex)) {
352 			error = incfs_write_status_to_backing_file(
353 						df->df_backing_file_context,
354 						df->df_status_offset,
355 						data_blocks_written,
356 						hash_blocks_written);
357 			mutex_unlock(&bfc->bc_mutex);
358 		}
359 
360 		if (error)
361 			/* Nothing can be done, just warn */
362 			pr_warn("incfs: failed to write status to backing file\n");
363 	}
364 
365 	incfs_free_mtree(df->df_hash_tree);
366 	incfs_free_bfc(df->df_backing_file_context);
367 	kfree(df->df_signature);
368 	kfree(df->df_verity_file_digest.data);
369 	kfree(df->df_verity_signature);
370 	mutex_destroy(&df->df_enable_verity);
371 	kfree(df);
372 }
373 
make_inode_ready_for_data_ops(struct mount_info * mi,struct inode * inode,struct file * backing_file)374 int make_inode_ready_for_data_ops(struct mount_info *mi,
375 				struct inode *inode,
376 				struct file *backing_file)
377 {
378 	struct inode_info *node = get_incfs_node(inode);
379 	struct data_file *df = NULL;
380 	int err = 0;
381 
382 	inode_lock(inode);
383 	if (S_ISREG(inode->i_mode)) {
384 		if (!node->n_file) {
385 			df = incfs_open_data_file(mi, backing_file);
386 
387 			if (IS_ERR(df))
388 				err = PTR_ERR(df);
389 			else
390 				node->n_file = df;
391 		}
392 	} else
393 		err = -EBADF;
394 	inode_unlock(inode);
395 	return err;
396 }
397 
incfs_open_dir_file(struct mount_info * mi,struct file * bf)398 struct dir_file *incfs_open_dir_file(struct mount_info *mi, struct file *bf)
399 {
400 	struct dir_file *dir = NULL;
401 
402 	if (!S_ISDIR(bf->f_inode->i_mode))
403 		return ERR_PTR(-EBADF);
404 
405 	dir = kzalloc(sizeof(*dir), GFP_NOFS);
406 	if (!dir)
407 		return ERR_PTR(-ENOMEM);
408 
409 	dir->backing_dir = get_file(bf);
410 	dir->mount_info = mi;
411 	return dir;
412 }
413 
incfs_free_dir_file(struct dir_file * dir)414 void incfs_free_dir_file(struct dir_file *dir)
415 {
416 	if (!dir)
417 		return;
418 	if (dir->backing_dir)
419 		fput(dir->backing_dir);
420 	kfree(dir);
421 }
422 
zstd_decompress_safe(struct mount_info * mi,struct mem_range src,struct mem_range dst)423 static ssize_t zstd_decompress_safe(struct mount_info *mi,
424 				    struct mem_range src, struct mem_range dst)
425 {
426 	ssize_t result;
427 	ZSTD_inBuffer inbuf = {.src = src.data,	.size = src.len};
428 	ZSTD_outBuffer outbuf = {.dst = dst.data, .size = dst.len};
429 
430 	result = mutex_lock_interruptible(&mi->mi_zstd_workspace_mutex);
431 	if (result)
432 		return result;
433 
434 	if (!mi->mi_zstd_stream) {
435 		unsigned int workspace_size = ZSTD_DStreamWorkspaceBound(
436 						INCFS_DATA_FILE_BLOCK_SIZE);
437 		void *workspace = kvmalloc(workspace_size, GFP_NOFS);
438 		ZSTD_DStream *stream;
439 
440 		if (!workspace) {
441 			result = -ENOMEM;
442 			goto out;
443 		}
444 
445 		stream = ZSTD_initDStream(INCFS_DATA_FILE_BLOCK_SIZE, workspace,
446 				  workspace_size);
447 		if (!stream) {
448 			kvfree(workspace);
449 			result = -EIO;
450 			goto out;
451 		}
452 
453 		mi->mi_zstd_workspace = workspace;
454 		mi->mi_zstd_stream = stream;
455 	}
456 
457 	result = ZSTD_decompressStream(mi->mi_zstd_stream, &outbuf, &inbuf) ?
458 		-EBADMSG : outbuf.pos;
459 
460 	mod_delayed_work(system_wq, &mi->mi_zstd_cleanup_work,
461 			 msecs_to_jiffies(5000));
462 
463 out:
464 	mutex_unlock(&mi->mi_zstd_workspace_mutex);
465 	return result;
466 }
467 
decompress(struct mount_info * mi,struct mem_range src,struct mem_range dst,int alg)468 static ssize_t decompress(struct mount_info *mi,
469 			  struct mem_range src, struct mem_range dst, int alg)
470 {
471 	int result;
472 
473 	switch (alg) {
474 	case INCFS_BLOCK_COMPRESSED_LZ4:
475 		result = LZ4_decompress_safe(src.data, dst.data, src.len,
476 					     dst.len);
477 		if (result < 0)
478 			return -EBADMSG;
479 		return result;
480 
481 	case INCFS_BLOCK_COMPRESSED_ZSTD:
482 		return zstd_decompress_safe(mi, src, dst);
483 
484 	default:
485 		WARN_ON(true);
486 		return -EOPNOTSUPP;
487 	}
488 }
489 
log_read_one_record(struct read_log * rl,struct read_log_state * rs)490 static void log_read_one_record(struct read_log *rl, struct read_log_state *rs)
491 {
492 	union log_record *record =
493 		(union log_record *)((u8 *)rl->rl_ring_buf + rs->next_offset);
494 	size_t record_size;
495 
496 	switch (record->full_record.type) {
497 	case FULL:
498 		rs->base_record = record->full_record;
499 		record_size = sizeof(record->full_record);
500 		break;
501 
502 	case SAME_FILE:
503 		rs->base_record.block_index =
504 			record->same_file.block_index;
505 		rs->base_record.absolute_ts_us +=
506 			record->same_file.relative_ts_us;
507 		rs->base_record.uid = record->same_file.uid;
508 		record_size = sizeof(record->same_file);
509 		break;
510 
511 	case SAME_FILE_CLOSE_BLOCK:
512 		rs->base_record.block_index +=
513 			record->same_file_close_block.block_index_delta;
514 		rs->base_record.absolute_ts_us +=
515 			record->same_file_close_block.relative_ts_us;
516 		record_size = sizeof(record->same_file_close_block);
517 		break;
518 
519 	case SAME_FILE_CLOSE_BLOCK_SHORT:
520 		rs->base_record.block_index +=
521 			record->same_file_close_block_short.block_index_delta;
522 		rs->base_record.absolute_ts_us +=
523 		   record->same_file_close_block_short.relative_ts_tens_us * 10;
524 		record_size = sizeof(record->same_file_close_block_short);
525 		break;
526 
527 	case SAME_FILE_NEXT_BLOCK:
528 		++rs->base_record.block_index;
529 		rs->base_record.absolute_ts_us +=
530 			record->same_file_next_block.relative_ts_us;
531 		record_size = sizeof(record->same_file_next_block);
532 		break;
533 
534 	case SAME_FILE_NEXT_BLOCK_SHORT:
535 		++rs->base_record.block_index;
536 		rs->base_record.absolute_ts_us +=
537 		    record->same_file_next_block_short.relative_ts_tens_us * 10;
538 		record_size = sizeof(record->same_file_next_block_short);
539 		break;
540 	}
541 
542 	rs->next_offset += record_size;
543 	if (rs->next_offset > rl->rl_size - sizeof(*record)) {
544 		rs->next_offset = 0;
545 		++rs->current_pass_no;
546 	}
547 	++rs->current_record_no;
548 }
549 
log_block_read(struct mount_info * mi,incfs_uuid_t * id,int block_index)550 static void log_block_read(struct mount_info *mi, incfs_uuid_t *id,
551 			   int block_index)
552 {
553 	struct read_log *log = &mi->mi_log;
554 	struct read_log_state *head, *tail;
555 	s64 now_us;
556 	s64 relative_us;
557 	union log_record record;
558 	size_t record_size;
559 	uid_t uid = current_uid().val;
560 	int block_delta;
561 	bool same_file, same_uid;
562 	bool next_block, close_block, very_close_block;
563 	bool close_time, very_close_time, very_very_close_time;
564 
565 	/*
566 	 * This may read the old value, but it's OK to delay the logging start
567 	 * right after the configuration update.
568 	 */
569 	if (READ_ONCE(log->rl_size) == 0)
570 		return;
571 
572 	now_us = ktime_to_us(ktime_get());
573 
574 	spin_lock(&log->rl_lock);
575 	if (log->rl_size == 0) {
576 		spin_unlock(&log->rl_lock);
577 		return;
578 	}
579 
580 	head = &log->rl_head;
581 	tail = &log->rl_tail;
582 	relative_us = now_us - head->base_record.absolute_ts_us;
583 
584 	same_file = !memcmp(id, &head->base_record.file_id,
585 			    sizeof(incfs_uuid_t));
586 	same_uid = uid == head->base_record.uid;
587 
588 	block_delta = block_index - head->base_record.block_index;
589 	next_block = block_delta == 1;
590 	very_close_block = block_delta >= S8_MIN && block_delta <= S8_MAX;
591 	close_block = block_delta >= S16_MIN && block_delta <= S16_MAX;
592 
593 	very_very_close_time = relative_us < (1 << 5) * 10;
594 	very_close_time = relative_us < (1 << 13);
595 	close_time = relative_us < (1 << 16);
596 
597 	if (same_file && same_uid && next_block && very_very_close_time) {
598 		record.same_file_next_block_short =
599 			(struct same_file_next_block_short){
600 				.type = SAME_FILE_NEXT_BLOCK_SHORT,
601 				.relative_ts_tens_us = div_s64(relative_us, 10),
602 			};
603 		record_size = sizeof(struct same_file_next_block_short);
604 	} else if (same_file && same_uid && next_block && very_close_time) {
605 		record.same_file_next_block = (struct same_file_next_block){
606 			.type = SAME_FILE_NEXT_BLOCK,
607 			.relative_ts_us = relative_us,
608 		};
609 		record_size = sizeof(struct same_file_next_block);
610 	} else if (same_file && same_uid && very_close_block &&
611 		   very_very_close_time) {
612 		record.same_file_close_block_short =
613 			(struct same_file_close_block_short){
614 				.type = SAME_FILE_CLOSE_BLOCK_SHORT,
615 				.relative_ts_tens_us = div_s64(relative_us, 10),
616 				.block_index_delta = block_delta,
617 			};
618 		record_size = sizeof(struct same_file_close_block_short);
619 	} else if (same_file && same_uid && close_block && very_close_time) {
620 		record.same_file_close_block = (struct same_file_close_block){
621 				.type = SAME_FILE_CLOSE_BLOCK,
622 				.relative_ts_us = relative_us,
623 				.block_index_delta = block_delta,
624 			};
625 		record_size = sizeof(struct same_file_close_block);
626 	} else if (same_file && close_time) {
627 		record.same_file = (struct same_file){
628 			.type = SAME_FILE,
629 			.block_index = block_index,
630 			.relative_ts_us = relative_us,
631 			.uid = uid,
632 		};
633 		record_size = sizeof(struct same_file);
634 	} else {
635 		record.full_record = (struct full_record){
636 			.type = FULL,
637 			.block_index = block_index,
638 			.file_id = *id,
639 			.absolute_ts_us = now_us,
640 			.uid = uid,
641 		};
642 		head->base_record.file_id = *id;
643 		record_size = sizeof(struct full_record);
644 	}
645 
646 	head->base_record.block_index = block_index;
647 	head->base_record.absolute_ts_us = now_us;
648 
649 	/* Advance tail beyond area we are going to overwrite */
650 	while (tail->current_pass_no < head->current_pass_no &&
651 	       tail->next_offset < head->next_offset + record_size)
652 		log_read_one_record(log, tail);
653 
654 	memcpy(((u8 *)log->rl_ring_buf) + head->next_offset, &record,
655 	       record_size);
656 	head->next_offset += record_size;
657 	if (head->next_offset > log->rl_size - sizeof(record)) {
658 		head->next_offset = 0;
659 		++head->current_pass_no;
660 	}
661 	++head->current_record_no;
662 
663 	spin_unlock(&log->rl_lock);
664 	schedule_delayed_work(&log->ml_wakeup_work, msecs_to_jiffies(16));
665 }
666 
validate_hash_tree(struct backing_file_context * bfc,struct file * f,int block_index,struct mem_range data,u8 * buf)667 static int validate_hash_tree(struct backing_file_context *bfc, struct file *f,
668 			      int block_index, struct mem_range data, u8 *buf)
669 {
670 	struct data_file *df = get_incfs_data_file(f);
671 	u8 stored_digest[INCFS_MAX_HASH_SIZE] = {};
672 	u8 calculated_digest[INCFS_MAX_HASH_SIZE] = {};
673 	struct mtree *tree = NULL;
674 	struct incfs_df_signature *sig = NULL;
675 	int digest_size;
676 	int hash_block_index = block_index;
677 	int lvl;
678 	int res;
679 	loff_t hash_block_offset[INCFS_MAX_MTREE_LEVELS];
680 	size_t hash_offset_in_block[INCFS_MAX_MTREE_LEVELS];
681 	int hash_per_block;
682 	pgoff_t file_pages;
683 
684 	/*
685 	 * Memory barrier to make sure tree is fully present if added via enable
686 	 * verity
687 	 */
688 	tree = smp_load_acquire(&df->df_hash_tree);
689 	sig = df->df_signature;
690 	if (!tree || !sig)
691 		return 0;
692 
693 	digest_size = tree->alg->digest_size;
694 	hash_per_block = INCFS_DATA_FILE_BLOCK_SIZE / digest_size;
695 	for (lvl = 0; lvl < tree->depth; lvl++) {
696 		loff_t lvl_off = tree->hash_level_suboffset[lvl];
697 
698 		hash_block_offset[lvl] =
699 			lvl_off + round_down(hash_block_index * digest_size,
700 					     INCFS_DATA_FILE_BLOCK_SIZE);
701 		hash_offset_in_block[lvl] = hash_block_index * digest_size %
702 					    INCFS_DATA_FILE_BLOCK_SIZE;
703 		hash_block_index /= hash_per_block;
704 	}
705 
706 	memcpy(stored_digest, tree->root_hash, digest_size);
707 
708 	file_pages = DIV_ROUND_UP(df->df_size, INCFS_DATA_FILE_BLOCK_SIZE);
709 	for (lvl = tree->depth - 1; lvl >= 0; lvl--) {
710 		pgoff_t hash_page =
711 			file_pages +
712 			hash_block_offset[lvl] / INCFS_DATA_FILE_BLOCK_SIZE;
713 		struct page *page = find_get_page_flags(
714 			f->f_inode->i_mapping, hash_page, FGP_ACCESSED);
715 
716 		if (page && PageChecked(page)) {
717 			u8 *addr = kmap_atomic(page);
718 
719 			memcpy(stored_digest, addr + hash_offset_in_block[lvl],
720 			       digest_size);
721 			kunmap_atomic(addr);
722 			put_page(page);
723 			continue;
724 		}
725 
726 		if (page)
727 			put_page(page);
728 
729 		res = incfs_kread(bfc, buf, INCFS_DATA_FILE_BLOCK_SIZE,
730 				  hash_block_offset[lvl] + sig->hash_offset);
731 		if (res < 0)
732 			return res;
733 		if (res != INCFS_DATA_FILE_BLOCK_SIZE)
734 			return -EIO;
735 		res = incfs_calc_digest(tree->alg,
736 					range(buf, INCFS_DATA_FILE_BLOCK_SIZE),
737 					range(calculated_digest, digest_size));
738 		if (res)
739 			return res;
740 
741 		if (memcmp(stored_digest, calculated_digest, digest_size)) {
742 			int i;
743 			bool zero = true;
744 
745 			pr_warn("incfs: Hash mismatch lvl:%d blk:%d\n",
746 				lvl, block_index);
747 			for (i = 0; i < digest_size; i++)
748 				if (stored_digest[i]) {
749 					zero = false;
750 					break;
751 				}
752 
753 			if (zero)
754 				pr_debug("Note saved_digest all zero - did you forget to load the hashes?\n");
755 			return -EBADMSG;
756 		}
757 
758 		memcpy(stored_digest, buf + hash_offset_in_block[lvl],
759 		       digest_size);
760 
761 		page = grab_cache_page(f->f_inode->i_mapping, hash_page);
762 		if (page) {
763 			u8 *addr = kmap_atomic(page);
764 
765 			memcpy(addr, buf, INCFS_DATA_FILE_BLOCK_SIZE);
766 			kunmap_atomic(addr);
767 			SetPageChecked(page);
768 			unlock_page(page);
769 			put_page(page);
770 		}
771 	}
772 
773 	res = incfs_calc_digest(tree->alg, data,
774 				range(calculated_digest, digest_size));
775 	if (res)
776 		return res;
777 
778 	if (memcmp(stored_digest, calculated_digest, digest_size)) {
779 		pr_debug("Leaf hash mismatch blk:%d\n", block_index);
780 		return -EBADMSG;
781 	}
782 
783 	return 0;
784 }
785 
get_file_segment(struct data_file * df,int block_index)786 static struct data_file_segment *get_file_segment(struct data_file *df,
787 						  int block_index)
788 {
789 	int seg_idx = block_index % ARRAY_SIZE(df->df_segments);
790 
791 	return &df->df_segments[seg_idx];
792 }
793 
is_data_block_present(struct data_file_block * block)794 static bool is_data_block_present(struct data_file_block *block)
795 {
796 	return (block->db_backing_file_data_offset != 0) &&
797 	       (block->db_stored_size != 0);
798 }
799 
convert_data_file_block(struct incfs_blockmap_entry * bme,struct data_file_block * res_block)800 static void convert_data_file_block(struct incfs_blockmap_entry *bme,
801 				    struct data_file_block *res_block)
802 {
803 	u16 flags = le16_to_cpu(bme->me_flags);
804 
805 	res_block->db_backing_file_data_offset =
806 		le16_to_cpu(bme->me_data_offset_hi);
807 	res_block->db_backing_file_data_offset <<= 32;
808 	res_block->db_backing_file_data_offset |=
809 		le32_to_cpu(bme->me_data_offset_lo);
810 	res_block->db_stored_size = le16_to_cpu(bme->me_data_size);
811 	res_block->db_comp_alg = flags & INCFS_BLOCK_COMPRESSED_MASK;
812 }
813 
get_data_file_block(struct data_file * df,int index,struct data_file_block * res_block)814 static int get_data_file_block(struct data_file *df, int index,
815 			       struct data_file_block *res_block)
816 {
817 	struct incfs_blockmap_entry bme = {};
818 	struct backing_file_context *bfc = NULL;
819 	loff_t blockmap_off = 0;
820 	int error = 0;
821 
822 	if (!df || !res_block)
823 		return -EFAULT;
824 
825 	blockmap_off = df->df_blockmap_off;
826 	bfc = df->df_backing_file_context;
827 
828 	if (index < 0 || blockmap_off == 0)
829 		return -EINVAL;
830 
831 	error = incfs_read_blockmap_entry(bfc, index, blockmap_off, &bme);
832 	if (error)
833 		return error;
834 
835 	convert_data_file_block(&bme, res_block);
836 	return 0;
837 }
838 
check_room_for_one_range(u32 size,u32 size_out)839 static int check_room_for_one_range(u32 size, u32 size_out)
840 {
841 	if (size_out + sizeof(struct incfs_filled_range) > size)
842 		return -ERANGE;
843 	return 0;
844 }
845 
copy_one_range(struct incfs_filled_range * range,void __user * buffer,u32 size,u32 * size_out)846 static int copy_one_range(struct incfs_filled_range *range, void __user *buffer,
847 			  u32 size, u32 *size_out)
848 {
849 	int error = check_room_for_one_range(size, *size_out);
850 	if (error)
851 		return error;
852 
853 	if (copy_to_user(((char __user *)buffer) + *size_out, range,
854 				sizeof(*range)))
855 		return -EFAULT;
856 
857 	*size_out += sizeof(*range);
858 	return 0;
859 }
860 
861 #define READ_BLOCKMAP_ENTRIES 512
incfs_get_filled_blocks(struct data_file * df,struct incfs_file_data * fd,struct incfs_get_filled_blocks_args * arg)862 int incfs_get_filled_blocks(struct data_file *df,
863 			    struct incfs_file_data *fd,
864 			    struct incfs_get_filled_blocks_args *arg)
865 {
866 	int error = 0;
867 	bool in_range = false;
868 	struct incfs_filled_range range;
869 	void __user *buffer = u64_to_user_ptr(arg->range_buffer);
870 	u32 size = arg->range_buffer_size;
871 	u32 end_index =
872 		arg->end_index ? arg->end_index : df->df_total_block_count;
873 	u32 *size_out = &arg->range_buffer_size_out;
874 	int i = READ_BLOCKMAP_ENTRIES - 1;
875 	int entries_read = 0;
876 	struct incfs_blockmap_entry *bme;
877 	int data_blocks_filled = 0;
878 	int hash_blocks_filled = 0;
879 
880 	*size_out = 0;
881 	if (end_index > df->df_total_block_count)
882 		end_index = df->df_total_block_count;
883 	arg->total_blocks_out = df->df_total_block_count;
884 	arg->data_blocks_out = df->df_data_block_count;
885 
886 	if (atomic_read(&df->df_data_blocks_written) ==
887 	    df->df_data_block_count) {
888 		pr_debug("File marked full, fast get_filled_blocks");
889 		if (arg->start_index > end_index) {
890 			arg->index_out = arg->start_index;
891 			return 0;
892 		}
893 		arg->index_out = arg->start_index;
894 
895 		error = check_room_for_one_range(size, *size_out);
896 		if (error)
897 			return error;
898 
899 		range = (struct incfs_filled_range){
900 			.begin = arg->start_index,
901 			.end = end_index,
902 		};
903 
904 		error = copy_one_range(&range, buffer, size, size_out);
905 		if (error)
906 			return error;
907 		arg->index_out = end_index;
908 		return 0;
909 	}
910 
911 	bme = kzalloc(sizeof(*bme) * READ_BLOCKMAP_ENTRIES,
912 		      GFP_NOFS | __GFP_COMP);
913 	if (!bme)
914 		return -ENOMEM;
915 
916 	for (arg->index_out = arg->start_index; arg->index_out < end_index;
917 	     ++arg->index_out) {
918 		struct data_file_block dfb;
919 
920 		if (++i == READ_BLOCKMAP_ENTRIES) {
921 			entries_read = incfs_read_blockmap_entries(
922 				df->df_backing_file_context, bme,
923 				arg->index_out, READ_BLOCKMAP_ENTRIES,
924 				df->df_blockmap_off);
925 			if (entries_read < 0) {
926 				error = entries_read;
927 				break;
928 			}
929 
930 			i = 0;
931 		}
932 
933 		if (i >= entries_read) {
934 			error = -EIO;
935 			break;
936 		}
937 
938 		convert_data_file_block(bme + i, &dfb);
939 
940 		if (is_data_block_present(&dfb)) {
941 			if (arg->index_out >= df->df_data_block_count)
942 				++hash_blocks_filled;
943 			else
944 				++data_blocks_filled;
945 		}
946 
947 		if (is_data_block_present(&dfb) == in_range)
948 			continue;
949 
950 		if (!in_range) {
951 			error = check_room_for_one_range(size, *size_out);
952 			if (error)
953 				break;
954 			in_range = true;
955 			range.begin = arg->index_out;
956 		} else {
957 			range.end = arg->index_out;
958 			error = copy_one_range(&range, buffer, size, size_out);
959 			if (error) {
960 				/* there will be another try out of the loop,
961 				 * it will reset the index_out if it fails too
962 				 */
963 				break;
964 			}
965 			in_range = false;
966 		}
967 	}
968 
969 	if (in_range) {
970 		range.end = arg->index_out;
971 		error = copy_one_range(&range, buffer, size, size_out);
972 		if (error)
973 			arg->index_out = range.begin;
974 	}
975 
976 	if (arg->start_index == 0) {
977 		fd->fd_get_block_pos = 0;
978 		fd->fd_filled_data_blocks = 0;
979 		fd->fd_filled_hash_blocks = 0;
980 	}
981 
982 	if (arg->start_index == fd->fd_get_block_pos) {
983 		fd->fd_get_block_pos = arg->index_out + 1;
984 		fd->fd_filled_data_blocks += data_blocks_filled;
985 		fd->fd_filled_hash_blocks += hash_blocks_filled;
986 	}
987 
988 	if (fd->fd_get_block_pos == df->df_total_block_count + 1) {
989 		if (fd->fd_filled_data_blocks >
990 		   atomic_read(&df->df_data_blocks_written))
991 			atomic_set(&df->df_data_blocks_written,
992 				   fd->fd_filled_data_blocks);
993 
994 		if (fd->fd_filled_hash_blocks >
995 		   atomic_read(&df->df_hash_blocks_written))
996 			atomic_set(&df->df_hash_blocks_written,
997 				   fd->fd_filled_hash_blocks);
998 	}
999 
1000 	kfree(bme);
1001 	return error;
1002 }
1003 
is_read_done(struct pending_read * read)1004 static bool is_read_done(struct pending_read *read)
1005 {
1006 	return atomic_read_acquire(&read->done) != 0;
1007 }
1008 
set_read_done(struct pending_read * read)1009 static void set_read_done(struct pending_read *read)
1010 {
1011 	atomic_set_release(&read->done, 1);
1012 }
1013 
1014 /*
1015  * Notifies a given data file about pending read from a given block.
1016  * Returns a new pending read entry.
1017  */
add_pending_read(struct data_file * df,int block_index)1018 static struct pending_read *add_pending_read(struct data_file *df,
1019 					     int block_index)
1020 {
1021 	struct pending_read *result = NULL;
1022 	struct data_file_segment *segment = NULL;
1023 	struct mount_info *mi = NULL;
1024 
1025 	segment = get_file_segment(df, block_index);
1026 	mi = df->df_mount_info;
1027 
1028 	result = kzalloc(sizeof(*result), GFP_NOFS);
1029 	if (!result)
1030 		return NULL;
1031 
1032 	result->file_id = df->df_id;
1033 	result->block_index = block_index;
1034 	result->timestamp_us = ktime_to_us(ktime_get());
1035 	result->uid = current_uid().val;
1036 
1037 	spin_lock(&mi->pending_read_lock);
1038 
1039 	result->serial_number = ++mi->mi_last_pending_read_number;
1040 	mi->mi_pending_reads_count++;
1041 
1042 	list_add_rcu(&result->mi_reads_list, &mi->mi_reads_list_head);
1043 	list_add_rcu(&result->segment_reads_list, &segment->reads_list_head);
1044 
1045 	spin_unlock(&mi->pending_read_lock);
1046 
1047 	wake_up_all(&mi->mi_pending_reads_notif_wq);
1048 	return result;
1049 }
1050 
free_pending_read_entry(struct rcu_head * entry)1051 static void free_pending_read_entry(struct rcu_head *entry)
1052 {
1053 	struct pending_read *read;
1054 
1055 	read = container_of(entry, struct pending_read, rcu);
1056 
1057 	kfree(read);
1058 }
1059 
1060 /* Notifies a given data file that pending read is completed. */
remove_pending_read(struct data_file * df,struct pending_read * read)1061 static void remove_pending_read(struct data_file *df, struct pending_read *read)
1062 {
1063 	struct mount_info *mi = NULL;
1064 
1065 	if (!df || !read) {
1066 		WARN_ON(!df);
1067 		WARN_ON(!read);
1068 		return;
1069 	}
1070 
1071 	mi = df->df_mount_info;
1072 
1073 	spin_lock(&mi->pending_read_lock);
1074 
1075 	list_del_rcu(&read->mi_reads_list);
1076 	list_del_rcu(&read->segment_reads_list);
1077 
1078 	mi->mi_pending_reads_count--;
1079 
1080 	spin_unlock(&mi->pending_read_lock);
1081 
1082 	/* Don't free. Wait for readers */
1083 	call_rcu(&read->rcu, free_pending_read_entry);
1084 }
1085 
notify_pending_reads(struct mount_info * mi,struct data_file_segment * segment,int index)1086 static void notify_pending_reads(struct mount_info *mi,
1087 		struct data_file_segment *segment,
1088 		int index)
1089 {
1090 	struct pending_read *entry = NULL;
1091 
1092 	/* Notify pending reads waiting for this block. */
1093 	rcu_read_lock();
1094 	list_for_each_entry_rcu(entry, &segment->reads_list_head,
1095 						segment_reads_list) {
1096 		if (entry->block_index == index)
1097 			set_read_done(entry);
1098 	}
1099 	rcu_read_unlock();
1100 	wake_up_all(&segment->new_data_arrival_wq);
1101 
1102 	atomic_inc(&mi->mi_blocks_written);
1103 	wake_up_all(&mi->mi_blocks_written_notif_wq);
1104 }
1105 
wait_for_data_block(struct data_file * df,int block_index,struct data_file_block * res_block,struct incfs_read_data_file_timeouts * timeouts,unsigned int * delayed_min_us)1106 static int wait_for_data_block(struct data_file *df, int block_index,
1107 			       struct data_file_block *res_block,
1108 			       struct incfs_read_data_file_timeouts *timeouts,
1109 			       unsigned int *delayed_min_us)
1110 {
1111 	struct data_file_block block = {};
1112 	struct data_file_segment *segment = NULL;
1113 	struct pending_read *read = NULL;
1114 	struct mount_info *mi = NULL;
1115 	int error;
1116 	int wait_res = 0;
1117 	unsigned int delayed_pending_us = 0;
1118 	bool delayed_pending = false;
1119 
1120 	if (!df || !res_block)
1121 		return -EFAULT;
1122 
1123 	if (block_index < 0 || block_index >= df->df_data_block_count)
1124 		return -EINVAL;
1125 
1126 	if (df->df_blockmap_off <= 0 || !df->df_mount_info)
1127 		return -ENODATA;
1128 
1129 	mi = df->df_mount_info;
1130 	segment = get_file_segment(df, block_index);
1131 
1132 	error = down_read_killable(&segment->rwsem);
1133 	if (error)
1134 		return error;
1135 
1136 	/* Look up the given block */
1137 	error = get_data_file_block(df, block_index, &block);
1138 
1139 	up_read(&segment->rwsem);
1140 
1141 	if (error)
1142 		return error;
1143 
1144 	/* If the block was found, just return it. No need to wait. */
1145 	if (is_data_block_present(&block)) {
1146 		*res_block = block;
1147 		if (timeouts && timeouts->min_time_us) {
1148 			*delayed_min_us = timeouts->min_time_us;
1149 			goto out;
1150 		}
1151 		return 0;
1152 	} else {
1153 		/* If it's not found, create a pending read */
1154 		if (timeouts && timeouts->max_pending_time_us) {
1155 			read = add_pending_read(df, block_index);
1156 			if (!read)
1157 				return -ENOMEM;
1158 		} else {
1159 			log_block_read(mi, &df->df_id, block_index);
1160 			return -ETIME;
1161 		}
1162 	}
1163 
1164 	/* Rest of function only applies if timeouts != NULL */
1165 	if (!timeouts) {
1166 		pr_warn("incfs: timeouts unexpectedly NULL\n");
1167 		return -EFSCORRUPTED;
1168 	}
1169 
1170 	/* Wait for notifications about block's arrival */
1171 	wait_res =
1172 		wait_event_interruptible_timeout(segment->new_data_arrival_wq,
1173 			(is_read_done(read)),
1174 			usecs_to_jiffies(timeouts->max_pending_time_us));
1175 
1176 	/* Woke up, the pending read is no longer needed. */
1177 	remove_pending_read(df, read);
1178 
1179 	if (wait_res == 0) {
1180 		/* Wait has timed out */
1181 		log_block_read(mi, &df->df_id, block_index);
1182 		return -ETIME;
1183 	}
1184 	if (wait_res < 0) {
1185 		/*
1186 		 * Only ERESTARTSYS is really expected here when a signal
1187 		 * comes while we wait.
1188 		 */
1189 		return wait_res;
1190 	}
1191 
1192 	delayed_pending = true;
1193 	delayed_pending_us = timeouts->max_pending_time_us -
1194 				jiffies_to_usecs(wait_res);
1195 	if (timeouts->min_pending_time_us > delayed_pending_us)
1196 		*delayed_min_us = timeouts->min_pending_time_us -
1197 					     delayed_pending_us;
1198 
1199 	error = down_read_killable(&segment->rwsem);
1200 	if (error)
1201 		return error;
1202 
1203 	/*
1204 	 * Re-read blocks info now, it has just arrived and
1205 	 * should be available.
1206 	 */
1207 	error = get_data_file_block(df, block_index, &block);
1208 	if (!error) {
1209 		if (is_data_block_present(&block))
1210 			*res_block = block;
1211 		else {
1212 			/*
1213 			 * Somehow wait finished successfully but block still
1214 			 * can't be found. It's not normal.
1215 			 */
1216 			pr_warn("incfs: Wait succeeded but block not found.\n");
1217 			error = -ENODATA;
1218 		}
1219 	}
1220 	up_read(&segment->rwsem);
1221 
1222 out:
1223 	if (error)
1224 		return error;
1225 
1226 	if (delayed_pending) {
1227 		mi->mi_reads_delayed_pending++;
1228 		mi->mi_reads_delayed_pending_us +=
1229 			delayed_pending_us;
1230 	}
1231 
1232 	if (delayed_min_us && *delayed_min_us) {
1233 		mi->mi_reads_delayed_min++;
1234 		mi->mi_reads_delayed_min_us += *delayed_min_us;
1235 	}
1236 
1237 	return 0;
1238 }
1239 
incfs_update_sysfs_error(struct file * file,int index,int result,struct mount_info * mi,struct data_file * df)1240 static int incfs_update_sysfs_error(struct file *file, int index, int result,
1241 				struct mount_info *mi, struct data_file *df)
1242 {
1243 	int error;
1244 
1245 	if (result >= 0)
1246 		return 0;
1247 
1248 	error = mutex_lock_interruptible(&mi->mi_le_mutex);
1249 	if (error)
1250 		return error;
1251 
1252 	mi->mi_le_file_id = df->df_id;
1253 	mi->mi_le_time_us = ktime_to_us(ktime_get());
1254 	mi->mi_le_page = index;
1255 	mi->mi_le_errno = result;
1256 	mi->mi_le_uid = current_uid().val;
1257 	mutex_unlock(&mi->mi_le_mutex);
1258 
1259 	return 0;
1260 }
1261 
incfs_read_data_file_block(struct mem_range dst,struct file * f,int index,struct mem_range tmp,struct incfs_read_data_file_timeouts * timeouts,unsigned int * delayed_min_us)1262 ssize_t incfs_read_data_file_block(struct mem_range dst, struct file *f,
1263 			int index, struct mem_range tmp,
1264 			struct incfs_read_data_file_timeouts *timeouts,
1265 			unsigned int *delayed_min_us)
1266 {
1267 	loff_t pos;
1268 	ssize_t result;
1269 	size_t bytes_to_read;
1270 	struct mount_info *mi = NULL;
1271 	struct backing_file_context *bfc = NULL;
1272 	struct data_file_block block = {};
1273 	struct data_file *df = get_incfs_data_file(f);
1274 
1275 	if (!dst.data || !df || !tmp.data)
1276 		return -EFAULT;
1277 
1278 	if (tmp.len < 2 * INCFS_DATA_FILE_BLOCK_SIZE)
1279 		return -ERANGE;
1280 
1281 	mi = df->df_mount_info;
1282 	bfc = df->df_backing_file_context;
1283 
1284 	result = wait_for_data_block(df, index, &block, timeouts,
1285 				     delayed_min_us);
1286 	if (result < 0)
1287 		goto out;
1288 
1289 	pos = block.db_backing_file_data_offset;
1290 	if (block.db_comp_alg == COMPRESSION_NONE) {
1291 		bytes_to_read = min(dst.len, block.db_stored_size);
1292 		result = incfs_kread(bfc, dst.data, bytes_to_read, pos);
1293 
1294 		/* Some data was read, but not enough */
1295 		if (result >= 0 && result != bytes_to_read)
1296 			result = -EIO;
1297 	} else {
1298 		bytes_to_read = min(tmp.len, block.db_stored_size);
1299 		result = incfs_kread(bfc, tmp.data, bytes_to_read, pos);
1300 		if (result == bytes_to_read) {
1301 			result =
1302 				decompress(mi, range(tmp.data, bytes_to_read),
1303 					   dst, block.db_comp_alg);
1304 			if (result < 0) {
1305 				const char *name =
1306 				    bfc->bc_file->f_path.dentry->d_name.name;
1307 
1308 				pr_warn_once("incfs: Decompression error. %s",
1309 					     name);
1310 			}
1311 		} else if (result >= 0) {
1312 			/* Some data was read, but not enough */
1313 			result = -EIO;
1314 		}
1315 	}
1316 
1317 	if (result > 0) {
1318 		int err = validate_hash_tree(bfc, f, index, dst, tmp.data);
1319 
1320 		if (err < 0)
1321 			result = err;
1322 	}
1323 
1324 	if (result >= 0)
1325 		log_block_read(mi, &df->df_id, index);
1326 
1327 out:
1328 	if (result == -ETIME)
1329 		mi->mi_reads_failed_timed_out++;
1330 	else if (result == -EBADMSG)
1331 		mi->mi_reads_failed_hash_verification++;
1332 	else if (result < 0)
1333 		mi->mi_reads_failed_other++;
1334 
1335 	incfs_update_sysfs_error(f, index, result, mi, df);
1336 
1337 	return result;
1338 }
1339 
incfs_read_merkle_tree_blocks(struct mem_range dst,struct data_file * df,size_t offset)1340 ssize_t incfs_read_merkle_tree_blocks(struct mem_range dst,
1341 				      struct data_file *df, size_t offset)
1342 {
1343 	struct backing_file_context *bfc = NULL;
1344 	struct incfs_df_signature *sig = NULL;
1345 	size_t to_read = dst.len;
1346 
1347 	if (!dst.data || !df)
1348 		return -EFAULT;
1349 
1350 	sig = df->df_signature;
1351 	bfc = df->df_backing_file_context;
1352 
1353 	if (offset > sig->hash_size)
1354 		return -ERANGE;
1355 
1356 	if (offset + to_read > sig->hash_size)
1357 		to_read = sig->hash_size - offset;
1358 
1359 	return incfs_kread(bfc, dst.data, to_read, sig->hash_offset + offset);
1360 }
1361 
incfs_process_new_data_block(struct data_file * df,struct incfs_fill_block * block,u8 * data,bool * complete)1362 int incfs_process_new_data_block(struct data_file *df,
1363 				 struct incfs_fill_block *block, u8 *data,
1364 				 bool *complete)
1365 {
1366 	struct mount_info *mi = NULL;
1367 	struct backing_file_context *bfc = NULL;
1368 	struct data_file_segment *segment = NULL;
1369 	struct data_file_block existing_block = {};
1370 	u16 flags = 0;
1371 	int error = 0;
1372 
1373 	if (!df || !block)
1374 		return -EFAULT;
1375 
1376 	bfc = df->df_backing_file_context;
1377 	mi = df->df_mount_info;
1378 
1379 	if (block->block_index >= df->df_data_block_count)
1380 		return -ERANGE;
1381 
1382 	segment = get_file_segment(df, block->block_index);
1383 	if (!segment)
1384 		return -EFAULT;
1385 
1386 	if (block->compression == COMPRESSION_LZ4)
1387 		flags |= INCFS_BLOCK_COMPRESSED_LZ4;
1388 	else if (block->compression == COMPRESSION_ZSTD)
1389 		flags |= INCFS_BLOCK_COMPRESSED_ZSTD;
1390 	else if (block->compression)
1391 		return -EINVAL;
1392 
1393 	error = down_read_killable(&segment->rwsem);
1394 	if (error)
1395 		return error;
1396 
1397 	error = get_data_file_block(df, block->block_index, &existing_block);
1398 
1399 	up_read(&segment->rwsem);
1400 
1401 	if (error)
1402 		return error;
1403 	if (is_data_block_present(&existing_block))
1404 		/* Block is already present, nothing to do here */
1405 		return 0;
1406 
1407 	error = down_write_killable(&segment->rwsem);
1408 	if (error)
1409 		return error;
1410 
1411 	/* Recheck inside write lock */
1412 	error = get_data_file_block(df, block->block_index, &existing_block);
1413 	if (error)
1414 		goto out_up_write;
1415 
1416 	if (is_data_block_present(&existing_block))
1417 		goto out_up_write;
1418 
1419 	error = mutex_lock_interruptible(&bfc->bc_mutex);
1420 	if (error)
1421 		goto out_up_write;
1422 
1423 	error = incfs_write_data_block_to_backing_file(bfc,
1424 			range(data, block->data_len), block->block_index,
1425 			df->df_blockmap_off, flags);
1426 	if (error)
1427 		goto out_mutex_unlock;
1428 
1429 	if (atomic_inc_return(&df->df_data_blocks_written)
1430 			>= df->df_data_block_count)
1431 		*complete = true;
1432 
1433 out_mutex_unlock:
1434 	mutex_unlock(&bfc->bc_mutex);
1435 	if (!error)
1436 		notify_pending_reads(mi, segment, block->block_index);
1437 
1438 out_up_write:
1439 	up_write(&segment->rwsem);
1440 
1441 	if (error)
1442 		pr_debug("%d error: %d\n", block->block_index, error);
1443 	return error;
1444 }
1445 
incfs_read_file_signature(struct data_file * df,struct mem_range dst)1446 int incfs_read_file_signature(struct data_file *df, struct mem_range dst)
1447 {
1448 	struct backing_file_context *bfc = df->df_backing_file_context;
1449 	struct incfs_df_signature *sig;
1450 	int read_res = 0;
1451 
1452 	if (!dst.data)
1453 		return -EFAULT;
1454 
1455 	sig = df->df_signature;
1456 	if (!sig)
1457 		return 0;
1458 
1459 	if (dst.len < sig->sig_size)
1460 		return -E2BIG;
1461 
1462 	read_res = incfs_kread(bfc, dst.data, sig->sig_size, sig->sig_offset);
1463 
1464 	if (read_res < 0)
1465 		return read_res;
1466 
1467 	if (read_res != sig->sig_size)
1468 		return -EIO;
1469 
1470 	return read_res;
1471 }
1472 
incfs_process_new_hash_block(struct data_file * df,struct incfs_fill_block * block,u8 * data)1473 int incfs_process_new_hash_block(struct data_file *df,
1474 				 struct incfs_fill_block *block, u8 *data)
1475 {
1476 	struct backing_file_context *bfc = NULL;
1477 	struct mount_info *mi = NULL;
1478 	struct mtree *hash_tree = NULL;
1479 	struct incfs_df_signature *sig = NULL;
1480 	loff_t hash_area_base = 0;
1481 	loff_t hash_area_size = 0;
1482 	int error = 0;
1483 
1484 	if (!df || !block)
1485 		return -EFAULT;
1486 
1487 	if (!(block->flags & INCFS_BLOCK_FLAGS_HASH))
1488 		return -EINVAL;
1489 
1490 	bfc = df->df_backing_file_context;
1491 	mi = df->df_mount_info;
1492 
1493 	if (!df)
1494 		return -ENOENT;
1495 
1496 	hash_tree = df->df_hash_tree;
1497 	sig = df->df_signature;
1498 	if (!hash_tree || !sig || sig->hash_offset == 0)
1499 		return -ENOTSUPP;
1500 
1501 	hash_area_base = sig->hash_offset;
1502 	hash_area_size = sig->hash_size;
1503 	if (hash_area_size < block->block_index * INCFS_DATA_FILE_BLOCK_SIZE
1504 				+ block->data_len) {
1505 		/* Hash block goes beyond dedicated hash area of this file. */
1506 		return -ERANGE;
1507 	}
1508 
1509 	error = mutex_lock_interruptible(&bfc->bc_mutex);
1510 	if (!error) {
1511 		error = incfs_write_hash_block_to_backing_file(
1512 			bfc, range(data, block->data_len), block->block_index,
1513 			hash_area_base, df->df_blockmap_off, df->df_size);
1514 		mutex_unlock(&bfc->bc_mutex);
1515 	}
1516 	if (!error)
1517 		atomic_inc(&df->df_hash_blocks_written);
1518 
1519 	return error;
1520 }
1521 
process_blockmap_md(struct incfs_blockmap * bm,struct metadata_handler * handler)1522 static int process_blockmap_md(struct incfs_blockmap *bm,
1523 			       struct metadata_handler *handler)
1524 {
1525 	struct data_file *df = handler->context;
1526 	int error = 0;
1527 	loff_t base_off = le64_to_cpu(bm->m_base_offset);
1528 	u32 block_count = le32_to_cpu(bm->m_block_count);
1529 
1530 	if (!df)
1531 		return -EFAULT;
1532 
1533 	if (df->df_data_block_count > block_count)
1534 		return -EBADMSG;
1535 
1536 	df->df_total_block_count = block_count;
1537 	df->df_blockmap_off = base_off;
1538 	return error;
1539 }
1540 
process_file_signature_md(struct incfs_file_signature * sg,struct metadata_handler * handler)1541 static int process_file_signature_md(struct incfs_file_signature *sg,
1542 				struct metadata_handler *handler)
1543 {
1544 	struct data_file *df = handler->context;
1545 	struct mtree *hash_tree = NULL;
1546 	int error = 0;
1547 	struct incfs_df_signature *signature =
1548 		kzalloc(sizeof(*signature), GFP_NOFS);
1549 	void *buf = NULL;
1550 	ssize_t read;
1551 
1552 	if (!signature)
1553 		return -ENOMEM;
1554 
1555 	if (!df || !df->df_backing_file_context ||
1556 	    !df->df_backing_file_context->bc_file) {
1557 		error = -ENOENT;
1558 		goto out;
1559 	}
1560 
1561 	signature->hash_offset = le64_to_cpu(sg->sg_hash_tree_offset);
1562 	signature->hash_size = le32_to_cpu(sg->sg_hash_tree_size);
1563 	signature->sig_offset = le64_to_cpu(sg->sg_sig_offset);
1564 	signature->sig_size = le32_to_cpu(sg->sg_sig_size);
1565 
1566 	buf = kzalloc(signature->sig_size, GFP_NOFS);
1567 	if (!buf) {
1568 		error = -ENOMEM;
1569 		goto out;
1570 	}
1571 
1572 	read = incfs_kread(df->df_backing_file_context, buf,
1573 			   signature->sig_size, signature->sig_offset);
1574 	if (read < 0) {
1575 		error = read;
1576 		goto out;
1577 	}
1578 
1579 	if (read != signature->sig_size) {
1580 		error = -EINVAL;
1581 		goto out;
1582 	}
1583 
1584 	hash_tree = incfs_alloc_mtree(range(buf, signature->sig_size),
1585 				      df->df_data_block_count);
1586 	if (IS_ERR(hash_tree)) {
1587 		error = PTR_ERR(hash_tree);
1588 		hash_tree = NULL;
1589 		goto out;
1590 	}
1591 	if (hash_tree->hash_tree_area_size != signature->hash_size) {
1592 		error = -EINVAL;
1593 		goto out;
1594 	}
1595 	if (signature->hash_size > 0 &&
1596 	    handler->md_record_offset <= signature->hash_offset) {
1597 		error = -EINVAL;
1598 		goto out;
1599 	}
1600 	if (handler->md_record_offset <= signature->sig_offset) {
1601 		error = -EINVAL;
1602 		goto out;
1603 	}
1604 	df->df_hash_tree = hash_tree;
1605 	hash_tree = NULL;
1606 	df->df_signature = signature;
1607 	signature = NULL;
1608 out:
1609 	incfs_free_mtree(hash_tree);
1610 	kfree(signature);
1611 	kfree(buf);
1612 
1613 	return error;
1614 }
1615 
process_status_md(struct incfs_status * is,struct metadata_handler * handler)1616 static int process_status_md(struct incfs_status *is,
1617 			     struct metadata_handler *handler)
1618 {
1619 	struct data_file *df = handler->context;
1620 
1621 	df->df_initial_data_blocks_written =
1622 		le32_to_cpu(is->is_data_blocks_written);
1623 	atomic_set(&df->df_data_blocks_written,
1624 		   df->df_initial_data_blocks_written);
1625 
1626 	df->df_initial_hash_blocks_written =
1627 		le32_to_cpu(is->is_hash_blocks_written);
1628 	atomic_set(&df->df_hash_blocks_written,
1629 		   df->df_initial_hash_blocks_written);
1630 
1631 	df->df_status_offset = handler->md_record_offset;
1632 	return 0;
1633 }
1634 
process_file_verity_signature_md(struct incfs_file_verity_signature * vs,struct metadata_handler * handler)1635 static int process_file_verity_signature_md(
1636 		struct incfs_file_verity_signature *vs,
1637 		struct metadata_handler *handler)
1638 {
1639 	struct data_file *df = handler->context;
1640 	struct incfs_df_verity_signature *verity_signature;
1641 
1642 	if (!df)
1643 		return -EFAULT;
1644 
1645 	verity_signature = kzalloc(sizeof(*verity_signature), GFP_NOFS);
1646 	if (!verity_signature)
1647 		return -ENOMEM;
1648 
1649 	verity_signature->offset = le64_to_cpu(vs->vs_offset);
1650 	verity_signature->size = le32_to_cpu(vs->vs_size);
1651 	if (verity_signature->size > FS_VERITY_MAX_SIGNATURE_SIZE) {
1652 		kfree(verity_signature);
1653 		return -EFAULT;
1654 	}
1655 
1656 	df->df_verity_signature = verity_signature;
1657 	return 0;
1658 }
1659 
incfs_scan_metadata_chain(struct data_file * df)1660 static int incfs_scan_metadata_chain(struct data_file *df)
1661 {
1662 	struct metadata_handler *handler = NULL;
1663 	int result = 0;
1664 	int records_count = 0;
1665 	int error = 0;
1666 	struct backing_file_context *bfc = NULL;
1667 	int nondata_block_count;
1668 
1669 	if (!df || !df->df_backing_file_context)
1670 		return -EFAULT;
1671 
1672 	bfc = df->df_backing_file_context;
1673 
1674 	handler = kzalloc(sizeof(*handler), GFP_NOFS);
1675 	if (!handler)
1676 		return -ENOMEM;
1677 
1678 	handler->md_record_offset = df->df_metadata_off;
1679 	handler->context = df;
1680 	handler->handle_blockmap = process_blockmap_md;
1681 	handler->handle_signature = process_file_signature_md;
1682 	handler->handle_status = process_status_md;
1683 	handler->handle_verity_signature = process_file_verity_signature_md;
1684 
1685 	while (handler->md_record_offset > 0) {
1686 		error = incfs_read_next_metadata_record(bfc, handler);
1687 		if (error) {
1688 			pr_warn("incfs: Error during reading incfs-metadata record. Offset: %lld Record #%d Error code: %d\n",
1689 				handler->md_record_offset, records_count + 1,
1690 				-error);
1691 			break;
1692 		}
1693 		records_count++;
1694 	}
1695 	if (error) {
1696 		pr_warn("incfs: Error %d after reading %d incfs-metadata records.\n",
1697 			 -error, records_count);
1698 		result = error;
1699 	} else
1700 		result = records_count;
1701 
1702 	nondata_block_count = df->df_total_block_count -
1703 		df->df_data_block_count;
1704 	if (df->df_hash_tree) {
1705 		int hash_block_count = get_blocks_count_for_size(
1706 			df->df_hash_tree->hash_tree_area_size);
1707 
1708 		/*
1709 		 * Files that were created with a hash tree have the hash tree
1710 		 * included in the block map, i.e. nondata_block_count ==
1711 		 * hash_block_count.  Files whose hash tree was added by
1712 		 * FS_IOC_ENABLE_VERITY will still have the original block
1713 		 * count, i.e. nondata_block_count == 0.
1714 		 */
1715 		if (nondata_block_count != hash_block_count &&
1716 		    nondata_block_count != 0)
1717 			result = -EINVAL;
1718 	} else if (nondata_block_count != 0) {
1719 		result = -EINVAL;
1720 	}
1721 
1722 	kfree(handler);
1723 	return result;
1724 }
1725 
1726 /*
1727  * Quickly checks if there are pending reads with a serial number larger
1728  * than a given one.
1729  */
incfs_fresh_pending_reads_exist(struct mount_info * mi,int last_number)1730 bool incfs_fresh_pending_reads_exist(struct mount_info *mi, int last_number)
1731 {
1732 	bool result = false;
1733 
1734 	spin_lock(&mi->pending_read_lock);
1735 	result = (mi->mi_last_pending_read_number > last_number) &&
1736 		(mi->mi_pending_reads_count > 0);
1737 	spin_unlock(&mi->pending_read_lock);
1738 	return result;
1739 }
1740 
incfs_collect_pending_reads(struct mount_info * mi,int sn_lowerbound,struct incfs_pending_read_info * reads,struct incfs_pending_read_info2 * reads2,int reads_size,int * new_max_sn)1741 int incfs_collect_pending_reads(struct mount_info *mi, int sn_lowerbound,
1742 				struct incfs_pending_read_info *reads,
1743 				struct incfs_pending_read_info2 *reads2,
1744 				int reads_size, int *new_max_sn)
1745 {
1746 	int reported_reads = 0;
1747 	struct pending_read *entry = NULL;
1748 
1749 	if (!mi)
1750 		return -EFAULT;
1751 
1752 	if (reads_size <= 0)
1753 		return 0;
1754 
1755 	if (!incfs_fresh_pending_reads_exist(mi, sn_lowerbound))
1756 		return 0;
1757 
1758 	rcu_read_lock();
1759 
1760 	list_for_each_entry_rcu(entry, &mi->mi_reads_list_head, mi_reads_list) {
1761 		if (entry->serial_number <= sn_lowerbound)
1762 			continue;
1763 
1764 		if (reads) {
1765 			reads[reported_reads].file_id = entry->file_id;
1766 			reads[reported_reads].block_index = entry->block_index;
1767 			reads[reported_reads].serial_number =
1768 				entry->serial_number;
1769 			reads[reported_reads].timestamp_us =
1770 				entry->timestamp_us;
1771 		}
1772 
1773 		if (reads2) {
1774 			reads2[reported_reads].file_id = entry->file_id;
1775 			reads2[reported_reads].block_index = entry->block_index;
1776 			reads2[reported_reads].serial_number =
1777 				entry->serial_number;
1778 			reads2[reported_reads].timestamp_us =
1779 				entry->timestamp_us;
1780 			reads2[reported_reads].uid = entry->uid;
1781 		}
1782 
1783 		if (entry->serial_number > *new_max_sn)
1784 			*new_max_sn = entry->serial_number;
1785 
1786 		reported_reads++;
1787 		if (reported_reads >= reads_size)
1788 			break;
1789 	}
1790 
1791 	rcu_read_unlock();
1792 
1793 	return reported_reads;
1794 }
1795 
incfs_get_log_state(struct mount_info * mi)1796 struct read_log_state incfs_get_log_state(struct mount_info *mi)
1797 {
1798 	struct read_log *log = &mi->mi_log;
1799 	struct read_log_state result;
1800 
1801 	spin_lock(&log->rl_lock);
1802 	result = log->rl_head;
1803 	spin_unlock(&log->rl_lock);
1804 	return result;
1805 }
1806 
incfs_get_uncollected_logs_count(struct mount_info * mi,const struct read_log_state * state)1807 int incfs_get_uncollected_logs_count(struct mount_info *mi,
1808 				     const struct read_log_state *state)
1809 {
1810 	struct read_log *log = &mi->mi_log;
1811 	u32 generation;
1812 	u64 head_no, tail_no;
1813 
1814 	spin_lock(&log->rl_lock);
1815 	tail_no = log->rl_tail.current_record_no;
1816 	head_no = log->rl_head.current_record_no;
1817 	generation = log->rl_head.generation_id;
1818 	spin_unlock(&log->rl_lock);
1819 
1820 	if (generation != state->generation_id)
1821 		return head_no - tail_no;
1822 	else
1823 		return head_no - max_t(u64, tail_no, state->current_record_no);
1824 }
1825 
incfs_collect_logged_reads(struct mount_info * mi,struct read_log_state * state,struct incfs_pending_read_info * reads,struct incfs_pending_read_info2 * reads2,int reads_size)1826 int incfs_collect_logged_reads(struct mount_info *mi,
1827 			       struct read_log_state *state,
1828 			       struct incfs_pending_read_info *reads,
1829 			       struct incfs_pending_read_info2 *reads2,
1830 			       int reads_size)
1831 {
1832 	int dst_idx;
1833 	struct read_log *log = &mi->mi_log;
1834 	struct read_log_state *head, *tail;
1835 
1836 	spin_lock(&log->rl_lock);
1837 	head = &log->rl_head;
1838 	tail = &log->rl_tail;
1839 
1840 	if (state->generation_id != head->generation_id) {
1841 		pr_debug("read ptr is wrong generation: %u/%u",
1842 			 state->generation_id, head->generation_id);
1843 
1844 		*state = (struct read_log_state){
1845 			.generation_id = head->generation_id,
1846 		};
1847 	}
1848 
1849 	if (state->current_record_no < tail->current_record_no) {
1850 		pr_debug("read ptr is behind, moving: %u/%u -> %u/%u\n",
1851 			 (u32)state->next_offset,
1852 			 (u32)state->current_pass_no,
1853 			 (u32)tail->next_offset, (u32)tail->current_pass_no);
1854 
1855 		*state = *tail;
1856 	}
1857 
1858 	for (dst_idx = 0; dst_idx < reads_size; dst_idx++) {
1859 		if (state->current_record_no == head->current_record_no)
1860 			break;
1861 
1862 		log_read_one_record(log, state);
1863 
1864 		if (reads)
1865 			reads[dst_idx] = (struct incfs_pending_read_info) {
1866 				.file_id = state->base_record.file_id,
1867 				.block_index = state->base_record.block_index,
1868 				.serial_number = state->current_record_no,
1869 				.timestamp_us =
1870 					state->base_record.absolute_ts_us,
1871 			};
1872 
1873 		if (reads2)
1874 			reads2[dst_idx] = (struct incfs_pending_read_info2) {
1875 				.file_id = state->base_record.file_id,
1876 				.block_index = state->base_record.block_index,
1877 				.serial_number = state->current_record_no,
1878 				.timestamp_us =
1879 					state->base_record.absolute_ts_us,
1880 				.uid = state->base_record.uid,
1881 			};
1882 	}
1883 
1884 	spin_unlock(&log->rl_lock);
1885 	return dst_idx;
1886 }
1887 
1888