GNU Linux-libre 4.4.294-gnu1
[releases.git] / tools / usb / ffs-test.c
1 /*
2  * ffs-test.c -- user mode filesystem api for usb composite function
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  *                    Author: Michal Nazarewicz <mina86@mina86.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 /* $(CROSS_COMPILE)cc -Wall -Wextra -g -o ffs-test ffs-test.c -lpthread */
23
24
25 #define _BSD_SOURCE /* for endian.h */
26
27 #include <endian.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <pthread.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/ioctl.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <unistd.h>
40 #include <tools/le_byteshift.h>
41
42 #include "../../include/uapi/linux/usb/functionfs.h"
43
44
45 /******************** Little Endian Handling ********************************/
46
47 /*
48  * cpu_to_le16/32 are used when initializing structures, a context where a
49  * function call is not allowed. To solve this, we code cpu_to_le16/32 in a way
50  * that allows them to be used when initializing structures.
51  */
52
53 #if __BYTE_ORDER == __LITTLE_ENDIAN
54 #define cpu_to_le16(x)  (x)
55 #define cpu_to_le32(x)  (x)
56 #else
57 #define cpu_to_le16(x)  ((((x) >> 8) & 0xffu) | (((x) & 0xffu) << 8))
58 #define cpu_to_le32(x)  \
59         ((((x) & 0xff000000u) >> 24) | (((x) & 0x00ff0000u) >>  8) | \
60         (((x) & 0x0000ff00u) <<  8) | (((x) & 0x000000ffu) << 24))
61 #endif
62
63 #define le32_to_cpu(x)  le32toh(x)
64 #define le16_to_cpu(x)  le16toh(x)
65
66 /******************** Messages and Errors ***********************************/
67
68 static const char argv0[] = "ffs-test";
69
70 static unsigned verbosity = 7;
71
72 static void _msg(unsigned level, const char *fmt, ...)
73 {
74         if (level < 2)
75                 level = 2;
76         else if (level > 7)
77                 level = 7;
78
79         if (level <= verbosity) {
80                 static const char levels[8][6] = {
81                         [2] = "crit:",
82                         [3] = "err: ",
83                         [4] = "warn:",
84                         [5] = "note:",
85                         [6] = "info:",
86                         [7] = "dbg: "
87                 };
88
89                 int _errno = errno;
90                 va_list ap;
91
92                 fprintf(stderr, "%s: %s ", argv0, levels[level]);
93                 va_start(ap, fmt);
94                 vfprintf(stderr, fmt, ap);
95                 va_end(ap);
96
97                 if (fmt[strlen(fmt) - 1] != '\n') {
98                         char buffer[128];
99                         strerror_r(_errno, buffer, sizeof buffer);
100                         fprintf(stderr, ": (-%d) %s\n", _errno, buffer);
101                 }
102
103                 fflush(stderr);
104         }
105 }
106
107 #define die(...)  (_msg(2, __VA_ARGS__), exit(1))
108 #define err(...)   _msg(3, __VA_ARGS__)
109 #define warn(...)  _msg(4, __VA_ARGS__)
110 #define note(...)  _msg(5, __VA_ARGS__)
111 #define info(...)  _msg(6, __VA_ARGS__)
112 #define debug(...) _msg(7, __VA_ARGS__)
113
114 #define die_on(cond, ...) do { \
115         if (cond) \
116                 die(__VA_ARGS__); \
117         } while (0)
118
119
120 /******************** Descriptors and Strings *******************************/
121
122 static const struct {
123         struct usb_functionfs_descs_head_v2 header;
124         __le32 fs_count;
125         __le32 hs_count;
126         struct {
127                 struct usb_interface_descriptor intf;
128                 struct usb_endpoint_descriptor_no_audio sink;
129                 struct usb_endpoint_descriptor_no_audio source;
130         } __attribute__((packed)) fs_descs, hs_descs;
131 } __attribute__((packed)) descriptors = {
132         .header = {
133                 .magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2),
134                 .flags = cpu_to_le32(FUNCTIONFS_HAS_FS_DESC |
135                                      FUNCTIONFS_HAS_HS_DESC),
136                 .length = cpu_to_le32(sizeof descriptors),
137         },
138         .fs_count = cpu_to_le32(3),
139         .fs_descs = {
140                 .intf = {
141                         .bLength = sizeof descriptors.fs_descs.intf,
142                         .bDescriptorType = USB_DT_INTERFACE,
143                         .bNumEndpoints = 2,
144                         .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
145                         .iInterface = 1,
146                 },
147                 .sink = {
148                         .bLength = sizeof descriptors.fs_descs.sink,
149                         .bDescriptorType = USB_DT_ENDPOINT,
150                         .bEndpointAddress = 1 | USB_DIR_IN,
151                         .bmAttributes = USB_ENDPOINT_XFER_BULK,
152                         /* .wMaxPacketSize = autoconfiguration (kernel) */
153                 },
154                 .source = {
155                         .bLength = sizeof descriptors.fs_descs.source,
156                         .bDescriptorType = USB_DT_ENDPOINT,
157                         .bEndpointAddress = 2 | USB_DIR_OUT,
158                         .bmAttributes = USB_ENDPOINT_XFER_BULK,
159                         /* .wMaxPacketSize = autoconfiguration (kernel) */
160                 },
161         },
162         .hs_count = cpu_to_le32(3),
163         .hs_descs = {
164                 .intf = {
165                         .bLength = sizeof descriptors.fs_descs.intf,
166                         .bDescriptorType = USB_DT_INTERFACE,
167                         .bNumEndpoints = 2,
168                         .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
169                         .iInterface = 1,
170                 },
171                 .sink = {
172                         .bLength = sizeof descriptors.hs_descs.sink,
173                         .bDescriptorType = USB_DT_ENDPOINT,
174                         .bEndpointAddress = 1 | USB_DIR_IN,
175                         .bmAttributes = USB_ENDPOINT_XFER_BULK,
176                         .wMaxPacketSize = cpu_to_le16(512),
177                 },
178                 .source = {
179                         .bLength = sizeof descriptors.hs_descs.source,
180                         .bDescriptorType = USB_DT_ENDPOINT,
181                         .bEndpointAddress = 2 | USB_DIR_OUT,
182                         .bmAttributes = USB_ENDPOINT_XFER_BULK,
183                         .wMaxPacketSize = cpu_to_le16(512),
184                         .bInterval = 1, /* NAK every 1 uframe */
185                 },
186         },
187 };
188
189 static size_t descs_to_legacy(void **legacy, const void *descriptors_v2)
190 {
191         const unsigned char *descs_end, *descs_start;
192         __u32 length, fs_count = 0, hs_count = 0, count;
193
194         /* Read v2 header */
195         {
196                 const struct {
197                         const struct usb_functionfs_descs_head_v2 header;
198                         const __le32 counts[];
199                 } __attribute__((packed)) *const in = descriptors_v2;
200                 const __le32 *counts = in->counts;
201                 __u32 flags;
202
203                 if (le32_to_cpu(in->header.magic) !=
204                     FUNCTIONFS_DESCRIPTORS_MAGIC_V2)
205                         return 0;
206                 length = le32_to_cpu(in->header.length);
207                 if (length <= sizeof in->header)
208                         return 0;
209                 length -= sizeof in->header;
210                 flags = le32_to_cpu(in->header.flags);
211                 if (flags & ~(FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
212                               FUNCTIONFS_HAS_SS_DESC))
213                         return 0;
214
215 #define GET_NEXT_COUNT_IF_FLAG(ret, flg) do {           \
216                         if (!(flags & (flg)))           \
217                                 break;                  \
218                         if (length < 4)                 \
219                                 return 0;               \
220                         ret = le32_to_cpu(*counts);     \
221                         length -= 4;                    \
222                         ++counts;                       \
223                 } while (0)
224
225                 GET_NEXT_COUNT_IF_FLAG(fs_count, FUNCTIONFS_HAS_FS_DESC);
226                 GET_NEXT_COUNT_IF_FLAG(hs_count, FUNCTIONFS_HAS_HS_DESC);
227                 GET_NEXT_COUNT_IF_FLAG(count, FUNCTIONFS_HAS_SS_DESC);
228
229                 count = fs_count + hs_count;
230                 if (!count)
231                         return 0;
232                 descs_start = (const void *)counts;
233
234 #undef GET_NEXT_COUNT_IF_FLAG
235         }
236
237         /*
238          * Find the end of FS and HS USB descriptors.  SS descriptors
239          * are ignored since legacy format does not support them.
240          */
241         descs_end = descs_start;
242         do {
243                 if (length < *descs_end)
244                         return 0;
245                 length -= *descs_end;
246                 descs_end += *descs_end;
247         } while (--count);
248
249         /* Allocate legacy descriptors and copy the data. */
250         {
251 #pragma GCC diagnostic push
252 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
253                 struct {
254                         struct usb_functionfs_descs_head header;
255                         __u8 descriptors[];
256                 } __attribute__((packed)) *out;
257 #pragma GCC diagnostic pop
258
259                 length = sizeof out->header + (descs_end - descs_start);
260                 out = malloc(length);
261                 out->header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
262                 out->header.length = cpu_to_le32(length);
263                 out->header.fs_count = cpu_to_le32(fs_count);
264                 out->header.hs_count = cpu_to_le32(hs_count);
265                 memcpy(out->descriptors, descs_start, descs_end - descs_start);
266                 *legacy = out;
267         }
268
269         return length;
270 }
271
272
273 #define STR_INTERFACE_ "Source/Sink"
274
275 static const struct {
276         struct usb_functionfs_strings_head header;
277         struct {
278                 __le16 code;
279                 const char str1[sizeof STR_INTERFACE_];
280         } __attribute__((packed)) lang0;
281 } __attribute__((packed)) strings = {
282         .header = {
283                 .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC),
284                 .length = cpu_to_le32(sizeof strings),
285                 .str_count = cpu_to_le32(1),
286                 .lang_count = cpu_to_le32(1),
287         },
288         .lang0 = {
289                 cpu_to_le16(0x0409), /* en-us */
290                 STR_INTERFACE_,
291         },
292 };
293
294 #define STR_INTERFACE strings.lang0.str1
295
296
297 /******************** Files and Threads Handling ****************************/
298
299 struct thread;
300
301 static ssize_t read_wrap(struct thread *t, void *buf, size_t nbytes);
302 static ssize_t write_wrap(struct thread *t, const void *buf, size_t nbytes);
303 static ssize_t ep0_consume(struct thread *t, const void *buf, size_t nbytes);
304 static ssize_t fill_in_buf(struct thread *t, void *buf, size_t nbytes);
305 static ssize_t empty_out_buf(struct thread *t, const void *buf, size_t nbytes);
306
307
308 static struct thread {
309         const char *const filename;
310         size_t buf_size;
311
312         ssize_t (*in)(struct thread *, void *, size_t);
313         const char *const in_name;
314
315         ssize_t (*out)(struct thread *, const void *, size_t);
316         const char *const out_name;
317
318         int fd;
319         pthread_t id;
320         void *buf;
321         ssize_t status;
322 } threads[] = {
323         {
324                 "ep0", 4 * sizeof(struct usb_functionfs_event),
325                 read_wrap, NULL,
326                 ep0_consume, "<consume>",
327                 0, 0, NULL, 0
328         },
329         {
330                 "ep1", 8 * 1024,
331                 fill_in_buf, "<in>",
332                 write_wrap, NULL,
333                 0, 0, NULL, 0
334         },
335         {
336                 "ep2", 8 * 1024,
337                 read_wrap, NULL,
338                 empty_out_buf, "<out>",
339                 0, 0, NULL, 0
340         },
341 };
342
343
344 static void init_thread(struct thread *t)
345 {
346         t->buf = malloc(t->buf_size);
347         die_on(!t->buf, "malloc");
348
349         t->fd = open(t->filename, O_RDWR);
350         die_on(t->fd < 0, "%s", t->filename);
351 }
352
353 static void cleanup_thread(void *arg)
354 {
355         struct thread *t = arg;
356         int ret, fd;
357
358         fd = t->fd;
359         if (t->fd < 0)
360                 return;
361         t->fd = -1;
362
363         /* test the FIFO ioctls (non-ep0 code paths) */
364         if (t != threads) {
365                 ret = ioctl(fd, FUNCTIONFS_FIFO_STATUS);
366                 if (ret < 0) {
367                         /* ENODEV reported after disconnect */
368                         if (errno != ENODEV)
369                                 err("%s: get fifo status", t->filename);
370                 } else if (ret) {
371                         warn("%s: unclaimed = %d\n", t->filename, ret);
372                         if (ioctl(fd, FUNCTIONFS_FIFO_FLUSH) < 0)
373                                 err("%s: fifo flush", t->filename);
374                 }
375         }
376
377         if (close(fd) < 0)
378                 err("%s: close", t->filename);
379
380         free(t->buf);
381         t->buf = NULL;
382 }
383
384 static void *start_thread_helper(void *arg)
385 {
386         const char *name, *op, *in_name, *out_name;
387         struct thread *t = arg;
388         ssize_t ret;
389
390         info("%s: starts\n", t->filename);
391         in_name = t->in_name ? t->in_name : t->filename;
392         out_name = t->out_name ? t->out_name : t->filename;
393
394         pthread_cleanup_push(cleanup_thread, arg);
395
396         for (;;) {
397                 pthread_testcancel();
398
399                 ret = t->in(t, t->buf, t->buf_size);
400                 if (ret > 0) {
401                         ret = t->out(t, t->buf, ret);
402                         name = out_name;
403                         op = "write";
404                 } else {
405                         name = in_name;
406                         op = "read";
407                 }
408
409                 if (ret > 0) {
410                         /* nop */
411                 } else if (!ret) {
412                         debug("%s: %s: EOF", name, op);
413                         break;
414                 } else if (errno == EINTR || errno == EAGAIN) {
415                         debug("%s: %s", name, op);
416                 } else {
417                         warn("%s: %s", name, op);
418                         break;
419                 }
420         }
421
422         pthread_cleanup_pop(1);
423
424         t->status = ret;
425         info("%s: ends\n", t->filename);
426         return NULL;
427 }
428
429 static void start_thread(struct thread *t)
430 {
431         debug("%s: starting\n", t->filename);
432
433         die_on(pthread_create(&t->id, NULL, start_thread_helper, t) < 0,
434                "pthread_create(%s)", t->filename);
435 }
436
437 static void join_thread(struct thread *t)
438 {
439         int ret = pthread_join(t->id, NULL);
440
441         if (ret < 0)
442                 err("%s: joining thread", t->filename);
443         else
444                 debug("%s: joined\n", t->filename);
445 }
446
447
448 static ssize_t read_wrap(struct thread *t, void *buf, size_t nbytes)
449 {
450         return read(t->fd, buf, nbytes);
451 }
452
453 static ssize_t write_wrap(struct thread *t, const void *buf, size_t nbytes)
454 {
455         return write(t->fd, buf, nbytes);
456 }
457
458
459 /******************** Empty/Fill buffer routines ****************************/
460
461 /* 0 -- stream of zeros, 1 -- i % 63, 2 -- pipe */
462 enum pattern { PAT_ZERO, PAT_SEQ, PAT_PIPE };
463 static enum pattern pattern;
464
465 static ssize_t
466 fill_in_buf(struct thread *ignore, void *buf, size_t nbytes)
467 {
468         size_t i;
469         __u8 *p;
470
471         (void)ignore;
472
473         switch (pattern) {
474         case PAT_ZERO:
475                 memset(buf, 0, nbytes);
476                 break;
477
478         case PAT_SEQ:
479                 for (p = buf, i = 0; i < nbytes; ++i, ++p)
480                         *p = i % 63;
481                 break;
482
483         case PAT_PIPE:
484                 return fread(buf, 1, nbytes, stdin);
485         }
486
487         return nbytes;
488 }
489
490 static ssize_t
491 empty_out_buf(struct thread *ignore, const void *buf, size_t nbytes)
492 {
493         const __u8 *p;
494         __u8 expected;
495         ssize_t ret;
496         size_t len;
497
498         (void)ignore;
499
500         switch (pattern) {
501         case PAT_ZERO:
502                 expected = 0;
503                 for (p = buf, len = 0; len < nbytes; ++p, ++len)
504                         if (*p)
505                                 goto invalid;
506                 break;
507
508         case PAT_SEQ:
509                 for (p = buf, len = 0; len < nbytes; ++p, ++len)
510                         if (*p != len % 63) {
511                                 expected = len % 63;
512                                 goto invalid;
513                         }
514                 break;
515
516         case PAT_PIPE:
517                 ret = fwrite(buf, nbytes, 1, stdout);
518                 if (ret > 0)
519                         fflush(stdout);
520                 break;
521
522 invalid:
523                 err("bad OUT byte %zd, expected %02x got %02x\n",
524                     len, expected, *p);
525                 for (p = buf, len = 0; len < nbytes; ++p, ++len) {
526                         if (0 == (len % 32))
527                                 fprintf(stderr, "%4zd:", len);
528                         fprintf(stderr, " %02x", *p);
529                         if (31 == (len % 32))
530                                 fprintf(stderr, "\n");
531                 }
532                 fflush(stderr);
533                 errno = EILSEQ;
534                 return -1;
535         }
536
537         return len;
538 }
539
540
541 /******************** Endpoints routines ************************************/
542
543 static void handle_setup(const struct usb_ctrlrequest *setup)
544 {
545         printf("bRequestType = %d\n", setup->bRequestType);
546         printf("bRequest     = %d\n", setup->bRequest);
547         printf("wValue       = %d\n", le16_to_cpu(setup->wValue));
548         printf("wIndex       = %d\n", le16_to_cpu(setup->wIndex));
549         printf("wLength      = %d\n", le16_to_cpu(setup->wLength));
550 }
551
552 static ssize_t
553 ep0_consume(struct thread *ignore, const void *buf, size_t nbytes)
554 {
555         static const char *const names[] = {
556                 [FUNCTIONFS_BIND] = "BIND",
557                 [FUNCTIONFS_UNBIND] = "UNBIND",
558                 [FUNCTIONFS_ENABLE] = "ENABLE",
559                 [FUNCTIONFS_DISABLE] = "DISABLE",
560                 [FUNCTIONFS_SETUP] = "SETUP",
561                 [FUNCTIONFS_SUSPEND] = "SUSPEND",
562                 [FUNCTIONFS_RESUME] = "RESUME",
563         };
564
565         const struct usb_functionfs_event *event = buf;
566         size_t n;
567
568         (void)ignore;
569
570         for (n = nbytes / sizeof *event; n; --n, ++event)
571                 switch (event->type) {
572                 case FUNCTIONFS_BIND:
573                 case FUNCTIONFS_UNBIND:
574                 case FUNCTIONFS_ENABLE:
575                 case FUNCTIONFS_DISABLE:
576                 case FUNCTIONFS_SETUP:
577                 case FUNCTIONFS_SUSPEND:
578                 case FUNCTIONFS_RESUME:
579                         printf("Event %s\n", names[event->type]);
580                         if (event->type == FUNCTIONFS_SETUP)
581                                 handle_setup(&event->u.setup);
582                         break;
583
584                 default:
585                         printf("Event %03u (unknown)\n", event->type);
586                 }
587
588         return nbytes;
589 }
590
591 static void ep0_init(struct thread *t, bool legacy_descriptors)
592 {
593         void *legacy;
594         ssize_t ret;
595         size_t len;
596
597         if (legacy_descriptors) {
598                 info("%s: writing descriptors\n", t->filename);
599                 goto legacy;
600         }
601
602         info("%s: writing descriptors (in v2 format)\n", t->filename);
603         ret = write(t->fd, &descriptors, sizeof descriptors);
604
605         if (ret < 0 && errno == EINVAL) {
606                 warn("%s: new format rejected, trying legacy\n", t->filename);
607 legacy:
608                 len = descs_to_legacy(&legacy, &descriptors);
609                 if (len) {
610                         ret = write(t->fd, legacy, len);
611                         free(legacy);
612                 }
613         }
614         die_on(ret < 0, "%s: write: descriptors", t->filename);
615
616         info("%s: writing strings\n", t->filename);
617         ret = write(t->fd, &strings, sizeof strings);
618         die_on(ret < 0, "%s: write: strings", t->filename);
619 }
620
621
622 /******************** Main **************************************************/
623
624 int main(int argc, char **argv)
625 {
626         bool legacy_descriptors;
627         unsigned i;
628
629         legacy_descriptors = argc > 2 && !strcmp(argv[1], "-l");
630
631         init_thread(threads);
632         ep0_init(threads, legacy_descriptors);
633
634         for (i = 1; i < sizeof threads / sizeof *threads; ++i)
635                 init_thread(threads + i);
636
637         for (i = 1; i < sizeof threads / sizeof *threads; ++i)
638                 start_thread(threads + i);
639
640         start_thread_helper(threads);
641
642         for (i = 1; i < sizeof threads / sizeof *threads; ++i)
643                 join_thread(threads + i);
644
645         return 0;
646 }