• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Cyril Hrubis <chrubis@suse.cz>
4  */
5 
6 #include <errno.h>
7 #include <limits.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #define TST_NO_DEFAULT_MAIN
11 #include "tst_test.h"
12 #include "old/old_device.h"
13 
14 extern struct tst_test *tst_test;
15 
16 static struct tst_test test = {
17 };
18 
print_help(void)19 static void print_help(void)
20 {
21 	fprintf(stderr, "\nUsage:\n");
22 	fprintf(stderr, "tst_device acquire [size [filename]]\n");
23 	fprintf(stderr, "tst_device release /path/to/device\n");
24 	fprintf(stderr, "tst_device clear /path/to/device\n\n");
25 }
26 
acquire_device(int argc,char * argv[])27 static int acquire_device(int argc, char *argv[])
28 {
29 	unsigned int size = 0;
30 	const char *device;
31 
32 	if (argc > 4)
33 		return 1;
34 
35 	if (argc >= 3) {
36 		size = atoi(argv[2]);
37 
38 		if (!size) {
39 			fprintf(stderr, "ERROR: Invalid device size '%s'",
40 				argv[2]);
41 			return 1;
42 		}
43 	}
44 
45 	if (argc >= 4)
46 		device = tst_acquire_loop_device(size, argv[3]);
47 	else
48 		device = tst_acquire_device__(size);
49 
50 	if (!device)
51 		return 1;
52 
53 	if (tst_clear_device(device)) {
54 		tst_release_device(device);
55 		return 1;
56 	}
57 
58 	printf("%s", device);
59 
60 	return 0;
61 }
62 
release_device(int argc,char * argv[])63 static int release_device(int argc, char *argv[])
64 {
65 	if (argc != 3)
66 		return 1;
67 
68 	/*
69 	 * tst_acquire_[loop_]device() was called in a different process.
70 	 * tst_release_device() would think that no device was acquired yet
71 	 * and do nothing. Call tst_detach_device() directly to bypass
72 	 * the check.
73 	 */
74 	return tst_detach_device(argv[2]);
75 }
76 
clear_device(int argc,char * argv[])77 static int clear_device(int argc, char *argv[])
78 {
79 	if (argc != 3)
80 		return 1;
81 
82 	if (tst_clear_device(argv[2]))
83 		return 1;
84 
85 	return 0;
86 }
87 
main(int argc,char * argv[])88 int main(int argc, char *argv[])
89 {
90 	/*
91 	 * Force messages to be printed from the new library i.e. tst_test.c
92 	 *
93 	 * The new library prints messages into stderr while the old one prints
94 	 * them into stdout. When messages are printed into stderr we can
95 	 * safely do:
96 	 *
97 	 * DEV=$(tst_device acquire)
98 	 */
99 	tst_test = &test;
100 
101 	if (argc < 2)
102 		goto help;
103 
104 	if (!strcmp(argv[1], "acquire")) {
105 		if (acquire_device(argc, argv))
106 			goto help;
107 	} else if (!strcmp(argv[1], "release")) {
108 		if (release_device(argc, argv))
109 			goto help;
110 	} else if (!strcmp(argv[1], "clear")) {
111 		if (clear_device(argc, argv))
112 			goto help;
113 	} else {
114 		fprintf(stderr, "ERROR: Invalid COMMAND '%s'\n", argv[1]);
115 		goto help;
116 	}
117 
118 	return 0;
119 help:
120 	print_help();
121 	return 1;
122 }
123