1 /*
2  * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 as published by
8  * the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * Authors: Adrian Hunter
20  *          Artem Bityutskiy (Битюцкий Артём)
21  */
22 
23 /* This file implements TNC functions for committing */
24 
25 #include <linux/random.h>
26 #include "ubifs.h"
27 
28 /**
29  * make_idx_node - make an index node for fill-the-gaps method of TNC commit.
30  * @c: UBIFS file-system description object
31  * @idx: buffer in which to place new index node
32  * @znode: znode from which to make new index node
33  * @lnum: LEB number where new index node will be written
34  * @offs: offset where new index node will be written
35  * @len: length of new index node
36  */
make_idx_node(struct ubifs_info * c,struct ubifs_idx_node * idx,struct ubifs_znode * znode,int lnum,int offs,int len)37 static int make_idx_node(struct ubifs_info *c, struct ubifs_idx_node *idx,
38 			 struct ubifs_znode *znode, int lnum, int offs, int len)
39 {
40 	struct ubifs_znode *zp;
41 	int i, err;
42 
43 	/* Make index node */
44 	idx->ch.node_type = UBIFS_IDX_NODE;
45 	idx->child_cnt = cpu_to_le16(znode->child_cnt);
46 	idx->level = cpu_to_le16(znode->level);
47 	for (i = 0; i < znode->child_cnt; i++) {
48 		struct ubifs_branch *br = ubifs_idx_branch(c, idx, i);
49 		struct ubifs_zbranch *zbr = &znode->zbranch[i];
50 
51 		key_write_idx(c, &zbr->key, &br->key);
52 		br->lnum = cpu_to_le32(zbr->lnum);
53 		br->offs = cpu_to_le32(zbr->offs);
54 		br->len = cpu_to_le32(zbr->len);
55 		if (!zbr->lnum || !zbr->len) {
56 			ubifs_err(c, "bad ref in znode");
57 			ubifs_dump_znode(c, znode);
58 			if (zbr->znode)
59 				ubifs_dump_znode(c, zbr->znode);
60 
61 			return -EINVAL;
62 		}
63 	}
64 	ubifs_prepare_node(c, idx, len, 0);
65 
66 	znode->lnum = lnum;
67 	znode->offs = offs;
68 	znode->len = len;
69 
70 	err = insert_old_idx_znode(c, znode);
71 
72 	/* Update the parent */
73 	zp = znode->parent;
74 	if (zp) {
75 		struct ubifs_zbranch *zbr;
76 
77 		zbr = &zp->zbranch[znode->iip];
78 		zbr->lnum = lnum;
79 		zbr->offs = offs;
80 		zbr->len = len;
81 	} else {
82 		c->zroot.lnum = lnum;
83 		c->zroot.offs = offs;
84 		c->zroot.len = len;
85 	}
86 	c->calc_idx_sz += ALIGN(len, 8);
87 
88 	atomic_long_dec(&c->dirty_zn_cnt);
89 
90 	ubifs_assert(c, ubifs_zn_dirty(znode));
91 	ubifs_assert(c, ubifs_zn_cow(znode));
92 
93 	/*
94 	 * Note, unlike 'write_index()' we do not add memory barriers here
95 	 * because this function is called with @c->tnc_mutex locked.
96 	 */
97 	__clear_bit(DIRTY_ZNODE, &znode->flags);
98 	__clear_bit(COW_ZNODE, &znode->flags);
99 
100 	return err;
101 }
102 
103 /**
104  * fill_gap - make index nodes in gaps in dirty index LEBs.
105  * @c: UBIFS file-system description object
106  * @lnum: LEB number that gap appears in
107  * @gap_start: offset of start of gap
108  * @gap_end: offset of end of gap
109  * @dirt: adds dirty space to this
110  *
111  * This function returns the number of index nodes written into the gap.
112  */
fill_gap(struct ubifs_info * c,int lnum,int gap_start,int gap_end,int * dirt)113 static int fill_gap(struct ubifs_info *c, int lnum, int gap_start, int gap_end,
114 		    int *dirt)
115 {
116 	int len, gap_remains, gap_pos, written, pad_len;
117 
118 	ubifs_assert(c, (gap_start & 7) == 0);
119 	ubifs_assert(c, (gap_end & 7) == 0);
120 	ubifs_assert(c, gap_end >= gap_start);
121 
122 	gap_remains = gap_end - gap_start;
123 	if (!gap_remains)
124 		return 0;
125 	gap_pos = gap_start;
126 	written = 0;
127 	while (c->enext) {
128 		len = ubifs_idx_node_sz(c, c->enext->child_cnt);
129 		if (len < gap_remains) {
130 			struct ubifs_znode *znode = c->enext;
131 			const int alen = ALIGN(len, 8);
132 			int err;
133 
134 			ubifs_assert(c, alen <= gap_remains);
135 			err = make_idx_node(c, c->ileb_buf + gap_pos, znode,
136 					    lnum, gap_pos, len);
137 			if (err)
138 				return err;
139 			gap_remains -= alen;
140 			gap_pos += alen;
141 			c->enext = znode->cnext;
142 			if (c->enext == c->cnext)
143 				c->enext = NULL;
144 			written += 1;
145 		} else
146 			break;
147 	}
148 	if (gap_end == c->leb_size) {
149 		c->ileb_len = ALIGN(gap_pos, c->min_io_size);
150 		/* Pad to end of min_io_size */
151 		pad_len = c->ileb_len - gap_pos;
152 	} else
153 		/* Pad to end of gap */
154 		pad_len = gap_remains;
155 	dbg_gc("LEB %d:%d to %d len %d nodes written %d wasted bytes %d",
156 	       lnum, gap_start, gap_end, gap_end - gap_start, written, pad_len);
157 	ubifs_pad(c, c->ileb_buf + gap_pos, pad_len);
158 	*dirt += pad_len;
159 	return written;
160 }
161 
162 /**
163  * find_old_idx - find an index node obsoleted since the last commit start.
164  * @c: UBIFS file-system description object
165  * @lnum: LEB number of obsoleted index node
166  * @offs: offset of obsoleted index node
167  *
168  * Returns %1 if found and %0 otherwise.
169  */
find_old_idx(struct ubifs_info * c,int lnum,int offs)170 static int find_old_idx(struct ubifs_info *c, int lnum, int offs)
171 {
172 	struct ubifs_old_idx *o;
173 	struct rb_node *p;
174 
175 	p = c->old_idx.rb_node;
176 	while (p) {
177 		o = rb_entry(p, struct ubifs_old_idx, rb);
178 		if (lnum < o->lnum)
179 			p = p->rb_left;
180 		else if (lnum > o->lnum)
181 			p = p->rb_right;
182 		else if (offs < o->offs)
183 			p = p->rb_left;
184 		else if (offs > o->offs)
185 			p = p->rb_right;
186 		else
187 			return 1;
188 	}
189 	return 0;
190 }
191 
192 /**
193  * is_idx_node_in_use - determine if an index node can be overwritten.
194  * @c: UBIFS file-system description object
195  * @key: key of index node
196  * @level: index node level
197  * @lnum: LEB number of index node
198  * @offs: offset of index node
199  *
200  * If @key / @lnum / @offs identify an index node that was not part of the old
201  * index, then this function returns %0 (obsolete).  Else if the index node was
202  * part of the old index but is now dirty %1 is returned, else if it is clean %2
203  * is returned. A negative error code is returned on failure.
204  */
is_idx_node_in_use(struct ubifs_info * c,union ubifs_key * key,int level,int lnum,int offs)205 static int is_idx_node_in_use(struct ubifs_info *c, union ubifs_key *key,
206 			      int level, int lnum, int offs)
207 {
208 	int ret;
209 
210 	ret = is_idx_node_in_tnc(c, key, level, lnum, offs);
211 	if (ret < 0)
212 		return ret; /* Error code */
213 	if (ret == 0)
214 		if (find_old_idx(c, lnum, offs))
215 			return 1;
216 	return ret;
217 }
218 
219 /**
220  * layout_leb_in_gaps - layout index nodes using in-the-gaps method.
221  * @c: UBIFS file-system description object
222  * @p: return LEB number in @c->gap_lebs[p]
223  *
224  * This function lays out new index nodes for dirty znodes using in-the-gaps
225  * method of TNC commit.
226  * This function merely puts the next znode into the next gap, making no attempt
227  * to try to maximise the number of znodes that fit.
228  * This function returns the number of index nodes written into the gaps, or a
229  * negative error code on failure.
230  */
layout_leb_in_gaps(struct ubifs_info * c,int p)231 static int layout_leb_in_gaps(struct ubifs_info *c, int p)
232 {
233 	struct ubifs_scan_leb *sleb;
234 	struct ubifs_scan_node *snod;
235 	int lnum, dirt = 0, gap_start, gap_end, err, written, tot_written;
236 
237 	tot_written = 0;
238 	/* Get an index LEB with lots of obsolete index nodes */
239 	lnum = ubifs_find_dirty_idx_leb(c);
240 	if (lnum < 0)
241 		/*
242 		 * There also may be dirt in the index head that could be
243 		 * filled, however we do not check there at present.
244 		 */
245 		return lnum; /* Error code */
246 	c->gap_lebs[p] = lnum;
247 	dbg_gc("LEB %d", lnum);
248 	/*
249 	 * Scan the index LEB.  We use the generic scan for this even though
250 	 * it is more comprehensive and less efficient than is needed for this
251 	 * purpose.
252 	 */
253 	sleb = ubifs_scan(c, lnum, 0, c->ileb_buf, 0);
254 	c->ileb_len = 0;
255 	if (IS_ERR(sleb))
256 		return PTR_ERR(sleb);
257 	gap_start = 0;
258 	list_for_each_entry(snod, &sleb->nodes, list) {
259 		struct ubifs_idx_node *idx;
260 		int in_use, level;
261 
262 		ubifs_assert(c, snod->type == UBIFS_IDX_NODE);
263 		idx = snod->node;
264 		key_read(c, ubifs_idx_key(c, idx), &snod->key);
265 		level = le16_to_cpu(idx->level);
266 		/* Determine if the index node is in use (not obsolete) */
267 		in_use = is_idx_node_in_use(c, &snod->key, level, lnum,
268 					    snod->offs);
269 		if (in_use < 0) {
270 			ubifs_scan_destroy(sleb);
271 			return in_use; /* Error code */
272 		}
273 		if (in_use) {
274 			if (in_use == 1)
275 				dirt += ALIGN(snod->len, 8);
276 			/*
277 			 * The obsolete index nodes form gaps that can be
278 			 * overwritten.  This gap has ended because we have
279 			 * found an index node that is still in use
280 			 * i.e. not obsolete
281 			 */
282 			gap_end = snod->offs;
283 			/* Try to fill gap */
284 			written = fill_gap(c, lnum, gap_start, gap_end, &dirt);
285 			if (written < 0) {
286 				ubifs_scan_destroy(sleb);
287 				return written; /* Error code */
288 			}
289 			tot_written += written;
290 			gap_start = ALIGN(snod->offs + snod->len, 8);
291 		}
292 	}
293 	ubifs_scan_destroy(sleb);
294 	c->ileb_len = c->leb_size;
295 	gap_end = c->leb_size;
296 	/* Try to fill gap */
297 	written = fill_gap(c, lnum, gap_start, gap_end, &dirt);
298 	if (written < 0)
299 		return written; /* Error code */
300 	tot_written += written;
301 	if (tot_written == 0) {
302 		struct ubifs_lprops lp;
303 
304 		dbg_gc("LEB %d wrote %d index nodes", lnum, tot_written);
305 		err = ubifs_read_one_lp(c, lnum, &lp);
306 		if (err)
307 			return err;
308 		if (lp.free == c->leb_size) {
309 			/*
310 			 * We must have snatched this LEB from the idx_gc list
311 			 * so we need to correct the free and dirty space.
312 			 */
313 			err = ubifs_change_one_lp(c, lnum,
314 						  c->leb_size - c->ileb_len,
315 						  dirt, 0, 0, 0);
316 			if (err)
317 				return err;
318 		}
319 		return 0;
320 	}
321 	err = ubifs_change_one_lp(c, lnum, c->leb_size - c->ileb_len, dirt,
322 				  0, 0, 0);
323 	if (err)
324 		return err;
325 	err = ubifs_leb_change(c, lnum, c->ileb_buf, c->ileb_len);
326 	if (err)
327 		return err;
328 	dbg_gc("LEB %d wrote %d index nodes", lnum, tot_written);
329 	return tot_written;
330 }
331 
332 /**
333  * get_leb_cnt - calculate the number of empty LEBs needed to commit.
334  * @c: UBIFS file-system description object
335  * @cnt: number of znodes to commit
336  *
337  * This function returns the number of empty LEBs needed to commit @cnt znodes
338  * to the current index head.  The number is not exact and may be more than
339  * needed.
340  */
get_leb_cnt(struct ubifs_info * c,int cnt)341 static int get_leb_cnt(struct ubifs_info *c, int cnt)
342 {
343 	int d;
344 
345 	/* Assume maximum index node size (i.e. overestimate space needed) */
346 	cnt -= (c->leb_size - c->ihead_offs) / c->max_idx_node_sz;
347 	if (cnt < 0)
348 		cnt = 0;
349 	d = c->leb_size / c->max_idx_node_sz;
350 	return DIV_ROUND_UP(cnt, d);
351 }
352 
353 /**
354  * layout_in_gaps - in-the-gaps method of committing TNC.
355  * @c: UBIFS file-system description object
356  * @cnt: number of dirty znodes to commit.
357  *
358  * This function lays out new index nodes for dirty znodes using in-the-gaps
359  * method of TNC commit.
360  *
361  * This function returns %0 on success and a negative error code on failure.
362  */
layout_in_gaps(struct ubifs_info * c,int cnt)363 static int layout_in_gaps(struct ubifs_info *c, int cnt)
364 {
365 	int err, leb_needed_cnt, written, p = 0, old_idx_lebs, *gap_lebs;
366 
367 	dbg_gc("%d znodes to write", cnt);
368 
369 	c->gap_lebs = kmalloc_array(c->lst.idx_lebs + 1, sizeof(int),
370 				    GFP_NOFS);
371 	if (!c->gap_lebs)
372 		return -ENOMEM;
373 
374 	old_idx_lebs = c->lst.idx_lebs;
375 	do {
376 		ubifs_assert(c, p < c->lst.idx_lebs);
377 		written = layout_leb_in_gaps(c, p);
378 		if (written < 0) {
379 			err = written;
380 			if (err != -ENOSPC) {
381 				kfree(c->gap_lebs);
382 				c->gap_lebs = NULL;
383 				return err;
384 			}
385 			if (!dbg_is_chk_index(c)) {
386 				/*
387 				 * Do not print scary warnings if the debugging
388 				 * option which forces in-the-gaps is enabled.
389 				 */
390 				ubifs_warn(c, "out of space");
391 				ubifs_dump_budg(c, &c->bi);
392 				ubifs_dump_lprops(c);
393 			}
394 			/* Try to commit anyway */
395 			break;
396 		}
397 		p++;
398 		cnt -= written;
399 		leb_needed_cnt = get_leb_cnt(c, cnt);
400 		dbg_gc("%d znodes remaining, need %d LEBs, have %d", cnt,
401 		       leb_needed_cnt, c->ileb_cnt);
402 		/*
403 		 * Dynamically change the size of @c->gap_lebs to prevent
404 		 * oob, because @c->lst.idx_lebs could be increased by
405 		 * function @get_idx_gc_leb (called by layout_leb_in_gaps->
406 		 * ubifs_find_dirty_idx_leb) during loop. Only enlarge
407 		 * @c->gap_lebs when needed.
408 		 *
409 		 */
410 		if (leb_needed_cnt > c->ileb_cnt && p >= old_idx_lebs &&
411 		    old_idx_lebs < c->lst.idx_lebs) {
412 			old_idx_lebs = c->lst.idx_lebs;
413 			gap_lebs = krealloc(c->gap_lebs, sizeof(int) *
414 					       (old_idx_lebs + 1), GFP_NOFS);
415 			if (!gap_lebs) {
416 				kfree(c->gap_lebs);
417 				c->gap_lebs = NULL;
418 				return -ENOMEM;
419 			}
420 			c->gap_lebs = gap_lebs;
421 		}
422 	} while (leb_needed_cnt > c->ileb_cnt);
423 
424 	c->gap_lebs[p] = -1;
425 	return 0;
426 }
427 
428 /**
429  * layout_in_empty_space - layout index nodes in empty space.
430  * @c: UBIFS file-system description object
431  *
432  * This function lays out new index nodes for dirty znodes using empty LEBs.
433  *
434  * This function returns %0 on success and a negative error code on failure.
435  */
layout_in_empty_space(struct ubifs_info * c)436 static int layout_in_empty_space(struct ubifs_info *c)
437 {
438 	struct ubifs_znode *znode, *cnext, *zp;
439 	int lnum, offs, len, next_len, buf_len, buf_offs, used, avail;
440 	int wlen, blen, err;
441 
442 	cnext = c->enext;
443 	if (!cnext)
444 		return 0;
445 
446 	lnum = c->ihead_lnum;
447 	buf_offs = c->ihead_offs;
448 
449 	buf_len = ubifs_idx_node_sz(c, c->fanout);
450 	buf_len = ALIGN(buf_len, c->min_io_size);
451 	used = 0;
452 	avail = buf_len;
453 
454 	/* Ensure there is enough room for first write */
455 	next_len = ubifs_idx_node_sz(c, cnext->child_cnt);
456 	if (buf_offs + next_len > c->leb_size)
457 		lnum = -1;
458 
459 	while (1) {
460 		znode = cnext;
461 
462 		len = ubifs_idx_node_sz(c, znode->child_cnt);
463 
464 		/* Determine the index node position */
465 		if (lnum == -1) {
466 			if (c->ileb_nxt >= c->ileb_cnt) {
467 				ubifs_err(c, "out of space");
468 				return -ENOSPC;
469 			}
470 			lnum = c->ilebs[c->ileb_nxt++];
471 			buf_offs = 0;
472 			used = 0;
473 			avail = buf_len;
474 		}
475 
476 		offs = buf_offs + used;
477 
478 		znode->lnum = lnum;
479 		znode->offs = offs;
480 		znode->len = len;
481 
482 		/* Update the parent */
483 		zp = znode->parent;
484 		if (zp) {
485 			struct ubifs_zbranch *zbr;
486 			int i;
487 
488 			i = znode->iip;
489 			zbr = &zp->zbranch[i];
490 			zbr->lnum = lnum;
491 			zbr->offs = offs;
492 			zbr->len = len;
493 		} else {
494 			c->zroot.lnum = lnum;
495 			c->zroot.offs = offs;
496 			c->zroot.len = len;
497 		}
498 		c->calc_idx_sz += ALIGN(len, 8);
499 
500 		/*
501 		 * Once lprops is updated, we can decrease the dirty znode count
502 		 * but it is easier to just do it here.
503 		 */
504 		atomic_long_dec(&c->dirty_zn_cnt);
505 
506 		/*
507 		 * Calculate the next index node length to see if there is
508 		 * enough room for it
509 		 */
510 		cnext = znode->cnext;
511 		if (cnext == c->cnext)
512 			next_len = 0;
513 		else
514 			next_len = ubifs_idx_node_sz(c, cnext->child_cnt);
515 
516 		/* Update buffer positions */
517 		wlen = used + len;
518 		used += ALIGN(len, 8);
519 		avail -= ALIGN(len, 8);
520 
521 		if (next_len != 0 &&
522 		    buf_offs + used + next_len <= c->leb_size &&
523 		    avail > 0)
524 			continue;
525 
526 		if (avail <= 0 && next_len &&
527 		    buf_offs + used + next_len <= c->leb_size)
528 			blen = buf_len;
529 		else
530 			blen = ALIGN(wlen, c->min_io_size);
531 
532 		/* The buffer is full or there are no more znodes to do */
533 		buf_offs += blen;
534 		if (next_len) {
535 			if (buf_offs + next_len > c->leb_size) {
536 				err = ubifs_update_one_lp(c, lnum,
537 					c->leb_size - buf_offs, blen - used,
538 					0, 0);
539 				if (err)
540 					return err;
541 				lnum = -1;
542 			}
543 			used -= blen;
544 			if (used < 0)
545 				used = 0;
546 			avail = buf_len - used;
547 			continue;
548 		}
549 		err = ubifs_update_one_lp(c, lnum, c->leb_size - buf_offs,
550 					  blen - used, 0, 0);
551 		if (err)
552 			return err;
553 		break;
554 	}
555 
556 	c->dbg->new_ihead_lnum = lnum;
557 	c->dbg->new_ihead_offs = buf_offs;
558 
559 	return 0;
560 }
561 
562 /**
563  * layout_commit - determine positions of index nodes to commit.
564  * @c: UBIFS file-system description object
565  * @no_space: indicates that insufficient empty LEBs were allocated
566  * @cnt: number of znodes to commit
567  *
568  * Calculate and update the positions of index nodes to commit.  If there were
569  * an insufficient number of empty LEBs allocated, then index nodes are placed
570  * into the gaps created by obsolete index nodes in non-empty index LEBs.  For
571  * this purpose, an obsolete index node is one that was not in the index as at
572  * the end of the last commit.  To write "in-the-gaps" requires that those index
573  * LEBs are updated atomically in-place.
574  */
layout_commit(struct ubifs_info * c,int no_space,int cnt)575 static int layout_commit(struct ubifs_info *c, int no_space, int cnt)
576 {
577 	int err;
578 
579 	if (no_space) {
580 		err = layout_in_gaps(c, cnt);
581 		if (err)
582 			return err;
583 	}
584 	err = layout_in_empty_space(c);
585 	return err;
586 }
587 
588 /**
589  * find_first_dirty - find first dirty znode.
590  * @znode: znode to begin searching from
591  */
find_first_dirty(struct ubifs_znode * znode)592 static struct ubifs_znode *find_first_dirty(struct ubifs_znode *znode)
593 {
594 	int i, cont;
595 
596 	if (!znode)
597 		return NULL;
598 
599 	while (1) {
600 		if (znode->level == 0) {
601 			if (ubifs_zn_dirty(znode))
602 				return znode;
603 			return NULL;
604 		}
605 		cont = 0;
606 		for (i = 0; i < znode->child_cnt; i++) {
607 			struct ubifs_zbranch *zbr = &znode->zbranch[i];
608 
609 			if (zbr->znode && ubifs_zn_dirty(zbr->znode)) {
610 				znode = zbr->znode;
611 				cont = 1;
612 				break;
613 			}
614 		}
615 		if (!cont) {
616 			if (ubifs_zn_dirty(znode))
617 				return znode;
618 			return NULL;
619 		}
620 	}
621 }
622 
623 /**
624  * find_next_dirty - find next dirty znode.
625  * @znode: znode to begin searching from
626  */
find_next_dirty(struct ubifs_znode * znode)627 static struct ubifs_znode *find_next_dirty(struct ubifs_znode *znode)
628 {
629 	int n = znode->iip + 1;
630 
631 	znode = znode->parent;
632 	if (!znode)
633 		return NULL;
634 	for (; n < znode->child_cnt; n++) {
635 		struct ubifs_zbranch *zbr = &znode->zbranch[n];
636 
637 		if (zbr->znode && ubifs_zn_dirty(zbr->znode))
638 			return find_first_dirty(zbr->znode);
639 	}
640 	return znode;
641 }
642 
643 /**
644  * get_znodes_to_commit - create list of dirty znodes to commit.
645  * @c: UBIFS file-system description object
646  *
647  * This function returns the number of znodes to commit.
648  */
get_znodes_to_commit(struct ubifs_info * c)649 static int get_znodes_to_commit(struct ubifs_info *c)
650 {
651 	struct ubifs_znode *znode, *cnext;
652 	int cnt = 0;
653 
654 	c->cnext = find_first_dirty(c->zroot.znode);
655 	znode = c->enext = c->cnext;
656 	if (!znode) {
657 		dbg_cmt("no znodes to commit");
658 		return 0;
659 	}
660 	cnt += 1;
661 	while (1) {
662 		ubifs_assert(c, !ubifs_zn_cow(znode));
663 		__set_bit(COW_ZNODE, &znode->flags);
664 		znode->alt = 0;
665 		cnext = find_next_dirty(znode);
666 		if (!cnext) {
667 			znode->cnext = c->cnext;
668 			break;
669 		}
670 		znode->cnext = cnext;
671 		znode = cnext;
672 		cnt += 1;
673 	}
674 	dbg_cmt("committing %d znodes", cnt);
675 	ubifs_assert(c, cnt == atomic_long_read(&c->dirty_zn_cnt));
676 	return cnt;
677 }
678 
679 /**
680  * alloc_idx_lebs - allocate empty LEBs to be used to commit.
681  * @c: UBIFS file-system description object
682  * @cnt: number of znodes to commit
683  *
684  * This function returns %-ENOSPC if it cannot allocate a sufficient number of
685  * empty LEBs.  %0 is returned on success, otherwise a negative error code
686  * is returned.
687  */
alloc_idx_lebs(struct ubifs_info * c,int cnt)688 static int alloc_idx_lebs(struct ubifs_info *c, int cnt)
689 {
690 	int i, leb_cnt, lnum;
691 
692 	c->ileb_cnt = 0;
693 	c->ileb_nxt = 0;
694 	leb_cnt = get_leb_cnt(c, cnt);
695 	dbg_cmt("need about %d empty LEBS for TNC commit", leb_cnt);
696 	if (!leb_cnt)
697 		return 0;
698 	c->ilebs = kmalloc_array(leb_cnt, sizeof(int), GFP_NOFS);
699 	if (!c->ilebs)
700 		return -ENOMEM;
701 	for (i = 0; i < leb_cnt; i++) {
702 		lnum = ubifs_find_free_leb_for_idx(c);
703 		if (lnum < 0)
704 			return lnum;
705 		c->ilebs[c->ileb_cnt++] = lnum;
706 		dbg_cmt("LEB %d", lnum);
707 	}
708 	if (dbg_is_chk_index(c) && !(prandom_u32() & 7))
709 		return -ENOSPC;
710 	return 0;
711 }
712 
713 /**
714  * free_unused_idx_lebs - free unused LEBs that were allocated for the commit.
715  * @c: UBIFS file-system description object
716  *
717  * It is possible that we allocate more empty LEBs for the commit than we need.
718  * This functions frees the surplus.
719  *
720  * This function returns %0 on success and a negative error code on failure.
721  */
free_unused_idx_lebs(struct ubifs_info * c)722 static int free_unused_idx_lebs(struct ubifs_info *c)
723 {
724 	int i, err = 0, lnum, er;
725 
726 	for (i = c->ileb_nxt; i < c->ileb_cnt; i++) {
727 		lnum = c->ilebs[i];
728 		dbg_cmt("LEB %d", lnum);
729 		er = ubifs_change_one_lp(c, lnum, LPROPS_NC, LPROPS_NC, 0,
730 					 LPROPS_INDEX | LPROPS_TAKEN, 0);
731 		if (!err)
732 			err = er;
733 	}
734 	return err;
735 }
736 
737 /**
738  * free_idx_lebs - free unused LEBs after commit end.
739  * @c: UBIFS file-system description object
740  *
741  * This function returns %0 on success and a negative error code on failure.
742  */
free_idx_lebs(struct ubifs_info * c)743 static int free_idx_lebs(struct ubifs_info *c)
744 {
745 	int err;
746 
747 	err = free_unused_idx_lebs(c);
748 	kfree(c->ilebs);
749 	c->ilebs = NULL;
750 	return err;
751 }
752 
753 /**
754  * ubifs_tnc_start_commit - start TNC commit.
755  * @c: UBIFS file-system description object
756  * @zroot: new index root position is returned here
757  *
758  * This function prepares the list of indexing nodes to commit and lays out
759  * their positions on flash. If there is not enough free space it uses the
760  * in-gap commit method. Returns zero in case of success and a negative error
761  * code in case of failure.
762  */
ubifs_tnc_start_commit(struct ubifs_info * c,struct ubifs_zbranch * zroot)763 int ubifs_tnc_start_commit(struct ubifs_info *c, struct ubifs_zbranch *zroot)
764 {
765 	int err = 0, cnt;
766 
767 	mutex_lock(&c->tnc_mutex);
768 	err = dbg_check_tnc(c, 1);
769 	if (err)
770 		goto out;
771 	cnt = get_znodes_to_commit(c);
772 	if (cnt != 0) {
773 		int no_space = 0;
774 
775 		err = alloc_idx_lebs(c, cnt);
776 		if (err == -ENOSPC)
777 			no_space = 1;
778 		else if (err)
779 			goto out_free;
780 		err = layout_commit(c, no_space, cnt);
781 		if (err)
782 			goto out_free;
783 		ubifs_assert(c, atomic_long_read(&c->dirty_zn_cnt) == 0);
784 		err = free_unused_idx_lebs(c);
785 		if (err)
786 			goto out;
787 	}
788 	destroy_old_idx(c);
789 	memcpy(zroot, &c->zroot, sizeof(struct ubifs_zbranch));
790 
791 	err = ubifs_save_dirty_idx_lnums(c);
792 	if (err)
793 		goto out;
794 
795 	spin_lock(&c->space_lock);
796 	/*
797 	 * Although we have not finished committing yet, update size of the
798 	 * committed index ('c->bi.old_idx_sz') and zero out the index growth
799 	 * budget. It is OK to do this now, because we've reserved all the
800 	 * space which is needed to commit the index, and it is save for the
801 	 * budgeting subsystem to assume the index is already committed,
802 	 * even though it is not.
803 	 */
804 	ubifs_assert(c, c->bi.min_idx_lebs == ubifs_calc_min_idx_lebs(c));
805 	c->bi.old_idx_sz = c->calc_idx_sz;
806 	c->bi.uncommitted_idx = 0;
807 	c->bi.min_idx_lebs = ubifs_calc_min_idx_lebs(c);
808 	spin_unlock(&c->space_lock);
809 	mutex_unlock(&c->tnc_mutex);
810 
811 	dbg_cmt("number of index LEBs %d", c->lst.idx_lebs);
812 	dbg_cmt("size of index %llu", c->calc_idx_sz);
813 	return err;
814 
815 out_free:
816 	free_idx_lebs(c);
817 out:
818 	mutex_unlock(&c->tnc_mutex);
819 	return err;
820 }
821 
822 /**
823  * write_index - write index nodes.
824  * @c: UBIFS file-system description object
825  *
826  * This function writes the index nodes whose positions were laid out in the
827  * layout_in_empty_space function.
828  */
write_index(struct ubifs_info * c)829 static int write_index(struct ubifs_info *c)
830 {
831 	struct ubifs_idx_node *idx;
832 	struct ubifs_znode *znode, *cnext;
833 	int i, lnum, offs, len, next_len, buf_len, buf_offs, used;
834 	int avail, wlen, err, lnum_pos = 0, blen, nxt_offs;
835 
836 	cnext = c->enext;
837 	if (!cnext)
838 		return 0;
839 
840 	/*
841 	 * Always write index nodes to the index head so that index nodes and
842 	 * other types of nodes are never mixed in the same erase block.
843 	 */
844 	lnum = c->ihead_lnum;
845 	buf_offs = c->ihead_offs;
846 
847 	/* Allocate commit buffer */
848 	buf_len = ALIGN(c->max_idx_node_sz, c->min_io_size);
849 	used = 0;
850 	avail = buf_len;
851 
852 	/* Ensure there is enough room for first write */
853 	next_len = ubifs_idx_node_sz(c, cnext->child_cnt);
854 	if (buf_offs + next_len > c->leb_size) {
855 		err = ubifs_update_one_lp(c, lnum, LPROPS_NC, 0, 0,
856 					  LPROPS_TAKEN);
857 		if (err)
858 			return err;
859 		lnum = -1;
860 	}
861 
862 	while (1) {
863 		cond_resched();
864 
865 		znode = cnext;
866 		idx = c->cbuf + used;
867 
868 		/* Make index node */
869 		idx->ch.node_type = UBIFS_IDX_NODE;
870 		idx->child_cnt = cpu_to_le16(znode->child_cnt);
871 		idx->level = cpu_to_le16(znode->level);
872 		for (i = 0; i < znode->child_cnt; i++) {
873 			struct ubifs_branch *br = ubifs_idx_branch(c, idx, i);
874 			struct ubifs_zbranch *zbr = &znode->zbranch[i];
875 
876 			key_write_idx(c, &zbr->key, &br->key);
877 			br->lnum = cpu_to_le32(zbr->lnum);
878 			br->offs = cpu_to_le32(zbr->offs);
879 			br->len = cpu_to_le32(zbr->len);
880 			if (!zbr->lnum || !zbr->len) {
881 				ubifs_err(c, "bad ref in znode");
882 				ubifs_dump_znode(c, znode);
883 				if (zbr->znode)
884 					ubifs_dump_znode(c, zbr->znode);
885 
886 				return -EINVAL;
887 			}
888 		}
889 		len = ubifs_idx_node_sz(c, znode->child_cnt);
890 		ubifs_prepare_node(c, idx, len, 0);
891 
892 		/* Determine the index node position */
893 		if (lnum == -1) {
894 			lnum = c->ilebs[lnum_pos++];
895 			buf_offs = 0;
896 			used = 0;
897 			avail = buf_len;
898 		}
899 		offs = buf_offs + used;
900 
901 		if (lnum != znode->lnum || offs != znode->offs ||
902 		    len != znode->len) {
903 			ubifs_err(c, "inconsistent znode posn");
904 			return -EINVAL;
905 		}
906 
907 		/* Grab some stuff from znode while we still can */
908 		cnext = znode->cnext;
909 
910 		ubifs_assert(c, ubifs_zn_dirty(znode));
911 		ubifs_assert(c, ubifs_zn_cow(znode));
912 
913 		/*
914 		 * It is important that other threads should see %DIRTY_ZNODE
915 		 * flag cleared before %COW_ZNODE. Specifically, it matters in
916 		 * the 'dirty_cow_znode()' function. This is the reason for the
917 		 * first barrier. Also, we want the bit changes to be seen to
918 		 * other threads ASAP, to avoid unnecesarry copying, which is
919 		 * the reason for the second barrier.
920 		 */
921 		clear_bit(DIRTY_ZNODE, &znode->flags);
922 		smp_mb__before_atomic();
923 		clear_bit(COW_ZNODE, &znode->flags);
924 		smp_mb__after_atomic();
925 
926 		/*
927 		 * We have marked the znode as clean but have not updated the
928 		 * @c->clean_zn_cnt counter. If this znode becomes dirty again
929 		 * before 'free_obsolete_znodes()' is called, then
930 		 * @c->clean_zn_cnt will be decremented before it gets
931 		 * incremented (resulting in 2 decrements for the same znode).
932 		 * This means that @c->clean_zn_cnt may become negative for a
933 		 * while.
934 		 *
935 		 * Q: why we cannot increment @c->clean_zn_cnt?
936 		 * A: because we do not have the @c->tnc_mutex locked, and the
937 		 *    following code would be racy and buggy:
938 		 *
939 		 *    if (!ubifs_zn_obsolete(znode)) {
940 		 *            atomic_long_inc(&c->clean_zn_cnt);
941 		 *            atomic_long_inc(&ubifs_clean_zn_cnt);
942 		 *    }
943 		 *
944 		 *    Thus, we just delay the @c->clean_zn_cnt update until we
945 		 *    have the mutex locked.
946 		 */
947 
948 		/* Do not access znode from this point on */
949 
950 		/* Update buffer positions */
951 		wlen = used + len;
952 		used += ALIGN(len, 8);
953 		avail -= ALIGN(len, 8);
954 
955 		/*
956 		 * Calculate the next index node length to see if there is
957 		 * enough room for it
958 		 */
959 		if (cnext == c->cnext)
960 			next_len = 0;
961 		else
962 			next_len = ubifs_idx_node_sz(c, cnext->child_cnt);
963 
964 		nxt_offs = buf_offs + used + next_len;
965 		if (next_len && nxt_offs <= c->leb_size) {
966 			if (avail > 0)
967 				continue;
968 			else
969 				blen = buf_len;
970 		} else {
971 			wlen = ALIGN(wlen, 8);
972 			blen = ALIGN(wlen, c->min_io_size);
973 			ubifs_pad(c, c->cbuf + wlen, blen - wlen);
974 		}
975 
976 		/* The buffer is full or there are no more znodes to do */
977 		err = ubifs_leb_write(c, lnum, c->cbuf, buf_offs, blen);
978 		if (err)
979 			return err;
980 		buf_offs += blen;
981 		if (next_len) {
982 			if (nxt_offs > c->leb_size) {
983 				err = ubifs_update_one_lp(c, lnum, LPROPS_NC, 0,
984 							  0, LPROPS_TAKEN);
985 				if (err)
986 					return err;
987 				lnum = -1;
988 			}
989 			used -= blen;
990 			if (used < 0)
991 				used = 0;
992 			avail = buf_len - used;
993 			memmove(c->cbuf, c->cbuf + blen, used);
994 			continue;
995 		}
996 		break;
997 	}
998 
999 	if (lnum != c->dbg->new_ihead_lnum ||
1000 	    buf_offs != c->dbg->new_ihead_offs) {
1001 		ubifs_err(c, "inconsistent ihead");
1002 		return -EINVAL;
1003 	}
1004 
1005 	c->ihead_lnum = lnum;
1006 	c->ihead_offs = buf_offs;
1007 
1008 	return 0;
1009 }
1010 
1011 /**
1012  * free_obsolete_znodes - free obsolete znodes.
1013  * @c: UBIFS file-system description object
1014  *
1015  * At the end of commit end, obsolete znodes are freed.
1016  */
free_obsolete_znodes(struct ubifs_info * c)1017 static void free_obsolete_znodes(struct ubifs_info *c)
1018 {
1019 	struct ubifs_znode *znode, *cnext;
1020 
1021 	cnext = c->cnext;
1022 	do {
1023 		znode = cnext;
1024 		cnext = znode->cnext;
1025 		if (ubifs_zn_obsolete(znode))
1026 			kfree(znode);
1027 		else {
1028 			znode->cnext = NULL;
1029 			atomic_long_inc(&c->clean_zn_cnt);
1030 			atomic_long_inc(&ubifs_clean_zn_cnt);
1031 		}
1032 	} while (cnext != c->cnext);
1033 }
1034 
1035 /**
1036  * return_gap_lebs - return LEBs used by the in-gap commit method.
1037  * @c: UBIFS file-system description object
1038  *
1039  * This function clears the "taken" flag for the LEBs which were used by the
1040  * "commit in-the-gaps" method.
1041  */
return_gap_lebs(struct ubifs_info * c)1042 static int return_gap_lebs(struct ubifs_info *c)
1043 {
1044 	int *p, err;
1045 
1046 	if (!c->gap_lebs)
1047 		return 0;
1048 
1049 	dbg_cmt("");
1050 	for (p = c->gap_lebs; *p != -1; p++) {
1051 		err = ubifs_change_one_lp(c, *p, LPROPS_NC, LPROPS_NC, 0,
1052 					  LPROPS_TAKEN, 0);
1053 		if (err)
1054 			return err;
1055 	}
1056 
1057 	kfree(c->gap_lebs);
1058 	c->gap_lebs = NULL;
1059 	return 0;
1060 }
1061 
1062 /**
1063  * ubifs_tnc_end_commit - update the TNC for commit end.
1064  * @c: UBIFS file-system description object
1065  *
1066  * Write the dirty znodes.
1067  */
ubifs_tnc_end_commit(struct ubifs_info * c)1068 int ubifs_tnc_end_commit(struct ubifs_info *c)
1069 {
1070 	int err;
1071 
1072 	if (!c->cnext)
1073 		return 0;
1074 
1075 	err = return_gap_lebs(c);
1076 	if (err)
1077 		return err;
1078 
1079 	err = write_index(c);
1080 	if (err)
1081 		return err;
1082 
1083 	mutex_lock(&c->tnc_mutex);
1084 
1085 	dbg_cmt("TNC height is %d", c->zroot.znode->level + 1);
1086 
1087 	free_obsolete_znodes(c);
1088 
1089 	c->cnext = NULL;
1090 	kfree(c->ilebs);
1091 	c->ilebs = NULL;
1092 
1093 	mutex_unlock(&c->tnc_mutex);
1094 
1095 	return 0;
1096 }
1097