summaryrefslogtreecommitdiff
path: root/miscutils/flash_lock_unlock.c
blob: fcb836b075214d58e8123322341a6d1bfd82bc2c (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
/* vi: set sw=4 ts=4: */
/* Ported to busybox from mtd-utils.
 *
 * Licensed under GPLv2, see file LICENSE in this source tree.
 */
#include "libbb.h"
#include <mtd/mtd-user.h>

int flash_lock_unlock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int flash_lock_unlock_main(int argc UNUSED_PARAM, char **argv)
{
	/* note: fields in these structs are 32-bits.
	 * apparently we can't win anything by using off_t
	 * or long long's for offset and/or sectors vars. */
	struct mtd_info_user info;
	struct erase_info_user lock;
	unsigned long offset;
	long sectors;
	int fd;

#define do_lock (ENABLE_FLASH_LOCK && (!ENABLE_FLASH_UNLOCK || (applet_name[6] == 'l')))

	if (!argv[1])
		bb_show_usage();

	/* parse offset and number of sectors to lock */
	offset = 0;
	sectors = -1;
	if (do_lock) {
		if (!argv[2] || !argv[3])
			bb_show_usage();
		offset = xstrtoul(argv[2], 0);
		sectors = xstrtol(argv[3], 0);
	}

	fd = xopen(argv[1], O_RDWR);

	xioctl(fd, MEMGETINFO, &info);

	lock.start = 0;
	lock.length = info.size;
	if (do_lock) {
		unsigned long size = info.size - info.erasesize;
		if (offset > size) {
			bb_error_msg_and_die("%lx is beyond device size %lx\n",
					offset, size);
		}

		if (sectors == -1) {
			sectors = info.size / info.erasesize;
		} else {
// isn't this useless?
			unsigned long num = info.size / info.erasesize;
			if (sectors > num) {
				bb_error_msg_and_die("%ld are too many "
						"sectors, device only has "
						"%ld\n", sectors, num);
			}
		}

		lock.start = offset;
		lock.length = sectors * info.erasesize;
		xioctl(fd, MEMLOCK, &lock);
	} else {
		xioctl(fd, MEMUNLOCK, &lock);
	}

	return EXIT_SUCCESS;
}