f2fs_format_utils.c revision 29ab4d8788d204edb362f01879e1d3d4f516e967
1/**
2 * f2fs_format_utils.c
3 *
4 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
5 *             http://www.samsung.com/
6 *
7 * Dual licensed under the GPL or LGPL version 2 licenses.
8 */
9#define _LARGEFILE_SOURCE
10#define _LARGEFILE64_SOURCE
11#ifndef _GNU_SOURCE
12#define _GNU_SOURCE
13#endif
14
15#include <stdio.h>
16#include <unistd.h>
17#include <sys/ioctl.h>
18#include <sys/stat.h>
19#include <fcntl.h>
20
21#include "f2fs_fs.h"
22
23#ifdef HAVE_LINUX_FS_H
24#include <linux/fs.h>
25#endif
26#ifdef HAVE_LINUX_FALLOC_H
27#include <linux/falloc.h>
28#endif
29
30int f2fs_trim_device()
31{
32	unsigned long long range[2];
33	struct stat stat_buf;
34
35	if (!config.trim)
36		return 0;
37
38	range[0] = 0;
39	range[1] = config.total_sectors * config.sector_size;
40
41	if (fstat(config.fd, &stat_buf) < 0 ) {
42		MSG(1, "\tError: Failed to get the device stat!!!\n");
43		return -1;
44	}
45
46#if defined(WITH_BLKDISCARD) && defined(BLKDISCARD)
47	MSG(0, "Info: Discarding device\n");
48	if (S_ISREG(stat_buf.st_mode)) {
49#ifdef FALLOC_FL_PUNCH_HOLE
50		if (fallocate(config.fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
51				range[0], range[1]) < 0) {
52			MSG(0, "Info: fallocate(PUNCH_HOLE|KEEP_SIZE) is failed\n");
53		}
54#endif
55		return 0;
56	} else if (S_ISBLK(stat_buf.st_mode)) {
57		if (ioctl(config.fd, BLKDISCARD, &range) < 0) {
58			MSG(0, "Info: This device doesn't support TRIM\n");
59		} else {
60			MSG(0, "Info: Discarded %lu sectors\n",
61						config.total_sectors);
62		}
63	} else
64		return -1;
65#endif
66	return 0;
67}
68
69