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: tst_device acquire [size [filename]]\n");
22 fprintf(stderr, " or: tst_device release /path/to/device\n\n");
23 }
24
acquire_device(int argc,char * argv[])25 static int acquire_device(int argc, char *argv[])
26 {
27 unsigned int size = 0;
28 const char *device;
29
30 if (argc > 4)
31 return 1;
32
33 if (argc >= 3) {
34 size = atoi(argv[2]);
35
36 if (!size) {
37 fprintf(stderr, "ERROR: Invalid device size '%s'",
38 argv[2]);
39 return 1;
40 }
41 }
42
43 if (argc >= 4) {
44 device = tst_acquire_loop_device(size, argv[3]);
45 } else {
46 device = tst_acquire_device__(size);
47 }
48
49 if (!device)
50 return 1;
51
52 if (tst_clear_device(device)) {
53 tst_release_device(device);
54 return 1;
55 }
56
57 printf("%s", device);
58
59 return 0;
60 }
61
release_device(int argc,char * argv[])62 static int release_device(int argc, char *argv[])
63 {
64 if (argc != 3)
65 return 1;
66
67 /*
68 * tst_acquire_[loop_]device() was called in a different process.
69 * tst_release_device() would think that no device was acquired yet
70 * and do nothing. Call tst_detach_device() directly to bypass
71 * the check.
72 */
73 return tst_detach_device(argv[2]);
74 }
75
main(int argc,char * argv[])76 int main(int argc, char *argv[])
77 {
78 /*
79 * Force messages to be printed from the new library i.e. tst_test.c
80 *
81 * The new library prints messages into stderr while the old one prints
82 * them into stdout. When messages are printed into stderr we can
83 * safely do:
84 *
85 * DEV=$(tst_device acquire)
86 */
87 tst_test = &test;
88
89 if (argc < 2)
90 goto help;
91
92 if (!strcmp(argv[1], "acquire")) {
93 if (acquire_device(argc, argv))
94 goto help;
95 } else if (!strcmp(argv[1], "release")) {
96 if (release_device(argc, argv))
97 goto help;
98 } else {
99 fprintf(stderr, "ERROR: Invalid COMMAND '%s'\n", argv[1]);
100 goto help;
101 }
102
103 return 0;
104 help:
105 print_help();
106 return 1;
107 }
108