xref: /openbmc/linux/fs/ubifs/sb.c (revision f125e2d4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This file is part of UBIFS.
4  *
5  * Copyright (C) 2006-2008 Nokia Corporation.
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  */
10 
11 /*
12  * This file implements UBIFS superblock. The superblock is stored at the first
13  * LEB of the volume and is never changed by UBIFS. Only user-space tools may
14  * change it. The superblock node mostly contains geometry information.
15  */
16 
17 #include "ubifs.h"
18 #include <linux/slab.h>
19 #include <linux/math64.h>
20 #include <linux/uuid.h>
21 
22 /*
23  * Default journal size in logical eraseblocks as a percent of total
24  * flash size.
25  */
26 #define DEFAULT_JNL_PERCENT 5
27 
28 /* Default maximum journal size in bytes */
29 #define DEFAULT_MAX_JNL (32*1024*1024)
30 
31 /* Default indexing tree fanout */
32 #define DEFAULT_FANOUT 8
33 
34 /* Default number of data journal heads */
35 #define DEFAULT_JHEADS_CNT 1
36 
37 /* Default positions of different LEBs in the main area */
38 #define DEFAULT_IDX_LEB  0
39 #define DEFAULT_DATA_LEB 1
40 #define DEFAULT_GC_LEB   2
41 
42 /* Default number of LEB numbers in LPT's save table */
43 #define DEFAULT_LSAVE_CNT 256
44 
45 /* Default reserved pool size as a percent of maximum free space */
46 #define DEFAULT_RP_PERCENT 5
47 
48 /* The default maximum size of reserved pool in bytes */
49 #define DEFAULT_MAX_RP_SIZE (5*1024*1024)
50 
51 /* Default time granularity in nanoseconds */
52 #define DEFAULT_TIME_GRAN 1000000000
53 
54 static int get_default_compressor(struct ubifs_info *c)
55 {
56 	if (ubifs_compr_present(c, UBIFS_COMPR_LZO))
57 		return UBIFS_COMPR_LZO;
58 
59 	if (ubifs_compr_present(c, UBIFS_COMPR_ZLIB))
60 		return UBIFS_COMPR_ZLIB;
61 
62 	return UBIFS_COMPR_NONE;
63 }
64 
65 /**
66  * create_default_filesystem - format empty UBI volume.
67  * @c: UBIFS file-system description object
68  *
69  * This function creates default empty file-system. Returns zero in case of
70  * success and a negative error code in case of failure.
71  */
72 static int create_default_filesystem(struct ubifs_info *c)
73 {
74 	struct ubifs_sb_node *sup;
75 	struct ubifs_mst_node *mst;
76 	struct ubifs_idx_node *idx;
77 	struct ubifs_branch *br;
78 	struct ubifs_ino_node *ino;
79 	struct ubifs_cs_node *cs;
80 	union ubifs_key key;
81 	int err, tmp, jnl_lebs, log_lebs, max_buds, main_lebs, main_first;
82 	int lpt_lebs, lpt_first, orph_lebs, big_lpt, ino_waste, sup_flags = 0;
83 	int min_leb_cnt = UBIFS_MIN_LEB_CNT;
84 	int idx_node_size;
85 	long long tmp64, main_bytes;
86 	__le64 tmp_le64;
87 	struct timespec64 ts;
88 	u8 hash[UBIFS_HASH_ARR_SZ];
89 	u8 hash_lpt[UBIFS_HASH_ARR_SZ];
90 
91 	/* Some functions called from here depend on the @c->key_len filed */
92 	c->key_len = UBIFS_SK_LEN;
93 
94 	/*
95 	 * First of all, we have to calculate default file-system geometry -
96 	 * log size, journal size, etc.
97 	 */
98 	if (c->leb_cnt < 0x7FFFFFFF / DEFAULT_JNL_PERCENT)
99 		/* We can first multiply then divide and have no overflow */
100 		jnl_lebs = c->leb_cnt * DEFAULT_JNL_PERCENT / 100;
101 	else
102 		jnl_lebs = (c->leb_cnt / 100) * DEFAULT_JNL_PERCENT;
103 
104 	if (jnl_lebs < UBIFS_MIN_JNL_LEBS)
105 		jnl_lebs = UBIFS_MIN_JNL_LEBS;
106 	if (jnl_lebs * c->leb_size > DEFAULT_MAX_JNL)
107 		jnl_lebs = DEFAULT_MAX_JNL / c->leb_size;
108 
109 	/*
110 	 * The log should be large enough to fit reference nodes for all bud
111 	 * LEBs. Because buds do not have to start from the beginning of LEBs
112 	 * (half of the LEB may contain committed data), the log should
113 	 * generally be larger, make it twice as large.
114 	 */
115 	tmp = 2 * (c->ref_node_alsz * jnl_lebs) + c->leb_size - 1;
116 	log_lebs = tmp / c->leb_size;
117 	/* Plus one LEB reserved for commit */
118 	log_lebs += 1;
119 	if (c->leb_cnt - min_leb_cnt > 8) {
120 		/* And some extra space to allow writes while committing */
121 		log_lebs += 1;
122 		min_leb_cnt += 1;
123 	}
124 
125 	max_buds = jnl_lebs - log_lebs;
126 	if (max_buds < UBIFS_MIN_BUD_LEBS)
127 		max_buds = UBIFS_MIN_BUD_LEBS;
128 
129 	/*
130 	 * Orphan nodes are stored in a separate area. One node can store a lot
131 	 * of orphan inode numbers, but when new orphan comes we just add a new
132 	 * orphan node. At some point the nodes are consolidated into one
133 	 * orphan node.
134 	 */
135 	orph_lebs = UBIFS_MIN_ORPH_LEBS;
136 	if (c->leb_cnt - min_leb_cnt > 1)
137 		/*
138 		 * For debugging purposes it is better to have at least 2
139 		 * orphan LEBs, because the orphan subsystem would need to do
140 		 * consolidations and would be stressed more.
141 		 */
142 		orph_lebs += 1;
143 
144 	main_lebs = c->leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS - log_lebs;
145 	main_lebs -= orph_lebs;
146 
147 	lpt_first = UBIFS_LOG_LNUM + log_lebs;
148 	c->lsave_cnt = DEFAULT_LSAVE_CNT;
149 	c->max_leb_cnt = c->leb_cnt;
150 	err = ubifs_create_dflt_lpt(c, &main_lebs, lpt_first, &lpt_lebs,
151 				    &big_lpt, hash_lpt);
152 	if (err)
153 		return err;
154 
155 	dbg_gen("LEB Properties Tree created (LEBs %d-%d)", lpt_first,
156 		lpt_first + lpt_lebs - 1);
157 
158 	main_first = c->leb_cnt - main_lebs;
159 
160 	sup = kzalloc(ALIGN(UBIFS_SB_NODE_SZ, c->min_io_size), GFP_KERNEL);
161 	mst = kzalloc(c->mst_node_alsz, GFP_KERNEL);
162 	idx_node_size = ubifs_idx_node_sz(c, 1);
163 	idx = kzalloc(ALIGN(idx_node_size, c->min_io_size), GFP_KERNEL);
164 	ino = kzalloc(ALIGN(UBIFS_INO_NODE_SZ, c->min_io_size), GFP_KERNEL);
165 	cs = kzalloc(ALIGN(UBIFS_CS_NODE_SZ, c->min_io_size), GFP_KERNEL);
166 
167 	if (!sup || !mst || !idx || !ino || !cs) {
168 		err = -ENOMEM;
169 		goto out;
170 	}
171 
172 	/* Create default superblock */
173 
174 	tmp64 = (long long)max_buds * c->leb_size;
175 	if (big_lpt)
176 		sup_flags |= UBIFS_FLG_BIGLPT;
177 	sup_flags |= UBIFS_FLG_DOUBLE_HASH;
178 
179 	if (ubifs_authenticated(c)) {
180 		sup_flags |= UBIFS_FLG_AUTHENTICATION;
181 		sup->hash_algo = cpu_to_le16(c->auth_hash_algo);
182 		err = ubifs_hmac_wkm(c, sup->hmac_wkm);
183 		if (err)
184 			goto out;
185 	} else {
186 		sup->hash_algo = cpu_to_le16(0xffff);
187 	}
188 
189 	sup->ch.node_type  = UBIFS_SB_NODE;
190 	sup->key_hash      = UBIFS_KEY_HASH_R5;
191 	sup->flags         = cpu_to_le32(sup_flags);
192 	sup->min_io_size   = cpu_to_le32(c->min_io_size);
193 	sup->leb_size      = cpu_to_le32(c->leb_size);
194 	sup->leb_cnt       = cpu_to_le32(c->leb_cnt);
195 	sup->max_leb_cnt   = cpu_to_le32(c->max_leb_cnt);
196 	sup->max_bud_bytes = cpu_to_le64(tmp64);
197 	sup->log_lebs      = cpu_to_le32(log_lebs);
198 	sup->lpt_lebs      = cpu_to_le32(lpt_lebs);
199 	sup->orph_lebs     = cpu_to_le32(orph_lebs);
200 	sup->jhead_cnt     = cpu_to_le32(DEFAULT_JHEADS_CNT);
201 	sup->fanout        = cpu_to_le32(DEFAULT_FANOUT);
202 	sup->lsave_cnt     = cpu_to_le32(c->lsave_cnt);
203 	sup->fmt_version   = cpu_to_le32(UBIFS_FORMAT_VERSION);
204 	sup->time_gran     = cpu_to_le32(DEFAULT_TIME_GRAN);
205 	if (c->mount_opts.override_compr)
206 		sup->default_compr = cpu_to_le16(c->mount_opts.compr_type);
207 	else
208 		sup->default_compr = cpu_to_le16(get_default_compressor(c));
209 
210 	generate_random_uuid(sup->uuid);
211 
212 	main_bytes = (long long)main_lebs * c->leb_size;
213 	tmp64 = div_u64(main_bytes * DEFAULT_RP_PERCENT, 100);
214 	if (tmp64 > DEFAULT_MAX_RP_SIZE)
215 		tmp64 = DEFAULT_MAX_RP_SIZE;
216 	sup->rp_size = cpu_to_le64(tmp64);
217 	sup->ro_compat_version = cpu_to_le32(UBIFS_RO_COMPAT_VERSION);
218 
219 	dbg_gen("default superblock created at LEB 0:0");
220 
221 	/* Create default master node */
222 
223 	mst->ch.node_type = UBIFS_MST_NODE;
224 	mst->log_lnum     = cpu_to_le32(UBIFS_LOG_LNUM);
225 	mst->highest_inum = cpu_to_le64(UBIFS_FIRST_INO);
226 	mst->cmt_no       = 0;
227 	mst->root_lnum    = cpu_to_le32(main_first + DEFAULT_IDX_LEB);
228 	mst->root_offs    = 0;
229 	tmp = ubifs_idx_node_sz(c, 1);
230 	mst->root_len     = cpu_to_le32(tmp);
231 	mst->gc_lnum      = cpu_to_le32(main_first + DEFAULT_GC_LEB);
232 	mst->ihead_lnum   = cpu_to_le32(main_first + DEFAULT_IDX_LEB);
233 	mst->ihead_offs   = cpu_to_le32(ALIGN(tmp, c->min_io_size));
234 	mst->index_size   = cpu_to_le64(ALIGN(tmp, 8));
235 	mst->lpt_lnum     = cpu_to_le32(c->lpt_lnum);
236 	mst->lpt_offs     = cpu_to_le32(c->lpt_offs);
237 	mst->nhead_lnum   = cpu_to_le32(c->nhead_lnum);
238 	mst->nhead_offs   = cpu_to_le32(c->nhead_offs);
239 	mst->ltab_lnum    = cpu_to_le32(c->ltab_lnum);
240 	mst->ltab_offs    = cpu_to_le32(c->ltab_offs);
241 	mst->lsave_lnum   = cpu_to_le32(c->lsave_lnum);
242 	mst->lsave_offs   = cpu_to_le32(c->lsave_offs);
243 	mst->lscan_lnum   = cpu_to_le32(main_first);
244 	mst->empty_lebs   = cpu_to_le32(main_lebs - 2);
245 	mst->idx_lebs     = cpu_to_le32(1);
246 	mst->leb_cnt      = cpu_to_le32(c->leb_cnt);
247 	ubifs_copy_hash(c, hash_lpt, mst->hash_lpt);
248 
249 	/* Calculate lprops statistics */
250 	tmp64 = main_bytes;
251 	tmp64 -= ALIGN(ubifs_idx_node_sz(c, 1), c->min_io_size);
252 	tmp64 -= ALIGN(UBIFS_INO_NODE_SZ, c->min_io_size);
253 	mst->total_free = cpu_to_le64(tmp64);
254 
255 	tmp64 = ALIGN(ubifs_idx_node_sz(c, 1), c->min_io_size);
256 	ino_waste = ALIGN(UBIFS_INO_NODE_SZ, c->min_io_size) -
257 			  UBIFS_INO_NODE_SZ;
258 	tmp64 += ino_waste;
259 	tmp64 -= ALIGN(ubifs_idx_node_sz(c, 1), 8);
260 	mst->total_dirty = cpu_to_le64(tmp64);
261 
262 	/*  The indexing LEB does not contribute to dark space */
263 	tmp64 = ((long long)(c->main_lebs - 1) * c->dark_wm);
264 	mst->total_dark = cpu_to_le64(tmp64);
265 
266 	mst->total_used = cpu_to_le64(UBIFS_INO_NODE_SZ);
267 
268 	dbg_gen("default master node created at LEB %d:0", UBIFS_MST_LNUM);
269 
270 	/* Create the root indexing node */
271 
272 	c->key_fmt = UBIFS_SIMPLE_KEY_FMT;
273 	c->key_hash = key_r5_hash;
274 
275 	idx->ch.node_type = UBIFS_IDX_NODE;
276 	idx->child_cnt = cpu_to_le16(1);
277 	ino_key_init(c, &key, UBIFS_ROOT_INO);
278 	br = ubifs_idx_branch(c, idx, 0);
279 	key_write_idx(c, &key, &br->key);
280 	br->lnum = cpu_to_le32(main_first + DEFAULT_DATA_LEB);
281 	br->len  = cpu_to_le32(UBIFS_INO_NODE_SZ);
282 
283 	dbg_gen("default root indexing node created LEB %d:0",
284 		main_first + DEFAULT_IDX_LEB);
285 
286 	/* Create default root inode */
287 
288 	ino_key_init_flash(c, &ino->key, UBIFS_ROOT_INO);
289 	ino->ch.node_type = UBIFS_INO_NODE;
290 	ino->creat_sqnum = cpu_to_le64(++c->max_sqnum);
291 	ino->nlink = cpu_to_le32(2);
292 
293 	ktime_get_coarse_real_ts64(&ts);
294 	tmp_le64 = cpu_to_le64(ts.tv_sec);
295 	ino->atime_sec   = tmp_le64;
296 	ino->ctime_sec   = tmp_le64;
297 	ino->mtime_sec   = tmp_le64;
298 	ino->atime_nsec  = 0;
299 	ino->ctime_nsec  = 0;
300 	ino->mtime_nsec  = 0;
301 	ino->mode = cpu_to_le32(S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
302 	ino->size = cpu_to_le64(UBIFS_INO_NODE_SZ);
303 
304 	/* Set compression enabled by default */
305 	ino->flags = cpu_to_le32(UBIFS_COMPR_FL);
306 
307 	dbg_gen("root inode created at LEB %d:0",
308 		main_first + DEFAULT_DATA_LEB);
309 
310 	/*
311 	 * The first node in the log has to be the commit start node. This is
312 	 * always the case during normal file-system operation. Write a fake
313 	 * commit start node to the log.
314 	 */
315 
316 	cs->ch.node_type = UBIFS_CS_NODE;
317 
318 	err = ubifs_write_node_hmac(c, sup, UBIFS_SB_NODE_SZ, 0, 0,
319 				    offsetof(struct ubifs_sb_node, hmac));
320 	if (err)
321 		goto out;
322 
323 	err = ubifs_write_node(c, ino, UBIFS_INO_NODE_SZ,
324 			       main_first + DEFAULT_DATA_LEB, 0);
325 	if (err)
326 		goto out;
327 
328 	ubifs_node_calc_hash(c, ino, hash);
329 	ubifs_copy_hash(c, hash, ubifs_branch_hash(c, br));
330 
331 	err = ubifs_write_node(c, idx, idx_node_size, main_first + DEFAULT_IDX_LEB, 0);
332 	if (err)
333 		goto out;
334 
335 	ubifs_node_calc_hash(c, idx, hash);
336 	ubifs_copy_hash(c, hash, mst->hash_root_idx);
337 
338 	err = ubifs_write_node_hmac(c, mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM, 0,
339 		offsetof(struct ubifs_mst_node, hmac));
340 	if (err)
341 		goto out;
342 
343 	err = ubifs_write_node_hmac(c, mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM + 1,
344 			       0, offsetof(struct ubifs_mst_node, hmac));
345 	if (err)
346 		goto out;
347 
348 	err = ubifs_write_node(c, cs, UBIFS_CS_NODE_SZ, UBIFS_LOG_LNUM, 0);
349 	if (err)
350 		goto out;
351 
352 	ubifs_msg(c, "default file-system created");
353 
354 	err = 0;
355 out:
356 	kfree(sup);
357 	kfree(mst);
358 	kfree(idx);
359 	kfree(ino);
360 	kfree(cs);
361 
362 	return err;
363 }
364 
365 /**
366  * validate_sb - validate superblock node.
367  * @c: UBIFS file-system description object
368  * @sup: superblock node
369  *
370  * This function validates superblock node @sup. Since most of data was read
371  * from the superblock and stored in @c, the function validates fields in @c
372  * instead. Returns zero in case of success and %-EINVAL in case of validation
373  * failure.
374  */
375 static int validate_sb(struct ubifs_info *c, struct ubifs_sb_node *sup)
376 {
377 	long long max_bytes;
378 	int err = 1, min_leb_cnt;
379 
380 	if (!c->key_hash) {
381 		err = 2;
382 		goto failed;
383 	}
384 
385 	if (sup->key_fmt != UBIFS_SIMPLE_KEY_FMT) {
386 		err = 3;
387 		goto failed;
388 	}
389 
390 	if (le32_to_cpu(sup->min_io_size) != c->min_io_size) {
391 		ubifs_err(c, "min. I/O unit mismatch: %d in superblock, %d real",
392 			  le32_to_cpu(sup->min_io_size), c->min_io_size);
393 		goto failed;
394 	}
395 
396 	if (le32_to_cpu(sup->leb_size) != c->leb_size) {
397 		ubifs_err(c, "LEB size mismatch: %d in superblock, %d real",
398 			  le32_to_cpu(sup->leb_size), c->leb_size);
399 		goto failed;
400 	}
401 
402 	if (c->log_lebs < UBIFS_MIN_LOG_LEBS ||
403 	    c->lpt_lebs < UBIFS_MIN_LPT_LEBS ||
404 	    c->orph_lebs < UBIFS_MIN_ORPH_LEBS ||
405 	    c->main_lebs < UBIFS_MIN_MAIN_LEBS) {
406 		err = 4;
407 		goto failed;
408 	}
409 
410 	/*
411 	 * Calculate minimum allowed amount of main area LEBs. This is very
412 	 * similar to %UBIFS_MIN_LEB_CNT, but we take into account real what we
413 	 * have just read from the superblock.
414 	 */
415 	min_leb_cnt = UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs;
416 	min_leb_cnt += c->lpt_lebs + c->orph_lebs + c->jhead_cnt + 6;
417 
418 	if (c->leb_cnt < min_leb_cnt || c->leb_cnt > c->vi.size) {
419 		ubifs_err(c, "bad LEB count: %d in superblock, %d on UBI volume, %d minimum required",
420 			  c->leb_cnt, c->vi.size, min_leb_cnt);
421 		goto failed;
422 	}
423 
424 	if (c->max_leb_cnt < c->leb_cnt) {
425 		ubifs_err(c, "max. LEB count %d less than LEB count %d",
426 			  c->max_leb_cnt, c->leb_cnt);
427 		goto failed;
428 	}
429 
430 	if (c->main_lebs < UBIFS_MIN_MAIN_LEBS) {
431 		ubifs_err(c, "too few main LEBs count %d, must be at least %d",
432 			  c->main_lebs, UBIFS_MIN_MAIN_LEBS);
433 		goto failed;
434 	}
435 
436 	max_bytes = (long long)c->leb_size * UBIFS_MIN_BUD_LEBS;
437 	if (c->max_bud_bytes < max_bytes) {
438 		ubifs_err(c, "too small journal (%lld bytes), must be at least %lld bytes",
439 			  c->max_bud_bytes, max_bytes);
440 		goto failed;
441 	}
442 
443 	max_bytes = (long long)c->leb_size * c->main_lebs;
444 	if (c->max_bud_bytes > max_bytes) {
445 		ubifs_err(c, "too large journal size (%lld bytes), only %lld bytes available in the main area",
446 			  c->max_bud_bytes, max_bytes);
447 		goto failed;
448 	}
449 
450 	if (c->jhead_cnt < NONDATA_JHEADS_CNT + 1 ||
451 	    c->jhead_cnt > NONDATA_JHEADS_CNT + UBIFS_MAX_JHEADS) {
452 		err = 9;
453 		goto failed;
454 	}
455 
456 	if (c->fanout < UBIFS_MIN_FANOUT ||
457 	    ubifs_idx_node_sz(c, c->fanout) > c->leb_size) {
458 		err = 10;
459 		goto failed;
460 	}
461 
462 	if (c->lsave_cnt < 0 || (c->lsave_cnt > DEFAULT_LSAVE_CNT &&
463 	    c->lsave_cnt > c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS -
464 	    c->log_lebs - c->lpt_lebs - c->orph_lebs)) {
465 		err = 11;
466 		goto failed;
467 	}
468 
469 	if (UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs + c->lpt_lebs +
470 	    c->orph_lebs + c->main_lebs != c->leb_cnt) {
471 		err = 12;
472 		goto failed;
473 	}
474 
475 	if (c->default_compr >= UBIFS_COMPR_TYPES_CNT) {
476 		err = 13;
477 		goto failed;
478 	}
479 
480 	if (c->rp_size < 0 || max_bytes < c->rp_size) {
481 		err = 14;
482 		goto failed;
483 	}
484 
485 	if (le32_to_cpu(sup->time_gran) > 1000000000 ||
486 	    le32_to_cpu(sup->time_gran) < 1) {
487 		err = 15;
488 		goto failed;
489 	}
490 
491 	if (!c->double_hash && c->fmt_version >= 5) {
492 		err = 16;
493 		goto failed;
494 	}
495 
496 	if (c->encrypted && c->fmt_version < 5) {
497 		err = 17;
498 		goto failed;
499 	}
500 
501 	return 0;
502 
503 failed:
504 	ubifs_err(c, "bad superblock, error %d", err);
505 	ubifs_dump_node(c, sup);
506 	return -EINVAL;
507 }
508 
509 /**
510  * ubifs_read_sb_node - read superblock node.
511  * @c: UBIFS file-system description object
512  *
513  * This function returns a pointer to the superblock node or a negative error
514  * code. Note, the user of this function is responsible of kfree()'ing the
515  * returned superblock buffer.
516  */
517 static struct ubifs_sb_node *ubifs_read_sb_node(struct ubifs_info *c)
518 {
519 	struct ubifs_sb_node *sup;
520 	int err;
521 
522 	sup = kmalloc(ALIGN(UBIFS_SB_NODE_SZ, c->min_io_size), GFP_NOFS);
523 	if (!sup)
524 		return ERR_PTR(-ENOMEM);
525 
526 	err = ubifs_read_node(c, sup, UBIFS_SB_NODE, UBIFS_SB_NODE_SZ,
527 			      UBIFS_SB_LNUM, 0);
528 	if (err) {
529 		kfree(sup);
530 		return ERR_PTR(err);
531 	}
532 
533 	return sup;
534 }
535 
536 static int authenticate_sb_node(struct ubifs_info *c,
537 				const struct ubifs_sb_node *sup)
538 {
539 	unsigned int sup_flags = le32_to_cpu(sup->flags);
540 	u8 hmac_wkm[UBIFS_HMAC_ARR_SZ];
541 	int authenticated = !!(sup_flags & UBIFS_FLG_AUTHENTICATION);
542 	int hash_algo;
543 	int err;
544 
545 	if (c->authenticated && !authenticated) {
546 		ubifs_err(c, "authenticated FS forced, but found FS without authentication");
547 		return -EINVAL;
548 	}
549 
550 	if (!c->authenticated && authenticated) {
551 		ubifs_err(c, "authenticated FS found, but no key given");
552 		return -EINVAL;
553 	}
554 
555 	ubifs_msg(c, "Mounting in %sauthenticated mode",
556 		  c->authenticated ? "" : "un");
557 
558 	if (!c->authenticated)
559 		return 0;
560 
561 	if (!IS_ENABLED(CONFIG_UBIFS_FS_AUTHENTICATION))
562 		return -EOPNOTSUPP;
563 
564 	hash_algo = le16_to_cpu(sup->hash_algo);
565 	if (hash_algo >= HASH_ALGO__LAST) {
566 		ubifs_err(c, "superblock uses unknown hash algo %d",
567 			  hash_algo);
568 		return -EINVAL;
569 	}
570 
571 	if (strcmp(hash_algo_name[hash_algo], c->auth_hash_name)) {
572 		ubifs_err(c, "This filesystem uses %s for hashing,"
573 			     " but %s is specified", hash_algo_name[hash_algo],
574 			     c->auth_hash_name);
575 		return -EINVAL;
576 	}
577 
578 	/*
579 	 * The super block node can either be authenticated by a HMAC or
580 	 * by a signature in a ubifs_sig_node directly following the
581 	 * super block node to support offline image creation.
582 	 */
583 	if (ubifs_hmac_zero(c, sup->hmac)) {
584 		err = ubifs_sb_verify_signature(c, sup);
585 	} else {
586 		err = ubifs_hmac_wkm(c, hmac_wkm);
587 		if (err)
588 			return err;
589 		if (ubifs_check_hmac(c, hmac_wkm, sup->hmac_wkm)) {
590 			ubifs_err(c, "provided key does not fit");
591 			return -ENOKEY;
592 		}
593 		err = ubifs_node_verify_hmac(c, sup, sizeof(*sup),
594 					     offsetof(struct ubifs_sb_node,
595 						      hmac));
596 	}
597 
598 	if (err)
599 		ubifs_err(c, "Failed to authenticate superblock: %d", err);
600 
601 	return err;
602 }
603 
604 /**
605  * ubifs_write_sb_node - write superblock node.
606  * @c: UBIFS file-system description object
607  * @sup: superblock node read with 'ubifs_read_sb_node()'
608  *
609  * This function returns %0 on success and a negative error code on failure.
610  */
611 int ubifs_write_sb_node(struct ubifs_info *c, struct ubifs_sb_node *sup)
612 {
613 	int len = ALIGN(UBIFS_SB_NODE_SZ, c->min_io_size);
614 	int err;
615 
616 	err = ubifs_prepare_node_hmac(c, sup, UBIFS_SB_NODE_SZ,
617 				      offsetof(struct ubifs_sb_node, hmac), 1);
618 	if (err)
619 		return err;
620 
621 	return ubifs_leb_change(c, UBIFS_SB_LNUM, sup, len);
622 }
623 
624 /**
625  * ubifs_read_superblock - read superblock.
626  * @c: UBIFS file-system description object
627  *
628  * This function finds, reads and checks the superblock. If an empty UBI volume
629  * is being mounted, this function creates default superblock. Returns zero in
630  * case of success, and a negative error code in case of failure.
631  */
632 int ubifs_read_superblock(struct ubifs_info *c)
633 {
634 	int err, sup_flags;
635 	struct ubifs_sb_node *sup;
636 
637 	if (c->empty) {
638 		err = create_default_filesystem(c);
639 		if (err)
640 			return err;
641 	}
642 
643 	sup = ubifs_read_sb_node(c);
644 	if (IS_ERR(sup))
645 		return PTR_ERR(sup);
646 
647 	c->sup_node = sup;
648 
649 	c->fmt_version = le32_to_cpu(sup->fmt_version);
650 	c->ro_compat_version = le32_to_cpu(sup->ro_compat_version);
651 
652 	/*
653 	 * The software supports all previous versions but not future versions,
654 	 * due to the unavailability of time-travelling equipment.
655 	 */
656 	if (c->fmt_version > UBIFS_FORMAT_VERSION) {
657 		ubifs_assert(c, !c->ro_media || c->ro_mount);
658 		if (!c->ro_mount ||
659 		    c->ro_compat_version > UBIFS_RO_COMPAT_VERSION) {
660 			ubifs_err(c, "on-flash format version is w%d/r%d, but software only supports up to version w%d/r%d",
661 				  c->fmt_version, c->ro_compat_version,
662 				  UBIFS_FORMAT_VERSION,
663 				  UBIFS_RO_COMPAT_VERSION);
664 			if (c->ro_compat_version <= UBIFS_RO_COMPAT_VERSION) {
665 				ubifs_msg(c, "only R/O mounting is possible");
666 				err = -EROFS;
667 			} else
668 				err = -EINVAL;
669 			goto out;
670 		}
671 
672 		/*
673 		 * The FS is mounted R/O, and the media format is
674 		 * R/O-compatible with the UBIFS implementation, so we can
675 		 * mount.
676 		 */
677 		c->rw_incompat = 1;
678 	}
679 
680 	if (c->fmt_version < 3) {
681 		ubifs_err(c, "on-flash format version %d is not supported",
682 			  c->fmt_version);
683 		err = -EINVAL;
684 		goto out;
685 	}
686 
687 	switch (sup->key_hash) {
688 	case UBIFS_KEY_HASH_R5:
689 		c->key_hash = key_r5_hash;
690 		c->key_hash_type = UBIFS_KEY_HASH_R5;
691 		break;
692 
693 	case UBIFS_KEY_HASH_TEST:
694 		c->key_hash = key_test_hash;
695 		c->key_hash_type = UBIFS_KEY_HASH_TEST;
696 		break;
697 	}
698 
699 	c->key_fmt = sup->key_fmt;
700 
701 	switch (c->key_fmt) {
702 	case UBIFS_SIMPLE_KEY_FMT:
703 		c->key_len = UBIFS_SK_LEN;
704 		break;
705 	default:
706 		ubifs_err(c, "unsupported key format");
707 		err = -EINVAL;
708 		goto out;
709 	}
710 
711 	c->leb_cnt       = le32_to_cpu(sup->leb_cnt);
712 	c->max_leb_cnt   = le32_to_cpu(sup->max_leb_cnt);
713 	c->max_bud_bytes = le64_to_cpu(sup->max_bud_bytes);
714 	c->log_lebs      = le32_to_cpu(sup->log_lebs);
715 	c->lpt_lebs      = le32_to_cpu(sup->lpt_lebs);
716 	c->orph_lebs     = le32_to_cpu(sup->orph_lebs);
717 	c->jhead_cnt     = le32_to_cpu(sup->jhead_cnt) + NONDATA_JHEADS_CNT;
718 	c->fanout        = le32_to_cpu(sup->fanout);
719 	c->lsave_cnt     = le32_to_cpu(sup->lsave_cnt);
720 	c->rp_size       = le64_to_cpu(sup->rp_size);
721 	c->rp_uid        = make_kuid(&init_user_ns, le32_to_cpu(sup->rp_uid));
722 	c->rp_gid        = make_kgid(&init_user_ns, le32_to_cpu(sup->rp_gid));
723 	sup_flags        = le32_to_cpu(sup->flags);
724 	if (!c->mount_opts.override_compr)
725 		c->default_compr = le16_to_cpu(sup->default_compr);
726 
727 	c->vfs_sb->s_time_gran = le32_to_cpu(sup->time_gran);
728 	memcpy(&c->uuid, &sup->uuid, 16);
729 	c->big_lpt = !!(sup_flags & UBIFS_FLG_BIGLPT);
730 	c->space_fixup = !!(sup_flags & UBIFS_FLG_SPACE_FIXUP);
731 	c->double_hash = !!(sup_flags & UBIFS_FLG_DOUBLE_HASH);
732 	c->encrypted = !!(sup_flags & UBIFS_FLG_ENCRYPTION);
733 
734 	err = authenticate_sb_node(c, sup);
735 	if (err)
736 		goto out;
737 
738 	if ((sup_flags & ~UBIFS_FLG_MASK) != 0) {
739 		ubifs_err(c, "Unknown feature flags found: %#x",
740 			  sup_flags & ~UBIFS_FLG_MASK);
741 		err = -EINVAL;
742 		goto out;
743 	}
744 
745 	if (!IS_ENABLED(CONFIG_FS_ENCRYPTION) && c->encrypted) {
746 		ubifs_err(c, "file system contains encrypted files but UBIFS"
747 			     " was built without crypto support.");
748 		err = -EINVAL;
749 		goto out;
750 	}
751 
752 	/* Automatically increase file system size to the maximum size */
753 	if (c->leb_cnt < c->vi.size && c->leb_cnt < c->max_leb_cnt) {
754 		int old_leb_cnt = c->leb_cnt;
755 
756 		c->leb_cnt = min_t(int, c->max_leb_cnt, c->vi.size);
757 		sup->leb_cnt = cpu_to_le32(c->leb_cnt);
758 
759 		c->superblock_need_write = 1;
760 
761 		dbg_mnt("Auto resizing from %d LEBs to %d LEBs",
762 			old_leb_cnt, c->leb_cnt);
763 	}
764 
765 	c->log_bytes = (long long)c->log_lebs * c->leb_size;
766 	c->log_last = UBIFS_LOG_LNUM + c->log_lebs - 1;
767 	c->lpt_first = UBIFS_LOG_LNUM + c->log_lebs;
768 	c->lpt_last = c->lpt_first + c->lpt_lebs - 1;
769 	c->orph_first = c->lpt_last + 1;
770 	c->orph_last = c->orph_first + c->orph_lebs - 1;
771 	c->main_lebs = c->leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS;
772 	c->main_lebs -= c->log_lebs + c->lpt_lebs + c->orph_lebs;
773 	c->main_first = c->leb_cnt - c->main_lebs;
774 
775 	err = validate_sb(c, sup);
776 out:
777 	return err;
778 }
779 
780 /**
781  * fixup_leb - fixup/unmap an LEB containing free space.
782  * @c: UBIFS file-system description object
783  * @lnum: the LEB number to fix up
784  * @len: number of used bytes in LEB (starting at offset 0)
785  *
786  * This function reads the contents of the given LEB number @lnum, then fixes
787  * it up, so that empty min. I/O units in the end of LEB are actually erased on
788  * flash (rather than being just all-0xff real data). If the LEB is completely
789  * empty, it is simply unmapped.
790  */
791 static int fixup_leb(struct ubifs_info *c, int lnum, int len)
792 {
793 	int err;
794 
795 	ubifs_assert(c, len >= 0);
796 	ubifs_assert(c, len % c->min_io_size == 0);
797 	ubifs_assert(c, len < c->leb_size);
798 
799 	if (len == 0) {
800 		dbg_mnt("unmap empty LEB %d", lnum);
801 		return ubifs_leb_unmap(c, lnum);
802 	}
803 
804 	dbg_mnt("fixup LEB %d, data len %d", lnum, len);
805 	err = ubifs_leb_read(c, lnum, c->sbuf, 0, len, 1);
806 	if (err)
807 		return err;
808 
809 	return ubifs_leb_change(c, lnum, c->sbuf, len);
810 }
811 
812 /**
813  * fixup_free_space - find & remap all LEBs containing free space.
814  * @c: UBIFS file-system description object
815  *
816  * This function walks through all LEBs in the filesystem and fiexes up those
817  * containing free/empty space.
818  */
819 static int fixup_free_space(struct ubifs_info *c)
820 {
821 	int lnum, err = 0;
822 	struct ubifs_lprops *lprops;
823 
824 	ubifs_get_lprops(c);
825 
826 	/* Fixup LEBs in the master area */
827 	for (lnum = UBIFS_MST_LNUM; lnum < UBIFS_LOG_LNUM; lnum++) {
828 		err = fixup_leb(c, lnum, c->mst_offs + c->mst_node_alsz);
829 		if (err)
830 			goto out;
831 	}
832 
833 	/* Unmap unused log LEBs */
834 	lnum = ubifs_next_log_lnum(c, c->lhead_lnum);
835 	while (lnum != c->ltail_lnum) {
836 		err = fixup_leb(c, lnum, 0);
837 		if (err)
838 			goto out;
839 		lnum = ubifs_next_log_lnum(c, lnum);
840 	}
841 
842 	/*
843 	 * Fixup the log head which contains the only a CS node at the
844 	 * beginning.
845 	 */
846 	err = fixup_leb(c, c->lhead_lnum,
847 			ALIGN(UBIFS_CS_NODE_SZ, c->min_io_size));
848 	if (err)
849 		goto out;
850 
851 	/* Fixup LEBs in the LPT area */
852 	for (lnum = c->lpt_first; lnum <= c->lpt_last; lnum++) {
853 		int free = c->ltab[lnum - c->lpt_first].free;
854 
855 		if (free > 0) {
856 			err = fixup_leb(c, lnum, c->leb_size - free);
857 			if (err)
858 				goto out;
859 		}
860 	}
861 
862 	/* Unmap LEBs in the orphans area */
863 	for (lnum = c->orph_first; lnum <= c->orph_last; lnum++) {
864 		err = fixup_leb(c, lnum, 0);
865 		if (err)
866 			goto out;
867 	}
868 
869 	/* Fixup LEBs in the main area */
870 	for (lnum = c->main_first; lnum < c->leb_cnt; lnum++) {
871 		lprops = ubifs_lpt_lookup(c, lnum);
872 		if (IS_ERR(lprops)) {
873 			err = PTR_ERR(lprops);
874 			goto out;
875 		}
876 
877 		if (lprops->free > 0) {
878 			err = fixup_leb(c, lnum, c->leb_size - lprops->free);
879 			if (err)
880 				goto out;
881 		}
882 	}
883 
884 out:
885 	ubifs_release_lprops(c);
886 	return err;
887 }
888 
889 /**
890  * ubifs_fixup_free_space - find & fix all LEBs with free space.
891  * @c: UBIFS file-system description object
892  *
893  * This function fixes up LEBs containing free space on first mount, if the
894  * appropriate flag was set when the FS was created. Each LEB with one or more
895  * empty min. I/O unit (i.e. free-space-count > 0) is re-written, to make sure
896  * the free space is actually erased. E.g., this is necessary for some NAND
897  * chips, since the free space may have been programmed like real "0xff" data
898  * (generating a non-0xff ECC), causing future writes to the not-really-erased
899  * NAND pages to behave badly. After the space is fixed up, the superblock flag
900  * is cleared, so that this is skipped for all future mounts.
901  */
902 int ubifs_fixup_free_space(struct ubifs_info *c)
903 {
904 	int err;
905 	struct ubifs_sb_node *sup = c->sup_node;
906 
907 	ubifs_assert(c, c->space_fixup);
908 	ubifs_assert(c, !c->ro_mount);
909 
910 	ubifs_msg(c, "start fixing up free space");
911 
912 	err = fixup_free_space(c);
913 	if (err)
914 		return err;
915 
916 	/* Free-space fixup is no longer required */
917 	c->space_fixup = 0;
918 	sup->flags &= cpu_to_le32(~UBIFS_FLG_SPACE_FIXUP);
919 
920 	c->superblock_need_write = 1;
921 
922 	ubifs_msg(c, "free space fixup complete");
923 	return err;
924 }
925 
926 int ubifs_enable_encryption(struct ubifs_info *c)
927 {
928 	int err;
929 	struct ubifs_sb_node *sup = c->sup_node;
930 
931 	if (!IS_ENABLED(CONFIG_FS_ENCRYPTION))
932 		return -EOPNOTSUPP;
933 
934 	if (c->encrypted)
935 		return 0;
936 
937 	if (c->ro_mount || c->ro_media)
938 		return -EROFS;
939 
940 	if (c->fmt_version < 5) {
941 		ubifs_err(c, "on-flash format version 5 is needed for encryption");
942 		return -EINVAL;
943 	}
944 
945 	sup->flags |= cpu_to_le32(UBIFS_FLG_ENCRYPTION);
946 
947 	err = ubifs_write_sb_node(c, sup);
948 	if (!err)
949 		c->encrypted = 1;
950 
951 	return err;
952 }
953