Refactoring usb gadget
[platform/core/system/libdevice-node.git] / hw / usb_cfs_client_common.c
1 /*
2  * libdevice-node
3  *
4  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the License);
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #include <errno.h>
20 #include <string.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <sys/mount.h>
24
25 #include <usbg/usbg.h>
26 #include <usbg/function/net.h>
27 #include <libsyscommon/dbus-systemd.h>
28
29 #include <hw/usb_gadget.h>
30 #include <hw/usb_client.h>
31
32 #define CONFIGFS_PATH "/sys/kernel/config"
33
34 #define CONFIGFS_GADGET_NAME "hal-gadget"
35 #define CONFIGFS_CONFIG_LABEL "hal-config"
36
37 #define NAME_INSTANCE_SEP '.'
38 #define MAX_INSTANCE_LEN 512
39
40 #define USB_FUNCS_PATH "/dev/usb-funcs"
41
42 #ifndef EXPORT
43 #define EXPORT  __attribute__ ((visibility("default")))
44 #endif
45
46 enum cfs_function_service_operation {
47         CFS_FUNCTION_SERVICE_START,
48         CFS_FUNCTION_SERVICE_STOP,
49         CFS_FUNCTION_SERVICE_POST_STOP,
50 };
51
52 struct cfs_client {
53         struct usb_client client;
54         usbg_state *ctx;
55         usbg_gadget *gadget;
56         usbg_udc *udc;
57 };
58
59 /* Based on values in slp-gadget kernel module */
60 struct usbg_gadget_attrs default_g_attrs = {
61         .idVendor = DEFAULT_VID,
62         .idProduct = DEFAULT_PID,
63         .bcdDevice = DEFAULT_BCD_DEVICE,
64 };
65
66 struct usbg_gadget_strs default_g_strs = {
67         .manufacturer = DEFAULT_MANUFACTURER,
68         .product = DEFAULT_PRODUCT,
69         .serial = DEFAULT_SERIAL,
70 };
71
72 static struct usb_function *cfs_find_usb_function(usbg_function *function)
73 {
74         char *sep;
75         char buf[MAX_INSTANCE_LEN];
76         const char *instance = usbg_get_function_instance(function);
77         const char *name = usbg_get_function_type_str(usbg_get_function_type(function));
78
79         /* Ex. name:"ffs",  instance: "sdb.default" */
80         if (strcmp(name, usbg_get_function_type_str(USBG_F_FFS)) == 0) {
81                 strncpy(buf, instance, sizeof(buf) - 1);
82                 buf[sizeof(buf) - 1] = '\0';
83
84                 /* Ex. "sdb.default" ==> "sdb" + "default" */
85                 sep = strchr(buf, NAME_INSTANCE_SEP);
86                 if (!sep || !sep[1])
87                         return NULL;
88                 *sep = '\0';
89
90                 name = buf;
91                 instance = sep + 1;
92         }
93
94         return find_usb_function_by_name_instance(name, instance);
95 }
96
97 static bool cfs_is_function_supported(struct usb_client *usb,
98                                          struct usb_function *func)
99 {
100         bool res;
101         int ret;
102
103         if (!func->is_functionfs) {
104                 ret = usbg_lookup_function_type(func->name);
105                 res = ret >= 0;
106         } else {
107                 /* TODO: Check if socket is available */
108                 res = true;
109         }
110
111         return res;
112 }
113
114 static bool cfs_is_gadget_supported(struct usb_client *usb,
115                                        struct usb_gadget *gadget)
116 {
117         int i, j;
118
119         if (!gadget || !gadget->configs || !gadget->funcs)
120                 return false;
121
122         /* No real restrictions for strings */
123         for (j = 0; gadget->configs && gadget->configs[j]; ++j) {
124                 struct usb_configuration *config = gadget->configs[j];
125
126                 if (!config->funcs)
127                         return false;
128
129                 for (i = 0; config->funcs[i]; ++i)
130                         if (!cfs_is_function_supported(usb, config->funcs[i]))
131                                 return false;
132         }
133
134         if (j == 0)
135                 return false;
136
137         return true;
138 }
139
140 static int cfs_set_gadget_attrs(struct cfs_client *cfs_client,
141                                 struct usb_gadget_attrs *attrs)
142 {
143         int ret;
144         struct usbg_gadget_attrs gadget_attrs;
145
146         ret = usbg_get_gadget_attrs(cfs_client->gadget, &gadget_attrs);
147         if (ret)
148                 return ret;
149
150         gadget_attrs.bDeviceClass = attrs->bDeviceClass;
151         gadget_attrs.bDeviceSubClass = attrs->bDeviceSubClass;
152         gadget_attrs.bDeviceProtocol = attrs->bDeviceProtocol;
153         gadget_attrs.idVendor = attrs->idVendor;
154         gadget_attrs.idProduct = attrs->idProduct;
155         gadget_attrs.bcdDevice = attrs->bcdDevice;
156
157         ret = usbg_set_gadget_attrs(cfs_client->gadget, &gadget_attrs);
158
159         return ret;
160 }
161
162 static int cfs_set_gadget_strs(struct cfs_client *cfs_client,
163                                   struct usb_gadget_strings *strs)
164 {
165         int ret;
166
167 #define SET_STR(FIELD, STR_ID)                          \
168         if (strs->FIELD) {                              \
169                 ret = usbg_set_gadget_str(cfs_client->gadget,   \
170                                           STR_ID,               \
171                                           strs->lang_code,      \
172                                           strs->FIELD);         \
173                 if (ret)                                        \
174                         return ret;                             \
175         }
176
177         SET_STR(manufacturer, USBG_STR_MANUFACTURER);
178         SET_STR(product, USBG_STR_PRODUCT);
179         SET_STR(serial, USBG_STR_SERIAL_NUMBER);
180 #undef SET_STR
181
182         return 0;
183 }
184
185 static int cfs_ensure_dir(char *path)
186 {
187         if (mkdir(path, 0770) < 0)
188                 return (errno == EEXIST) ? 0 : -errno;
189
190         return 0;
191 }
192
193
194 static int cfs_prep_ffs_service(struct usb_function *usb_func, usbg_function *function)
195 {
196         int ret;
197         const char *name;
198         const char *service;
199         const char *instance;
200         const char *dev_name;
201         char buf[MAX_INSTANCE_LEN];
202
203         if (!usb_func || !function)
204                 return -EINVAL;
205
206         if (usbg_get_function_type(function) != USBG_F_FFS)
207                 return -EINVAL;
208
209         name = usb_func->name;
210         service = usb_func->service;
211         instance = usb_func->instance;
212         dev_name = usbg_get_function_instance(function);
213
214         /* "/dev/usb-funcs" + "/" + "sdb" + "/" + "default"  + '0' */
215         if (strlen(USB_FUNCS_PATH) + strlen(name) + strlen(instance) + 3  > sizeof(buf))
216                 return -ENAMETOOLONG;
217
218         /* mkdir /dev/usb-funcs */
219         ret = cfs_ensure_dir(USB_FUNCS_PATH);
220         if (ret < 0)
221                 return ret;
222
223         /* mkdir /dev/usb-funcs/sdb */
224         snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
225         ret = cfs_ensure_dir(buf);
226         if (ret < 0)
227                 goto out_rmdir;
228
229         /* mkdir /dev/usb-funcs/sdb/default */
230         snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
231         ret = cfs_ensure_dir(buf);
232         if (ret < 0)
233                 goto out_rmdir;
234
235         /* mount -t functionfs sdb.default /dev/usb-funcs/sdb/default */
236         ret = mount(dev_name, buf, "functionfs", 0, NULL);
237         if (ret < 0)
238                 goto out_rmdir;
239
240         /* start sdbd.socket */
241         ret = systemd_start_unit_wait_started(service, ".socket", -1);
242         if (ret < 0)
243                 goto out_unmount;
244
245         return 0;
246
247 out_unmount:
248         umount(buf);
249
250 out_rmdir:
251         snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
252         rmdir(buf);
253
254         snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
255         rmdir(buf);
256
257         rmdir(USB_FUNCS_PATH);
258
259         return ret;
260 }
261
262 static int cfs_cleanup_ffs_service(usbg_function *function)
263 {
264         int ret;
265         char buf[MAX_INSTANCE_LEN];
266         struct usb_function *usb_function;
267
268         if (!function)
269                 return -EINVAL;
270
271         usb_function = cfs_find_usb_function(function);
272         if (!usb_function)
273                 return -ENOENT;
274
275         /* stop .socket first and stop .service later becuase of socket activation */
276         if (usb_function->service) {
277                 (void)systemd_stop_unit_wait_stopped(usb_function->service, ".socket", -1);
278                 (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
279         }
280
281         /* umount /dev/usb-funcs/[sdb|mtp]/default and remove it's directory */
282         ret = snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, usb_function->name, usb_function->instance);
283         if (ret < 0)
284                 return ret;
285
286         ret = umount(buf);
287         if (ret < 0)
288                 return ret;
289
290         ret = rmdir(buf);
291         if (ret < 0)
292                 return ret;
293
294         /* remove /dev/usb-funcs/[sdb|mtp] directory */
295         ret = snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, usb_function->name);
296         if (ret < 0)
297                 return ret;
298
299         ret = rmdir(buf);
300         if (ret < 0 && errno != ENOTEMPTY)
301                 return ret;
302
303         /* remove /dev/usb-funcs/ directory */
304         ret = rmdir(USB_FUNCS_PATH);
305         if (ret < 0 && errno != ENOTEMPTY)
306                 return ret;
307
308         return 0;
309 }
310
311
312 static int cfs_set_rndis_mac_addr(usbg_gadget *gadget, usbg_function *func)
313 {
314         int i, ret;
315         struct ether_addr ethaddr;
316         struct usbg_gadget_strs strs;
317         struct usbg_f_net *nf = usbg_to_net_function(func);
318
319         if (!nf)
320                 return -EINVAL;
321
322         ret = usbg_get_gadget_strs(gadget, LANG_US_ENG, &strs);
323         if (ret != USBG_SUCCESS)
324                 return ret;
325
326         for (i = 0; i < ETHER_ADDR_LEN; i++)
327                 ethaddr.ether_addr_octet[i] = 0;
328
329         for (i = 0; (i < 256) && strs.serial[i]; i++) {
330                 ethaddr.ether_addr_octet[i % (ETHER_ADDR_LEN - 1) + 1] ^= strs.serial[i];
331         }
332         ethaddr.ether_addr_octet[0] &= 0xfe;     /* clear multicast bit */
333         ethaddr.ether_addr_octet[0] |= 0x02;     /* set local assignment bit (IEEE802) */
334
335         usbg_free_gadget_strs(&strs);
336
337         /* host_addr changes mac address */
338         ret = usbg_f_net_set_host_addr(nf, &ethaddr);
339
340         return ret;
341 }
342
343 static int cfs_cleanup_all_config_and_function(struct cfs_client *cfs_client)
344 {
345         int ret;
346         usbg_config *config;
347         usbg_function *function;
348
349         /* delete all configs */
350 restart_rm_config:
351         usbg_for_each_config(config, cfs_client->gadget) {
352                 ret = usbg_rm_config(config, USBG_RM_RECURSE);
353                 if (ret)
354                         return ret;
355
356                 goto restart_rm_config; /* You cannot delete a config directly in an iterator. */
357         }
358
359         /* delete all functions */
360 restart_rm_function:
361         usbg_for_each_function(function, cfs_client->gadget) {
362                 if (usbg_get_function_type(function) == USBG_F_FFS) {
363                         ret = cfs_cleanup_ffs_service(function);
364                         if (ret)
365                                 return ret;
366                 }
367
368                 ret = usbg_rm_function(function, USBG_RM_RECURSE);
369                 if (ret)
370                         return ret;
371
372                 goto restart_rm_function; /* You cannot delete a function directly in an iterator. */
373         }
374
375         return 0;
376 }
377
378 static int cfs_set_gadget_config(struct cfs_client *cfs_client, int config_id, struct usb_configuration *usb_config)
379 {
380         int i;
381         int ret;
382         int function_type;
383         usbg_config *config;
384         usbg_function *function;
385         struct usb_function *usb_func;
386         char instance[MAX_INSTANCE_LEN];
387         struct usbg_config_attrs cattrs = {
388                 .bmAttributes = usb_config->attrs.bmAttributs,
389                 .bMaxPower = usb_config->attrs.MaxPower/2,
390         };
391
392         if (!usb_config->funcs || !usb_config->funcs[0])
393                 return -EINVAL;
394
395         ret = usbg_create_config(cfs_client->gadget, config_id, CONFIGFS_CONFIG_LABEL, &cattrs, NULL, &config);
396         if (ret)
397                 return ret;
398
399         for (i = 0; usb_config->strs && usb_config->strs[i].lang_code; ++i) {
400                 ret = usbg_set_config_string(config, usb_config->strs[i].lang_code, usb_config->strs[i].config_str);
401                 if (ret)
402                         return ret;
403         }
404
405         for (i = 0; usb_config->funcs[i]; ++i) {
406                 usb_func = usb_config->funcs[i];
407
408                 /* name("sdb") + NAME_INSTANCE_SEP(".") + instance("default") + '\0' */
409                 if (strlen(usb_func->name) + strlen(usb_func->instance) + 2 > sizeof(instance))
410                         return -ENAMETOOLONG;
411
412                 /* In functionfs, the instance is used in the format "[sdb|mtp].default" instead of "default" */
413                 if (usb_func->is_functionfs) {
414                         function_type = USBG_F_FFS;
415                         snprintf(instance, sizeof(instance), "%s%c%s", usb_func->name, NAME_INSTANCE_SEP, usb_func->instance);
416                 } else {
417                         function_type = usbg_lookup_function_type(usb_func->name);
418                         strncpy(instance, usb_func->instance, sizeof(instance) - 1);
419                         instance[sizeof(instance) - 1] = '\0';
420                 }
421
422                 function = usbg_get_function(cfs_client->gadget, function_type, instance);
423                 if (!function) {
424                         ret = usbg_create_function(cfs_client->gadget, function_type, instance, NULL, &function);
425                         if (ret)
426                                 return ret;
427
428                         /* Setting rndis mac address. This should be done at this point,
429                          * since the node host_addr changes to read only after the function
430                          * is added to config. */
431                         if (usbg_get_function_type(function) == USBG_F_RNDIS)
432                                 (void)cfs_set_rndis_mac_addr(cfs_client->gadget, function); /* A random value is used if fails */
433
434                         if (usbg_get_function_type(function) == USBG_F_FFS) {
435                                 ret = cfs_prep_ffs_service(usb_func, function);
436                                 if (ret)
437                                         return ret;
438                         }
439                 }
440
441                 ret = usbg_add_config_function(config, NULL, function);
442                 if (ret)
443                         return ret;
444         }
445
446         return 0;
447 }
448
449 static int cfs_reconfigure_gadget(struct usb_client *usb, struct usb_gadget *gadget)
450 {
451         int i;
452         int ret;
453         struct cfs_client *cfs_client;
454
455         if (!usb || !gadget || !cfs_is_gadget_supported(usb, gadget))
456                 return -EINVAL;
457
458         cfs_client = container_of(usb, struct cfs_client, client);
459
460         ret = cfs_set_gadget_attrs(cfs_client, &gadget->attrs);
461         if (ret)
462                 return ret;
463
464         for (i = 0; gadget->strs && gadget->strs[i].lang_code > 0; ++i) {
465                 ret = cfs_set_gadget_strs(cfs_client, gadget->strs + i);
466                 if (ret)
467                         return ret;
468         }
469
470         ret = cfs_cleanup_all_config_and_function(cfs_client);
471         if (ret)
472                 return ret;
473
474         for (i = 0; gadget->configs && gadget->configs[i]; ++i) {
475                 ret = cfs_set_gadget_config(cfs_client, i + 1, gadget->configs[i]);
476                 if (ret)
477                         return ret;
478         }
479
480         return 0;
481 }
482
483 static void cfs_start_stop_service_and_handler(usbg_gadget *gadget, enum cfs_function_service_operation operation)
484 {
485         usbg_function *function;
486         struct usb_function *usb_function;
487
488         usbg_for_each_function(function, gadget) {
489                 usb_function = cfs_find_usb_function(function);
490                 if (!usb_function)
491                         continue;
492
493                 switch(operation) {
494                 case CFS_FUNCTION_SERVICE_START:
495                         if (usb_function->handler)
496                                 usb_function->handler(1);
497
498                         /* functionfs service is automatically started by socket activation */
499                         if (!usb_function->is_functionfs && usb_function->service)
500                                 (void)systemd_start_unit_wait_started(usb_function->service, ".service", -1);
501                         break;
502
503                 case CFS_FUNCTION_SERVICE_STOP:
504                         if (!usb_function->is_functionfs && usb_function->service)
505                                 (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
506
507                         if (usb_function->handler)
508                                 usb_function->handler(0);
509                         break;
510
511                 case CFS_FUNCTION_SERVICE_POST_STOP:
512                         if (usb_function->is_functionfs && usb_function->service)
513                                 (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
514                         break;
515
516                 default:
517                         break;
518                 }
519         }
520 }
521
522 static int cfs_enable(struct usb_client *usb)
523 {
524         int ret;
525         struct cfs_client *cfs_client;
526
527         if (!usb)
528                 return -EINVAL;
529
530         cfs_client = container_of(usb, struct cfs_client, client);
531
532         ret = usbg_enable_gadget(cfs_client->gadget, cfs_client->udc);
533         if (ret)
534                 return ret;
535
536         cfs_start_stop_service_and_handler(cfs_client->gadget, CFS_FUNCTION_SERVICE_START);
537
538         return 0;
539 }
540
541 static int cfs_disable(struct usb_client *usb)
542 {
543         int ret;
544         struct cfs_client *cfs_client;
545
546         if (!usb)
547                 return -EINVAL;
548
549         cfs_client = container_of(usb, struct cfs_client, client);
550
551         cfs_start_stop_service_and_handler(cfs_client->gadget, CFS_FUNCTION_SERVICE_STOP);
552
553         ret = usbg_disable_gadget(cfs_client->gadget); /* ignore error checking */
554
555         /*
556          * Since functionfs service works with socket activation, you must stop it after disabling gadget.
557          * If usb data may come in after stopping functionfs service and before disabling gadget,
558          * functionfs service wakes up again by socket activation.
559          */
560         cfs_start_stop_service_and_handler(cfs_client->gadget, CFS_FUNCTION_SERVICE_POST_STOP);
561
562         return ret;
563 }
564
565 EXPORT
566 int hw_cfs_gadget_open(struct hw_info *info,
567                 const char *id, struct hw_common **common)
568 {
569         struct cfs_client *cfs_client;
570         int ret;
571
572         if (!info || !common)
573                 return -EINVAL;
574
575         cfs_client = calloc(1, sizeof(*cfs_client));
576         if (!cfs_client)
577                 return -ENOMEM;
578
579         ret = usbg_init(CONFIGFS_PATH, &cfs_client->ctx);
580         if (ret)
581                 goto err_usbg_init;
582
583         cfs_client->udc = usbg_get_first_udc(cfs_client->ctx);
584         if (!cfs_client->udc) {
585                 ret = -ENODEV;
586                 goto err_no_udc;
587         }
588
589         ret = usbg_create_gadget(cfs_client->ctx, CONFIGFS_GADGET_NAME,
590                                  &default_g_attrs, &default_g_strs,
591                                  &cfs_client->gadget);
592         if (ret)
593                 goto err_create_gadget;
594
595         cfs_client->client.common.info = info;
596
597         cfs_client->client.reconfigure_gadget = cfs_reconfigure_gadget;
598         cfs_client->client.enable = cfs_enable;
599         cfs_client->client.disable = cfs_disable;
600
601         *common = &cfs_client->client.common;
602
603         return 0;
604
605 err_create_gadget:
606 err_no_udc:
607         usbg_cleanup(cfs_client->ctx);
608 err_usbg_init:
609         free(cfs_client);
610
611         return ret;
612 }
613
614 EXPORT
615 int hw_cfs_gadget_close(struct hw_common *common)
616 {
617         usbg_function *function;
618         struct cfs_client *cfs_client;
619         struct usb_function *usb_func;
620
621         if (!common)
622                 return -EINVAL;
623
624         cfs_client = container_of(common, struct cfs_client, client.common);
625
626         usbg_for_each_function(function, cfs_client->gadget) {
627                 usb_func = cfs_find_usb_function(function);
628                 if (!usb_func)
629                         continue;
630
631                 if (usb_func->is_functionfs && usb_func->service) {
632                         (void)systemd_stop_unit_wait_stopped(usb_func->service, ".socket", -1);
633                         (void)systemd_stop_unit_wait_stopped(usb_func->service, ".service", -1);
634                 }
635         }
636
637         /*
638          * For now we don't check for errors
639          * but we should somehow handle them
640          */
641         usbg_rm_gadget(cfs_client->gadget, USBG_RM_RECURSE);
642         usbg_cleanup(cfs_client->ctx);
643         free(cfs_client);
644
645         return 0;
646 }
647