aboutsummaryrefslogtreecommitdiff
path: root/misc-utils/ftl_format.c
blob: 34d436c6d6857dde9710bcf2e46e1a79c7409cdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/* Ported to MTD system.
 * Based on:
 */
/*======================================================================

  Utility to create an FTL partition in a memory region

  ftl_format.c 1.13 1999/10/25 20:01:35

  The contents of this file are subject to the Mozilla Public
  License Version 1.1 (the "License"); you may not use this file
  except in compliance with the License. You may obtain a copy of
  the License at http://www.mozilla.org/MPL/

  Software distributed under the License is distributed on an "AS
  IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  implied. See the License for the specific language governing
  rights and limitations under the License.

  The initial developer of the original code is David A. Hinds
  <dhinds@pcmcia.sourceforge.org>.  Portions created by David A. Hinds
  are Copyright (C) 1999 David A. Hinds.  All Rights Reserved.

  Alternatively, the contents of this file may be used under the
  terms of the GNU Public License version 2 (the "GPL"), in which
  case the provisions of the GPL are applicable instead of the
  above.  If you wish to allow the use of your version of this file
  only under the terms of the GPL and not to allow others to use
  your version of this file under the MPL, indicate your decision
  by deleting the provisions above and replace them with the notice
  and other provisions required by the GPL.  If you do not delete
  the provisions above, a recipient may use your version of this
  file under either the MPL or the GPL.

  ======================================================================*/

#define PROGRAM_NAME "ftl_format"

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

#include <mtd/mtd-user.h>
#include <mtd/ftl-user.h>
#include <mtd_swab.h>
#include "common.h"

/*====================================================================*/

static void print_size(u_int s)
{
	if ((s > 0x100000) && ((s % 0x100000) == 0))
		printf("%d mb", s / 0x100000);
	else if ((s > 0x400) && ((s % 0x400) == 0))
		printf("%d kb", s / 0x400);
	else
		printf("%d bytes", s);
}

/*====================================================================*/

static const char LinkTarget[] = {
	0x13, 0x03, 'C', 'I', 'S'
};
static const char DataOrg[] = {
	0x46, 0x39, 0x00, 'F', 'T', 'L', '1', '0', '0', 0x00
};

static void build_header(erase_unit_header_t *hdr, u_int RegionSize,
		u_int BlockSize, u_int Spare, int Reserve,
		u_int BootSize)
{
	u_int i, BootUnits, nbam, __FormattedSize;

	/* Default everything to the erased state */
	memset(hdr, 0xff, sizeof(*hdr));
	memcpy(hdr->LinkTargetTuple, LinkTarget, 5);
	memcpy(hdr->DataOrgTuple, DataOrg, 10);
	hdr->EndTuple[0] = hdr->EndTuple[1] = 0xff;
	BootSize = (BootSize + (BlockSize-1)) & ~(BlockSize-1);
	BootUnits = BootSize / BlockSize;

	/* We only support 512-byte blocks */
	hdr->BlockSize = 9;
	hdr->EraseUnitSize = 0;
	for (i = BlockSize; i > 1; i >>= 1)
		hdr->EraseUnitSize++;
	hdr->EraseCount = cpu_to_le32(0);
	hdr->FirstPhysicalEUN = cpu_to_le16(BootUnits);
	hdr->NumEraseUnits = cpu_to_le16((RegionSize - BootSize) >> hdr->EraseUnitSize);
	hdr->NumTransferUnits = Spare;
	__FormattedSize = RegionSize - ((Spare + BootUnits) << hdr->EraseUnitSize);
	/* Leave a little bit of space between the CIS and BAM */
	hdr->BAMOffset = cpu_to_le32(0x80);
	/* Adjust size to account for BAM space */
	nbam = ((1 << (hdr->EraseUnitSize - hdr->BlockSize)) * sizeof(u_int)
			+ le32_to_cpu(hdr->BAMOffset) + (1 << hdr->BlockSize) - 1) >> hdr->BlockSize;

	__FormattedSize -=
		(le16_to_cpu(hdr->NumEraseUnits) - Spare) * (nbam << hdr->BlockSize);
	__FormattedSize -= ((__FormattedSize * Reserve / 100) & ~0xfff);

	hdr->FormattedSize = cpu_to_le32(__FormattedSize);

	/* hdr->FirstVMAddress defaults to erased state */
	hdr->NumVMPages = cpu_to_le16(0);
	hdr->Flags = 0;
	/* hdr->Code defaults to erased state */
	hdr->SerialNumber = cpu_to_le32(time(NULL));
	/* hdr->AltEUHOffset defaults to erased state */

} /* build_header */

/*====================================================================*/

static int format_partition(int fd, int quiet, int interrogate,
		u_int spare, int reserve, u_int bootsize)
{
	mtd_info_t mtd;
	erase_info_t erase;
	erase_unit_header_t hdr;
	u_int step, lun, i, nbam, *bam;

	/* Get partition size, block size */
	if (ioctl(fd, MEMGETINFO, &mtd) != 0) {
		perror("get info failed");
		return -1;
	}

#if 0
	/* Intel Series 100 Flash: skip first block */
	if ((region.JedecMfr == 0x89) && (region.JedecInfo == 0xaa) &&
			(bootsize == 0)) {
		if (!quiet)
			printf("Skipping first block to protect CIS info...\n");
		bootsize = 1;
	}
#endif

	/* Create header */
	build_header(&hdr, mtd.size, mtd.erasesize,
			spare, reserve, bootsize);

	if (!quiet) {
		printf("Partition size = ");
		print_size(mtd.size);
		printf(", erase unit size = ");
		print_size(mtd.erasesize);
		printf(", %d transfer units\n", spare);
		if (bootsize != 0) {
			print_size(le16_to_cpu(hdr.FirstPhysicalEUN) << hdr.EraseUnitSize);
			printf(" allocated for boot image\n");
		}
		printf("Reserved %d%%, formatted size = ", reserve);
		print_size(le32_to_cpu(hdr.FormattedSize));
		printf("\n");
		fflush(stdout);
	}

	if (interrogate)
		if (!prompt("This will destroy all data on the target device. Confirm?", false))
			return -1;

	/* Create basic block allocation table for control blocks */
	nbam = ((mtd.erasesize >> hdr.BlockSize) * sizeof(u_int)
			+ le32_to_cpu(hdr.BAMOffset) + (1 << hdr.BlockSize) - 1) >> hdr.BlockSize;
	bam = malloc(nbam * sizeof(u_int));
	for (i = 0; i < nbam; i++)
		bam[i] = cpu_to_le32(BLOCK_CONTROL);

	/* Erase partition */
	if (!quiet) {
		printf("Erasing all blocks...\n");
		fflush(stdout);
	}
	erase.length = mtd.erasesize;
	erase.start = mtd.erasesize * le16_to_cpu(hdr.FirstPhysicalEUN);
	for (i = 0; i < le16_to_cpu(hdr.NumEraseUnits); i++) {
		if (ioctl(fd, MEMERASE, &erase) < 0) {
			if (!quiet) {
				putchar('\n');
				fflush(stdout);
			}
			perror("block erase failed");
			free(bam);
			return -1;
		}
		erase.start += erase.length;
		if (!quiet) {
			if (mtd.size <= 0x800000) {
				if (erase.start % 0x100000) {
					if (!(erase.start % 0x20000)) putchar('-');
				}
				else putchar('+');
			}
			else {
				if (erase.start % 0x800000) {
					if (!(erase.start % 0x100000)) putchar('+');
				}
				else putchar('*');
			}
			fflush(stdout);
		}
	}
	if (!quiet) putchar('\n');

	/* Prepare erase units */
	if (!quiet) {
		printf("Writing erase unit headers...\n");
		fflush(stdout);
	}
	lun = 0;
	/* Distribute transfer units over the entire region */
	step = spare ? (le16_to_cpu(hdr.NumEraseUnits) / spare) : (le16_to_cpu(hdr.NumEraseUnits) + 1);
	for (i = 0; i < le16_to_cpu(hdr.NumEraseUnits); i++) {
		off_t ofs = (off_t) (i + le16_to_cpu(hdr.FirstPhysicalEUN)) << hdr.EraseUnitSize;
		if (lseek(fd, ofs, SEEK_SET) == -1) {
			perror("seek failed");
			break;
		}
		/* Is this a transfer unit? */
		if (((i+1) % step) == 0)
			hdr.LogicalEUN = cpu_to_le16(0xffff);
		else {
			hdr.LogicalEUN = cpu_to_le16(lun);
			lun++;
		}
		if (write(fd, &hdr, sizeof(hdr)) == -1) {
			perror("write failed");
			break;
		}
		if (lseek(fd, ofs + le32_to_cpu(hdr.BAMOffset), SEEK_SET) == -1) {
			perror("seek failed");
			break;
		}
		if (write(fd, bam, nbam * sizeof(u_int)) == -1) {
			perror("write failed");
			break;
		}
	}

	free(bam);

	if (i < le16_to_cpu(hdr.NumEraseUnits))
		return -1;
	else
		return 0;
} /* format_partition */

/*====================================================================*/

static const struct option long_opts[] = {
	{"help", no_argument, 0, 'h'},
	{"version", no_argument, 0, 'V'},
	{0, 0, 0, 0},
};

static const char *short_opts = "qir:s:b:Vh";

int main(int argc, char *argv[])
{
	int quiet, interrogate, reserve, c;
	int optch, errflg, fd, ret;
	u_int spare, bootsize;
	char *s;
	extern char *optarg;
	struct stat buf;

	quiet = 0;
	interrogate = 0;
	spare = 1;
	reserve = 5;
	errflg = 0;
	bootsize = 0;

	while ((optch = getopt_long(argc, argv, short_opts, long_opts, &c)) != -1) {
		switch (optch) {
			case 'q':
				quiet = 1; break;
			case 'i':
				interrogate = 1; break;
			case 's':
				spare = strtoul(optarg, NULL, 0); break;
			case 'r':
				reserve = strtoul(optarg, NULL, 0); break;
			case 'b':
				bootsize = strtoul(optarg, &s, 0);
				if ((*s == 'k') || (*s == 'K'))
					bootsize *= 1024;
				break;
			case 'V':
				common_print_version();
				exit(EXIT_SUCCESS);
			case 'h':
				errflg = 1; break;
			default:
				errflg = -1; break;
		}
	}
	if (errflg || (optind != argc-1)) {
		fprintf(stderr, "usage: %s [-q] [-i] [-s spare-blocks]"
				" [-r reserve-percent] [-b bootsize] device\n", PROGRAM_NAME);
		exit(errflg > 0 ? EXIT_SUCCESS : EXIT_FAILURE);
	}

	fd = open(argv[optind], O_RDWR);
	if (fd == -1) {
		perror("open failed");
		exit(EXIT_FAILURE);
	}
	if (fstat(fd, &buf) != 0) {
		perror("status check failed");
		close(fd);
		exit(EXIT_FAILURE);
	}
	if (!(buf.st_mode & S_IFCHR)) {
		fprintf(stderr, "%s is not a character special device\n",
				argv[optind]);
		close(fd);
		exit(EXIT_FAILURE);
	}

	ret = format_partition(fd, quiet, interrogate, spare, reserve,
			bootsize);
	if (!quiet) {
		if (ret)
			printf("format failed.\n");
		else
			printf("format successful.\n");
	}
	close(fd);

	return ret ? EXIT_FAILURE : EXIT_SUCCESS;
}