1/**
2 * libf2fs.c
3 *
4 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
5 *             http://www.samsung.com/
6 *
7 * Dual licensed under the GPL or LGPL version 2 licenses.
8 */
9#define _LARGEFILE64_SOURCE
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <errno.h>
15#include <unistd.h>
16#include <fcntl.h>
17#include <mntent.h>
18#include <time.h>
19#include <sys/stat.h>
20#include <sys/mount.h>
21#include <sys/ioctl.h>
22#include <linux/hdreg.h>
23
24#include <f2fs_fs.h>
25
26void ASCIIToUNICODE(u_int16_t *out_buf, u_int8_t *in_buf)
27{
28	u_int8_t *pchTempPtr = in_buf;
29	u_int16_t *pwTempPtr = out_buf;
30
31	while (*pchTempPtr != '\0') {
32		*pwTempPtr = (u_int16_t)*pchTempPtr;
33		pchTempPtr++;
34		pwTempPtr++;
35	}
36	*pwTempPtr = '\0';
37	return;
38}
39
40int log_base_2(u_int32_t num)
41{
42	int ret = 0;
43	if (num <= 0 || (num & (num - 1)) != 0)
44		return -1;
45
46	while (num >>= 1)
47		ret++;
48	return ret;
49}
50
51/*
52 * f2fs bit operations
53 */
54static const int bits_in_byte[256] = {
55	0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
56	1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
57	1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
58	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
59	1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
60	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
61	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
62	3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
63	1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
64	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
65	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
66	3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
67	2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
68	3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
69	3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
70	4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
71};
72
73int get_bits_in_byte(unsigned char n)
74{
75	return bits_in_byte[n];
76}
77
78int set_bit(unsigned int nr,void * addr)
79{
80	int             mask, retval;
81	unsigned char   *ADDR = (unsigned char *) addr;
82
83	ADDR += nr >> 3;
84	mask = 1 << ((nr & 0x07));
85	retval = mask & *ADDR;
86	*ADDR |= mask;
87	return retval;
88}
89
90int clear_bit(unsigned int nr, void * addr)
91{
92	int             mask, retval;
93	unsigned char   *ADDR = (unsigned char *) addr;
94
95	ADDR += nr >> 3;
96	mask = 1 << ((nr & 0x07));
97	retval = mask & *ADDR;
98	*ADDR &= ~mask;
99	return retval;
100}
101
102int test_bit(unsigned int nr, const void * addr)
103{
104	const __u32 *p = (const __u32 *)addr;
105
106	nr = nr ^ 0;
107
108	return ((1 << (nr & 31)) & (p[nr >> 5])) != 0;
109}
110
111int f2fs_test_bit(unsigned int nr, const char *p)
112{
113	int mask;
114	char *addr = (char *)p;
115
116	addr += (nr >> 3);
117	mask = 1 << (7 - (nr & 0x07));
118	return (mask & *addr) != 0;
119}
120
121int f2fs_set_bit(unsigned int nr, char *addr)
122{
123	int mask;
124	int ret;
125
126	addr += (nr >> 3);
127	mask = 1 << (7 - (nr & 0x07));
128	ret = mask & *addr;
129	*addr |= mask;
130	return ret;
131}
132
133int f2fs_clear_bit(unsigned int nr, char *addr)
134{
135	int mask;
136	int ret;
137
138	addr += (nr >> 3);
139	mask = 1 << (7 - (nr & 0x07));
140	ret = mask & *addr;
141	*addr &= ~mask;
142	return ret;
143}
144
145static inline unsigned long __ffs(unsigned long word)
146{
147	int num = 0;
148
149#if BITS_PER_LONG == 64
150	if ((word & 0xffffffff) == 0) {
151		num += 32;
152		word >>= 32;
153	}
154#endif
155	if ((word & 0xffff) == 0) {
156		num += 16;
157		word >>= 16;
158	}
159	if ((word & 0xff) == 0) {
160		num += 8;
161		word >>= 8;
162	}
163	if ((word & 0xf) == 0) {
164		num += 4;
165		word >>= 4;
166	}
167	if ((word & 0x3) == 0) {
168		num += 2;
169		word >>= 2;
170	}
171	if ((word & 0x1) == 0)
172		num += 1;
173	return num;
174}
175
176unsigned long find_next_bit(const unsigned long *addr, unsigned long size,
177                unsigned long offset)
178{
179        const unsigned long *p = addr + BIT_WORD(offset);
180        unsigned long result = offset & ~(BITS_PER_LONG-1);
181        unsigned long tmp;
182
183        if (offset >= size)
184                return size;
185        size -= result;
186        offset %= BITS_PER_LONG;
187        if (offset) {
188                tmp = *(p++);
189                tmp &= (~0UL << offset);
190                if (size < BITS_PER_LONG)
191                        goto found_first;
192                if (tmp)
193                        goto found_middle;
194                size -= BITS_PER_LONG;
195                result += BITS_PER_LONG;
196        }
197        while (size & ~(BITS_PER_LONG-1)) {
198                if ((tmp = *(p++)))
199                        goto found_middle;
200                result += BITS_PER_LONG;
201                size -= BITS_PER_LONG;
202        }
203        if (!size)
204                return result;
205        tmp = *p;
206
207found_first:
208        tmp &= (~0UL >> (BITS_PER_LONG - size));
209        if (tmp == 0UL)		/* Are any bits set? */
210                return result + size;   /* Nope. */
211found_middle:
212        return result + __ffs(tmp);
213}
214
215/*
216 * Hashing code adapted from ext3
217 */
218#define DELTA 0x9E3779B9
219
220static void TEA_transform(unsigned int buf[4], unsigned int const in[])
221{
222	__u32 sum = 0;
223	__u32 b0 = buf[0], b1 = buf[1];
224	__u32 a = in[0], b = in[1], c = in[2], d = in[3];
225	int     n = 16;
226
227	do {
228		sum += DELTA;
229		b0 += ((b1 << 4)+a) ^ (b1+sum) ^ ((b1 >> 5)+b);
230		b1 += ((b0 << 4)+c) ^ (b0+sum) ^ ((b0 >> 5)+d);
231	} while (--n);
232
233	buf[0] += b0;
234	buf[1] += b1;
235
236}
237
238static void str2hashbuf(const unsigned char *msg, int len,
239					unsigned int *buf, int num)
240{
241	unsigned pad, val;
242	int i;
243
244	pad = (__u32)len | ((__u32)len << 8);
245	pad |= pad << 16;
246
247	val = pad;
248	if (len > num * 4)
249		len = num * 4;
250	for (i = 0; i < len; i++) {
251		if ((i % 4) == 0)
252			val = pad;
253		val = msg[i] + (val << 8);
254		if ((i % 4) == 3) {
255			*buf++ = val;
256			val = pad;
257			num--;
258		}
259	}
260	if (--num >= 0)
261		*buf++ = val;
262	while (--num >= 0)
263		*buf++ = pad;
264
265}
266
267/**
268 * Return hash value of directory entry
269 * @param name          dentry name
270 * @param len           name lenth
271 * @return              return on success hash value, errno on failure
272 */
273f2fs_hash_t f2fs_dentry_hash(const unsigned char *name, int len)
274{
275	__u32 hash;
276	f2fs_hash_t	f2fs_hash;
277	const unsigned char	*p;
278	__u32 in[8], buf[4];
279
280	/* special hash codes for special dentries */
281	if ((len <= 2) && (name[0] == '.') &&
282		(name[1] == '.' || name[1] == '\0'))
283		return 0;
284
285	/* Initialize the default seed for the hash checksum functions */
286	buf[0] = 0x67452301;
287	buf[1] = 0xefcdab89;
288	buf[2] = 0x98badcfe;
289	buf[3] = 0x10325476;
290
291	p = name;
292	while (1) {
293		str2hashbuf(p, len, in, 4);
294		TEA_transform(buf, in);
295		p += 16;
296		if (len <= 16)
297			break;
298		len -= 16;
299	}
300	hash = buf[0];
301
302	f2fs_hash = cpu_to_le32(hash & ~F2FS_HASH_COL_BIT);
303	return f2fs_hash;
304}
305
306unsigned int addrs_per_inode(struct f2fs_inode *i)
307{
308	if (i->i_inline & F2FS_INLINE_XATTR)
309		return DEF_ADDRS_PER_INODE - F2FS_INLINE_XATTR_ADDRS;
310	return DEF_ADDRS_PER_INODE;
311}
312
313/*
314 * CRC32
315 */
316#define CRCPOLY_LE 0xedb88320
317
318u_int32_t f2fs_cal_crc32(u_int32_t crc, void *buf, int len)
319{
320	int i;
321	unsigned char *p = (unsigned char *)buf;
322	while (len--) {
323		crc ^= *p++;
324		for (i = 0; i < 8; i++)
325			crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0);
326	}
327	return crc;
328}
329
330int f2fs_crc_valid(u_int32_t blk_crc, void *buf, int len)
331{
332	u_int32_t cal_crc = 0;
333
334	cal_crc = f2fs_cal_crc32(F2FS_SUPER_MAGIC, buf, len);
335
336	if (cal_crc != blk_crc)	{
337		DBG(0,"CRC validation failed: cal_crc = %u, "
338			"blk_crc = %u buff_size = 0x%x\n",
339			cal_crc, blk_crc, len);
340		return -1;
341	}
342	return 0;
343}
344
345/*
346 * device information
347 */
348void f2fs_init_configuration(struct f2fs_configuration *c)
349{
350	c->total_sectors = 0;
351	c->sector_size = DEFAULT_SECTOR_SIZE;
352	c->sectors_per_blk = DEFAULT_SECTORS_PER_BLOCK;
353	c->blks_per_seg = DEFAULT_BLOCKS_PER_SEGMENT;
354
355	/* calculated by overprovision ratio */
356	c->reserved_segments = 48;
357	c->overprovision = 5;
358	c->segs_per_sec = 1;
359	c->secs_per_zone = 1;
360	c->heap = 1;
361	c->vol_label = "";
362	c->device_name = NULL;
363	c->trim = 1;
364}
365
366static int is_mounted(const char *mpt, const char *device)
367{
368	FILE *file = NULL;
369	struct mntent *mnt = NULL;
370
371	file = setmntent(mpt, "r");
372	if (file == NULL)
373		return 0;
374
375	while ((mnt = getmntent(file)) != NULL) {
376		if (!strcmp(device, mnt->mnt_fsname))
377			break;
378	}
379	endmntent(file);
380	return mnt ? 1 : 0;
381}
382
383int f2fs_dev_is_umounted(struct f2fs_configuration *c)
384{
385	struct stat st_buf;
386	int ret = 0;
387
388	ret = is_mounted(MOUNTED, c->device_name);
389	if (ret) {
390		MSG(0, "\tError: Not available on mounted device!\n");
391		return -1;
392	}
393
394	/*
395	 * if failed due to /etc/mtab file not present
396	 * try with /proc/mounts.
397	 */
398	ret = is_mounted("/proc/mounts", c->device_name);
399	if (ret) {
400		MSG(0, "\tError: Not available on mounted device!\n");
401		return -1;
402	}
403
404	/*
405	 * If f2fs is umounted with -l, the process can still use
406	 * the file system. In this case, we should not format.
407	 */
408	if (stat(c->device_name, &st_buf) == 0 && S_ISBLK(st_buf.st_mode)) {
409		int fd = open(c->device_name, O_RDONLY | O_EXCL);
410
411		if (fd >= 0) {
412			close(fd);
413		} else if (errno == EBUSY) {
414			MSG(0, "\tError: In use by the system!\n");
415			return -1;
416		}
417	}
418	return 0;
419}
420
421int f2fs_get_device_info(struct f2fs_configuration *c)
422{
423	int32_t fd = 0;
424	uint32_t sector_size;
425#ifndef BLKGETSIZE64
426	uint32_t total_sectors;
427#endif
428	struct stat stat_buf;
429	struct hd_geometry geom;
430	u_int64_t wanted_total_sectors = c->total_sectors;
431
432	fd = open(c->device_name, O_RDWR);
433	if (fd < 0) {
434		MSG(0, "\tError: Failed to open the device!\n");
435		return -1;
436	}
437	c->fd = fd;
438
439	if (fstat(fd, &stat_buf) < 0 ) {
440		MSG(0, "\tError: Failed to get the device stat!\n");
441		return -1;
442	}
443
444	if (S_ISREG(stat_buf.st_mode)) {
445		c->total_sectors = stat_buf.st_size / c->sector_size;
446	} else if (S_ISBLK(stat_buf.st_mode)) {
447		if (ioctl(fd, BLKSSZGET, &sector_size) < 0) {
448			MSG(0, "\tError: Using the default sector size\n");
449		} else {
450			if (c->sector_size < sector_size) {
451				MSG(0, "\tError: Cannot set the sector size to:"
452					" %d as the device does not support"
453					"\nSetting the sector size to : %d\n",
454					c->sector_size, sector_size);
455				c->sector_size = sector_size;
456				c->sectors_per_blk = PAGE_SIZE / sector_size;
457			}
458		}
459
460#ifdef BLKGETSIZE64
461		if (ioctl(fd, BLKGETSIZE64, &c->total_sectors) < 0) {
462			MSG(0, "\tError: Cannot get the device size\n");
463			return -1;
464		}
465		c->total_sectors /= c->sector_size;
466#else
467		if (ioctl(fd, BLKGETSIZE, &total_sectors) < 0) {
468			MSG(0, "\tError: Cannot get the device size\n");
469			return -1;
470		}
471		total_sectors /= c->sector_size;
472		c->total_sectors = total_sectors;
473#endif
474		if (ioctl(fd, HDIO_GETGEO, &geom) < 0)
475			c->start_sector = 0;
476		else
477			c->start_sector = geom.start;
478	} else {
479		MSG(0, "\tError: Volume type is not supported!!!\n");
480		return -1;
481	}
482	if (wanted_total_sectors && wanted_total_sectors < c->total_sectors) {
483		MSG(0, "Info: total device sectors = %"PRIu64" (in 512bytes)\n",
484					c->total_sectors);
485		c->total_sectors = wanted_total_sectors;
486
487	}
488	MSG(0, "Info: sector size = %u\n", c->sector_size);
489	MSG(0, "Info: total sectors = %"PRIu64" (in 512bytes)\n",
490					c->total_sectors);
491	if (c->total_sectors <
492			(F2FS_MIN_VOLUME_SIZE / DEFAULT_SECTOR_SIZE)) {
493		MSG(0, "Error: Min volume size supported is %d\n",
494				F2FS_MIN_VOLUME_SIZE);
495		return -1;
496	}
497
498	return 0;
499}
500
501