1/*
2 * Copyright (c) International Business Machines Corp., 2006
3 * Copyright (c) Nokia Corporation, 2006, 2007
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
13 * the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 *
19 * Author: Artem Bityutskiy (Битюцкий Артём)
20 */
21
22/*
23 * This file includes volume table manipulation code. The volume table is an
24 * on-flash table containing volume meta-data like name, number of reserved
25 * physical eraseblocks, type, etc. The volume table is stored in the so-called
26 * "layout volume".
27 *
28 * The layout volume is an internal volume which is organized as follows. It
29 * consists of two logical eraseblocks - LEB 0 and LEB 1. Each logical
30 * eraseblock stores one volume table copy, i.e. LEB 0 and LEB 1 duplicate each
31 * other. This redundancy guarantees robustness to unclean reboots. The volume
32 * table is basically an array of volume table records. Each record contains
33 * full information about the volume and protected by a CRC checksum. Note,
34 * nowadays we use the atomic LEB change operation when updating the volume
35 * table, so we do not really need 2 LEBs anymore, but we preserve the older
36 * design for the backward compatibility reasons.
37 *
38 * When the volume table is changed, it is first changed in RAM. Then LEB 0 is
39 * erased, and the updated volume table is written back to LEB 0. Then same for
40 * LEB 1. This scheme guarantees recoverability from unclean reboots.
41 *
42 * In this UBI implementation the on-flash volume table does not contain any
43 * information about how much data static volumes contain.
44 *
45 * But it would still be beneficial to store this information in the volume
46 * table. For example, suppose we have a static volume X, and all its physical
47 * eraseblocks became bad for some reasons. Suppose we are attaching the
48 * corresponding MTD device, for some reason we find no logical eraseblocks
49 * corresponding to the volume X. According to the volume table volume X does
50 * exist. So we don't know whether it is just empty or all its physical
51 * eraseblocks went bad. So we cannot alarm the user properly.
52 *
53 * The volume table also stores so-called "update marker", which is used for
54 * volume updates. Before updating the volume, the update marker is set, and
55 * after the update operation is finished, the update marker is cleared. So if
56 * the update operation was interrupted (e.g. by an unclean reboot) - the
57 * update marker is still there and we know that the volume's contents is
58 * damaged.
59 */
60
61#include <linux/crc32.h>
62#include <linux/err.h>
63#include <linux/slab.h>
64#include <asm/div64.h>
65#include "ubi.h"
66
67static void self_vtbl_check(const struct ubi_device *ubi);
68
69/* Empty volume table record */
70static struct ubi_vtbl_record empty_vtbl_record;
71
72/**
73 * ubi_change_vtbl_record - change volume table record.
74 * @ubi: UBI device description object
75 * @idx: table index to change
76 * @vtbl_rec: new volume table record
77 *
78 * This function changes volume table record @idx. If @vtbl_rec is %NULL, empty
79 * volume table record is written. The caller does not have to calculate CRC of
80 * the record as it is done by this function. Returns zero in case of success
81 * and a negative error code in case of failure.
82 */
83int ubi_change_vtbl_record(struct ubi_device *ubi, int idx,
84			   struct ubi_vtbl_record *vtbl_rec)
85{
86	int i, err;
87	uint32_t crc;
88	struct ubi_volume *layout_vol;
89
90	ubi_assert(idx >= 0 && idx < ubi->vtbl_slots);
91	layout_vol = ubi->volumes[vol_id2idx(ubi, UBI_LAYOUT_VOLUME_ID)];
92
93	if (!vtbl_rec)
94		vtbl_rec = &empty_vtbl_record;
95	else {
96		crc = crc32(UBI_CRC32_INIT, vtbl_rec, UBI_VTBL_RECORD_SIZE_CRC);
97		vtbl_rec->crc = cpu_to_be32(crc);
98	}
99
100	memcpy(&ubi->vtbl[idx], vtbl_rec, sizeof(struct ubi_vtbl_record));
101	for (i = 0; i < UBI_LAYOUT_VOLUME_EBS; i++) {
102		err = ubi_eba_atomic_leb_change(ubi, layout_vol, i, ubi->vtbl,
103						ubi->vtbl_size);
104		if (err)
105			return err;
106	}
107
108	self_vtbl_check(ubi);
109	return 0;
110}
111
112/**
113 * ubi_vtbl_rename_volumes - rename UBI volumes in the volume table.
114 * @ubi: UBI device description object
115 * @rename_list: list of &struct ubi_rename_entry objects
116 *
117 * This function re-names multiple volumes specified in @req in the volume
118 * table. Returns zero in case of success and a negative error code in case of
119 * failure.
120 */
121int ubi_vtbl_rename_volumes(struct ubi_device *ubi,
122			    struct list_head *rename_list)
123{
124	int i, err;
125	struct ubi_rename_entry *re;
126	struct ubi_volume *layout_vol;
127
128	list_for_each_entry(re, rename_list, list) {
129		uint32_t crc;
130		struct ubi_volume *vol = re->desc->vol;
131		struct ubi_vtbl_record *vtbl_rec = &ubi->vtbl[vol->vol_id];
132
133		if (re->remove) {
134			memcpy(vtbl_rec, &empty_vtbl_record,
135			       sizeof(struct ubi_vtbl_record));
136			continue;
137		}
138
139		vtbl_rec->name_len = cpu_to_be16(re->new_name_len);
140		memcpy(vtbl_rec->name, re->new_name, re->new_name_len);
141		memset(vtbl_rec->name + re->new_name_len, 0,
142		       UBI_VOL_NAME_MAX + 1 - re->new_name_len);
143		crc = crc32(UBI_CRC32_INIT, vtbl_rec,
144			    UBI_VTBL_RECORD_SIZE_CRC);
145		vtbl_rec->crc = cpu_to_be32(crc);
146	}
147
148	layout_vol = ubi->volumes[vol_id2idx(ubi, UBI_LAYOUT_VOLUME_ID)];
149	for (i = 0; i < UBI_LAYOUT_VOLUME_EBS; i++) {
150		err = ubi_eba_atomic_leb_change(ubi, layout_vol, i, ubi->vtbl,
151						ubi->vtbl_size);
152		if (err)
153			return err;
154	}
155
156	return 0;
157}
158
159/**
160 * vtbl_check - check if volume table is not corrupted and sensible.
161 * @ubi: UBI device description object
162 * @vtbl: volume table
163 *
164 * This function returns zero if @vtbl is all right, %1 if CRC is incorrect,
165 * and %-EINVAL if it contains inconsistent data.
166 */
167static int vtbl_check(const struct ubi_device *ubi,
168		      const struct ubi_vtbl_record *vtbl)
169{
170	int i, n, reserved_pebs, alignment, data_pad, vol_type, name_len;
171	int upd_marker, err;
172	uint32_t crc;
173	const char *name;
174
175	for (i = 0; i < ubi->vtbl_slots; i++) {
176		cond_resched();
177
178		reserved_pebs = be32_to_cpu(vtbl[i].reserved_pebs);
179		alignment = be32_to_cpu(vtbl[i].alignment);
180		data_pad = be32_to_cpu(vtbl[i].data_pad);
181		upd_marker = vtbl[i].upd_marker;
182		vol_type = vtbl[i].vol_type;
183		name_len = be16_to_cpu(vtbl[i].name_len);
184		name = &vtbl[i].name[0];
185
186		crc = crc32(UBI_CRC32_INIT, &vtbl[i], UBI_VTBL_RECORD_SIZE_CRC);
187		if (be32_to_cpu(vtbl[i].crc) != crc) {
188			ubi_err(ubi, "bad CRC at record %u: %#08x, not %#08x",
189				 i, crc, be32_to_cpu(vtbl[i].crc));
190			ubi_dump_vtbl_record(&vtbl[i], i);
191			return 1;
192		}
193
194		if (reserved_pebs == 0) {
195			if (memcmp(&vtbl[i], &empty_vtbl_record,
196						UBI_VTBL_RECORD_SIZE)) {
197				err = 2;
198				goto bad;
199			}
200			continue;
201		}
202
203		if (reserved_pebs < 0 || alignment < 0 || data_pad < 0 ||
204		    name_len < 0) {
205			err = 3;
206			goto bad;
207		}
208
209		if (alignment > ubi->leb_size || alignment == 0) {
210			err = 4;
211			goto bad;
212		}
213
214		n = alignment & (ubi->min_io_size - 1);
215		if (alignment != 1 && n) {
216			err = 5;
217			goto bad;
218		}
219
220		n = ubi->leb_size % alignment;
221		if (data_pad != n) {
222			ubi_err(ubi, "bad data_pad, has to be %d", n);
223			err = 6;
224			goto bad;
225		}
226
227		if (vol_type != UBI_VID_DYNAMIC && vol_type != UBI_VID_STATIC) {
228			err = 7;
229			goto bad;
230		}
231
232		if (upd_marker != 0 && upd_marker != 1) {
233			err = 8;
234			goto bad;
235		}
236
237		if (reserved_pebs > ubi->good_peb_count) {
238			ubi_err(ubi, "too large reserved_pebs %d, good PEBs %d",
239				reserved_pebs, ubi->good_peb_count);
240			err = 9;
241			goto bad;
242		}
243
244		if (name_len > UBI_VOL_NAME_MAX) {
245			err = 10;
246			goto bad;
247		}
248
249		if (name[0] == '\0') {
250			err = 11;
251			goto bad;
252		}
253
254		if (name_len != strnlen(name, name_len + 1)) {
255			err = 12;
256			goto bad;
257		}
258	}
259
260	/* Checks that all names are unique */
261	for (i = 0; i < ubi->vtbl_slots - 1; i++) {
262		for (n = i + 1; n < ubi->vtbl_slots; n++) {
263			int len1 = be16_to_cpu(vtbl[i].name_len);
264			int len2 = be16_to_cpu(vtbl[n].name_len);
265
266			if (len1 > 0 && len1 == len2 &&
267			    !strncmp(vtbl[i].name, vtbl[n].name, len1)) {
268				ubi_err(ubi, "volumes %d and %d have the same name \"%s\"",
269					i, n, vtbl[i].name);
270				ubi_dump_vtbl_record(&vtbl[i], i);
271				ubi_dump_vtbl_record(&vtbl[n], n);
272				return -EINVAL;
273			}
274		}
275	}
276
277	return 0;
278
279bad:
280	ubi_err(ubi, "volume table check failed: record %d, error %d", i, err);
281	ubi_dump_vtbl_record(&vtbl[i], i);
282	return -EINVAL;
283}
284
285/**
286 * create_vtbl - create a copy of volume table.
287 * @ubi: UBI device description object
288 * @ai: attaching information
289 * @copy: number of the volume table copy
290 * @vtbl: contents of the volume table
291 *
292 * This function returns zero in case of success and a negative error code in
293 * case of failure.
294 */
295static int create_vtbl(struct ubi_device *ubi, struct ubi_attach_info *ai,
296		       int copy, void *vtbl)
297{
298	int err, tries = 0;
299	struct ubi_vid_hdr *vid_hdr;
300	struct ubi_ainf_peb *new_aeb;
301
302	dbg_gen("create volume table (copy #%d)", copy + 1);
303
304	vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
305	if (!vid_hdr)
306		return -ENOMEM;
307
308retry:
309	new_aeb = ubi_early_get_peb(ubi, ai);
310	if (IS_ERR(new_aeb)) {
311		err = PTR_ERR(new_aeb);
312		goto out_free;
313	}
314
315	vid_hdr->vol_type = UBI_LAYOUT_VOLUME_TYPE;
316	vid_hdr->vol_id = cpu_to_be32(UBI_LAYOUT_VOLUME_ID);
317	vid_hdr->compat = UBI_LAYOUT_VOLUME_COMPAT;
318	vid_hdr->data_size = vid_hdr->used_ebs =
319			     vid_hdr->data_pad = cpu_to_be32(0);
320	vid_hdr->lnum = cpu_to_be32(copy);
321	vid_hdr->sqnum = cpu_to_be64(++ai->max_sqnum);
322
323	/* The EC header is already there, write the VID header */
324	err = ubi_io_write_vid_hdr(ubi, new_aeb->pnum, vid_hdr);
325	if (err)
326		goto write_error;
327
328	/* Write the layout volume contents */
329	err = ubi_io_write_data(ubi, vtbl, new_aeb->pnum, 0, ubi->vtbl_size);
330	if (err)
331		goto write_error;
332
333	/*
334	 * And add it to the attaching information. Don't delete the old version
335	 * of this LEB as it will be deleted and freed in 'ubi_add_to_av()'.
336	 */
337	err = ubi_add_to_av(ubi, ai, new_aeb->pnum, new_aeb->ec, vid_hdr, 0);
338	kmem_cache_free(ai->aeb_slab_cache, new_aeb);
339	ubi_free_vid_hdr(ubi, vid_hdr);
340	return err;
341
342write_error:
343	if (err == -EIO && ++tries <= 5) {
344		/*
345		 * Probably this physical eraseblock went bad, try to pick
346		 * another one.
347		 */
348		list_add(&new_aeb->u.list, &ai->erase);
349		goto retry;
350	}
351	kmem_cache_free(ai->aeb_slab_cache, new_aeb);
352out_free:
353	ubi_free_vid_hdr(ubi, vid_hdr);
354	return err;
355
356}
357
358/**
359 * process_lvol - process the layout volume.
360 * @ubi: UBI device description object
361 * @ai: attaching information
362 * @av: layout volume attaching information
363 *
364 * This function is responsible for reading the layout volume, ensuring it is
365 * not corrupted, and recovering from corruptions if needed. Returns volume
366 * table in case of success and a negative error code in case of failure.
367 */
368static struct ubi_vtbl_record *process_lvol(struct ubi_device *ubi,
369					    struct ubi_attach_info *ai,
370					    struct ubi_ainf_volume *av)
371{
372	int err;
373	struct rb_node *rb;
374	struct ubi_ainf_peb *aeb;
375	struct ubi_vtbl_record *leb[UBI_LAYOUT_VOLUME_EBS] = { NULL, NULL };
376	int leb_corrupted[UBI_LAYOUT_VOLUME_EBS] = {1, 1};
377
378	/*
379	 * UBI goes through the following steps when it changes the layout
380	 * volume:
381	 * a. erase LEB 0;
382	 * b. write new data to LEB 0;
383	 * c. erase LEB 1;
384	 * d. write new data to LEB 1.
385	 *
386	 * Before the change, both LEBs contain the same data.
387	 *
388	 * Due to unclean reboots, the contents of LEB 0 may be lost, but there
389	 * should LEB 1. So it is OK if LEB 0 is corrupted while LEB 1 is not.
390	 * Similarly, LEB 1 may be lost, but there should be LEB 0. And
391	 * finally, unclean reboots may result in a situation when neither LEB
392	 * 0 nor LEB 1 are corrupted, but they are different. In this case, LEB
393	 * 0 contains more recent information.
394	 *
395	 * So the plan is to first check LEB 0. Then
396	 * a. if LEB 0 is OK, it must be containing the most recent data; then
397	 *    we compare it with LEB 1, and if they are different, we copy LEB
398	 *    0 to LEB 1;
399	 * b. if LEB 0 is corrupted, but LEB 1 has to be OK, and we copy LEB 1
400	 *    to LEB 0.
401	 */
402
403	dbg_gen("check layout volume");
404
405	/* Read both LEB 0 and LEB 1 into memory */
406	ubi_rb_for_each_entry(rb, aeb, &av->root, u.rb) {
407		leb[aeb->lnum] = vzalloc(ubi->vtbl_size);
408		if (!leb[aeb->lnum]) {
409			err = -ENOMEM;
410			goto out_free;
411		}
412
413		err = ubi_io_read_data(ubi, leb[aeb->lnum], aeb->pnum, 0,
414				       ubi->vtbl_size);
415		if (err == UBI_IO_BITFLIPS || mtd_is_eccerr(err))
416			/*
417			 * Scrub the PEB later. Note, -EBADMSG indicates an
418			 * uncorrectable ECC error, but we have our own CRC and
419			 * the data will be checked later. If the data is OK,
420			 * the PEB will be scrubbed (because we set
421			 * aeb->scrub). If the data is not OK, the contents of
422			 * the PEB will be recovered from the second copy, and
423			 * aeb->scrub will be cleared in
424			 * 'ubi_add_to_av()'.
425			 */
426			aeb->scrub = 1;
427		else if (err)
428			goto out_free;
429	}
430
431	err = -EINVAL;
432	if (leb[0]) {
433		leb_corrupted[0] = vtbl_check(ubi, leb[0]);
434		if (leb_corrupted[0] < 0)
435			goto out_free;
436	}
437
438	if (!leb_corrupted[0]) {
439		/* LEB 0 is OK */
440		if (leb[1])
441			leb_corrupted[1] = memcmp(leb[0], leb[1],
442						  ubi->vtbl_size);
443		if (leb_corrupted[1]) {
444			ubi_warn(ubi, "volume table copy #2 is corrupted");
445			err = create_vtbl(ubi, ai, 1, leb[0]);
446			if (err)
447				goto out_free;
448			ubi_msg(ubi, "volume table was restored");
449		}
450
451		/* Both LEB 1 and LEB 2 are OK and consistent */
452		vfree(leb[1]);
453		return leb[0];
454	} else {
455		/* LEB 0 is corrupted or does not exist */
456		if (leb[1]) {
457			leb_corrupted[1] = vtbl_check(ubi, leb[1]);
458			if (leb_corrupted[1] < 0)
459				goto out_free;
460		}
461		if (leb_corrupted[1]) {
462			/* Both LEB 0 and LEB 1 are corrupted */
463			ubi_err(ubi, "both volume tables are corrupted");
464			goto out_free;
465		}
466
467		ubi_warn(ubi, "volume table copy #1 is corrupted");
468		err = create_vtbl(ubi, ai, 0, leb[1]);
469		if (err)
470			goto out_free;
471		ubi_msg(ubi, "volume table was restored");
472
473		vfree(leb[0]);
474		return leb[1];
475	}
476
477out_free:
478	vfree(leb[0]);
479	vfree(leb[1]);
480	return ERR_PTR(err);
481}
482
483/**
484 * create_empty_lvol - create empty layout volume.
485 * @ubi: UBI device description object
486 * @ai: attaching information
487 *
488 * This function returns volume table contents in case of success and a
489 * negative error code in case of failure.
490 */
491static struct ubi_vtbl_record *create_empty_lvol(struct ubi_device *ubi,
492						 struct ubi_attach_info *ai)
493{
494	int i;
495	struct ubi_vtbl_record *vtbl;
496
497	vtbl = vzalloc(ubi->vtbl_size);
498	if (!vtbl)
499		return ERR_PTR(-ENOMEM);
500
501	for (i = 0; i < ubi->vtbl_slots; i++)
502		memcpy(&vtbl[i], &empty_vtbl_record, UBI_VTBL_RECORD_SIZE);
503
504	for (i = 0; i < UBI_LAYOUT_VOLUME_EBS; i++) {
505		int err;
506
507		err = create_vtbl(ubi, ai, i, vtbl);
508		if (err) {
509			vfree(vtbl);
510			return ERR_PTR(err);
511		}
512	}
513
514	return vtbl;
515}
516
517/**
518 * init_volumes - initialize volume information for existing volumes.
519 * @ubi: UBI device description object
520 * @ai: scanning information
521 * @vtbl: volume table
522 *
523 * This function allocates volume description objects for existing volumes.
524 * Returns zero in case of success and a negative error code in case of
525 * failure.
526 */
527static int init_volumes(struct ubi_device *ubi,
528			const struct ubi_attach_info *ai,
529			const struct ubi_vtbl_record *vtbl)
530{
531	int i, reserved_pebs = 0;
532	struct ubi_ainf_volume *av;
533	struct ubi_volume *vol;
534
535	for (i = 0; i < ubi->vtbl_slots; i++) {
536		cond_resched();
537
538		if (be32_to_cpu(vtbl[i].reserved_pebs) == 0)
539			continue; /* Empty record */
540
541		vol = kzalloc(sizeof(struct ubi_volume), GFP_KERNEL);
542		if (!vol)
543			return -ENOMEM;
544
545		vol->reserved_pebs = be32_to_cpu(vtbl[i].reserved_pebs);
546		vol->alignment = be32_to_cpu(vtbl[i].alignment);
547		vol->data_pad = be32_to_cpu(vtbl[i].data_pad);
548		vol->upd_marker = vtbl[i].upd_marker;
549		vol->vol_type = vtbl[i].vol_type == UBI_VID_DYNAMIC ?
550					UBI_DYNAMIC_VOLUME : UBI_STATIC_VOLUME;
551		vol->name_len = be16_to_cpu(vtbl[i].name_len);
552		vol->usable_leb_size = ubi->leb_size - vol->data_pad;
553		memcpy(vol->name, vtbl[i].name, vol->name_len);
554		vol->name[vol->name_len] = '\0';
555		vol->vol_id = i;
556
557		if (vtbl[i].flags & UBI_VTBL_AUTORESIZE_FLG) {
558			/* Auto re-size flag may be set only for one volume */
559			if (ubi->autoresize_vol_id != -1) {
560				ubi_err(ubi, "more than one auto-resize volume (%d and %d)",
561					ubi->autoresize_vol_id, i);
562				kfree(vol);
563				return -EINVAL;
564			}
565
566			ubi->autoresize_vol_id = i;
567		}
568
569		ubi_assert(!ubi->volumes[i]);
570		ubi->volumes[i] = vol;
571		ubi->vol_count += 1;
572		vol->ubi = ubi;
573		reserved_pebs += vol->reserved_pebs;
574
575		/*
576		 * In case of dynamic volume UBI knows nothing about how many
577		 * data is stored there. So assume the whole volume is used.
578		 */
579		if (vol->vol_type == UBI_DYNAMIC_VOLUME) {
580			vol->used_ebs = vol->reserved_pebs;
581			vol->last_eb_bytes = vol->usable_leb_size;
582			vol->used_bytes =
583				(long long)vol->used_ebs * vol->usable_leb_size;
584			continue;
585		}
586
587		/* Static volumes only */
588		av = ubi_find_av(ai, i);
589		if (!av || !av->leb_count) {
590			/*
591			 * No eraseblocks belonging to this volume found. We
592			 * don't actually know whether this static volume is
593			 * completely corrupted or just contains no data. And
594			 * we cannot know this as long as data size is not
595			 * stored on flash. So we just assume the volume is
596			 * empty. FIXME: this should be handled.
597			 */
598			continue;
599		}
600
601		if (av->leb_count != av->used_ebs) {
602			/*
603			 * We found a static volume which misses several
604			 * eraseblocks. Treat it as corrupted.
605			 */
606			ubi_warn(ubi, "static volume %d misses %d LEBs - corrupted",
607				 av->vol_id, av->used_ebs - av->leb_count);
608			vol->corrupted = 1;
609			continue;
610		}
611
612		vol->used_ebs = av->used_ebs;
613		vol->used_bytes =
614			(long long)(vol->used_ebs - 1) * vol->usable_leb_size;
615		vol->used_bytes += av->last_data_size;
616		vol->last_eb_bytes = av->last_data_size;
617	}
618
619	/* And add the layout volume */
620	vol = kzalloc(sizeof(struct ubi_volume), GFP_KERNEL);
621	if (!vol)
622		return -ENOMEM;
623
624	vol->reserved_pebs = UBI_LAYOUT_VOLUME_EBS;
625	vol->alignment = UBI_LAYOUT_VOLUME_ALIGN;
626	vol->vol_type = UBI_DYNAMIC_VOLUME;
627	vol->name_len = sizeof(UBI_LAYOUT_VOLUME_NAME) - 1;
628	memcpy(vol->name, UBI_LAYOUT_VOLUME_NAME, vol->name_len + 1);
629	vol->usable_leb_size = ubi->leb_size;
630	vol->used_ebs = vol->reserved_pebs;
631	vol->last_eb_bytes = vol->reserved_pebs;
632	vol->used_bytes =
633		(long long)vol->used_ebs * (ubi->leb_size - vol->data_pad);
634	vol->vol_id = UBI_LAYOUT_VOLUME_ID;
635	vol->ref_count = 1;
636
637	ubi_assert(!ubi->volumes[i]);
638	ubi->volumes[vol_id2idx(ubi, vol->vol_id)] = vol;
639	reserved_pebs += vol->reserved_pebs;
640	ubi->vol_count += 1;
641	vol->ubi = ubi;
642
643	if (reserved_pebs > ubi->avail_pebs) {
644		ubi_err(ubi, "not enough PEBs, required %d, available %d",
645			reserved_pebs, ubi->avail_pebs);
646		if (ubi->corr_peb_count)
647			ubi_err(ubi, "%d PEBs are corrupted and not used",
648				ubi->corr_peb_count);
649		return -ENOSPC;
650	}
651	ubi->rsvd_pebs += reserved_pebs;
652	ubi->avail_pebs -= reserved_pebs;
653
654	return 0;
655}
656
657/**
658 * check_av - check volume attaching information.
659 * @vol: UBI volume description object
660 * @av: volume attaching information
661 *
662 * This function returns zero if the volume attaching information is consistent
663 * to the data read from the volume tabla, and %-EINVAL if not.
664 */
665static int check_av(const struct ubi_volume *vol,
666		    const struct ubi_ainf_volume *av)
667{
668	int err;
669
670	if (av->highest_lnum >= vol->reserved_pebs) {
671		err = 1;
672		goto bad;
673	}
674	if (av->leb_count > vol->reserved_pebs) {
675		err = 2;
676		goto bad;
677	}
678	if (av->vol_type != vol->vol_type) {
679		err = 3;
680		goto bad;
681	}
682	if (av->used_ebs > vol->reserved_pebs) {
683		err = 4;
684		goto bad;
685	}
686	if (av->data_pad != vol->data_pad) {
687		err = 5;
688		goto bad;
689	}
690	return 0;
691
692bad:
693	ubi_err(vol->ubi, "bad attaching information, error %d", err);
694	ubi_dump_av(av);
695	ubi_dump_vol_info(vol);
696	return -EINVAL;
697}
698
699/**
700 * check_attaching_info - check that attaching information.
701 * @ubi: UBI device description object
702 * @ai: attaching information
703 *
704 * Even though we protect on-flash data by CRC checksums, we still don't trust
705 * the media. This function ensures that attaching information is consistent to
706 * the information read from the volume table. Returns zero if the attaching
707 * information is OK and %-EINVAL if it is not.
708 */
709static int check_attaching_info(const struct ubi_device *ubi,
710			       struct ubi_attach_info *ai)
711{
712	int err, i;
713	struct ubi_ainf_volume *av;
714	struct ubi_volume *vol;
715
716	if (ai->vols_found > UBI_INT_VOL_COUNT + ubi->vtbl_slots) {
717		ubi_err(ubi, "found %d volumes while attaching, maximum is %d + %d",
718			ai->vols_found, UBI_INT_VOL_COUNT, ubi->vtbl_slots);
719		return -EINVAL;
720	}
721
722	if (ai->highest_vol_id >= ubi->vtbl_slots + UBI_INT_VOL_COUNT &&
723	    ai->highest_vol_id < UBI_INTERNAL_VOL_START) {
724		ubi_err(ubi, "too large volume ID %d found",
725			ai->highest_vol_id);
726		return -EINVAL;
727	}
728
729	for (i = 0; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
730		cond_resched();
731
732		av = ubi_find_av(ai, i);
733		vol = ubi->volumes[i];
734		if (!vol) {
735			if (av)
736				ubi_remove_av(ai, av);
737			continue;
738		}
739
740		if (vol->reserved_pebs == 0) {
741			ubi_assert(i < ubi->vtbl_slots);
742
743			if (!av)
744				continue;
745
746			/*
747			 * During attaching we found a volume which does not
748			 * exist according to the information in the volume
749			 * table. This must have happened due to an unclean
750			 * reboot while the volume was being removed. Discard
751			 * these eraseblocks.
752			 */
753			ubi_msg(ubi, "finish volume %d removal", av->vol_id);
754			ubi_remove_av(ai, av);
755		} else if (av) {
756			err = check_av(vol, av);
757			if (err)
758				return err;
759		}
760	}
761
762	return 0;
763}
764
765/**
766 * ubi_read_volume_table - read the volume table.
767 * @ubi: UBI device description object
768 * @ai: attaching information
769 *
770 * This function reads volume table, checks it, recover from errors if needed,
771 * or creates it if needed. Returns zero in case of success and a negative
772 * error code in case of failure.
773 */
774int ubi_read_volume_table(struct ubi_device *ubi, struct ubi_attach_info *ai)
775{
776	int i, err;
777	struct ubi_ainf_volume *av;
778
779	empty_vtbl_record.crc = cpu_to_be32(0xf116c36b);
780
781	/*
782	 * The number of supported volumes is limited by the eraseblock size
783	 * and by the UBI_MAX_VOLUMES constant.
784	 */
785	ubi->vtbl_slots = ubi->leb_size / UBI_VTBL_RECORD_SIZE;
786	if (ubi->vtbl_slots > UBI_MAX_VOLUMES)
787		ubi->vtbl_slots = UBI_MAX_VOLUMES;
788
789	ubi->vtbl_size = ubi->vtbl_slots * UBI_VTBL_RECORD_SIZE;
790	ubi->vtbl_size = ALIGN(ubi->vtbl_size, ubi->min_io_size);
791
792	av = ubi_find_av(ai, UBI_LAYOUT_VOLUME_ID);
793	if (!av) {
794		/*
795		 * No logical eraseblocks belonging to the layout volume were
796		 * found. This could mean that the flash is just empty. In
797		 * this case we create empty layout volume.
798		 *
799		 * But if flash is not empty this must be a corruption or the
800		 * MTD device just contains garbage.
801		 */
802		if (ai->is_empty) {
803			ubi->vtbl = create_empty_lvol(ubi, ai);
804			if (IS_ERR(ubi->vtbl))
805				return PTR_ERR(ubi->vtbl);
806		} else {
807			ubi_err(ubi, "the layout volume was not found");
808			return -EINVAL;
809		}
810	} else {
811		if (av->leb_count > UBI_LAYOUT_VOLUME_EBS) {
812			/* This must not happen with proper UBI images */
813			ubi_err(ubi, "too many LEBs (%d) in layout volume",
814				av->leb_count);
815			return -EINVAL;
816		}
817
818		ubi->vtbl = process_lvol(ubi, ai, av);
819		if (IS_ERR(ubi->vtbl))
820			return PTR_ERR(ubi->vtbl);
821	}
822
823	ubi->avail_pebs = ubi->good_peb_count - ubi->corr_peb_count;
824
825	/*
826	 * The layout volume is OK, initialize the corresponding in-RAM data
827	 * structures.
828	 */
829	err = init_volumes(ubi, ai, ubi->vtbl);
830	if (err)
831		goto out_free;
832
833	/*
834	 * Make sure that the attaching information is consistent to the
835	 * information stored in the volume table.
836	 */
837	err = check_attaching_info(ubi, ai);
838	if (err)
839		goto out_free;
840
841	return 0;
842
843out_free:
844	vfree(ubi->vtbl);
845	for (i = 0; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
846		kfree(ubi->volumes[i]);
847		ubi->volumes[i] = NULL;
848	}
849	return err;
850}
851
852/**
853 * self_vtbl_check - check volume table.
854 * @ubi: UBI device description object
855 */
856static void self_vtbl_check(const struct ubi_device *ubi)
857{
858	if (!ubi_dbg_chk_gen(ubi))
859		return;
860
861	if (vtbl_check(ubi, ubi->vtbl)) {
862		ubi_err(ubi, "self-check failed");
863		BUG();
864	}
865}
866