Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
507 kaklik 1
/*----------------------------------------------------------------------------/
2
/  FatFs - FAT file system module  R0.06                     (C)ChaN, 2008
3
/-----------------------------------------------------------------------------/
4
/ The FatFs module is an experimenal project to implement FAT file system to
5
/ cheap microcontrollers. This is a free software and is opened for education,
6
/ research and development under license policy of following trems.
7
/
8
/  Copyright (C) 2008, ChaN, all right reserved.
9
/
10
/ * The FatFs module is a free software and there is no warranty.
11
/ * You can use, modify and/or redistribute it for personal, non-profit or
12
/   commercial use without restriction under your responsibility.
13
/ * Redistributions of source code must retain the above copyright notice.
14
/
15
/-----------------------------------------------------------------------------/
16
/ Feb 26,'06 R0.00  Prototype.
17
/
18
/ Apr 29,'06 R0.01  First stable version.
19
/
20
/ Jun 01,'06 R0.02  Added FAT12 support.
21
/                   Removed unbuffered mode.
22
/                   Fixed a problem on small (<32M) patition.
23
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
24
/
25
/ Sep 22,'06 R0.03  Added f_rename().
26
/                   Changed option _FS_MINIMUM to _FS_MINIMIZE.
27
/ Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
28
/                   Fixed f_mkdir() creates incorrect directory on FAT32.
29
/
30
/ Feb 04,'07 R0.04  Supported multiple drive system.
31
/                   Changed some interfaces for multiple drive system.
32
/                   Changed f_mountdrv() to f_mount().
33
/                   Added f_mkfs().
34
/ Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
35
/                   Added a capability of extending file size to f_lseek().
36
/                   Added minimization level 3.
37
/                   Fixed an endian sensitive code in f_mkfs().
38
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
39
/                   Added FSInfo support.
40
/                   Fixed DBCS name can result FR_INVALID_NAME.
41
/                   Fixed short seek (<= csize) collapses the file object.
42
/
43
/ Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().
44
/                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
45
/                   Fixed f_mkdir() on FAT32 creates incorrect directory.
46
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
47
/                   Fixed off by one error at FAT sub-type determination.
48
/                   Fixed btr in f_read() can be mistruncated.
49
/                   Fixed cached sector is not flushed when create and close
50
/                   without write.
51
/
52
/ Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().
53
/                   Improved performance of f_lseek() on moving to the same
54
/                   or following cluster.
55
/---------------------------------------------------------------------------*/
56
 
57
#include <string.h>
58
#include "ff.h"			/* FatFs declarations */
59
#include "diskio.h"		/* Include file for user provided disk functions */
60
 
61
 
62
/*--------------------------------------------------------------------------
63
 
64
   Module Private Functions
65
 
66
---------------------------------------------------------------------------*/
67
 
68
static
69
FATFS *FatFs[_DRIVES];	/* Pointer to the file system objects (logical drives) */
70
static
71
WORD fsid;				/* File system mount ID */
72
 
73
 
74
 
75
/*-----------------------------------------------------------------------*/
76
/* Change window offset                                                  */
77
/*-----------------------------------------------------------------------*/
78
 
79
static
80
BOOL move_window (	/* TRUE: successful, FALSE: failed */
81
	FATFS *fs,		/* File system object */
82
	DWORD sector	/* Sector number to make apperance in the fs->win[] */
83
)					/* Move to zero only writes back dirty window */
84
{
85
	DWORD wsect;
86
 
87
 
88
	wsect = fs->winsect;
89
	if (wsect != sector) {	/* Changed current window */
90
#if !_FS_READONLY
91
		BYTE n;
92
		if (fs->winflag) {	/* Write back dirty window if needed */
93
			if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
94
				return FALSE;
95
			fs->winflag = 0;
96
			if (wsect < (fs->fatbase + fs->sects_fat)) {	/* In FAT area */
97
				for (n = fs->n_fats; n >= 2; n--) {	/* Refrect the change to FAT copy */
98
					wsect += fs->sects_fat;
99
					disk_write(fs->drive, fs->win, wsect, 1);
100
				}
101
			}
102
		}
103
#endif
104
		if (sector) {
105
			if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
106
				return FALSE;
107
			fs->winsect = sector;
108
		}
109
	}
110
	return TRUE;
111
}
112
 
113
 
114
 
115
 
116
/*-----------------------------------------------------------------------*/
117
/* Clean-up cached data                                                  */
118
/*-----------------------------------------------------------------------*/
119
 
120
#if !_FS_READONLY
121
static
122
FRESULT sync (	/* FR_OK: successful, FR_RW_ERROR: failed */
123
	FATFS *fs	/* File system object */
124
)
125
{
126
	fs->winflag = 1;
127
	if (!move_window(fs, 0)) return FR_RW_ERROR;
128
#if _USE_FSINFO
129
	/* Update FSInfo sector if needed */
130
	if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
131
		fs->winsect = 0;
132
		memset(fs->win, 0, 512);
133
		ST_WORD(&fs->win[BS_55AA], 0xAA55);
134
		ST_DWORD(&fs->win[FSI_LeadSig], 0x41615252);
135
		ST_DWORD(&fs->win[FSI_StrucSig], 0x61417272);
136
		ST_DWORD(&fs->win[FSI_Free_Count], fs->free_clust);
137
		ST_DWORD(&fs->win[FSI_Nxt_Free], fs->last_clust);
138
		disk_write(fs->drive, fs->win, fs->fsi_sector, 1);
139
		fs->fsi_flag = 0;
140
	}
141
#endif
142
	/* Make sure that no pending write process in the physical drive */
143
	if (disk_ioctl(fs->drive, CTRL_SYNC, NULL) != RES_OK)
144
		return FR_RW_ERROR;
145
	return FR_OK;
146
}
147
#endif
148
 
149
 
150
 
151
 
152
/*-----------------------------------------------------------------------*/
153
/* Get a cluster status                                                  */
154
/*-----------------------------------------------------------------------*/
155
 
156
static
157
DWORD get_cluster (	/* 0,>=2: successful, 1: failed */
158
	FATFS *fs,		/* File system object */
159
	DWORD clust		/* Cluster# to get the link information */
160
)
161
{
162
	WORD wc, bc;
163
	DWORD fatsect;
164
 
165
 
166
	if (clust >= 2 && clust < fs->max_clust) {		/* Is it a valid cluster#? */
167
		fatsect = fs->fatbase;
168
		switch (fs->fs_type) {
169
		case FS_FAT12 :
170
			bc = (WORD)clust * 3 / 2;
171
			if (!move_window(fs, fatsect + (bc / SS(fs)))) break;
172
			wc = fs->win[bc & (SS(fs) - 1)]; bc++;
173
			if (!move_window(fs, fatsect + (bc / SS(fs)))) break;
174
			wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;
175
			return (clust & 1) ? (wc >> 4) : (wc & 0xFFF);
176
 
177
		case FS_FAT16 :
178
			if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) break;
179
			return LD_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)]);
180
 
181
		case FS_FAT32 :
182
			if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) break;
183
			return LD_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
184
		}
185
	}
186
 
187
	return 1;	/* Out of cluster range, or an error occured */
188
}
189
 
190
 
191
 
192
 
193
/*-----------------------------------------------------------------------*/
194
/* Change a cluster status                                               */
195
/*-----------------------------------------------------------------------*/
196
 
197
#if !_FS_READONLY
198
static
199
BOOL put_cluster (	/* TRUE: successful, FALSE: failed */
200
	FATFS *fs,		/* File system object */
201
	DWORD clust,	/* Cluster# to change (must be 2 to fs->max_clust-1) */
202
	DWORD val		/* New value to mark the cluster */
203
)
204
{
205
	WORD bc;
206
	BYTE *p;
207
	DWORD fatsect;
208
 
209
 
210
	fatsect = fs->fatbase;
211
	switch (fs->fs_type) {
212
	case FS_FAT12 :
213
		bc = (WORD)clust * 3 / 2;
214
		if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
215
		p = &fs->win[bc & (SS(fs) - 1)];
216
		*p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
217
		bc++;
218
		fs->winflag = 1;
219
		if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
220
		p = &fs->win[bc & (SS(fs) - 1)];
221
		*p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
222
		break;
223
 
224
	case FS_FAT16 :
225
		if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) return FALSE;
226
		ST_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)], (WORD)val);
227
		break;
228
 
229
	case FS_FAT32 :
230
		if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) return FALSE;
231
		ST_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)], val);
232
		break;
233
 
234
	default :
235
		return FALSE;
236
	}
237
	fs->winflag = 1;
238
	return TRUE;
239
}
240
#endif /* !_FS_READONLY */
241
 
242
 
243
 
244
 
245
/*-----------------------------------------------------------------------*/
246
/* Remove a cluster chain                                                */
247
/*-----------------------------------------------------------------------*/
248
 
249
#if !_FS_READONLY
250
static
251
BOOL remove_chain (	/* TRUE: successful, FALSE: failed */
252
	FATFS *fs,		/* File system object */
253
	DWORD clust		/* Cluster# to remove chain from */
254
)
255
{
256
	DWORD nxt;
257
 
258
 
259
	while (clust >= 2 && clust < fs->max_clust) {
260
		nxt = get_cluster(fs, clust);
261
		if (nxt == 1) return FALSE;
262
		if (!put_cluster(fs, clust, 0)) return FALSE;
263
		if (fs->free_clust != 0xFFFFFFFF) {
264
			fs->free_clust++;
265
#if _USE_FSINFO
266
			fs->fsi_flag = 1;
267
#endif
268
		}
269
		clust = nxt;
270
	}
271
	return TRUE;
272
}
273
#endif
274
 
275
 
276
 
277
 
278
/*-----------------------------------------------------------------------*/
279
/* Stretch or create a cluster chain                                     */
280
/*-----------------------------------------------------------------------*/
281
 
282
#if !_FS_READONLY
283
static
284
DWORD create_chain (	/* 0: No free cluster, 1: Error, >=2: New cluster number */
285
	FATFS *fs,			/* File system object */
286
	DWORD clust			/* Cluster# to stretch, 0 means create new */
287
)
288
{
289
	DWORD cstat, ncl, scl, mcl = fs->max_clust;
290
 
291
 
292
	if (clust == 0) {		/* Create new chain */
293
		scl = fs->last_clust;			/* Get suggested start point */
294
		if (scl == 0 || scl >= mcl) scl = 1;
295
	}
296
	else {					/* Stretch existing chain */
297
		cstat = get_cluster(fs, clust);	/* Check the cluster status */
298
		if (cstat < 2) return 1;		/* It is an invalid cluster */
299
		if (cstat < mcl) return cstat;	/* It is already followed by next cluster */
300
		scl = clust;
301
	}
302
 
303
	ncl = scl;				/* Start cluster */
304
	for (;;) {
305
		ncl++;							/* Next cluster */
306
		if (ncl >= mcl) {				/* Wrap around */
307
			ncl = 2;
308
			if (ncl > scl) return 0;	/* No free custer */
309
		}
310
		cstat = get_cluster(fs, ncl);	/* Get the cluster status */
311
		if (cstat == 0) break;			/* Found a free cluster */
312
		if (cstat == 1) return 1;		/* Any error occured */
313
		if (ncl == scl) return 0;		/* No free custer */
314
	}
315
 
316
	if (!put_cluster(fs, ncl, 0x0FFFFFFF)) return 1;			/* Mark the new cluster "in use" */
317
	if (clust != 0 && !put_cluster(fs, clust, ncl)) return 1;	/* Link it to previous one if needed */
318
 
319
	fs->last_clust = ncl;				/* Update fsinfo */
320
	if (fs->free_clust != 0xFFFFFFFF) {
321
		fs->free_clust--;
322
#if _USE_FSINFO
323
		fs->fsi_flag = 1;
324
#endif
325
	}
326
 
327
	return ncl;		/* Return new cluster number */
328
}
329
#endif /* !_FS_READONLY */
330
 
331
 
332
 
333
 
334
/*-----------------------------------------------------------------------*/
335
/* Get sector# from cluster#                                             */
336
/*-----------------------------------------------------------------------*/
337
 
338
static
339
DWORD clust2sect (	/* !=0: sector number, 0: failed - invalid cluster# */
340
	FATFS *fs,		/* File system object */
341
	DWORD clust		/* Cluster# to be converted */
342
)
343
{
344
	clust -= 2;
345
	if (clust >= (fs->max_clust - 2)) return 0;		/* Invalid cluster# */
346
	return clust * fs->csize + fs->database;
347
}
348
 
349
 
350
 
351
 
352
/*-----------------------------------------------------------------------*/
353
/* Move directory pointer to next                                        */
354
/*-----------------------------------------------------------------------*/
355
 
356
static
357
BOOL next_dir_entry (	/* TRUE: successful, FALSE: could not move next */
358
	DIR *dj				/* Pointer to directory object */
359
)
360
{
361
	DWORD clust;
362
	WORD idx;
363
 
364
 
365
	idx = dj->index + 1;
366
	if ((idx & ((SS(dj->fs) - 1) / 32)) == 0) {		/* Table sector changed? */
367
		dj->sect++;				/* Next sector */
368
		if (dj->clust == 0) {	/* In static table */
369
			if (idx >= dj->fs->n_rootdir) return FALSE;	/* Reached to end of table */
370
		} else {					/* In dynamic table */
371
			if (((idx / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) {	/* Cluster changed? */
372
				clust = get_cluster(dj->fs, dj->clust);			/* Get next cluster */
373
				if (clust < 2 || clust >= dj->fs->max_clust)	/* Reached to end of table */
374
					return FALSE;
375
				dj->clust = clust;				/* Initialize for new cluster */
376
				dj->sect = clust2sect(dj->fs, clust);
377
			}
378
		}
379
	}
380
	dj->index = idx;	/* Lower several bits of dj->index indicates offset in dj->sect */
381
	return TRUE;
382
}
383
 
384
 
385
 
386
 
387
/*-----------------------------------------------------------------------*/
388
/* Get file status from directory entry                                  */
389
/*-----------------------------------------------------------------------*/
390
 
391
#if _FS_MINIMIZE <= 1
392
static
393
void get_fileinfo (	/* No return code */
394
	FILINFO *finfo, /* Ptr to store the file information */
395
	const BYTE *dir	/* Ptr to the directory entry */
396
)
397
{
398
	BYTE n, c, a;
399
	char *p;
400
 
401
 
402
	p = &finfo->fname[0];
403
	a = _USE_NTFLAG ? dir[DIR_NTres] : 0;		/* NT flag */
404
	for (n = 0; n < 8; n++) {	/* Convert file name (body) */
405
		c = dir[n];
406
		if (c == ' ') break;
407
		if (c == 0x05) c = 0xE5;
408
		if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20;
409
		*p++ = c;
410
	}
411
	if (dir[8] != ' ') {		/* Convert file name (extension) */
412
		*p++ = '.';
413
		for (n = 8; n < 11; n++) {
414
			c = dir[n];
415
			if (c == ' ') break;
416
			if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20;
417
			*p++ = c;
418
		}
419
	}
420
	*p = '\0';
421
 
422
	finfo->fattrib = dir[DIR_Attr];					/* Attribute */
423
	finfo->fsize = LD_DWORD(&dir[DIR_FileSize]);	/* Size */
424
	finfo->fdate = LD_WORD(&dir[DIR_WrtDate]);		/* Date */
425
	finfo->ftime = LD_WORD(&dir[DIR_WrtTime]);		/* Time */
426
}
427
#endif /* _FS_MINIMIZE <= 1 */
428
 
429
 
430
 
431
 
432
/*-----------------------------------------------------------------------*/
433
/* Pick a paragraph and create the name in format of directory entry     */
434
/*-----------------------------------------------------------------------*/
435
 
436
static
437
char make_dirfile (		/* 1: error - detected an invalid format, '\0'or'/': next character */
438
	const char **path,	/* Pointer to the file path pointer */
439
	char *dirname		/* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */
440
)
441
{
442
	BYTE n, t, c, a, b;
443
 
444
 
445
	memset(dirname, ' ', 8+3);	/* Fill buffer with spaces */
446
	a = 0; b = 0x18;	/* NT flag */
447
	n = 0; t = 8;
448
	for (;;) {
449
		c = *(*path)++;
450
		if (c == '\0' || c == '/') {		/* Reached to end of str or directory separator */
451
			if (n == 0) break;
452
			dirname[11] = _USE_NTFLAG ? (a & b) : 0;
453
			return c;
454
		}
455
		if (c <= ' ' || c == 0x7F) break;		/* Reject invisible chars */
456
		if (c == '.') {
457
			if (!(a & 1) && n >= 1 && n <= 8) {	/* Enter extension part */
458
				n = 8; t = 11; continue;
459
			}
460
			break;
461
		}
462
		if (_USE_SJIS &&
463
			((c >= 0x81 && c <= 0x9F) ||	/* Accept S-JIS code */
464
		    (c >= 0xE0 && c <= 0xFC))) {
465
			if (n == 0 && c == 0xE5)		/* Change heading \xE5 to \x05 */
466
				c = 0x05;
467
			a ^= 0x01; goto md_l2;
468
		}
469
		if (c == '"') break;				/* Reject " */
470
		if (c <= ')') goto md_l1;			/* Accept ! # $ % & ' ( ) */
471
		if (c <= ',') break;				/* Reject * + , */
472
		if (c <= '9') goto md_l1;			/* Accept - 0-9 */
473
		if (c <= '?') break;				/* Reject : ; < = > ? */
474
		if (!(a & 1)) {	/* These checks are not applied to S-JIS 2nd byte */
475
			if (c == '|') break;			/* Reject | */
476
			if (c >= '[' && c <= ']') break;/* Reject [ \ ] */
477
			if (_USE_NTFLAG && c >= 'A' && c <= 'Z')
478
				(t == 8) ? (b &= 0xF7) : (b &= 0xEF);
479
			if (c >= 'a' && c <= 'z') {		/* Convert to upper case */
480
				c -= 0x20;
481
				if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10);
482
			}
483
		}
484
	md_l1:
485
		a &= 0xFE;
486
	md_l2:
487
		if (n >= t) break;
488
		dirname[n++] = c;
489
	}
490
	return 1;
491
}
492
 
493
 
494
 
495
 
496
/*-----------------------------------------------------------------------*/
497
/* Trace a file path                                                     */
498
/*-----------------------------------------------------------------------*/
499
 
500
static
501
FRESULT trace_path (	/* FR_OK(0): successful, !=0: error code */
502
	DIR *dj,			/* Pointer to directory object to return last directory */
503
	char *fn,			/* Pointer to last segment name to return {file(8),ext(3),attr(1)} */
504
	const char *path,	/* Full-path string to trace a file or directory */
505
	BYTE **dir			/* Pointer to pointer to found entry to retutn */
506
)
507
{
508
	DWORD clust;
509
	char ds;
510
	BYTE *dptr = NULL;
511
	FATFS *fs = dj->fs;
512
 
513
 
514
	/* Initialize directory object */
515
	clust = fs->dirbase;
516
	if (fs->fs_type == FS_FAT32) {
517
		dj->clust = dj->sclust = clust;
518
		dj->sect = clust2sect(fs, clust);
519
	} else {
520
		dj->clust = dj->sclust = 0;
521
		dj->sect = clust;
522
	}
523
	dj->index = 0;
524
 
525
	if (*path == '\0') {					/* Null path means the root directory */
526
		*dir = NULL; return FR_OK;
527
	}
528
 
529
	for (;;) {
530
		ds = make_dirfile(&path, fn);			/* Get a paragraph into fn[] */
531
		if (ds == 1) return FR_INVALID_NAME;
532
		for (;;) {
533
			if (!move_window(fs, dj->sect)) return FR_RW_ERROR;
534
			dptr = &fs->win[(dj->index & ((SS(fs) - 1) / 32)) * 32];	/* Pointer to the directory entry */
535
			if (dptr[DIR_Name] == 0)						/* Has it reached to end of dir? */
536
				return !ds ? FR_NO_FILE : FR_NO_PATH;
537
			if (dptr[DIR_Name] != 0xE5						/* Matched? */
538
				&& !(dptr[DIR_Attr] & AM_VOL)
539
				&& !memcmp(&dptr[DIR_Name], fn, 8+3) ) break;
540
			if (!next_dir_entry(dj))						/* Next directory pointer */
541
				return !ds ? FR_NO_FILE : FR_NO_PATH;
542
		}
543
		if (!ds) { *dir = dptr; return FR_OK; }				/* Matched with end of path */
544
		if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH;	/* Cannot trace because it is a file */
545
		clust = ((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16) | LD_WORD(&dptr[DIR_FstClusLO]); /* Get cluster# of the directory */
546
		dj->clust = dj->sclust = clust;				/* Restart scanning at the new directory */
547
		dj->sect = clust2sect(fs, clust);
548
		dj->index = 2;
549
	}
550
}
551
 
552
 
553
 
554
 
555
/*-----------------------------------------------------------------------*/
556
/* Reserve a directory entry                                             */
557
/*-----------------------------------------------------------------------*/
558
 
559
#if !_FS_READONLY
560
static
561
FRESULT reserve_direntry (	/* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */
562
	DIR *dj,				/* Target directory to create new entry */
563
	BYTE **dir				/* Pointer to pointer to created entry to retutn */
564
)
565
{
566
	DWORD clust, sector;
567
	BYTE c, n, *dptr;
568
	FATFS *fs = dj->fs;
569
 
570
 
571
	/* Re-initialize directory object */
572
	clust = dj->sclust;
573
	if (clust != 0) {	/* Dyanmic directory table */
574
		dj->clust = clust;
575
		dj->sect = clust2sect(fs, clust);
576
	} else {			/* Static directory table */
577
		dj->sect = fs->dirbase;
578
	}
579
	dj->index = 0;
580
 
581
	do {
582
		if (!move_window(fs, dj->sect)) return FR_RW_ERROR;
583
		dptr = &fs->win[(dj->index & ((SS(dj->fs) - 1) / 32)) * 32];	/* Pointer to the directory entry */
584
		c = dptr[DIR_Name];
585
		if (c == 0 || c == 0xE5) {		/* Found an empty entry */
586
			*dir = dptr; return FR_OK;
587
		}
588
	} while (next_dir_entry(dj));		/* Next directory pointer */
589
	/* Reached to end of the directory table */
590
 
591
	/* Abort when it is a static table or could not stretch dynamic table */
592
	if (clust == 0 || !(clust = create_chain(fs, dj->clust))) return FR_DENIED;
593
	if (clust == 1 || !move_window(fs, 0)) return FR_RW_ERROR;
594
 
595
	/* Cleanup the expanded table */
596
	fs->winsect = sector = clust2sect(fs, clust);
597
	memset(fs->win, 0, SS(fs));
598
	for (n = fs->csize; n; n--) {
599
		if (disk_write(fs->drive, fs->win, sector, 1) != RES_OK)
600
			return FR_RW_ERROR;
601
		sector++;
602
	}
603
	fs->winflag = 1;
604
	*dir = fs->win;
605
 
606
	return FR_OK;
607
}
608
#endif /* !_FS_READONLY */
609
 
610
 
611
 
612
 
613
/*-----------------------------------------------------------------------*/
614
/* Load boot record and check if it is an FAT boot record                */
615
/*-----------------------------------------------------------------------*/
616
 
617
static
618
BYTE check_fs (	/* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record or error */
619
	FATFS *fs,	/* File system object */
620
	DWORD sect	/* Sector# (lba) to check if it is an FAT boot record or not */
621
)
622
{
623
	if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK)	/* Load boot record */
624
		return 2;
625
	if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55)				/* Check record signature (always placed at offset 510 even if the sector size is >512) */
626
		return 2;
627
 
628
	if (!memcmp(&fs->win[BS_FilSysType], "FAT", 3))			/* Check FAT signature */
629
		return 0;
630
	if (!memcmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80))
631
		return 0;
632
 
633
	return 1;
634
}
635
 
636
 
637
 
638
 
639
/*-----------------------------------------------------------------------*/
640
/* Make sure that the file system is valid                               */
641
/*-----------------------------------------------------------------------*/
642
 
643
static
644
FRESULT auto_mount (	/* FR_OK(0): successful, !=0: any error occured */
645
	const char **path,	/* Pointer to pointer to the path name (drive number) */
646
	FATFS **rfs,		/* Pointer to pointer to the found file system object */
647
	BYTE chk_wp			/* !=0: Check media write protection for write access */
648
)
649
{
650
	BYTE drv, fmt, *tbl;
651
	DSTATUS stat;
652
	DWORD bootsect, fatsize, totalsect, maxclust;
653
	const char *p = *path;
654
	FATFS *fs;
655
 
656
 
657
	/* Get drive number from the path name */
658
	while (*p == ' ') p++;		/* Strip leading spaces */
659
	drv = p[0] - '0';			/* Is there a drive number? */
660
	if (drv <= 9 && p[1] == ':')
661
		p += 2;				/* Found a drive number, get and strip it */
662
	else
663
		drv = 0;			/* No drive number is given, use drive number 0 as default */
664
	if (*p == '/') p++;		/* Strip heading slash */
665
	*path = p;				/* Return pointer to the path name */
666
 
667
	/* Check if the drive number is valid or not */
668
	if (drv >= _DRIVES) return FR_INVALID_DRIVE;	/* Is the drive number valid? */
669
	*rfs = fs = FatFs[drv];					/* Returen pointer to the corresponding file system object */
670
	if (!fs) return FR_NOT_ENABLED;			/* Is the file system object registered? */
671
 
672
	if (fs->fs_type) {						/* If the logical drive has been mounted */
673
		stat = disk_status(fs->drive);
674
		if (!(stat & STA_NOINIT)) {			/* and physical drive is kept initialized (has not been changed), */
675
#if !_FS_READONLY
676
			if (chk_wp && (stat & STA_PROTECT))	/* Check write protection if needed */
677
				return FR_WRITE_PROTECTED;
678
#endif
679
			return FR_OK;					/* The file system object is valid */
680
		}
681
	}
682
 
683
	/* The logical drive must be re-mounted. Following code attempts to mount the logical drive */
684
 
685
	memset(fs, 0, sizeof(FATFS));		/* Clean-up the file system object */
686
	fs->drive = LD2PD(drv);				/* Bind the logical drive and a physical drive */
687
	stat = disk_initialize(fs->drive);	/* Initialize low level disk I/O layer */
688
	if (stat & STA_NOINIT)				/* Check if the drive is ready */
689
		return FR_NOT_READY;
690
#if S_MAX_SIZ > 512						/* Get disk sector size if needed */
691
	if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > S_MAX_SIZ)
692
		return FR_NO_FILESYSTEM;
693
#endif
694
#if !_FS_READONLY
695
	if (chk_wp && (stat & STA_PROTECT))	/* Check write protection if needed */
696
		return FR_WRITE_PROTECTED;
697
#endif
698
	/* Search FAT partition on the drive */
699
	fmt = check_fs(fs, bootsect = 0);	/* Check sector 0 as an SFD format */
700
	if (fmt == 1) {						/* Not an FAT boot record, it may be patitioned */
701
		/* Check a partition listed in top of the partition table */
702
		tbl = &fs->win[MBR_Table + LD2PT(drv) * 16];	/* Partition table */
703
		if (tbl[4]) {									/* Is the partition existing? */
704
			bootsect = LD_DWORD(&tbl[8]);				/* Partition offset in LBA */
705
			fmt = check_fs(fs, bootsect);				/* Check the partition */
706
		}
707
	}
708
	if (fmt || LD_WORD(&fs->win[BPB_BytsPerSec]) != SS(fs))	/* No valid FAT patition is found */
709
		return FR_NO_FILESYSTEM;
710
 
711
	/* Initialize the file system object */
712
	fatsize = LD_WORD(&fs->win[BPB_FATSz16]);			/* Number of sectors per FAT */
713
	if (!fatsize) fatsize = LD_DWORD(&fs->win[BPB_FATSz32]);
714
	fs->sects_fat = fatsize;
715
	fs->n_fats = fs->win[BPB_NumFATs];					/* Number of FAT copies */
716
	fatsize *= fs->n_fats;								/* (Number of sectors in FAT area) */
717
	fs->fatbase = bootsect + LD_WORD(&fs->win[BPB_RsvdSecCnt]); /* FAT start sector (lba) */
718
	fs->csize = fs->win[BPB_SecPerClus];				/* Number of sectors per cluster */
719
	fs->n_rootdir = LD_WORD(&fs->win[BPB_RootEntCnt]);	/* Nmuber of root directory entries */
720
	totalsect = LD_WORD(&fs->win[BPB_TotSec16]);		/* Number of sectors on the file system */
721
	if (!totalsect) totalsect = LD_DWORD(&fs->win[BPB_TotSec32]);
722
	fs->max_clust = maxclust = (totalsect				/* max_clust = Last cluster# + 1 */
723
		- LD_WORD(&fs->win[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / (SS(fs)/32)
724
		) / fs->csize + 2;
725
 
726
	fmt = FS_FAT12;										/* Determine the FAT sub type */
727
	if (maxclust >= 0xFF7) fmt = FS_FAT16;
728
	if (maxclust >= 0xFFF7) fmt = FS_FAT32;
729
 
730
	if (fmt == FS_FAT32)
731
		fs->dirbase = LD_DWORD(&fs->win[BPB_RootClus]);	/* Root directory start cluster */
732
	else
733
		fs->dirbase = fs->fatbase + fatsize;			/* Root directory start sector (lba) */
734
	fs->database = fs->fatbase + fatsize + fs->n_rootdir / (SS(fs)/32);	/* Data start sector (lba) */
735
 
736
#if !_FS_READONLY
737
	/* Initialize allocation information */
738
	fs->free_clust = 0xFFFFFFFF;
739
#if _USE_FSINFO
740
	/* Get fsinfo if needed */
741
	if (fmt == FS_FAT32) {
742
		fs->fsi_sector = bootsect + LD_WORD(&fs->win[BPB_FSInfo]);
743
		if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK &&
744
			LD_WORD(&fs->win[BS_55AA]) == 0xAA55 &&
745
			LD_DWORD(&fs->win[FSI_LeadSig]) == 0x41615252 &&
746
			LD_DWORD(&fs->win[FSI_StrucSig]) == 0x61417272) {
747
			fs->last_clust = LD_DWORD(&fs->win[FSI_Nxt_Free]);
748
			fs->free_clust = LD_DWORD(&fs->win[FSI_Free_Count]);
749
		}
750
	}
751
#endif
752
#endif
753
 
754
	fs->fs_type = fmt;			/* FAT syb-type */
755
	fs->id = ++fsid;			/* File system mount ID */
756
	return FR_OK;
757
}
758
 
759
 
760
 
761
 
762
/*-----------------------------------------------------------------------*/
763
/* Check if the file/dir object is valid or not                          */
764
/*-----------------------------------------------------------------------*/
765
 
766
static
767
FRESULT validate (		/* FR_OK(0): The object is valid, !=0: Invalid */
768
	const FATFS *fs,	/* Pointer to the file system object */
769
	WORD id				/* Member id of the target object to be checked */
770
)
771
{
772
	if (!fs || !fs->fs_type || fs->id != id)
773
		return FR_INVALID_OBJECT;
774
	if (disk_status(fs->drive) & STA_NOINIT)
775
		return FR_NOT_READY;
776
 
777
	return FR_OK;
778
}
779
 
780
 
781
 
782
 
783
/*--------------------------------------------------------------------------
784
 
785
   Public Functions
786
 
787
--------------------------------------------------------------------------*/
788
 
789
 
790
 
791
/*-----------------------------------------------------------------------*/
792
/* Mount/Unmount a Locical Drive                                         */
793
/*-----------------------------------------------------------------------*/
794
 
795
FRESULT f_mount (
796
	BYTE drv,		/* Logical drive number to be mounted/unmounted */
797
	FATFS *fs		/* Pointer to new file system object (NULL for unmount)*/
798
)
799
{
800
	if (drv >= _DRIVES) return FR_INVALID_DRIVE;
801
 
802
	if (FatFs[drv]) FatFs[drv]->fs_type = 0;	/* Clear old object */
803
 
804
	FatFs[drv] = fs;			/* Register and clear new object */
805
	if (fs) fs->fs_type = 0;
806
 
807
	return FR_OK;
808
}
809
 
810
 
811
 
812
 
813
/*-----------------------------------------------------------------------*/
814
/* Open or Create a File                                                 */
815
/*-----------------------------------------------------------------------*/
816
 
817
FRESULT f_open (
818
	FIL *fp,			/* Pointer to the blank file object */
819
	const char *path,	/* Pointer to the file name */
820
	BYTE mode			/* Access mode and file open mode flags */
821
)
822
{
823
	FRESULT res;
824
	DIR dj;
825
	BYTE *dir;
826
	char fn[8+3+1];
827
 
828
 
829
	fp->fs = NULL;		/* Clear file object */
830
#if !_FS_READONLY
831
	mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW);
832
	res = auto_mount(&path, &dj.fs, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)));
833
#else
834
	mode &= FA_READ;
835
	res = auto_mount(&path, &dj.fs, 0);
836
#endif
837
	if (res != FR_OK) return res;
838
	res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
839
 
840
#if !_FS_READONLY
841
	/* Create or Open a file */
842
	if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {
843
		DWORD ps, rs;
844
		if (res != FR_OK) {		/* No file, create new */
845
			if (res != FR_NO_FILE) return res;
846
			res = reserve_direntry(&dj, &dir);
847
			if (res != FR_OK) return res;
848
			memset(dir, 0, 32);		/* Initialize the new entry with open name */
849
			memcpy(&dir[DIR_Name], fn, 8+3);
850
			dir[DIR_NTres] = fn[11];
851
			mode |= FA_CREATE_ALWAYS;
852
		}
853
		else {					/* Any object is already existing */
854
			if (mode & FA_CREATE_NEW)			/* Cannot create new */
855
				return FR_EXIST;
856
			if (!dir || (dir[DIR_Attr] & (AM_RDO|AM_DIR)))	/* Cannot overwrite it (R/O or DIR) */
857
				return FR_DENIED;
858
			if (mode & FA_CREATE_ALWAYS) {		/* Resize it to zero if needed */
859
				rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);	/* Get start cluster */
860
				ST_WORD(&dir[DIR_FstClusHI], 0);	/* cluster = 0 */
861
				ST_WORD(&dir[DIR_FstClusLO], 0);
862
				ST_DWORD(&dir[DIR_FileSize], 0);	/* size = 0 */
863
				dj.fs->winflag = 1;
864
				ps = dj.fs->winsect;			/* Remove the cluster chain */
865
				if (!remove_chain(dj.fs, rs) || !move_window(dj.fs, ps))
866
					return FR_RW_ERROR;
867
				dj.fs->last_clust = rs - 1;		/* Reuse the cluster hole */
868
			}
869
		}
870
		if (mode & FA_CREATE_ALWAYS) {
871
			dir[DIR_Attr] = 0;					/* Reset attribute */
872
			ps = get_fattime();
873
			ST_DWORD(&dir[DIR_CrtTime], ps);	/* Created time */
874
			dj.fs->winflag = 1;
875
			mode |= FA__WRITTEN;				/* Set file changed flag */
876
		}
877
	}
878
	/* Open an existing file */
879
	else {
880
#endif /* !_FS_READONLY */
881
		if (res != FR_OK) return res;			/* Trace failed */
882
		if (!dir || (dir[DIR_Attr] & AM_DIR))	/* It is a directory */
883
			return FR_NO_FILE;
884
#if !_FS_READONLY
885
		if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
886
			return FR_DENIED;
887
	}
888
	fp->dir_sect = dj.fs->winsect;		/* Pointer to the directory entry */
889
	fp->dir_ptr = dir;
890
#endif
891
	fp->flag = mode;					/* File access mode */
892
	fp->org_clust =						/* File start cluster */
893
		((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
894
	fp->fsize = LD_DWORD(&dir[DIR_FileSize]);	/* File size */
895
	fp->fptr = 0; fp->csect = 255;		/* File pointer */
896
	fp->curr_sect = 0;
897
	fp->fs = dj.fs; fp->id = dj.fs->id;	/* Owner file system object of the file */
898
 
899
	return FR_OK;
900
}
901
 
902
 
903
 
904
 
905
/*-----------------------------------------------------------------------*/
906
/* Read File                                                             */
907
/*-----------------------------------------------------------------------*/
908
 
909
FRESULT f_read (
910
	FIL *fp, 		/* Pointer to the file object */
911
	void *buff,		/* Pointer to data buffer */
912
	UINT btr,		/* Number of bytes to read */
913
	UINT *br		/* Pointer to number of bytes read */
914
)
915
{
916
	FRESULT res;
917
	DWORD clust, sect, remain;
918
	UINT rcnt, cc;
919
	BYTE *rbuff = buff;
920
 
921
 
922
	*br = 0;
923
	res = validate(fp->fs, fp->id);					/* Check validity of the object */
924
	if (res != FR_OK) return res;
925
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;	/* Check error flag */
926
	if (!(fp->flag & FA_READ)) return FR_DENIED;	/* Check access mode */
927
	remain = fp->fsize - fp->fptr;
928
	if (btr > remain) btr = (UINT)remain;			/* Truncate btr by remaining bytes */
929
 
930
	for ( ;  btr;									/* Repeat until all data transferred */
931
		rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
932
		if ((fp->fptr % SS(fp->fs)) == 0) {			/* On the sector boundary? */
933
			if (fp->csect >= fp->fs->csize) {		/* On the cluster boundary? */
934
				clust = (fp->fptr == 0) ?			/* On the top of the file? */
935
					fp->org_clust : get_cluster(fp->fs, fp->curr_clust);
936
				if (clust < 2 || clust >= fp->fs->max_clust) goto fr_error;
937
				fp->curr_clust = clust;				/* Update current cluster */
938
				fp->csect = 0;						/* Reset sector address in the cluster */
939
			}
940
			sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect;	/* Get current sector */
941
			cc = btr / SS(fp->fs);					/* When remaining bytes >= sector size, */
942
			if (cc) {								/* Read maximum contiguous sectors directly */
943
				if (fp->csect + cc > fp->fs->csize)	/* Clip at cluster boundary */
944
					cc = fp->fs->csize - fp->csect;
945
				if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
946
					goto fr_error;
947
				fp->csect += (BYTE)cc;				/* Next sector address in the cluster */
948
				rcnt = SS(fp->fs) * cc;				/* Number of bytes transferred */
949
				continue;
950
			}
951
			if (sect != fp->curr_sect) {			/* Is window offset changed? */
952
#if !_FS_READONLY
953
				if (fp->flag & FA__DIRTY) {			/* Write back file I/O buffer if needed */
954
					if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
955
						goto fr_error;
956
					fp->flag &= (BYTE)~FA__DIRTY;
957
				}
958
#endif
959
				if (disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK)	/* Fill file I/O buffer with file data */
960
					goto fr_error;
961
				fp->curr_sect = sect;
962
			}
963
			fp->csect++;							/* Next sector address in the cluster */
964
		}
965
		rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));	/* Get partial sector from file I/O buffer */
966
		if (rcnt > btr) rcnt = btr;
967
		memcpy(rbuff, &fp->buffer[fp->fptr % SS(fp->fs)], rcnt);
968
	}
969
 
970
	return FR_OK;
971
 
972
fr_error:	/* Abort this file due to an unrecoverable error */
973
	fp->flag |= FA__ERROR;
974
	return FR_RW_ERROR;
975
}
976
 
977
 
978
 
979
 
980
#if !_FS_READONLY
981
/*-----------------------------------------------------------------------*/
982
/* Write File                                                            */
983
/*-----------------------------------------------------------------------*/
984
 
985
FRESULT f_write (
986
	FIL *fp,			/* Pointer to the file object */
987
	const void *buff,	/* Pointer to the data to be written */
988
	UINT btw,			/* Number of bytes to write */
989
	UINT *bw			/* Pointer to number of bytes written */
990
)
991
{
992
	FRESULT res;
993
	DWORD clust, sect;
994
	UINT wcnt, cc;
995
	const BYTE *wbuff = buff;
996
 
997
 
998
	*bw = 0;
999
	res = validate(fp->fs, fp->id);					/* Check validity of the object */
1000
	if (res != FR_OK) return res;
1001
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;	/* Check error flag */
1002
	if (!(fp->flag & FA_WRITE)) return FR_DENIED;	/* Check access mode */
1003
	if (fp->fsize + btw < fp->fsize) return FR_OK;	/* File size cannot reach 4GB */
1004
 
1005
	for ( ;  btw;									/* Repeat until all data transferred */
1006
		wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
1007
		if ((fp->fptr % SS(fp->fs)) == 0) {			/* On the sector boundary? */
1008
			if (fp->csect >= fp->fs->csize) {		/* On the cluster boundary? */
1009
				if (fp->fptr == 0) {				/* On the top of the file? */
1010
					clust = fp->org_clust;			/* Follow from the origin */
1011
					if (clust == 0)					/* When there is no cluster chain, */
1012
						fp->org_clust = clust = create_chain(fp->fs, 0);	/* Create a new cluster chain */
1013
				} else {							/* Middle or end of the file */
1014
					clust = create_chain(fp->fs, fp->curr_clust);			/* Trace or streach cluster chain */
1015
				}
1016
				if (clust == 0) break;				/* Could not allocate a new cluster (disk full) */
1017
				if (clust == 1 || clust >= fp->fs->max_clust) goto fw_error;
1018
				fp->curr_clust = clust;				/* Update current cluster */
1019
				fp->csect = 0;						/* Reset sector address in the cluster */
1020
			}
1021
			sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect;	/* Get current sector */
1022
			cc = btw / SS(fp->fs);					/* When remaining bytes >= sector size, */
1023
			if (cc) {								/* Write maximum contiguous sectors directly */
1024
				if (fp->csect + cc > fp->fs->csize)	/* Clip at cluster boundary */
1025
					cc = fp->fs->csize - fp->csect;
1026
				if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)
1027
					goto fw_error;
1028
				fp->csect += (BYTE)cc;				/* Next sector address in the cluster */
1029
				wcnt = SS(fp->fs) * cc;				/* Number of bytes transferred */
1030
				continue;
1031
			}
1032
			if (sect != fp->curr_sect) {			/* Is window offset changed? */
1033
				if (fp->flag & FA__DIRTY) {			/* Write back file I/O buffer if needed */
1034
					if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
1035
						goto fw_error;
1036
					fp->flag &= (BYTE)~FA__DIRTY;
1037
				}
1038
				if (fp->fptr < fp->fsize &&  		/* Fill file I/O buffer with file data */
1039
					disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK)
1040
						goto fw_error;
1041
				fp->curr_sect = sect;
1042
			}
1043
			fp->csect++;							/* Next sector address in the cluster */
1044
		}
1045
		wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));	/* Put partial sector into file I/O buffer */
1046
		if (wcnt > btw) wcnt = btw;
1047
		memcpy(&fp->buffer[fp->fptr % SS(fp->fs)], wbuff, wcnt);
1048
		fp->flag |= FA__DIRTY;
1049
	}
1050
 
1051
	if (fp->fptr > fp->fsize) fp->fsize = fp->fptr;	/* Update file size if needed */
1052
	fp->flag |= FA__WRITTEN;						/* Set file changed flag */
1053
	return FR_OK;
1054
 
1055
fw_error:	/* Abort this file due to an unrecoverable error */
1056
	fp->flag |= FA__ERROR;
1057
	return FR_RW_ERROR;
1058
}
1059
 
1060
 
1061
 
1062
 
1063
/*-----------------------------------------------------------------------*/
1064
/* Synchronize the file object                                           */
1065
/*-----------------------------------------------------------------------*/
1066
 
1067
FRESULT f_sync (
1068
	FIL *fp		/* Pointer to the file object */
1069
)
1070
{
1071
	FRESULT res;
1072
	DWORD tim;
1073
	BYTE *dir;
1074
 
1075
 
1076
	res = validate(fp->fs, fp->id);		/* Check validity of the object */
1077
	if (res == FR_OK) {
1078
		if (fp->flag & FA__WRITTEN) {	/* Has the file been written? */
1079
			/* Write back data buffer if needed */
1080
			if (fp->flag & FA__DIRTY) {
1081
				if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
1082
					return FR_RW_ERROR;
1083
				fp->flag &= (BYTE)~FA__DIRTY;
1084
			}
1085
			/* Update the directory entry */
1086
			if (!move_window(fp->fs, fp->dir_sect))
1087
				return FR_RW_ERROR;
1088
			dir = fp->dir_ptr;
1089
			dir[DIR_Attr] |= AM_ARC;						/* Set archive bit */
1090
			ST_DWORD(&dir[DIR_FileSize], fp->fsize);		/* Update file size */
1091
			ST_WORD(&dir[DIR_FstClusLO], fp->org_clust);	/* Update start cluster */
1092
			ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16);
1093
			tim = get_fattime();					/* Updated time */
1094
			ST_DWORD(&dir[DIR_WrtTime], tim);
1095
			fp->flag &= (BYTE)~FA__WRITTEN;
1096
			res = sync(fp->fs);
1097
		}
1098
	}
1099
	return res;
1100
}
1101
 
1102
#endif /* !_FS_READONLY */
1103
 
1104
 
1105
 
1106
 
1107
/*-----------------------------------------------------------------------*/
1108
/* Close File                                                            */
1109
/*-----------------------------------------------------------------------*/
1110
 
1111
FRESULT f_close (
1112
	FIL *fp		/* Pointer to the file object to be closed */
1113
)
1114
{
1115
	FRESULT res;
1116
 
1117
 
1118
#if !_FS_READONLY
1119
	res = f_sync(fp);
1120
#else
1121
	res = validate(fp->fs, fp->id);
1122
#endif
1123
	if (res == FR_OK) fp->fs = NULL;
1124
	return res;
1125
}
1126
 
1127
 
1128
 
1129
 
1130
#if _FS_MINIMIZE <= 2
1131
/*-----------------------------------------------------------------------*/
1132
/* Seek File R/W Pointer                                                 */
1133
/*-----------------------------------------------------------------------*/
1134
 
1135
FRESULT f_lseek (
1136
	FIL *fp,		/* Pointer to the file object */
1137
	DWORD ofs		/* File pointer from top of file */
1138
)
1139
{
1140
	FRESULT res;
1141
	DWORD clust, csize, nsect, ifptr;
1142
 
1143
 
1144
	res = validate(fp->fs, fp->id);		/* Check validity of the object */
1145
	if (res != FR_OK) return res;
1146
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;
1147
	if (ofs > fp->fsize					/* In read-only mode, clip offset with the file size */
1148
#if !_FS_READONLY
1149
		 && !(fp->flag & FA_WRITE)
1150
#endif
1151
		) ofs = fp->fsize;
1152
 
1153
	ifptr = fp->fptr;
1154
	fp->fptr = 0; fp->csect = 255;
1155
	nsect = 0;
1156
	if (ofs > 0) {
1157
		csize = (DWORD)fp->fs->csize * SS(fp->fs);	/* Cluster size (byte) */
1158
		if (ifptr > 0 &&
1159
			(ofs - 1) / csize >= (ifptr - 1) / csize) {/* When seek to same or following cluster, */
1160
			fp->fptr = (ifptr - 1) & ~(csize - 1);	/* start from the current cluster */
1161
			ofs -= fp->fptr;
1162
			clust = fp->curr_clust;
1163
		} else {									/* When seek to back cluster, */
1164
			clust = fp->org_clust;					/* start from the first cluster */
1165
#if !_FS_READONLY
1166
			if (clust == 0) {						/* If no cluster chain, create a new chain */
1167
				clust = create_chain(fp->fs, 0);
1168
				if (clust == 1) goto fk_error;
1169
				fp->org_clust = clust;
1170
			}
1171
#endif
1172
			fp->curr_clust = clust;
1173
		}
1174
		if (clust != 0) {
1175
			while (ofs > csize) {					/* Cluster following loop */
1176
#if !_FS_READONLY
1177
				if (fp->flag & FA_WRITE) {			/* Check if in write mode or not */
1178
					clust = create_chain(fp->fs, clust);	/* Force streached if in write mode */
1179
					if (clust == 0) {				/* When disk gets full, clip file size */
1180
						ofs = csize; break;
1181
					}
1182
				} else
1183
#endif
1184
					clust = get_cluster(fp->fs, clust);	/* Follow cluster chain if not in write mode */
1185
				if (clust < 2 || clust >= fp->fs->max_clust) goto fk_error;
1186
				fp->curr_clust = clust;
1187
				fp->fptr += csize;
1188
				ofs -= csize;
1189
			}
1190
			fp->fptr += ofs;
1191
			fp->csect = (BYTE)(ofs / SS(fp->fs));	/* Sector offset in the cluster */
1192
			if (ofs & (SS(fp->fs) - 1)) {
1193
				nsect = clust2sect(fp->fs, clust) + fp->csect;	/* Current sector */
1194
				fp->csect++;
1195
			}
1196
		}
1197
	}
1198
	if (nsect && nsect != fp->curr_sect) {
1199
#if !_FS_READONLY
1200
		if (fp->flag & FA__DIRTY) {			/* Write-back dirty buffer if needed */
1201
			if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK)
1202
				goto fk_error;
1203
			fp->flag &= (BYTE)~FA__DIRTY;
1204
		}
1205
#endif
1206
		if (disk_read(fp->fs->drive, fp->buffer, nsect, 1) != RES_OK)
1207
			goto fk_error;
1208
		fp->curr_sect = nsect;
1209
	}
1210
 
1211
#if !_FS_READONLY
1212
	if (fp->fptr > fp->fsize) {			/* Set changed flag if the file was extended */
1213
		fp->fsize = fp->fptr;
1214
		fp->flag |= FA__WRITTEN;
1215
	}
1216
#endif
1217
 
1218
	return FR_OK;
1219
 
1220
fk_error:	/* Abort this file due to an unrecoverable error */
1221
	fp->flag |= FA__ERROR;
1222
	return FR_RW_ERROR;
1223
}
1224
 
1225
 
1226
 
1227
 
1228
#if _FS_MINIMIZE <= 1
1229
/*-----------------------------------------------------------------------*/
1230
/* Create a directroy object                                             */
1231
/*-----------------------------------------------------------------------*/
1232
 
1233
FRESULT f_opendir (
1234
	DIR *dj,			/* Pointer to directory object to create */
1235
	const char *path	/* Pointer to the directory path */
1236
)
1237
{
1238
	FRESULT res;
1239
	BYTE *dir;
1240
	char fn[8+3+1];
1241
 
1242
 
1243
	res = auto_mount(&path, &dj->fs, 0);
1244
	if (res == FR_OK) {
1245
		res = trace_path(dj, fn, path, &dir);	/* Trace the directory path */
1246
		if (res == FR_OK) {						/* Trace completed */
1247
			if (dir) {							/* It is not the root dir */
1248
				if (dir[DIR_Attr] & AM_DIR) {	/* The entry is a directory */
1249
					dj->clust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
1250
					dj->sect = clust2sect(dj->fs, dj->clust);
1251
					dj->index = 2;
1252
				} else {						/* The entry is not a directory */
1253
					res = FR_NO_FILE;
1254
				}
1255
			}
1256
			dj->id = dj->fs->id;
1257
		}
1258
	}
1259
 
1260
	return res;
1261
}
1262
 
1263
 
1264
 
1265
 
1266
/*-----------------------------------------------------------------------*/
1267
/* Read Directory Entry in Sequense                                      */
1268
/*-----------------------------------------------------------------------*/
1269
 
1270
FRESULT f_readdir (
1271
	DIR *dj,			/* Pointer to the directory object */
1272
	FILINFO *finfo		/* Pointer to file information to return */
1273
)
1274
{
1275
	BYTE *dir, c, res;
1276
 
1277
 
1278
	res = validate(dj->fs, dj->id);			/* Check validity of the object */
1279
	if (res != FR_OK) return res;
1280
 
1281
	finfo->fname[0] = 0;
1282
	while (dj->sect) {
1283
		if (!move_window(dj->fs, dj->sect))
1284
			return FR_RW_ERROR;
1285
		dir = &dj->fs->win[(dj->index & ((SS(dj->fs) - 1) >> 5)) * 32];	/* pointer to the directory entry */
1286
		c = dir[DIR_Name];
1287
		if (c == 0) break;							/* Has it reached to end of dir? */
1288
		if (c != 0xE5 && !(dir[DIR_Attr] & AM_VOL))	/* Is it a valid entry? */
1289
			get_fileinfo(finfo, dir);
1290
		if (!next_dir_entry(dj)) dj->sect = 0;		/* Next entry */
1291
		if (finfo->fname[0]) break;					/* Found valid entry */
1292
	}
1293
 
1294
	return FR_OK;
1295
}
1296
 
1297
 
1298
 
1299
 
1300
#if _FS_MINIMIZE == 0
1301
/*-----------------------------------------------------------------------*/
1302
/* Get File Status                                                       */
1303
/*-----------------------------------------------------------------------*/
1304
 
1305
FRESULT f_stat (
1306
	const char *path,	/* Pointer to the file path */
1307
	FILINFO *finfo		/* Pointer to file information to return */
1308
)
1309
{
1310
	FRESULT res;
1311
	DIR dj;
1312
	BYTE *dir;
1313
	char fn[8+3+1];
1314
 
1315
 
1316
	res = auto_mount(&path, &dj.fs, 0);
1317
	if (res == FR_OK) {
1318
		res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
1319
		if (res == FR_OK) {						/* Trace completed */
1320
			if (dir)	/* Found an object */
1321
				get_fileinfo(finfo, dir);
1322
			else		/* It is root dir */
1323
				res = FR_INVALID_NAME;
1324
		}
1325
	}
1326
 
1327
	return res;
1328
}
1329
 
1330
 
1331
 
1332
#if !_FS_READONLY
1333
/*-----------------------------------------------------------------------*/
1334
/* Truncate File                                                         */
1335
/*-----------------------------------------------------------------------*/
1336
 
1337
FRESULT f_truncate (
1338
	FIL *fp		/* Pointer to the file object */
1339
)
1340
{
1341
	FRESULT res;
1342
	DWORD ncl;
1343
 
1344
 
1345
	res = validate(fp->fs, fp->id);		/* Check validity of the object */
1346
	if (res != FR_OK) return res;
1347
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;	/* Check error flag */
1348
	if (!(fp->flag & FA_WRITE)) return FR_DENIED;	/* Check access mode */
1349
 
1350
	if (fp->fsize > fp->fptr) {
1351
		fp->fsize = fp->fptr;	/* Set file size to current R/W point */
1352
		fp->flag |= FA__WRITTEN;
1353
		if (fp->fptr == 0) {	/* When set file size to zero, remove entire cluster chain */
1354
			if (!remove_chain(fp->fs, fp->org_clust)) goto ft_error;
1355
			fp->org_clust = 0;
1356
		} else {				/* When truncate a part of the file, remove remaining clusters */
1357
			ncl = get_cluster(fp->fs, fp->curr_clust);
1358
			if (ncl < 2) goto ft_error;
1359
			if (ncl < fp->fs->max_clust) {
1360
				if (!put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF)) goto ft_error;
1361
				if (!remove_chain(fp->fs, ncl)) goto ft_error;
1362
			}
1363
		}
1364
	}
1365
 
1366
	return FR_OK;
1367
 
1368
ft_error:	/* Abort this file due to an unrecoverable error */
1369
	fp->flag |= FA__ERROR;
1370
	return FR_RW_ERROR;
1371
}
1372
 
1373
 
1374
 
1375
 
1376
/*-----------------------------------------------------------------------*/
1377
/* Get Number of Free Clusters                                           */
1378
/*-----------------------------------------------------------------------*/
1379
 
1380
FRESULT f_getfree (
1381
	const char *drv,	/* Pointer to the logical drive number (root dir) */
1382
	DWORD *nclust,		/* Pointer to the variable to return number of free clusters */
1383
	FATFS **fatfs		/* Pointer to pointer to corresponding file system object to return */
1384
)
1385
{
1386
	FRESULT res;
1387
	DWORD n, clust, sect;
1388
	BYTE fat, f, *p;
1389
 
1390
 
1391
	/* Get drive number */
1392
	res = auto_mount(&drv, fatfs, 0);
1393
	if (res != FR_OK) return res;
1394
 
1395
	/* If number of free cluster is valid, return it without cluster scan. */
1396
	if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) {
1397
		*nclust = (*fatfs)->free_clust;
1398
		return FR_OK;
1399
	}
1400
 
1401
	/* Get number of free clusters */
1402
	fat = (*fatfs)->fs_type;
1403
	n = 0;
1404
	if (fat == FS_FAT12) {
1405
		clust = 2;
1406
		do {
1407
			if ((WORD)get_cluster(*fatfs, clust) == 0) n++;
1408
		} while (++clust < (*fatfs)->max_clust);
1409
	} else {
1410
		clust = (*fatfs)->max_clust;
1411
		sect = (*fatfs)->fatbase;
1412
		f = 0; p = 0;
1413
		do {
1414
			if (!f) {
1415
				if (!move_window(*fatfs, sect++)) return FR_RW_ERROR;
1416
				p = (*fatfs)->win;
1417
			}
1418
			if (fat == FS_FAT16) {
1419
				if (LD_WORD(p) == 0) n++;
1420
				p += 2; f += 1;
1421
			} else {
1422
				if (LD_DWORD(p) == 0) n++;
1423
				p += 4; f += 2;
1424
			}
1425
		} while (--clust);
1426
	}
1427
	(*fatfs)->free_clust = n;
1428
#if _USE_FSINFO
1429
	if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
1430
#endif
1431
 
1432
	*nclust = n;
1433
	return FR_OK;
1434
}
1435
 
1436
 
1437
 
1438
 
1439
/*-----------------------------------------------------------------------*/
1440
/* Delete a File or Directory                                            */
1441
/*-----------------------------------------------------------------------*/
1442
 
1443
FRESULT f_unlink (
1444
	const char *path		/* Pointer to the file or directory path */
1445
)
1446
{
1447
	FRESULT res;
1448
	DIR dj;
1449
	BYTE *dir, *sdir;
1450
	DWORD dclust, dsect;
1451
	char fn[8+3+1];
1452
 
1453
 
1454
	res = auto_mount(&path, &dj.fs, 1);
1455
	if (res != FR_OK) return res;
1456
	res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
1457
	if (res != FR_OK) return res;			/* Trace failed */
1458
	if (!dir) return FR_INVALID_NAME;		/* It is the root directory */
1459
	if (dir[DIR_Attr] & AM_RDO) return FR_DENIED;	/* It is a R/O object */
1460
	dsect = dj.fs->winsect;
1461
	dclust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
1462
 
1463
	if (dir[DIR_Attr] & AM_DIR) {			/* It is a sub-directory */
1464
		dj.clust = dclust;					/* Check if the sub-dir is empty or not */
1465
		dj.sect = clust2sect(dj.fs, dclust);
1466
		dj.index = 2;
1467
		do {
1468
			if (!move_window(dj.fs, dj.sect)) return FR_RW_ERROR;
1469
			sdir = &dj.fs->win[(dj.index & ((SS(dj.fs) - 1) >> 5)) * 32];
1470
			if (sdir[DIR_Name] == 0) break;
1471
			if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL))
1472
				return FR_DENIED;	/* The directory is not empty */
1473
		} while (next_dir_entry(&dj));
1474
	}
1475
 
1476
	if (!move_window(dj.fs, dsect)) return FR_RW_ERROR;	/* Mark the directory entry 'deleted' */
1477
	dir[DIR_Name] = 0xE5;
1478
	dj.fs->winflag = 1;
1479
	if (!remove_chain(dj.fs, dclust)) return FR_RW_ERROR;	/* Remove the cluster chain */
1480
 
1481
	return sync(dj.fs);
1482
}
1483
 
1484
 
1485
 
1486
 
1487
/*-----------------------------------------------------------------------*/
1488
/* Create a Directory                                                    */
1489
/*-----------------------------------------------------------------------*/
1490
 
1491
FRESULT f_mkdir (
1492
	const char *path		/* Pointer to the directory path */
1493
)
1494
{
1495
	FRESULT res;
1496
	DIR dj;
1497
	BYTE *dir, *fw, n;
1498
	char fn[8+3+1];
1499
	DWORD sect, dsect, dclust, pclust, tim;
1500
 
1501
 
1502
	res = auto_mount(&path, &dj.fs, 1);
1503
	if (res != FR_OK) return res;
1504
	res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
1505
	if (res == FR_OK) return FR_EXIST;		/* Any file or directory is already existing */
1506
	if (res != FR_NO_FILE) return res;
1507
 
1508
	res = reserve_direntry(&dj, &dir); 		/* Reserve a directory entry */
1509
	if (res != FR_OK) return res;
1510
	sect = dj.fs->winsect;
1511
	dclust = create_chain(dj.fs, 0);		/* Allocate a cluster for new directory table */
1512
	if (dclust == 1) return FR_RW_ERROR;
1513
	dsect = clust2sect(dj.fs, dclust);
1514
	if (!dsect) return FR_DENIED;
1515
	if (!move_window(dj.fs, dsect)) return FR_RW_ERROR;
1516
 
1517
	fw = dj.fs->win;
1518
	memset(fw, 0, SS(dj.fs));				/* Clear the new directory table */
1519
	for (n = 1; n < dj.fs->csize; n++) {
1520
		if (disk_write(dj.fs->drive, fw, ++dsect, 1) != RES_OK)
1521
			return FR_RW_ERROR;
1522
	}
1523
	memset(&fw[DIR_Name], ' ', 8+3);		/* Create "." entry */
1524
	fw[DIR_Name] = '.';
1525
	fw[DIR_Attr] = AM_DIR;
1526
	tim = get_fattime();
1527
	ST_DWORD(&fw[DIR_WrtTime], tim);
1528
	memcpy(&fw[32], &fw[0], 32); fw[33] = '.';	/* Create ".." entry */
1529
	ST_WORD(&fw[   DIR_FstClusLO], dclust);
1530
	ST_WORD(&fw[   DIR_FstClusHI], dclust >> 16);
1531
	pclust = dj.sclust;
1532
	if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase) pclust = 0;
1533
	ST_WORD(&fw[32+DIR_FstClusLO], pclust);
1534
	ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16);
1535
	dj.fs->winflag = 1;
1536
 
1537
	if (!move_window(dj.fs, sect)) return FR_RW_ERROR;
1538
	memset(&dir[0], 0, 32);						/* Initialize the new entry */
1539
	memcpy(&dir[DIR_Name], fn, 8+3);			/* Name */
1540
	dir[DIR_NTres] = fn[11];
1541
	dir[DIR_Attr] = AM_DIR;						/* Attribute */
1542
	ST_DWORD(&dir[DIR_WrtTime], tim);			/* Crated time */
1543
	ST_WORD(&dir[DIR_FstClusLO], dclust);		/* Table start cluster */
1544
	ST_WORD(&dir[DIR_FstClusHI], dclust >> 16);
1545
 
1546
	return sync(dj.fs);
1547
}
1548
 
1549
 
1550
 
1551
 
1552
/*-----------------------------------------------------------------------*/
1553
/* Change File Attribute                                                 */
1554
/*-----------------------------------------------------------------------*/
1555
 
1556
FRESULT f_chmod (
1557
	const char *path,	/* Pointer to the file path */
1558
	BYTE value,			/* Attribute bits */
1559
	BYTE mask			/* Attribute mask to change */
1560
)
1561
{
1562
	FRESULT res;
1563
	DIR dj;
1564
	BYTE *dir;
1565
	char fn[8+3+1];
1566
 
1567
 
1568
	res = auto_mount(&path, &dj.fs, 1);
1569
	if (res == FR_OK) {
1570
		res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
1571
		if (res == FR_OK) {				/* Trace completed */
1572
			if (!dir) {
1573
				res = FR_INVALID_NAME;	/* Root directory */
1574
			} else {
1575
				mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;	/* Valid attribute mask */
1576
				dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask);	/* Apply attribute change */
1577
				res = sync(dj.fs);
1578
			}
1579
		}
1580
	}
1581
	return res;
1582
}
1583
 
1584
 
1585
 
1586
 
1587
/*-----------------------------------------------------------------------*/
1588
/* Change Timestamp                                                      */
1589
/*-----------------------------------------------------------------------*/
1590
 
1591
FRESULT f_utime (
1592
	const char *path,		/* Pointer to the file/directory name */
1593
	const FILINFO *finfo	/* Pointer to the timestamp to be set */
1594
)
1595
{
1596
	FRESULT res;
1597
	DIR dj;
1598
	BYTE *dir;
1599
	char fn[8+3+1];
1600
 
1601
 
1602
	res = auto_mount(&path, &dj.fs, 1);
1603
	if (res == FR_OK) {
1604
		res = trace_path(&dj, fn, path, &dir);	/* Trace the file path */
1605
		if (res == FR_OK) {				/* Trace completed */
1606
			if (!dir) {
1607
				res = FR_INVALID_NAME;	/* Root directory */
1608
			} else {
1609
				ST_WORD(&dir[DIR_WrtTime], finfo->ftime);
1610
				ST_WORD(&dir[DIR_WrtDate], finfo->fdate);
1611
				res = sync(dj.fs);
1612
			}
1613
		}
1614
	}
1615
	return res;
1616
}
1617
 
1618
 
1619
 
1620
 
1621
/*-----------------------------------------------------------------------*/
1622
/* Rename File/Directory                                                 */
1623
/*-----------------------------------------------------------------------*/
1624
 
1625
FRESULT f_rename (
1626
	const char *path_old,	/* Pointer to the old name */
1627
	const char *path_new	/* Pointer to the new name */
1628
)
1629
{
1630
	FRESULT res;
1631
	DIR dj;
1632
	DWORD sect_old;
1633
	BYTE *dir_old, *dir_new, direntry[32-11];
1634
	char fn[8+3+1];
1635
 
1636
 
1637
	res = auto_mount(&path_old, &dj.fs, 1);
1638
	if (res != FR_OK) return res;
1639
 
1640
	res = trace_path(&dj, fn, path_old, &dir_old);	/* Check old object */
1641
	if (res != FR_OK) return res;				/* The old object is not found */
1642
	if (!dir_old) return FR_NO_FILE;
1643
	sect_old = dj.fs->winsect;					/* Save the object information */
1644
	memcpy(direntry, &dir_old[DIR_Attr], 32-11);
1645
 
1646
	res = trace_path(&dj, fn, path_new, &dir_new);	/* Check new object */
1647
	if (res == FR_OK) return FR_EXIST;			/* The new object name is already existing */
1648
	if (res != FR_NO_FILE) return res;			/* Is there no old name? */
1649
	res = reserve_direntry(&dj, &dir_new); 		/* Reserve a directory entry */
1650
	if (res != FR_OK) return res;
1651
 
1652
	memcpy(&dir_new[DIR_Attr], direntry, 32-11);	/* Create new entry */
1653
	memcpy(&dir_new[DIR_Name], fn, 8+3);
1654
	dir_new[DIR_NTres] = fn[11];
1655
	dj.fs->winflag = 1;
1656
 
1657
	if (!move_window(dj.fs, sect_old)) return FR_RW_ERROR;	/* Delete old entry */
1658
	dir_old[DIR_Name] = 0xE5;
1659
 
1660
	return sync(dj.fs);
1661
}
1662
 
1663
#endif /* !_FS_READONLY */
1664
#endif /* _FS_MINIMIZE == 0 */
1665
#endif /* _FS_MINIMIZE <= 1 */
1666
#endif /* _FS_MINIMIZE <= 2 */
1667
 
1668
 
1669
 
1670
#if _USE_MKFS && !_FS_READONLY
1671
/*-----------------------------------------------------------------------*/
1672
/* Create File System on the Drive                                       */
1673
/*-----------------------------------------------------------------------*/
1674
#define N_ROOTDIR	512			/* Multiple of 32 and <= 2048 */
1675
#define N_FATS		1			/* 1 or 2 */
1676
#define MAX_SECTOR	64000000UL	/* Maximum partition size */
1677
#define MIN_SECTOR	2000UL		/* Minimum partition size */
1678
 
1679
 
1680
 
1681
FRESULT f_mkfs (
1682
	BYTE drv,			/* Logical drive number */
1683
	BYTE partition,		/* Partitioning rule 0:FDISK, 1:SFD */
1684
	WORD allocsize		/* Allocation unit size [bytes] */
1685
)
1686
{
1687
	BYTE fmt, m, *tbl;
1688
	DWORD b_part, b_fat, b_dir, b_data;		/* Area offset (LBA) */
1689
	DWORD n_part, n_rsv, n_fat, n_dir;		/* Area size */
1690
	DWORD n_clust, n;
1691
	FATFS *fs;
1692
	DSTATUS stat;
1693
 
1694
 
1695
	/* Check validity of the parameters */
1696
	if (drv >= _DRIVES) return FR_INVALID_DRIVE;
1697
	if (partition >= 2) return FR_MKFS_ABORTED;
1698
	for (n = 512; n <= 32768U && n != allocsize; n <<= 1);
1699
	if (n != allocsize) return FR_MKFS_ABORTED;
1700
 
1701
	/* Check mounted drive and clear work area */
1702
	fs = FatFs[drv];
1703
	if (!fs) return FR_NOT_ENABLED;
1704
	fs->fs_type = 0;
1705
	drv = LD2PD(drv);
1706
 
1707
	/* Get disk statics */
1708
	stat = disk_initialize(drv);
1709
	if (stat & STA_NOINIT) return FR_NOT_READY;
1710
	if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
1711
	if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
1712
		return FR_MKFS_ABORTED;
1713
	if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;
1714
	b_part = (!partition) ? 63 : 0;		/* Boot sector */
1715
	n_part -= b_part;
1716
#if S_MAX_SIZ > 512						/* Check disk sector size */
1717
	if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
1718
		|| SS(fs) > S_MAX_SIZ
1719
		|| SS(fs) > allocsize)
1720
		return FR_MKFS_ABORTED;
1721
#endif
1722
	allocsize /= SS(fs);		/* Number of sectors per cluster */
1723
 
1724
	/* Pre-compute number of clusters and FAT type */
1725
	n_clust = n_part / allocsize;
1726
	fmt = FS_FAT12;
1727
	if (n_clust >= 0xFF5) fmt = FS_FAT16;
1728
	if (n_clust >= 0xFFF5) fmt = FS_FAT32;
1729
 
1730
	/* Determine offset and size of FAT structure */
1731
	switch (fmt) {
1732
	case FS_FAT12:
1733
		n_fat = ((n_clust * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
1734
		n_rsv = 1 + partition;
1735
		n_dir = N_ROOTDIR * 32 / SS(fs);
1736
		break;
1737
	case FS_FAT16:
1738
		n_fat = ((n_clust * 2) + 4 + SS(fs) - 1) / SS(fs);
1739
		n_rsv = 1 + partition;
1740
		n_dir = N_ROOTDIR * 32 / SS(fs);
1741
		break;
1742
	default:
1743
		n_fat = ((n_clust * 4) + 8 + SS(fs) - 1) / SS(fs);
1744
		n_rsv = 33 - partition;
1745
		n_dir = 0;
1746
	}
1747
	b_fat = b_part + n_rsv;			/* FATs start sector */
1748
	b_dir = b_fat + n_fat * N_FATS;	/* Directory start sector */
1749
	b_data = b_dir + n_dir;			/* Data start sector */
1750
 
1751
	/* Align data start sector to erase block boundary (for flash memory media) */
1752
	if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
1753
	n = (b_data + n - 1) & ~(n - 1);
1754
	n_fat += (n - b_data) / N_FATS;
1755
	/* b_dir and b_data are no longer used below */
1756
 
1757
	/* Determine number of cluster and final check of validity of the FAT type */
1758
	n_clust = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
1759
	if (   (fmt == FS_FAT16 && n_clust < 0xFF5)
1760
		|| (fmt == FS_FAT32 && n_clust < 0xFFF5))
1761
		return FR_MKFS_ABORTED;
1762
 
1763
	/* Create partition table if needed */
1764
	if (!partition) {
1765
		DWORD n_disk = b_part + n_part;
1766
 
1767
		tbl = &fs->win[MBR_Table];
1768
		ST_DWORD(&tbl[0], 0x00010180);	/* Partition start in CHS */
1769
		if (n_disk < 63UL * 255 * 1024) {	/* Partition end in CHS */
1770
			n_disk = n_disk / 63 / 255;
1771
			tbl[7] = (BYTE)n_disk;
1772
			tbl[6] = (BYTE)((n_disk >> 2) | 63);
1773
		} else {
1774
			ST_WORD(&tbl[6], 0xFFFF);
1775
		}
1776
		tbl[5] = 254;
1777
		if (fmt != FS_FAT32)			/* System ID */
1778
			tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
1779
		else
1780
			tbl[4] = 0x0c;
1781
		ST_DWORD(&tbl[8], 63);			/* Partition start in LBA */
1782
		ST_DWORD(&tbl[12], n_part);		/* Partition size in LBA */
1783
		ST_WORD(&tbl[64], 0xAA55);		/* Signature */
1784
		if (disk_write(drv, fs->win, 0, 1) != RES_OK)
1785
			return FR_RW_ERROR;
1786
	}
1787
 
1788
	/* Create boot record */
1789
	tbl = fs->win;								/* Clear buffer */
1790
	memset(tbl, 0, SS(fs));
1791
	ST_DWORD(&tbl[BS_jmpBoot], 0x90FEEB);		/* Boot code (jmp $, nop) */
1792
	ST_WORD(&tbl[BPB_BytsPerSec], SS(fs));		/* Sector size */
1793
	tbl[BPB_SecPerClus] = (BYTE)allocsize;		/* Sectors per cluster */
1794
	ST_WORD(&tbl[BPB_RsvdSecCnt], n_rsv);		/* Reserved sectors */
1795
	tbl[BPB_NumFATs] = N_FATS;					/* Number of FATs */
1796
	ST_WORD(&tbl[BPB_RootEntCnt], SS(fs) / 32 * n_dir); /* Number of rootdir entries */
1797
	if (n_part < 0x10000) {						/* Number of total sectors */
1798
		ST_WORD(&tbl[BPB_TotSec16], n_part);
1799
	} else {
1800
		ST_DWORD(&tbl[BPB_TotSec32], n_part);
1801
	}
1802
	tbl[BPB_Media] = 0xF8;						/* Media descripter */
1803
	ST_WORD(&tbl[BPB_SecPerTrk], 63);			/* Number of sectors per track */
1804
	ST_WORD(&tbl[BPB_NumHeads], 255);			/* Number of heads */
1805
	ST_DWORD(&tbl[BPB_HiddSec], b_part);		/* Hidden sectors */
1806
	n = get_fattime();							/* Use current time as a VSN */
1807
	if (fmt != FS_FAT32) {
1808
		ST_DWORD(&tbl[BS_VolID], n);			/* Volume serial number */
1809
		ST_WORD(&tbl[BPB_FATSz16], n_fat);		/* Number of secters per FAT */
1810
		tbl[BS_DrvNum] = 0x80;					/* Drive number */
1811
		tbl[BS_BootSig] = 0x29;					/* Extended boot signature */
1812
		memcpy(&tbl[BS_VolLab], "NO NAME    FAT     ", 19);	/* Volume lavel, FAT signature */
1813
	} else {
1814
		ST_DWORD(&tbl[BS_VolID32], n);			/* Volume serial number */
1815
		ST_DWORD(&tbl[BPB_FATSz32], n_fat);		/* Number of secters per FAT */
1816
		ST_DWORD(&tbl[BPB_RootClus], 2);		/* Root directory cluster (2) */
1817
		ST_WORD(&tbl[BPB_FSInfo], 1);			/* FSInfo record (bs+1) */
1818
		ST_WORD(&tbl[BPB_BkBootSec], 6);		/* Backup boot record (bs+6) */
1819
		tbl[BS_DrvNum32] = 0x80;				/* Drive number */
1820
		tbl[BS_BootSig32] = 0x29;				/* Extended boot signature */
1821
		memcpy(&tbl[BS_VolLab32], "NO NAME    FAT32   ", 19);	/* Volume lavel, FAT signature */
1822
	}
1823
	ST_WORD(&tbl[BS_55AA], 0xAA55);			/* Signature */
1824
	if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
1825
		return FR_RW_ERROR;
1826
	if (fmt == FS_FAT32)
1827
		disk_write(drv, tbl, b_part+6, 1);
1828
 
1829
	/* Initialize FAT area */
1830
	for (m = 0; m < N_FATS; m++) {
1831
		memset(tbl, 0, SS(fs));		/* 1st sector of the FAT  */
1832
		if (fmt != FS_FAT32) {
1833
			n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8;
1834
			ST_DWORD(&tbl[0], n);			/* Reserve cluster #0-1 (FAT12/16) */
1835
		} else {
1836
			ST_DWORD(&tbl[0], 0xFFFFFFF8);	/* Reserve cluster #0-1 (FAT32) */
1837
			ST_DWORD(&tbl[4], 0xFFFFFFFF);
1838
			ST_DWORD(&tbl[8], 0x0FFFFFFF);	/* Reserve cluster #2 for root dir */
1839
		}
1840
		if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
1841
			return FR_RW_ERROR;
1842
		memset(tbl, 0, SS(fs));		/* Following FAT entries are filled by zero */
1843
		for (n = 1; n < n_fat; n++) {
1844
			if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
1845
				return FR_RW_ERROR;
1846
		}
1847
	}
1848
 
1849
	/* Initialize Root directory */
1850
	m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);
1851
	do {
1852
		if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
1853
			return FR_RW_ERROR;
1854
	} while (--m);
1855
 
1856
	/* Create FSInfo record if needed */
1857
	if (fmt == FS_FAT32) {
1858
		ST_WORD(&tbl[BS_55AA], 0xAA55);
1859
		ST_DWORD(&tbl[FSI_LeadSig], 0x41615252);
1860
		ST_DWORD(&tbl[FSI_StrucSig], 0x61417272);
1861
		ST_DWORD(&tbl[FSI_Free_Count], n_clust - 1);
1862
		ST_DWORD(&tbl[FSI_Nxt_Free], 0xFFFFFFFF);
1863
		disk_write(drv, tbl, b_part+1, 1);
1864
		disk_write(drv, tbl, b_part+7, 1);
1865
	}
1866
 
1867
	return (disk_ioctl(drv, CTRL_SYNC, NULL) == RES_OK) ? FR_OK : FR_RW_ERROR;
1868
}
1869
 
1870
#endif /* _USE_MKFS && !_FS_READONLY */
1871
 
1872
 
1873
 
1874
 
1875
#if _USE_STRFUNC >= 1
1876
/*-----------------------------------------------------------------------*/
1877
/* Get a string from the file                                            */
1878
/*-----------------------------------------------------------------------*/
1879
char* fgets (
1880
	char* buff,	/* Pointer to the string buffer to read */
1881
	int len,	/* Size of string buffer */
1882
	FIL* fil	/* Pointer to the file object */
1883
)
1884
{
1885
	int i = 0;
1886
	char *p = buff;
1887
	UINT rc;
1888
 
1889
 
1890
	while (i < len - 1) {			/* Read bytes until buffer gets filled */
1891
		f_read(fil, p, 1, &rc);
1892
		if (rc != 1) break;			/* Break when no data to read */
1893
#if _USE_STRFUNC >= 2
1894
		if (*p == '\r') continue;	/* Strip '\r' */
1895
#endif
1896
		i++;
1897
		if (*p++ == '\n') break;	/* Break when reached end of line */
1898
	}
1899
	*p = 0;
1900
	return i ? buff : 0;			/* When no data read (eof or error), return with error. */
1901
}
1902
 
1903
 
1904
 
1905
#if !_FS_READONLY
1906
#include <stdarg.h>
1907
/*-----------------------------------------------------------------------*/
1908
/* Put a character to the file                                           */
1909
/*-----------------------------------------------------------------------*/
1910
int fputc (
1911
	int chr,	/* A character to be output */
1912
	FIL* fil	/* Ponter to the file object */
1913
)
1914
{
1915
	UINT bw;
1916
	char c;
1917
 
1918
 
1919
#if _USE_STRFUNC >= 2
1920
	if (chr == '\n') fputc ('\r', fil);	/* LF -> CRLF conversion */
1921
#endif
1922
	if (!fil) {	/* Special value may be used to switch the destination to any other device */
1923
	/*	put_console(chr);	*/
1924
		return chr;
1925
	}
1926
	c = (char)chr;
1927
	f_write(fil, &c, 1, &bw);	/* Write a byte to the file */
1928
	return bw ? chr : EOF;		/* Return the resulut */
1929
}
1930
 
1931
 
1932
 
1933
 
1934
/*-----------------------------------------------------------------------*/
1935
/* Put a string to the file                                              */
1936
/*-----------------------------------------------------------------------*/
1937
int fputs (
1938
	const char* str,	/* Pointer to the string to be output */
1939
	FIL* fil			/* Pointer to the file object */
1940
)
1941
{
1942
	int n;
1943
 
1944
 
1945
	for (n = 0; *str; str++, n++) {
1946
		if (fputc(*str, fil) == EOF) return EOF;
1947
	}
1948
	return n;
1949
}
1950
 
1951
 
1952
 
1953
 
1954
/*-----------------------------------------------------------------------*/
1955
/* Put a formatted string to the file                                    */
1956
/*-----------------------------------------------------------------------*/
1957
int fprintf (
1958
	FIL* fil,			/* Pointer to the file object */
1959
	const char* str,	/* Pointer to the format string */
1960
	...					/* Optional arguments... */
1961
)
1962
{
1963
	va_list arp;
1964
	UCHAR c, f, r;
1965
	ULONG val;
1966
	char s[16];
1967
	int i, w, res, cc;
1968
 
1969
 
1970
	va_start(arp, str);
1971
 
1972
	for (cc = res = 0; cc != EOF; res += cc) {
1973
		c = *str++;
1974
		if (c == 0) break;			/* End of string */
1975
		if (c != '%') {				/* Non escape cahracter */
1976
			cc = fputc(c, fil);
1977
			if (cc != EOF) cc = 1;
1978
			continue;
1979
		}
1980
		w = f = 0;
1981
		c = *str++;
1982
		if (c == '0') {				/* Flag: '0' padding */
1983
			f = 1; c = *str++;
1984
		}
1985
		while (c >= '0' && c <= '9') {	/* Precision */
1986
			w = w * 10 + (c - '0');
1987
			c = *str++;
1988
		}
1989
		if (c == 'l') {				/* Prefix: Size is long int */
1990
			f |= 2; c = *str++;
1991
		}
1992
		if (c == 's') {				/* Type is string */
1993
			cc = fputs(va_arg(arp, char*), fil);
1994
			continue;
1995
		}
1996
		if (c == 'c') {				/* Type is character */
1997
			cc = fputc(va_arg(arp, char), fil);
1998
			if (cc != EOF) cc = 1;
1999
			continue;
2000
		}
2001
		r = 0;
2002
		if (c == 'd') r = 10;		/* Type is signed decimal */
2003
		if (c == 'u') r = 10;		/* Type is unsigned decimal */
2004
		if (c == 'X') r = 16;		/* Type is unsigned hexdecimal */
2005
		if (r == 0) break;			/* Unknown type */
2006
		if (f & 2) {				/* Get the value */
2007
			val = (ULONG)va_arg(arp, long);
2008
		} else {
2009
			val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
2010
		}
2011
		/* Put numeral string */
2012
		if (c == 'd') {
2013
			if (val >= 0x80000000) {
2014
				val = 0 - val;
2015
				f |= 4;
2016
			}
2017
		}
2018
		i = sizeof(s) - 1; s[i] = 0;
2019
		do {
2020
			c = (UCHAR)(val % r + '0');
2021
			if (c > '9') c += 7;
2022
			s[--i] = c;
2023
			val /= r;
2024
		} while (i && val);
2025
		if (i && (f & 4)) s[--i] = '-';
2026
		w = sizeof(s) - 1 - w;
2027
		while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
2028
		cc = fputs(&s[i], fil);
2029
	}
2030
 
2031
	va_end(arp);
2032
	return (cc == EOF) ? cc : res;
2033
}
2034
 
2035
#endif /* !_FS_READONLY */
2036
#endif /* _USE_STRFUNC >= 1*/