Rename usb modules 93/273793/5
authorYoungjae Cho <y0.cho@samsung.com>
Thu, 14 Apr 2022 00:33:24 +0000 (09:33 +0900)
committerYoungjae Cho <y0.cho@samsung.com>
Thu, 14 Apr 2022 04:57:21 +0000 (13:57 +0900)
- usb -> usb-gadget
- usbhost -> usb-host

Change-Id: I2ccce17d76e71399798424654dca9844f9874625
Signed-off-by: Youngjae Cho <y0.cho@samsung.com>
27 files changed:
CMakeLists.txt
src/usb-gadget/usb-dbus.c [new file with mode: 0644]
src/usb-gadget/usb-debug.c [new file with mode: 0644]
src/usb-gadget/usb-debug.h [new file with mode: 0644]
src/usb-gadget/usb-gadget-cfs-gadget.c [new file with mode: 0644]
src/usb-gadget/usb-gadget-legacy-gadget.c [new file with mode: 0644]
src/usb-gadget/usb-gadget.c [new file with mode: 0644]
src/usb-gadget/usb-gadget.h [new file with mode: 0644]
src/usb-gadget/usb-state.c [new file with mode: 0644]
src/usb-gadget/usb-tethering.c [new file with mode: 0644]
src/usb-gadget/usb-tethering.h [new file with mode: 0644]
src/usb-gadget/usb.c [new file with mode: 0644]
src/usb-gadget/usb.h [new file with mode: 0644]
src/usb-host/usb-host.c [new file with mode: 0644]
src/usb/usb-dbus.c [deleted file]
src/usb/usb-debug.c [deleted file]
src/usb/usb-debug.h [deleted file]
src/usb/usb-gadget-cfs-gadget.c [deleted file]
src/usb/usb-gadget-legacy-gadget.c [deleted file]
src/usb/usb-gadget.c [deleted file]
src/usb/usb-gadget.h [deleted file]
src/usb/usb-state.c [deleted file]
src/usb/usb-tethering.c [deleted file]
src/usb/usb-tethering.h [deleted file]
src/usb/usb.c [deleted file]
src/usb/usb.h [deleted file]
src/usbhost/usb-host.c [deleted file]

index 287aac91213b977f0c1ba25df437ff5d655ca700..61437917ff683098ed96c25138119525b7ebab03 100644 (file)
@@ -122,13 +122,13 @@ ENDIF()
 
 # usb client
 IF(USB_MODULE STREQUAL on)
-       ADD_SOURCE(src/usb USB_SRCS)
+       ADD_SOURCE(src/usb-gadget USB_SRCS)
        SET(SRCS ${SRCS} ${USB_SRCS})
 ENDIF()
 
 # usb host
 IF(USBHOST_MODULE STREQUAL on)
-       ADD_SOURCE(src/usbhost USBHOST_SRCS)
+       ADD_SOURCE(src/usb-host USBHOST_SRCS)
        SET(SRCS ${SRCS} ${USBHOST_SRCS})
 ENDIF()
 
diff --git a/src/usb-gadget/usb-dbus.c b/src/usb-gadget/usb-dbus.c
new file mode 100644 (file)
index 0000000..35eb16d
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <stdbool.h>
+
+#include <vconf.h>
+#include <libsyscommon/libgdbus.h>
+
+#include "core/log.h"
+
+#include "usb.h"
+#include "usb-gadget.h"
+#include "usb-debug.h"
+
+/* Legacy signals */
+#define SIGNAL_STATE_CHANGED  "StateChanged"
+#define SIGNAL_MODE_CHANGED   "ModeChanged"
+#define SIGNAL_CONFIG_ENABLED "ConfigEnabled"
+#define CHANGE_USB_MODE       "ChangeUsbMode"
+
+static int get_usb_state(void)
+{
+       int ret, val;
+       int result = 0;
+
+       ret = vconf_get_int(VCONFKEY_SYSMAN_USB_STATUS, &val);
+       if (ret != VCONF_OK) {
+               _E("Failed to get vconf value for USB status: %d", vconf_get_ext_errno());
+               return ret;
+       }
+
+       if (val == VCONFKEY_SYSMAN_USB_DISCONNECTED)
+               result = val;
+       else {
+               result = VCONFKEY_SYSMAN_USB_CONNECTED;
+               if (val == VCONFKEY_SYSMAN_USB_AVAILABLE)
+                       result |= VCONFKEY_SYSMAN_USB_AVAILABLE;
+       }
+
+       return result;
+}
+
+void broadcast_usb_state_changed(void)
+{
+       int ret;
+       unsigned int state;
+       static unsigned int prev_state = UINT_MAX;
+
+       state = get_usb_state();
+       if (state == prev_state)
+               return;
+       prev_state = state;
+
+       _I("USB state(%u) changed.", state);
+
+       ret = gdbus_signal_emit(NULL,
+                       DEVICED_PATH_USB,
+                       DEVICED_INTERFACE_USB,
+                       SIGNAL_STATE_CHANGED,
+                       g_variant_new("(u)", state));
+       if (ret < 0)
+               _E("Failed to send USB dbus signal.");
+}
+
+static void change_usb_client_mode(GDBusConnection  *conn,
+       const gchar      *sender,
+       const gchar      *path,
+       const gchar      *iface,
+       const gchar      *name,
+       GVariant         *param,
+       gpointer          data)
+
+{
+       int ret;
+       unsigned int mode;
+       int req_vconf = -1;
+
+       if (!g_variant_get_safe(param, "(i)", &req_vconf)) {
+               _E("failed to get params from gvariant. expected:%s, type:%s", "(i)", g_variant_get_type_string(param));
+               return;
+       }
+
+       if (req_vconf < 0) {
+               _E("Failed to get USB req_vconf.");
+               return;
+       }
+
+       _I("USB mode is changed by dbus signal to %d.", req_vconf);
+
+       mode = get_mode_bitmap_from_vconf(req_vconf);
+
+       if (mode == USB_FUNCTION_INVALID) {
+               _E("Failed to convert vconf to USB mode. There is no mode matches up with vconf %d.", req_vconf);
+               return;
+       }
+
+       /* Deviced must never run in USB_FUNCTION_NONE mode. */
+       if (mode == USB_FUNCTION_NONE) {
+               _E("Ignore this request. There is USB_FUNCTION_NONE mode matches up with vconf %d.", req_vconf);
+               return;
+       }
+
+       ret = usb_change_mode(mode, true);
+       if (ret < 0)
+               _E("Failed to change USB mode: %d", ret);
+}
+
+/* dbus methods */
+static GVariant *get_usb_client_state(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       unsigned int state;
+
+       state = get_usb_state();
+
+       return g_variant_new("(u)", state);
+}
+
+static GVariant *get_usb_client_mode(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       unsigned int mode;
+
+       mode = usb_state_get_current_mode();
+
+       return g_variant_new("(u)", mode);
+}
+
+static const dbus_method_s dbus_methods[] = {
+       { "GetState", NULL, "u", get_usb_client_state },  /* from Tizen 2.3 */
+       { "GetMode", NULL, "u", get_usb_client_mode  },   /* from Tizen 2.3 */
+       /* Add methods here */
+};
+
+static const dbus_interface_u dbus_interface = {
+       .oh = NULL,
+       .name = DEVICED_INTERFACE_USB,
+       .methods = dbus_methods,
+       .nr_methods = ARRAY_SIZE(dbus_methods),
+};
+
+
+int usb_dbus_init(void)
+{
+       int ret;
+
+       ret = gdbus_add_object(NULL, DEVICED_PATH_USB, &dbus_interface);
+       if (ret < 0)
+               _E("Failed to init dbus method for USB: %d", ret);
+
+       ret = gdbus_signal_subscribe(NULL, DEVICED_PATH_USB,
+               DEVICED_INTERFACE_USB, "ChangeUsbMode",
+               change_usb_client_mode, NULL, NULL);
+       if (ret <= 0) {
+               _E("Failed to subscribe dbus signal for USB: %d", ret);
+               return ret;
+       }
+
+       return 0;
+}
diff --git a/src/usb-gadget/usb-debug.c b/src/usb-gadget/usb-debug.c
new file mode 100644 (file)
index 0000000..22b5025
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include <vconf.h>
+
+#include "core/log.h"
+#include "shared/device-notifier.h"
+
+#include "usb.h"
+#include "usb-gadget.h"
+
+static bool debug_state;
+
+int get_usb_debug_state(void)
+{
+       int state;
+
+       /* Never use debug_state variable, anyone other than deviced can change this vconf. */
+
+       if (vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &state) != VCONF_OK) {
+               _E("Failed to get vconf value for USB debug mode: %d", vconf_get_ext_errno());
+               return -1;
+       }
+
+       return state;
+}
+
+void set_usb_debug_state(bool on)
+{
+       int state = on ? 1 : 0;
+
+       /*
+        * VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL can also be written outside of deviced.
+        * So you should always write regardless of the internal debug_state of deviced.
+        */
+       if (vconf_set_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, state) == VCONF_OK)
+               debug_state = on;
+       else
+               _E("Failed to set vconf value for USB debug mode: %d", vconf_get_ext_errno());
+}
+
+static void usb_debug_changed(keynode_t *key, void *data)
+{
+       int mode;
+
+       if (!key)
+               return;
+
+       mode = vconf_keynode_get_bool(key);
+
+       /* This also prevents vconf self-loop by set_usb_debug_state(). */
+       if (mode == debug_state) {
+               _I("USB debug mode is already %s.", mode ? "ON" : "OFF");
+               return;
+       }
+
+       debug_state = mode;
+
+       _I("USB debug mode is changed to %s.", mode ? "ON" : "OFF");
+
+       device_notify(DEVICE_NOTIFIER_USB_DEBUG_MODE, (void *)(intptr_t) mode);
+}
+
+static int usb_debug_mode_changed(void *on)
+{
+       int ret;
+       unsigned int new_mode;
+       bool rndis_is_enabled = false;
+       const unsigned int curr_mode = usb_state_get_selected_mode();
+
+       if (curr_mode & USB_FUNCTION_RNDIS)
+               rndis_is_enabled = true;
+
+       /*
+        * debug  on + rndis  on : USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS
+        * debug  on + rndis off : USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB
+        * debug off + rndis  on : USB_FUNCTION_RNDIS
+        * debug off + rndis off : USB_FUNCTION_MTP | USB_FUNCTION_ACM
+        */
+
+       if ((int)(intptr_t) on) {
+               if (rndis_is_enabled)
+                       new_mode = USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS;
+               else
+                       new_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB;
+       } else {
+               if (rndis_is_enabled)
+                       new_mode = USB_FUNCTION_RNDIS;
+               else
+                       new_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM;
+       }
+
+       ret = usb_change_mode(new_mode, false);
+       if (ret < 0)
+               _E("Failed to change USB mode to (%d).", new_mode);
+
+       return ret;
+}
+
+void add_usb_debug_handler(void)
+{
+       int state = 0;
+
+       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL,
+                               usb_debug_changed, NULL) != VCONF_OK)
+               _E("Failed to add USB debug handler.");
+
+       register_notifier(DEVICE_NOTIFIER_USB_DEBUG_MODE, usb_debug_mode_changed);
+
+       if (vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &state) == VCONF_OK)
+               debug_state = (state == 0 ? false : true);
+       else
+               _E("Failed to get vconf value for USB debug mode: %d", vconf_get_ext_errno());
+}
+
+void remove_usb_debug_handler(void)
+{
+       vconf_ignore_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, usb_debug_changed);
+       unregister_notifier(DEVICE_NOTIFIER_USB_DEBUG_MODE, usb_debug_mode_changed);
+}
diff --git a/src/usb-gadget/usb-debug.h b/src/usb-gadget/usb-debug.h
new file mode 100644 (file)
index 0000000..bab0392
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __USB_DEBUG_H__
+#define __USB_DEBUG_H__
+
+#include <stdbool.h>
+
+int get_usb_debug_state(void);
+void set_usb_debug_state(bool on);
+void add_usb_debug_handler(void);
+void remove_usb_debug_handler(void);
+
+#endif /* __USB_DEBUG_H__ */
diff --git a/src/usb-gadget/usb-gadget-cfs-gadget.c b/src/usb-gadget/usb-gadget-cfs-gadget.c
new file mode 100644 (file)
index 0000000..61583e0
--- /dev/null
@@ -0,0 +1,645 @@
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <linux/limits.h>
+
+#include <usbg/usbg.h>
+#include <usbg/function/net.h>
+
+#include <libsyscommon/libsystemd.h>
+
+#include <shared/log.h>
+#include "usb-gadget.h"
+
+#define CONFIGFS_PATH "/sys/kernel/config"
+
+#define CONFIGFS_GADGET_NAME "hal-gadget"
+#define CONFIGFS_CONFIG_LABEL "hal-config"
+
+#define NAME_INSTANCE_SEP '.'
+#define MAX_INSTANCE_LEN 512
+
+#define USB_FUNCS_PATH "/dev/usb-funcs"
+
+enum cfs_function_service_operation {
+       CFS_FUNCTION_SERVICE_START,
+       CFS_FUNCTION_SERVICE_STOP,
+       CFS_FUNCTION_SERVICE_POST_STOP,
+};
+
+struct cfs_client {
+       usbg_state *ctx;
+       usbg_gadget *gadget;
+       usbg_udc *udc;
+};
+
+/* Based on values in slp-gadget kernel module */
+struct usbg_gadget_attrs default_g_attrs = {
+       .idVendor = DEFAULT_VID,
+       .idProduct = DEFAULT_PID,
+       .bcdDevice = DEFAULT_BCD_DEVICE,
+};
+
+struct usbg_gadget_strs default_g_strs = {
+       .manufacturer = DEFAULT_MANUFACTURER,
+       .product = DEFAULT_PRODUCT,
+       .serial = DEFAULT_SERIAL,
+};
+
+struct cfs_client *g_cfs_client;
+
+static struct usb_function *cfs_find_usb_function(usbg_function *function)
+{
+       char *sep;
+       char buf[MAX_INSTANCE_LEN];
+       const char *instance = usbg_get_function_instance(function);
+       const char *name = usbg_get_function_type_str(usbg_get_function_type(function));
+
+       /* Ex. name:"ffs",  instance: "sdb.default" */
+       if (strcmp(name, usbg_get_function_type_str(USBG_F_FFS)) == 0) {
+               strncpy(buf, instance, sizeof(buf) - 1);
+               buf[sizeof(buf) - 1] = '\0';
+
+               /* Ex. "sdb.default" ==> "sdb" + "default" */
+               sep = strchr(buf, NAME_INSTANCE_SEP);
+               if (!sep || !sep[1])
+                       return NULL;
+               *sep = '\0';
+
+               name = buf;
+               instance = sep + 1;
+       }
+
+       return find_usb_function_by_name_instance(name, instance);
+}
+
+static bool cfs_is_function_supported(struct usb_function *func)
+{
+       char buf[PATH_MAX];
+
+       if (func->is_functionfs) {
+               /* functionfs must have a service */
+               if (!func->service)
+                       return false;
+
+               snprintf(buf, sizeof(buf), "/usr/lib/systemd/system/%s.socket", func->service);
+               if (access(buf, F_OK))
+                       return false;
+       } else {
+               if (usbg_lookup_function_type(func->name) < 0)
+                       return false;
+       }
+
+       return true;
+}
+
+static bool cfs_is_gadget_supported(struct usb_gadget *gadget)
+{
+       int i, j;
+       struct usb_configuration *config;
+
+       if (!gadget || !gadget->configs || !gadget->configs[0] || !gadget->configs[0]->funcs[0])
+               return false;
+
+       if (!gadget->attrs.idVendor || !gadget->attrs.idProduct || !gadget->attrs.bcdDevice)
+               return false;
+
+       /* only strings in US_en are allowed */
+       if (gadget->strs.lang_code != DEFAULT_LANG)
+               return false;
+
+       if (!gadget->strs.manufacturer || !gadget->strs.product || !gadget->strs.serial)
+               return false;
+
+       for (j = 0; gadget->configs[j]; ++j) {
+               config = gadget->configs[j];
+
+               if (!config->funcs)
+                       return false;
+
+               for (i = 0; config->funcs[i]; ++i)
+                       if (!cfs_is_function_supported(config->funcs[i]))
+                               return false;
+       }
+
+       return true;
+}
+
+static int cfs_set_gadget_attrs(struct cfs_client *cfs_client,
+                               struct usb_gadget_attrs *attrs)
+{
+       int ret;
+       struct usbg_gadget_attrs gadget_attrs;
+
+       ret = usbg_get_gadget_attrs(cfs_client->gadget, &gadget_attrs);
+       if (ret)
+               return ret;
+
+       gadget_attrs.bDeviceClass = attrs->bDeviceClass;
+       gadget_attrs.bDeviceSubClass = attrs->bDeviceSubClass;
+       gadget_attrs.bDeviceProtocol = attrs->bDeviceProtocol;
+       gadget_attrs.idVendor = attrs->idVendor;
+       gadget_attrs.idProduct = attrs->idProduct;
+       gadget_attrs.bcdDevice = attrs->bcdDevice;
+
+       ret = usbg_set_gadget_attrs(cfs_client->gadget, &gadget_attrs);
+
+       return ret;
+}
+
+static int cfs_set_gadget_strs(struct cfs_client *cfs_client, struct usb_gadget_strings *strs)
+{
+       int ret;
+
+       if (!strs->manufacturer || !strs->product || !strs->serial)
+               return -EINVAL;
+
+       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_MANUFACTURER, strs->lang_code, strs->manufacturer);
+       if (ret)
+               return ret;
+
+       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_PRODUCT, strs->lang_code, strs->product);
+       if (ret)
+               return ret;
+
+       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_SERIAL_NUMBER, strs->lang_code, strs->serial);
+       if (ret)
+               return ret;
+
+       return 0;
+}
+
+static int cfs_ensure_dir(char *path)
+{
+       if (mkdir(path, 0770) < 0)
+               return (errno == EEXIST) ? 0 : -errno;
+
+       return 0;
+}
+
+
+static int cfs_prep_ffs_service(struct usb_function *usb_func, usbg_function *function)
+{
+       int ret;
+       const char *name;
+       const char *service;
+       const char *instance;
+       const char *dev_name;
+       char buf[MAX_INSTANCE_LEN];
+
+       if (!usb_func || !function)
+               return -EINVAL;
+
+       if (usbg_get_function_type(function) != USBG_F_FFS)
+               return -EINVAL;
+
+       name = usb_func->name;
+       service = usb_func->service;
+       instance = usb_func->instance;
+       dev_name = usbg_get_function_instance(function);
+
+       /* "/dev/usb-funcs" + "/" + "sdb" + "/" + "default"  + '0' */
+       if (strlen(USB_FUNCS_PATH) + strlen(name) + strlen(instance) + 3  > sizeof(buf))
+               return -ENAMETOOLONG;
+
+       /* mkdir /dev/usb-funcs */
+       ret = cfs_ensure_dir(USB_FUNCS_PATH);
+       if (ret < 0)
+               return ret;
+
+       /* mkdir /dev/usb-funcs/sdb */
+       snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
+       ret = cfs_ensure_dir(buf);
+       if (ret < 0)
+               goto out_rmdir;
+
+       /* mkdir /dev/usb-funcs/sdb/default */
+       snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
+       ret = cfs_ensure_dir(buf);
+       if (ret < 0)
+               goto out_rmdir;
+
+       /* mount -t functionfs sdb.default /dev/usb-funcs/sdb/default */
+       ret = mount(dev_name, buf, "functionfs", 0, NULL);
+       if (ret < 0)
+               goto out_rmdir;
+
+       /* start sdbd.socket */
+       ret = systemd_start_unit_wait_started(service, ".socket", -1);
+       if (ret < 0)
+               goto out_unmount;
+
+       return 0;
+
+out_unmount:
+       umount(buf);
+
+out_rmdir:
+       snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
+       rmdir(buf);
+
+       snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
+       rmdir(buf);
+
+       rmdir(USB_FUNCS_PATH);
+
+       return ret;
+}
+
+static int cfs_cleanup_ffs_service(usbg_function *function)
+{
+       int ret;
+       char buf[MAX_INSTANCE_LEN];
+       struct usb_function *usb_function;
+
+       if (!function)
+               return -EINVAL;
+
+       usb_function = cfs_find_usb_function(function);
+       if (!usb_function)
+               return -ENOENT;
+
+       /* stop .socket first and stop .service later becuase of socket activation */
+       if (usb_function->service) {
+               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".socket", -1);
+               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
+       }
+
+       /* umount /dev/usb-funcs/[sdb|mtp]/default and remove it's directory */
+       ret = snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, usb_function->name, usb_function->instance);
+       if (ret < 0)
+               return ret;
+
+       ret = umount(buf);
+       if (ret < 0)
+               return ret;
+
+       ret = rmdir(buf);
+       if (ret < 0)
+               return ret;
+
+       /* remove /dev/usb-funcs/[sdb|mtp] directory */
+       ret = snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, usb_function->name);
+       if (ret < 0)
+               return ret;
+
+       ret = rmdir(buf);
+       if (ret < 0 && errno != ENOTEMPTY)
+               return ret;
+
+       /* remove /dev/usb-funcs/ directory */
+       ret = rmdir(USB_FUNCS_PATH);
+       if (ret < 0 && errno != ENOTEMPTY)
+               return ret;
+
+       return 0;
+}
+
+
+static int cfs_set_rndis_mac_addr(usbg_gadget *gadget, usbg_function *func)
+{
+       int i, ret;
+       struct ether_addr ethaddr;
+       struct usbg_gadget_strs strs;
+       struct usbg_f_net *nf = usbg_to_net_function(func);
+
+       if (!nf)
+               return -EINVAL;
+
+       ret = usbg_get_gadget_strs(gadget, LANG_US_ENG, &strs);
+       if (ret != USBG_SUCCESS)
+               return ret;
+
+       for (i = 0; i < ETHER_ADDR_LEN; i++)
+               ethaddr.ether_addr_octet[i] = 0;
+
+       for (i = 0; (i < 256) && strs.serial[i]; i++) {
+               ethaddr.ether_addr_octet[i % (ETHER_ADDR_LEN - 1) + 1] ^= strs.serial[i];
+       }
+       ethaddr.ether_addr_octet[0] &= 0xfe;     /* clear multicast bit */
+       ethaddr.ether_addr_octet[0] |= 0x02;     /* set local assignment bit (IEEE802) */
+
+       usbg_free_gadget_strs(&strs);
+
+       /* host_addr changes mac address */
+       ret = usbg_f_net_set_host_addr(nf, &ethaddr);
+
+       return ret;
+}
+
+static int cfs_cleanup_all_config_and_function(struct cfs_client *cfs_client)
+{
+       int ret;
+       usbg_config *config;
+       usbg_function *function;
+
+       /* delete all configs */
+restart_rm_config:
+       usbg_for_each_config(config, cfs_client->gadget) {
+               ret = usbg_rm_config(config, USBG_RM_RECURSE);
+               if (ret)
+                       return ret;
+
+               goto restart_rm_config; /* You cannot delete a config directly in an iterator. */
+       }
+
+       /* delete all functions */
+restart_rm_function:
+       usbg_for_each_function(function, cfs_client->gadget) {
+               if (usbg_get_function_type(function) == USBG_F_FFS) {
+                       ret = cfs_cleanup_ffs_service(function);
+                       if (ret)
+                               return ret;
+               }
+
+               ret = usbg_rm_function(function, USBG_RM_RECURSE);
+               if (ret)
+                       return ret;
+
+               goto restart_rm_function; /* You cannot delete a function directly in an iterator. */
+       }
+
+       return 0;
+}
+
+static int cfs_set_gadget_config(struct cfs_client *cfs_client, int config_id, struct usb_configuration *usb_config)
+{
+       int i;
+       int ret;
+       int function_type;
+       usbg_config *config;
+       usbg_function *function;
+       struct usb_function *usb_func;
+       char instance[MAX_INSTANCE_LEN];
+       struct usbg_config_attrs cattrs = {
+               .bmAttributes = usb_config->attrs.bmAttributs,
+               .bMaxPower = usb_config->attrs.MaxPower/2,
+       };
+
+       if (!usb_config->funcs || !usb_config->funcs[0])
+               return -EINVAL;
+
+       ret = usbg_create_config(cfs_client->gadget, config_id, CONFIGFS_CONFIG_LABEL, &cattrs, NULL, &config);
+       if (ret)
+               return ret;
+
+       if (usb_config->strs.config_str) {
+               ret = usbg_set_config_string(config, usb_config->strs.lang_code, usb_config->strs.config_str);
+               if (ret)
+                       return ret;
+       }
+
+       for (i = 0; usb_config->funcs[i]; ++i) {
+               usb_func = usb_config->funcs[i];
+
+               /* name("sdb") + NAME_INSTANCE_SEP(".") + instance("default") + '\0' */
+               if (strlen(usb_func->name) + strlen(usb_func->instance) + 2 > sizeof(instance))
+                       return -ENAMETOOLONG;
+
+               /* In functionfs, the instance is used in the format "[sdb|mtp].default" instead of "default" */
+               if (usb_func->is_functionfs) {
+                       function_type = USBG_F_FFS;
+                       snprintf(instance, sizeof(instance), "%s%c%s", usb_func->name, NAME_INSTANCE_SEP, usb_func->instance);
+               } else {
+                       function_type = usbg_lookup_function_type(usb_func->name);
+                       strncpy(instance, usb_func->instance, sizeof(instance) - 1);
+                       instance[sizeof(instance) - 1] = '\0';
+               }
+
+               function = usbg_get_function(cfs_client->gadget, function_type, instance);
+               if (!function) {
+                       ret = usbg_create_function(cfs_client->gadget, function_type, instance, NULL, &function);
+                       if (ret)
+                               return ret;
+
+                       /* Setting rndis mac address. This should be done at this point,
+                        * since the node host_addr changes to read only after the function
+                        * is added to config. */
+                       if (usbg_get_function_type(function) == USBG_F_RNDIS)
+                               (void)cfs_set_rndis_mac_addr(cfs_client->gadget, function); /* A random value is used if fails */
+
+                       if (usbg_get_function_type(function) == USBG_F_FFS) {
+                               ret = cfs_prep_ffs_service(usb_func, function);
+                               if (ret)
+                                       return ret;
+                       }
+               }
+
+               ret = usbg_add_config_function(config, NULL, function);
+               if (ret)
+                       return ret;
+       }
+
+       return 0;
+}
+
+static void cfs_start_stop_service_and_handler(usbg_gadget *gadget, enum cfs_function_service_operation operation)
+{
+       usbg_function *function;
+       struct usb_function *usb_function;
+
+       usbg_for_each_function(function, gadget) {
+               usb_function = cfs_find_usb_function(function);
+               if (!usb_function)
+                       continue;
+
+               switch(operation) {
+               case CFS_FUNCTION_SERVICE_START:
+                       if (usb_function->handler)
+                               usb_function->handler(1);
+
+                       /* functionfs service is automatically started by socket activation */
+                       if (!usb_function->is_functionfs && usb_function->service)
+                               (void)systemd_start_unit_wait_started(usb_function->service, ".service", -1);
+                       break;
+
+               case CFS_FUNCTION_SERVICE_STOP:
+                       if (!usb_function->is_functionfs && usb_function->service && !usb_function->remain_after_disable)
+                               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
+
+                       if (usb_function->handler)
+                               usb_function->handler(0);
+                       break;
+
+               case CFS_FUNCTION_SERVICE_POST_STOP:
+                       if (usb_function->is_functionfs && usb_function->service && !usb_function->remain_after_disable)
+                               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
+                       break;
+
+               default:
+                       break;
+               }
+       }
+}
+
+static int usb_gadget_cfs_enable(void)
+{
+       int ret;
+
+       if (!g_cfs_client)
+               return -EINVAL;
+
+       ret = usbg_enable_gadget(g_cfs_client->gadget, g_cfs_client->udc);
+       if (ret)
+               return ret;
+
+       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_START);
+
+       return 0;
+}
+
+static int usb_gadget_cfs_disable(void)
+{
+       int ret;
+
+       if (!g_cfs_client)
+               return -EINVAL;
+
+       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_STOP);
+
+       ret = usbg_disable_gadget(g_cfs_client->gadget); /* ignore error checking */
+
+       /*
+        * Since functionfs service works with socket activation, you must stop it after disabling gadget.
+        * If usb data may come in after stopping functionfs service and before disabling gadget,
+        * functionfs service wakes up again by socket activation.
+        */
+       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_POST_STOP);
+
+       return ret;
+}
+
+static int usb_gadget_cfs_reconfigure_gadget(struct usb_gadget *gadget)
+{
+       int i;
+       int ret;
+
+       if (!g_cfs_client || !gadget)
+               return -EINVAL;
+
+       /* Verify the gadget and check if function is supported */
+       if (!cfs_is_gadget_supported(gadget))
+               return -ENOTSUP;
+
+       ret = cfs_set_gadget_attrs(g_cfs_client, &gadget->attrs);
+       if (ret)
+               return ret;
+
+       ret = cfs_set_gadget_strs(g_cfs_client, &gadget->strs);
+       if (ret)
+               return ret;
+
+       ret = cfs_cleanup_all_config_and_function(g_cfs_client);
+       if (ret)
+               return ret;
+
+       for (i = 0; gadget->configs[i]; ++i) {
+               ret = cfs_set_gadget_config(g_cfs_client, i + 1, gadget->configs[i]);
+               if (ret)
+                       return ret;
+       }
+
+       return 0;
+}
+
+static int usb_gadget_cfs_open(void)
+{
+       int ret;
+
+       g_cfs_client = calloc(1, sizeof(*g_cfs_client));
+       if (!g_cfs_client)
+               return -ENOMEM;
+
+       ret = usbg_init(CONFIGFS_PATH, &g_cfs_client->ctx);
+       if (ret)
+               goto err_usbg_init;
+
+       g_cfs_client->udc = usbg_get_first_udc(g_cfs_client->ctx);
+       if (!g_cfs_client->udc) {
+               ret = -ENODEV;
+               goto err_no_udc;
+       }
+
+       ret = usbg_create_gadget(g_cfs_client->ctx, CONFIGFS_GADGET_NAME,
+                                &default_g_attrs, &default_g_strs, &g_cfs_client->gadget);
+       if (ret)
+               goto err_create_gadget;
+
+       return 0;
+
+err_create_gadget:
+err_no_udc:
+       usbg_cleanup(g_cfs_client->ctx);
+err_usbg_init:
+       free(g_cfs_client);
+
+       return ret;
+}
+
+static int usb_gadget_cfs_close(void)
+{
+       usbg_function *function;
+       struct usb_function *usb_func;
+
+       if (!g_cfs_client)
+               return -EINVAL;
+
+       usbg_for_each_function(function, g_cfs_client->gadget) {
+               usb_func = cfs_find_usb_function(function);
+               if (!usb_func)
+                       continue;
+
+               if (usb_func->is_functionfs && usb_func->service) {
+                       (void)systemd_stop_unit_wait_stopped(usb_func->service, ".socket", -1);
+                       (void)systemd_stop_unit_wait_stopped(usb_func->service, ".service", -1);
+               }
+       }
+
+       /*
+        * For now we don't check for errors
+        * but we should somehow handle them
+        */
+       usbg_rm_gadget(g_cfs_client->gadget, USBG_RM_RECURSE);
+       usbg_cleanup(g_cfs_client->ctx);
+       free(g_cfs_client);
+
+       return 0;
+}
+
+int usb_gadget_cfs_supported(void)
+{
+       FILE *fp;
+       char *line = NULL;
+       size_t len = 0;
+       int configfs = 0;
+
+       fp = fopen("/proc/filesystems", "r");
+       if (!fp)
+               return 0;
+
+       while (getline(&line, &len, fp) != -1) {
+               if (strstr(line, "configfs"))
+                       configfs = 1;
+       }
+
+       fclose(fp);
+       free(line);
+
+       if (configfs)
+               CRITICAL_LOG("Usb-gadget is supported via configfs.");
+
+       return configfs;
+}
+
+void usb_gadget_bind_cfs_gadget(int (**open) (void), int (**close) (void), int (**enable) (void),
+       int (**disable) (void), int (**reconfigure) (struct usb_gadget *))
+{
+       *open = usb_gadget_cfs_open;
+       *close = usb_gadget_cfs_close;
+       *enable = usb_gadget_cfs_enable;
+       *disable = usb_gadget_cfs_disable;
+       *reconfigure = usb_gadget_cfs_reconfigure_gadget;
+}
diff --git a/src/usb-gadget/usb-gadget-legacy-gadget.c b/src/usb-gadget/usb-gadget-legacy-gadget.c
new file mode 100644 (file)
index 0000000..aa1f6b1
--- /dev/null
@@ -0,0 +1,358 @@
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdbool.h>
+#include <linux/limits.h>
+
+#include <libsyscommon/file.h>
+#include <libsyscommon/libsystemd.h>
+
+#include <shared/log.h>
+#include "usb-gadget.h"
+
+#define MAX_GADGET_STR_LEN 256
+
+#define LEGACY_ROOTPATH        "/sys/class/usb_mode/usb0"
+
+/* Device descriptor values */
+#define LEGACY_ID_VENDOR_PATH       LEGACY_ROOTPATH"/idVendor"
+#define LEGACY_ID_PRODUCT_PATH      LEGACY_ROOTPATH"/idProduct"
+#define LEGACY_BCD_DEVICE_PATH      LEGACY_ROOTPATH"/bcdDevice"
+#define LEGACY_CLASS_PATH           LEGACY_ROOTPATH"/bDeviceClass"
+#define LEGACY_SUBCLASS_PATH        LEGACY_ROOTPATH"/bDeviceSubClass"
+#define LEGACY_PROTOCOL_PATH        LEGACY_ROOTPATH"/bDeviceProtocol"
+
+/* Strings */
+#define LEGACY_IMANUFACTURER_PATH   LEGACY_ROOTPATH"/iManufacturer"
+#define LEGACY_IPRODUCT_PATH        LEGACY_ROOTPATH"/iProduct"
+
+/* Functions in each config */
+#define LEGACY_CONFIG_1_PATH        LEGACY_ROOTPATH"/funcs_fconf"
+#define LEGACY_CONFIG_2_PATH        LEGACY_ROOTPATH"/funcs_sconf"
+
+/* should be single char */
+#define LEGACY_FUNC_SEP             ","
+
+/* ON/OFF switch */
+#define LEGACY_ENABLE_PATH          LEGACY_ROOTPATH"/enable"
+#define LEGACY_ENABLE               "1"
+#define LEGACY_DISABLE              "0"
+
+static bool legacy_is_function_supported(struct usb_function *func)
+{
+       char buf[PATH_MAX];
+
+       snprintf (buf, sizeof(buf), "%s/f_%s", LEGACY_ROOTPATH, func->name);
+       if (access(buf, F_OK))
+               return false;
+
+       return true;
+}
+
+static bool legacy_is_gadget_supported(struct usb_gadget *gadget)
+{
+       int i, j;
+       struct usb_configuration *config;
+
+       if (!gadget || !gadget->configs || !gadget->configs[0] || !gadget->configs[0]->funcs[0])
+               return false;
+
+       if (!gadget->attrs.idVendor || !gadget->attrs.idProduct || !gadget->attrs.bcdDevice)
+                       return false;
+
+       /* only strings in US_en are allowed */
+       if (gadget->strs.lang_code != DEFAULT_LANG)
+                       return false;
+
+       if (!gadget->strs.manufacturer || !gadget->strs.product)
+               return false;
+
+       for (j = 0; gadget->configs[j]; ++j) {
+               config = gadget->configs[j];
+
+               if (!config->funcs)
+                       return false;
+
+               for (i = 0; config->funcs[i]; ++i)
+                       if (!legacy_is_function_supported(config->funcs[i]))
+                               return false;
+       }
+
+       return true;
+}
+
+/* TODO. Maybe move this to sys ? */
+static int legacy_set_int_hex(char *path, int val)
+{
+       int r;
+       char buf[MAX_GADGET_STR_LEN];
+
+       if (!path)
+               return -EINVAL;
+
+       snprintf(buf, sizeof(buf), "%x", val);
+       r = sys_set_str(path, buf);
+       if (r < 0)
+               return r;
+
+       return 0;
+}
+
+static int legacy_set_gadget_attrs(struct usb_gadget_attrs *attrs)
+{
+       int ret;
+
+       ret = sys_set_int(LEGACY_CLASS_PATH, attrs->bDeviceClass);
+       if (ret)
+               return ret;
+
+       ret = sys_set_int(LEGACY_SUBCLASS_PATH, attrs->bDeviceSubClass);
+       if (ret)
+               return ret;
+
+       ret = sys_set_int(LEGACY_PROTOCOL_PATH, attrs->bDeviceProtocol);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_int_hex(LEGACY_ID_VENDOR_PATH, attrs->idVendor);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_int_hex(LEGACY_ID_PRODUCT_PATH, attrs->idProduct);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_int_hex(LEGACY_BCD_DEVICE_PATH, attrs->bcdDevice);
+       if (ret)
+               return ret;
+
+       return 0;
+}
+
+static int legacy_set_gadget_strs(struct usb_gadget_strings *strs)
+{
+       int ret;
+
+       if (!strs->manufacturer || !strs->product)
+               return -EINVAL;
+
+       ret = sys_set_str(LEGACY_IMANUFACTURER_PATH, strs->manufacturer);
+       if (ret)
+               return ret;
+
+       ret = sys_set_str(LEGACY_IPRODUCT_PATH, strs->product);
+       if (ret)
+               return ret;
+
+       /* The serial is written by the slp gadget kernel driver */
+
+       return 0;
+}
+
+static int legacy_set_gadget_config(char *cpath,
+                                   struct usb_configuration *config)
+{
+       char buf[MAX_GADGET_STR_LEN];
+       int left = sizeof(buf);
+       char *pos = buf;
+       int ret;
+       int i;
+
+       if (!config) {
+               buf[0] = '\n';
+               buf[1] = '\0';
+               goto empty_config;
+       }
+
+       for (i = 0; config->funcs[i]; ++i) {
+               ret = snprintf(pos, left, "%s" LEGACY_FUNC_SEP,
+                              config->funcs[i]->name);
+               if (ret >= left)
+                       return -EOVERFLOW;
+
+               pos += ret;
+               left -= ret;
+       }
+
+       /* eliminate last separator */
+       *(pos - 1) = '\0';
+
+empty_config:
+       return sys_set_str(cpath, buf);
+}
+
+static void legacy_start_stop_service_and_handler(bool start)
+{
+       int i;
+       int ret;
+       int n_func = 0;
+       char *ptr;
+       char *begin;
+       char *fname;
+       char *sep = LEGACY_FUNC_SEP;
+       char buf[MAX_GADGET_STR_LEN];
+       struct usb_function *func;
+       struct usb_function *funcs[USB_FUNCTION_IDX_MAX];
+
+       /* SLP gadget uses two USB configuration.
+        * (/sys/class/usb_mode/usb0/funcs_fconf and /sys/class/usb_mode/usb0/funcs_sconf)
+        *
+        * One usb function can be included in two configurations simultaneously.
+        * In this situation, a handler associated with function can be called twice for a usb function.
+        * To prevent duplicate calls,
+        * Collect all functions and remove duplicates and process them.
+        */
+
+       /* First configuration */
+       ret = sys_get_str(LEGACY_CONFIG_1_PATH, buf, sizeof(buf));
+       if (ret)
+               goto second_configuration;
+
+       /* Caution: buf ends with '\n' */
+       ptr = strchr(buf, '\n');
+       if (ptr)
+               *ptr = 0;
+
+       begin = buf;
+       for (fname = strsep(&begin, sep); fname; fname = strsep(&begin, sep)) {
+               func = find_usb_function_by_name(fname);
+               if (!func)
+                       continue;
+
+               for (i = 0; i < n_func; i++)
+                       if (funcs[i] == func)
+                               continue;
+
+               if(n_func >= USB_FUNCTION_IDX_MAX) /* What happen */
+                       break;
+
+               funcs[n_func] = func;
+               n_func++;
+       }
+
+       /* Second configuration */
+second_configuration:
+       ret = sys_get_str(LEGACY_CONFIG_2_PATH, buf, sizeof(buf));
+       if (ret)
+               return;
+
+       /* Caution: buf ends with '\n' */
+       ptr = strchr(buf, '\n');
+       if (ptr)
+               *ptr = 0;
+
+       begin = buf;
+       for (fname = strsep(&begin, sep); fname; fname = strsep(&begin, sep)) {
+               func = find_usb_function_by_name(fname);
+               if (!func)
+                       continue;
+
+               for (i = 0; i < n_func; i++)
+                       if (funcs[i] == func)
+                               continue;
+
+               if(n_func >= USB_FUNCTION_IDX_MAX) /* What happen */
+                       break;
+
+               funcs[n_func] = func;
+               n_func++;
+       }
+
+       for (i = 0; i < n_func; i++) {
+               if (start) {
+                       if (funcs[i]->handler)
+                               funcs[i]->handler(1);
+
+                       if (funcs[i]->service)
+                               (void)systemd_start_unit_wait_started(funcs[i]->service, ".service", -1);
+               } else {
+                       if (funcs[i]->service && !funcs[i]->remain_after_disable)
+                               (void)systemd_stop_unit_wait_stopped(funcs[i]->service, ".service", -1);
+
+                       if (funcs[i]->handler)
+                               funcs[i]->handler(0);
+               }
+       }
+}
+
+static int usb_gadget_legacy_enable(void)
+{
+       int ret;
+
+       ret = sys_set_str(LEGACY_ENABLE_PATH, LEGACY_ENABLE);
+       if (ret < 0)
+               return ret;
+
+       legacy_start_stop_service_and_handler(true);
+
+       return 0;
+}
+
+static int usb_gadget_legacy_disable(void)
+{
+       legacy_start_stop_service_and_handler(false);
+
+       return sys_set_str(LEGACY_ENABLE_PATH, LEGACY_DISABLE);
+}
+
+static int usb_gadget_legacy_reconfigure_gadget(struct usb_gadget *gadget)
+{
+       int ret;
+
+       if (!gadget)
+               return -EINVAL;
+
+       /* Verify the gadget and check if function is supported */
+       if (!legacy_is_gadget_supported(gadget))
+               return -ENOTSUP;
+
+       ret = legacy_set_gadget_attrs(&gadget->attrs);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_gadget_strs(&gadget->strs);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_gadget_config(LEGACY_CONFIG_1_PATH, gadget->configs[0]);
+       if (ret)
+               return ret;
+
+       ret = legacy_set_gadget_config(LEGACY_CONFIG_2_PATH, gadget->configs[1]);
+       if (ret)
+               return ret;
+
+       return 0;
+}
+
+static int usb_gadget_legacy_open(void)
+{
+       return 0;
+}
+
+static int usb_gadget_legacy_close(void)
+{
+       return 0;
+}
+
+int usb_gadget_legacy_supported(void)
+{
+       int ret;
+
+       ret = (access("/sys/class/usb_mode/usb0/enable", F_OK) == 0);
+       if (ret)
+               CRITICAL_LOG("Usb-gadget is supported via legacy samsung gadget.");
+
+       return ret;
+}
+
+void usb_gadget_bind_legacy_gadget(int (**open) (void), int (**close) (void), int (**enable) (void),
+       int (**disable) (void), int (**reconfigure) (struct usb_gadget *))
+{
+       *open = usb_gadget_legacy_open;
+       *close = usb_gadget_legacy_close;
+       *enable = usb_gadget_legacy_enable;
+       *disable = usb_gadget_legacy_disable;
+       *reconfigure = usb_gadget_legacy_reconfigure_gadget;
+}
diff --git a/src/usb-gadget/usb-gadget.c b/src/usb-gadget/usb-gadget.c
new file mode 100644 (file)
index 0000000..efa1da8
--- /dev/null
@@ -0,0 +1,465 @@
+#include <stdlib.h>
+#include <string.h>
+
+#include <libsyscommon/libsystemd.h>
+#include <libsyscommon/list.h>
+#include <vconf-internal-usb-keys.h>
+
+#include <shared/log.h>
+
+#include "usb-gadget.h"
+
+static int (*__usb_gadget_open) (void);
+static int (*__usb_gadget_close) (void);
+static int (*__usb_gadget_enable) (void);
+static int (*__usb_gadget_disable) (void);
+static int (*__usb_gadget_reconfigure) (struct usb_gadget *gadget);
+
+/* temporary extern access */
+struct _usb_mode_mapping_table {
+       int          mode_v; /* Integer defined by vconf */
+       unsigned int mode;   /* Bitmap of usb function combination */
+       struct usb_gadget_attrs attrs;
+};
+extern GList *usb_mode_mapping_table_custom;
+
+static void rndis_handler(int enable)
+{
+       if (enable)
+               (void)systemd_start_unit_wait_started("rndis.service", NULL, -1);
+       else
+               (void)systemd_stop_unit_wait_stopped("rndis.service", NULL, -1);
+}
+
+#define DEFINE_USB_FUNCTION(_id, _name, _is_functionfs, _service, _handler)  \
+       static struct usb_function _##_name##_function = {                   \
+               .id = _id,                                                   \
+               .name = #_name,                                              \
+               .instance = "default",                                       \
+               .is_functionfs = _is_functionfs,                             \
+               .service = _service,                                         \
+               .remain_after_disable = 0,                                   \
+               .handler = _handler,                                         \
+       }
+
+DEFINE_USB_FUNCTION(USB_FUNCTION_MTP,         mtp,         1, "mtp-responder", NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_ACM,         acm,         0, "data-router",   NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_SDB,         sdb,         1, "sdbd",          NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_RNDIS,       rndis,       0, "sshd",          rndis_handler);
+DEFINE_USB_FUNCTION(USB_FUNCTION_DIAG,        diag,        1, "diag",          NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_CONN_GADGET, conn_gadget, 0, NULL,            NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_DM,          dm,          0, NULL,            NULL);
+DEFINE_USB_FUNCTION(USB_FUNCTION_RMNET,       rmnet,       0, NULL,            NULL);
+
+#undef DEFINE_USB_FUNCTION
+
+/* Caution: index order of arrary is important, because simple_translator_open() uses it. */
+static struct usb_function *_available_funcs[] = {
+       [USB_FUNCTION_IDX_MTP]         = &_mtp_function,
+       [USB_FUNCTION_IDX_ACM]         = &_acm_function,
+       [USB_FUNCTION_IDX_SDB]         = &_sdb_function,
+       [USB_FUNCTION_IDX_RNDIS]       = &_rndis_function,
+       [USB_FUNCTION_IDX_DIAG]        = &_diag_function,
+       [USB_FUNCTION_IDX_CONN_GADGET] = &_conn_gadget_function,
+       [USB_FUNCTION_IDX_DM]          = &_dm_function,
+       [USB_FUNCTION_IDX_RMNET]       = &_rmnet_function,
+       [USB_FUNCTION_IDX_MAX]         = NULL /* An indicator to end the array */
+};
+static struct usb_function *find_usb_function_by_id(int id);
+
+struct usb_function *find_usb_function_by_name(const char *name)
+{
+       int i;
+
+       if(!name || !name[0])
+               return NULL;
+
+       for (i = 0; _available_funcs[i]; i++)
+               if (!strcmp(name, _available_funcs[i]->name))
+                       return _available_funcs[i];
+
+       return NULL;
+}
+
+struct usb_function *find_usb_function_by_name_instance(const char *name, const char *instance)
+{
+       int i;
+
+       if(!name || !name[0] || !instance || !instance[0])
+               return NULL;
+
+       for (i = 0; _available_funcs[i]; ++i)
+               if (!strcmp(name, _available_funcs[i]->name) && !strcmp(instance, _available_funcs[i]->instance))
+                       return _available_funcs[i];
+
+       return NULL;
+}
+
+static void simple_cleanup_config(struct usb_configuration *config)
+{
+       if (!config)
+               return;
+
+       free(config->strs.config_str);
+
+       if (config->funcs)
+               free(config->funcs);
+
+       free(config);
+}
+
+static void cleanup_gadget(struct usb_gadget *gadget)
+{
+       int i;
+
+       if (!gadget)
+               return;
+
+       free(gadget->strs.manufacturer);
+       free(gadget->strs.product);
+       free(gadget->strs.serial);
+
+       if (gadget->configs) {
+               for (i = 0; gadget->configs[i]; ++i)
+                       simple_cleanup_config(gadget->configs[i]);
+
+               free(gadget->configs);
+       }
+
+       free(gadget);
+}
+
+static int alloc_default_config(struct usb_configuration **_config)
+{
+       struct usb_configuration *config;
+
+       config = calloc(1, sizeof(*config));
+       if (!config)
+               return -ENOMEM;
+
+       config->attrs.bmAttributs = DEFAULT_BMATTRIBUTES;
+       config->attrs.MaxPower = DEFAULT_MAX_POWER;
+
+       /* TODO. Here is where to set the string used in config of configfs */
+
+       *_config = config;
+
+       return 0;
+}
+
+static int alloc_default_gadget(char *serial, struct usb_gadget **_gadget)
+{
+       struct usb_gadget *gadget;
+       struct usb_configuration **configs;
+
+       gadget = calloc(1, sizeof(*gadget));
+       if (!gadget)
+               goto out;
+
+       gadget->attrs.idVendor = DEFAULT_VID;
+       gadget->attrs.idProduct = DEFAULT_PID;
+       gadget->attrs.bcdDevice = DEFAULT_BCD_DEVICE;
+
+       gadget->strs.lang_code = DEFAULT_LANG;
+       gadget->strs.manufacturer = strdup(DEFAULT_MANUFACTURER);
+       gadget->strs.product = strdup(DEFAULT_PRODUCT);
+       gadget->strs.serial = strdup(serial);
+
+       if (!gadget->strs.manufacturer || !gadget->strs.product || !gadget->strs.serial)
+               goto free_strs;
+
+       /* slp-gadget use max 2 confiuration and NULL termination */
+       configs = calloc(3, sizeof(*configs));
+       if (!configs)
+               goto free_strs;
+
+       gadget->configs = configs;
+       *_gadget = gadget;
+
+       return 0;
+
+free_strs:
+       free(gadget->strs.manufacturer);
+       free(gadget->strs.product);
+       free(gadget->strs.serial);
+       free(gadget);
+out:
+       return -ENOMEM;
+}
+
+static int id_to_gadget(struct usb_gadget_id *gadget_id, char *serial, struct usb_gadget **_gadget)
+{
+       int ret;
+       int i, j;
+       int n_configs;
+       struct usb_gadget *gadget;
+       int functions[2][sizeof(gadget_id->function_mask)*8]; /* zero terminates */
+
+       GList *elem;
+       const struct _usb_mode_mapping_table *cm = NULL;
+
+       if (!gadget_id || !serial || !_gadget)
+               return -EINVAL;
+
+       ret = alloc_default_gadget(serial, &gadget);
+       if (ret)
+               goto out;
+
+       /* find custom mode */
+       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, cm) {
+               if (cm->mode == gadget_id->function_mask)
+                       break;
+       }
+
+       if (cm) {
+               int i, j;
+
+               j = 0;
+               n_configs = 1;
+               for (i = 0; i < USB_FUNCTION_IDX_MAX; ++i) {
+                       if (cm->mode & (1 << i))
+                               functions[0][j++] = (1 << i);
+               }
+               functions[0][j] = 0;
+
+               if (cm->attrs.idVendor)
+                       gadget->attrs.idVendor = cm->attrs.idVendor;
+               if (cm->attrs.idProduct)
+                       gadget->attrs.idProduct = cm->attrs.idProduct;
+
+       } else {
+               /*
+                * Currently all gadgets use inly single configuration but
+                * slp-gadget is capable to handle two of them
+                *
+                * Order of interfaces in configuration is significant
+                * so in this switch we sort our functions in a correct order
+                */
+               switch (gadget_id->function_mask) {
+                       /* MTP, ACM, SDB */
+                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_MTP;
+                               functions[0][1] = USB_FUNCTION_ACM;
+                               functions[0][2] = 0;
+                               gadget->attrs.idProduct = 0x6860;
+                               break;
+
+                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_MTP;
+                               functions[0][1] = USB_FUNCTION_ACM;
+                               functions[0][2] = USB_FUNCTION_SDB;
+                               functions[0][3] = 0;
+                               gadget->attrs.idProduct = 0x6860;
+                               break;
+
+                               /* DIAG */
+                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_MTP;
+                               functions[0][1] = USB_FUNCTION_ACM;
+                               functions[0][2] = USB_FUNCTION_SDB;
+                               functions[0][3] = USB_FUNCTION_DIAG;
+                               functions[0][4] = 0;
+                               gadget->attrs.idProduct = 0x6860;
+                               break;
+
+                               /* RNDIS */
+                       case USB_FUNCTION_RNDIS:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_RNDIS;
+                               functions[0][1] = 0;
+                               gadget->attrs.idProduct = 0x6863;
+                               break;
+
+                       case USB_FUNCTION_RNDIS | USB_FUNCTION_DIAG:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_RNDIS;
+                               functions[0][1] = USB_FUNCTION_DIAG;
+                               functions[0][2] = 0;
+                               gadget->attrs.idProduct = 0x6864;
+                               break;
+
+                       case USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_RNDIS;
+                               functions[0][1] = USB_FUNCTION_ACM;
+                               functions[0][2] = USB_FUNCTION_SDB;
+                               functions[0][3] = 0;
+                               gadget->attrs.idProduct = 0x6864;
+                               break;
+
+                               /* RMNET */
+                       case USB_FUNCTION_DIAG | USB_FUNCTION_RMNET:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_DIAG;
+                               functions[0][1] = USB_FUNCTION_RMNET;
+                               functions[0][2] = 0;
+                               gadget->attrs.idProduct = 0x685d;
+                               break;
+
+                               /* DM */
+                       case USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DM:
+                               n_configs = 1;
+                               functions[0][0] = USB_FUNCTION_ACM;
+                               functions[0][1] = USB_FUNCTION_SDB;
+                               functions[0][2] = USB_FUNCTION_DM;
+                               functions[0][3] = 0;
+                               gadget->attrs.idProduct = 0x6860;
+                               break;
+
+                       default:
+                               ret = -EINVAL;
+                               goto free_gadget;
+               };
+       }
+
+       for (j = 0; j < n_configs; ++j) {
+               int n_funcs_in_config;
+               struct usb_configuration *config;
+
+               for (i = 0; functions[j][i]; ++i);
+               n_funcs_in_config = i;
+
+               ret = alloc_default_config(&config);
+               if (ret)
+                       goto free_configs;
+
+               gadget->configs[j] = config;
+               config->funcs = calloc(n_funcs_in_config + 1, sizeof(void *));
+               if (!config->funcs)
+                       goto free_configs;
+
+               for (i = 0; functions[j][i]; ++i) {
+                       config->funcs[i] = find_usb_function_by_id(functions[j][i]);
+                       if (!config->funcs[i])
+                               goto free_configs;
+               }
+       }
+
+       *_gadget = gadget;
+
+       return 0;
+
+free_configs:
+free_gadget:
+       cleanup_gadget(gadget);
+out:
+       return ret;
+}
+
+
+static struct usb_function *find_usb_function_by_id(int id)
+{
+       int i;
+
+       for (i = 0; _available_funcs[i]; i++)
+               if (_available_funcs[i]->id == id)
+                       return _available_funcs[i];
+
+       return NULL;
+}
+
+
+int usb_gadget_enable(void)
+{
+       if (!__usb_gadget_enable) {
+               _E("Not supported usb_gadget_enable.");
+               return -ENOTSUP;
+       }
+
+       return __usb_gadget_enable();
+}
+
+int usb_gadget_disable(void)
+{
+       if (!__usb_gadget_disable) {
+               _E("Not supported usb_gadget_disable.");
+               return -ENOTSUP;
+       }
+
+       return __usb_gadget_disable();
+}
+
+int usb_gadget_change_mode(unsigned int mode)
+{
+       struct usb_gadget *gadget;
+       struct usb_gadget_id gadget_id = {0, };
+       char serial[] = "123456";
+       int ret;
+
+       if (!__usb_gadget_reconfigure) {
+               _E("Not supported usb_gadget_reconfigure.");
+               return -ENOTSUP;
+       }
+
+       gadget_id.function_mask = mode;
+
+       ret = id_to_gadget(&gadget_id, serial, &gadget);
+       if (ret) {
+               _E("Failed to id_to_gadget, %d", ret);
+               return ret;
+       }
+
+       ret = __usb_gadget_reconfigure(gadget);
+       cleanup_gadget(gadget);
+       if (ret) {
+               _E("Failed to reconfigure gadget, %d", ret);
+               return ret;
+       }
+
+       return 0;
+}
+
+int usb_gadget_init(void)
+{
+       if (usb_gadget_legacy_supported()) {
+               /* legacy samsung gadget */
+               usb_gadget_bind_legacy_gadget(&__usb_gadget_open,
+                       &__usb_gadget_close,
+                       &__usb_gadget_enable,
+                       &__usb_gadget_disable,
+                       &__usb_gadget_reconfigure);
+       } else if (usb_gadget_cfs_supported()) {
+               /* configfs/functionfs gadget */
+               usb_gadget_bind_cfs_gadget(&__usb_gadget_open,
+                       &__usb_gadget_close,
+                       &__usb_gadget_enable,
+                       &__usb_gadget_disable,
+                       &__usb_gadget_reconfigure);
+       } else {
+               CRITICAL_LOG("Usb-gadget is not supported.");
+               return -ENOTSUP;
+       }
+
+       /* open supported usb-gadget */
+       __usb_gadget_open();
+
+       /* Use mtp-responder-dummy.socket when there is no mtp-responser.socket.
+        *
+        * The mtp-responder.socket is special in the configfs environment.
+        * If mtp-responder.socket is missing, gadget configuration will fail.
+        * As a result, all usb operations do not work properly.
+        * So in environments that mtp doesn't support, use dummy mtp.
+        */
+       if (access("/usr/lib/systemd/system/mtp-responder.socket", F_OK)) {
+               _available_funcs[USB_FUNCTION_IDX_MTP]->service = "mtp-responder-dummy";
+       }
+
+       return 0;
+}
+
+int usb_gadget_exit(void)
+{
+       if (__usb_gadget_close)
+               __usb_gadget_close();
+
+       __usb_gadget_open = NULL;
+       __usb_gadget_close = NULL;
+       __usb_gadget_enable = NULL;
+       __usb_gadget_disable = NULL;
+       __usb_gadget_reconfigure = NULL;
+
+       return 0;
+}
diff --git a/src/usb-gadget/usb-gadget.h b/src/usb-gadget/usb-gadget.h
new file mode 100644 (file)
index 0000000..e98442f
--- /dev/null
@@ -0,0 +1,114 @@
+#ifndef __USB_GADGET_H__
+#define __USB_GADGET_H__
+
+#include <stdint.h>
+#include <device/usb-gadget.h>
+
+/*The default USB configuration */
+#define DEFAULT_VID 0x04e8
+#define DEFAULT_PID 0x6860
+#define DEFAULT_BCD_DEVICE 0x0100
+
+#define DEFAULT_LANG 0x409 /* US_en */
+#define DEFAULT_MANUFACTURER "Samsung"
+#define DEFAULT_PRODUCT "TIZEN"
+#define DEFAULT_SERIAL "01234TEST"
+
+#define DEFAULT_BMATTRIBUTES ((1 << 7) | (1 << 6))
+#define DEFAULT_MAX_POWER 500
+
+struct usb_function {
+       int id;
+       const char *name;
+       const char *instance;
+
+       int is_functionfs;
+       const char *service;
+
+       /* do not stop the service on disabling usb-gadget function */
+       int remain_after_disable;
+
+       void (*handler)(int enable);
+};
+
+struct usb_configuration_attributes {
+       uint8_t bmAttributs;
+       int MaxPower;
+};
+
+struct usb_configuration_strings {
+       uint16_t lang_code;
+       char *config_str;
+};
+
+struct usb_configuration {
+       struct usb_configuration_attributes attrs;
+       struct usb_configuration_strings strs;
+       struct usb_function **funcs;
+};
+
+struct usb_gadget_attrs {
+       uint8_t bDeviceClass;
+       uint8_t bDeviceSubClass;
+       uint8_t bDeviceProtocol;
+       uint16_t idVendor;
+       uint16_t idProduct;
+       uint16_t bcdDevice;
+};
+
+struct usb_gadget_strings {
+       uint16_t lang_code;
+       char *manufacturer;
+       char *product;
+       char *serial;
+};
+
+struct usb_gadget {
+       struct usb_gadget_attrs attrs;
+       struct usb_gadget_strings strs;
+       struct usb_configuration **configs;
+};
+
+struct usb_gadget_id {
+       unsigned int function_mask;
+};
+
+enum {
+       USB_FUNCTION_IDX_MTP         = 0,
+       USB_FUNCTION_IDX_ACM         = 1,
+       USB_FUNCTION_IDX_SDB         = 2,
+       USB_FUNCTION_IDX_RNDIS       = 3,
+       USB_FUNCTION_IDX_DIAG        = 4,
+       USB_FUNCTION_IDX_CONN_GADGET = 5,
+       USB_FUNCTION_IDX_DM          = 6,
+       USB_FUNCTION_IDX_RMNET       = 7,
+       USB_FUNCTION_IDX_MAX         = USB_FUNCTION_IDX_RMNET + 1
+};
+
+
+struct usb_function *find_usb_function_by_name(const char *name);
+struct usb_function *find_usb_function_by_name_instance(const char *name, const char *instance);
+
+int usb_gadget_enable(void);
+int usb_gadget_disable(void);
+int usb_gadget_change_mode(unsigned int mode);
+int usb_gadget_init(void);
+int usb_gadget_exit(void);
+
+/* legacy samsung gadget */
+int usb_gadget_legacy_supported(void);
+void usb_gadget_bind_legacy_gadget(int (**open) (void),
+       int (**close) (void),
+       int (**enable) (void),
+       int (**disable) (void),
+       int (**reconfigure) (struct usb_gadget *));
+
+/* configfs/functionfs gadget */
+int usb_gadget_cfs_supported(void);
+void usb_gadget_bind_cfs_gadget(int (**open) (void),
+       int (**close) (void),
+       int (**enable) (void),
+       int (**disable) (void),
+       int (**reconfigure) (struct usb_gadget *));
+
+#endif //__USB_GADGET_H__
diff --git a/src/usb-gadget/usb-state.c b/src/usb-gadget/usb-state.c
new file mode 100644 (file)
index 0000000..d05f9a3
--- /dev/null
@@ -0,0 +1,503 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <string.h>
+#include <vconf.h>
+#include <bundle.h>
+#include <eventsystem.h>
+#include <libsyscommon/ini-parser.h>
+
+#include "core/log.h"
+#include "apps/apps.h"
+#include "extcon/extcon.h"
+
+#include "usb.h"
+#include "usb-debug.h"
+#include "usb-gadget.h"
+
+#define PATH_USB_GADGET_CONF    "/hal/etc/deviced/usb_gadget.conf"
+
+static int noti_id = -1;
+
+static unsigned int usb_current_mode = USB_FUNCTION_NONE;
+static unsigned int usb_selected_mode = USB_FUNCTION_NONE;
+
+static extcon_usb_state_e usb_connection = USB_DISCONNECTED;
+
+/**
+ * Important
+ * You must keep the order for the specific items.
+ *
+ * There may be several mode_v for a mode.
+ * In this case, the representative value should be placed on top.
+ *
+ * In case of SET_USB_SDB_DIAG and SET_USB_DIAG_SDB, the SET_USB_SDB_DIAG should be above.
+ * As another example, SET_USB_RNDIS_SDB should be at the top of them.
+ */
+static const struct _usb_mode_mapping_table {
+       int          mode_v; /* Integer defined by vconf */
+       unsigned int mode;   /* Bitmap of usb function combination */
+       struct usb_gadget_attrs attrs;
+} usb_mode_mapping_table[] = {
+       /* Hack for performance. In most cases this is the value. */
+       {SET_USB_DEFAULT,         USB_FUNCTION_MTP | USB_FUNCTION_ACM},
+       {SET_USB_SDB,             USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB},
+
+       {SET_USB_NONE,            USB_FUNCTION_NONE},
+       {SET_USB_RNDIS,           USB_FUNCTION_RNDIS},
+       {SET_USB_RNDIS_DIAG,      USB_FUNCTION_RNDIS | USB_FUNCTION_DIAG},
+       {SET_USB_DIAG_RMNET,      USB_FUNCTION_DIAG | USB_FUNCTION_RMNET},
+       {SET_USB_ACM_SDB_DM,      USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DM},
+
+       {SET_USB_SDB_DIAG,        USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG},
+       {SET_USB_DIAG_SDB,        USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG},
+
+       {SET_USB_RNDIS_SDB,       USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
+       {SET_USB_RNDIS_TETHERING, USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
+       {SET_USB_RNDIS_SDB_ACM,   USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
+};
+
+static const int mapping_table_len = sizeof(usb_mode_mapping_table) / sizeof(usb_mode_mapping_table[0]);
+
+/*
+ * Private, custom defined mode mapping.
+ * You can define custom mode_v with mode from /hal/etc/deviced/usb_gadget.conf
+ * A custom mapping precedes the above default mapping if the custom mode_v overlaps
+ * default mode_v.
+ *
+ * Do not declare it with static storage class as it will be exported as dynamic symbol
+ * so that dlopen-ed device-common can refer it.
+ */
+GList *usb_mode_mapping_table_custom;
+
+/*
+ * Do not declare it with static storage class as it will be exported as dynamic symbol
+ * so that dlopen-ed device-common can refer it.
+ */
+struct service_config {
+       char name[128];
+       int remain_after_disable; /* do not stop the service on disabling usb-gadget function */
+};
+GList *service_config_list;
+
+unsigned int get_mode_bitmap_from_vconf(int mode_v)
+{
+       int i;
+       GList *elem;
+       struct _usb_mode_mapping_table *table;
+
+       /* lookup from custom mapping table first */
+       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, table) {
+               if (table->mode_v == mode_v)
+                       return table->mode;
+       }
+
+       /* and then lookup the default mapping table */
+       for (i = 0; i < mapping_table_len; i++) {
+               if (usb_mode_mapping_table[i].mode_v == mode_v)
+                       return usb_mode_mapping_table[i].mode;
+       }
+
+       return USB_FUNCTION_INVALID;
+}
+
+static int get_mode_vconf_from_bitmap(unsigned int mode)
+{
+       int i;
+       GList *elem;
+       struct _usb_mode_mapping_table *table;
+
+       /* lookup from custom mapping table first */
+       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, table) {
+               if (table->mode == mode)
+                       return table->mode_v;
+       }
+
+       /* Caution: The order to search the usb_mode_mapping_table must start with a low index. */
+       for (i = 0; i < mapping_table_len; i++) {
+               if (usb_mode_mapping_table[i].mode == mode)
+                       return usb_mode_mapping_table[i].mode_v;
+       }
+
+       return SET_USB_INVALID;
+}
+
+static void usb_state_send_system_event(int status)
+{
+       bundle *b;
+       const char *str;
+
+       switch (status) {
+       case VCONFKEY_SYSMAN_USB_DISCONNECTED:
+               str = EVT_VAL_USB_DISCONNECTED;
+               break;
+
+       case VCONFKEY_SYSMAN_USB_CONNECTED:
+               str = EVT_VAL_USB_CONNECTED;
+               break;
+
+       case VCONFKEY_SYSMAN_USB_AVAILABLE:
+               str = EVT_VAL_USB_AVAILABLE;
+               break;
+
+       default:
+               return;
+       }
+
+       _I("USB system_event (%s)", str);
+
+       b = bundle_create();
+       bundle_add_str(b, EVT_KEY_USB_STATUS, str);
+       eventsystem_send_system_event(SYS_EVENT_USB_STATUS, b);
+       bundle_free(b);
+}
+
+static void parse_property_systemd_unit(gpointer data, gpointer udata)
+{
+       struct section_property *prop = (struct section_property *) data;
+       struct service_config *svc = (struct service_config *) udata;
+
+       if (MATCH(prop->key, "Service")) {
+               strncpy(svc->name, prop->value, sizeof(svc->name) - 1);
+               svc->name[sizeof(svc->name) - 1] = '\0';
+       } else if (MATCH(prop->key, "RemainAfterDisable")) {
+               svc->remain_after_disable = MATCH(prop->value, "yes");
+       }
+}
+
+static unsigned int parse_usb_function(char *fstr)
+{
+       // Parse Function=, e.g., "Function=diag,acm"
+       unsigned int ret = USB_FUNCTION_NONE;
+       char *p, *saveptr;
+
+       if (!fstr)
+               return ret;
+
+       p = strtok_r(fstr, ",", &saveptr);
+       if (!p)
+               return ret;
+
+       do {
+               if (strncasecmp(p, "mtp", sizeof("mtp")) == 0) {
+                       ret |= USB_FUNCTION_MTP;
+               } else if (strncasecmp(p, "acm", sizeof("acm")) == 0) {
+                       ret |= USB_FUNCTION_ACM;
+               } else if(strncasecmp(p, "sdb", sizeof("sdb")) == 0) {
+                       ret |= USB_FUNCTION_SDB;
+               } else if (strncasecmp(p, "rndis", sizeof("rndis")) == 0) {
+                       ret |= USB_FUNCTION_RNDIS;
+               } else if (strncasecmp(p, "diag", sizeof("diag")) == 0) {
+                       ret |= USB_FUNCTION_DIAG;
+               } else if (strncasecmp(p, "conngadget", sizeof("conngadget")) == 0) {
+                       ret |= USB_FUNCTION_CONN_GADGET;
+               } else if (strncasecmp(p, "dm", sizeof("dm")) == 0) {
+                       ret |= USB_FUNCTION_DM;
+               } else if (strncasecmp(p, "rmnet", sizeof("rmnet")) == 0) {
+                       ret |= USB_FUNCTION_RMNET;
+               }
+       } while ((p = strtok_r(NULL, ",", &saveptr)));
+
+       return ret;
+}
+
+static void parse_property_attribute(gpointer data, gpointer udata)
+{
+       struct section_property *prop = (struct section_property *) data;
+       struct _usb_mode_mapping_table *table = (struct _usb_mode_mapping_table *) udata;
+       unsigned int value;
+
+       if (MATCH(prop->key, "Mode")) {
+               sscanf(prop->value, "%d", &table->mode_v);
+       } else if (MATCH(prop->key, "Function")) {
+               table->mode = parse_usb_function(prop->value);
+       } else if (MATCH(prop->key, "bDeviceClass")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.bDeviceClass = (uint8_t) value;
+       } else if (MATCH(prop->key, "bDeviceSubClass")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.bDeviceSubClass = (uint8_t) value;
+       } else if (MATCH(prop->key, "bDeviceProtocol")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.bDeviceProtocol = (uint8_t) value;
+       } else if (MATCH(prop->key, "idVendor")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.idVendor = (uint16_t) value;
+       } else if (MATCH(prop->key, "idProduct")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.idProduct = (uint16_t) value;
+       } else if (MATCH(prop->key, "bcdDevice")) {
+               sscanf(prop->value, "%x", &value);
+               table->attrs.bcdDevice = (uint16_t) value;
+       }
+}
+
+static int load_usb_gadget_config(const struct parse_result *result, void *data)
+{
+       if (MATCH(result->section, "SystemdUnit")) {
+               struct service_config svc = { 0, };
+               void *entry = NULL;
+
+               g_list_foreach(result->props, parse_property_systemd_unit, &svc);
+
+               entry = malloc(sizeof(struct service_config));
+               if (!entry) {
+                       _E("Failed to alloc service config");
+                       return 0;
+               }
+
+               _I("usb-gadget service config: name=%s, remain_after_disable=%d",
+                       svc.name, svc.remain_after_disable);
+               service_config_list = g_list_prepend(service_config_list, memcpy(entry, &svc, sizeof(svc)));
+
+       } else if (MATCH(result->section, "Attribute")) {
+               struct _usb_mode_mapping_table table = { 0, };
+               void *entry = NULL;
+
+               g_list_foreach(result->props, parse_property_attribute, &table);
+
+               // if it hasn't defined mode, use default or pre-defined one
+               if (table.mode == USB_FUNCTION_NONE)
+                       table.mode = get_mode_bitmap_from_vconf(table.mode_v);
+
+               if (table.mode == USB_FUNCTION_INVALID)
+                       return 0;
+
+               if (table.mode_v >= SET_USB_NONE && table.mode_v <= SET_USB_RNDIS_SDB_ACM)
+                       _W("The custom mode=%d replaces the predefined usb-gadget configuration", table.mode_v);
+
+               entry = malloc(sizeof(struct _usb_mode_mapping_table));
+               if (!entry) {
+                       _E("Failed to alloc mapping table");
+                       return 0;
+               }
+
+               _I("Custom usb-gadget: mode=%d, function=%#x, idVendor=%#x, idProduct=%#x",
+                       table.mode_v, table.mode, table.attrs.idVendor, table.attrs.idProduct);
+
+               usb_mode_mapping_table_custom = g_list_prepend(usb_mode_mapping_table_custom, memcpy(entry, &table, sizeof(table)));
+       }
+
+       return 0;
+}
+
+void usb_state_load_custom_mode(void)
+{
+       libsys_config_parse_by_section(PATH_USB_GADGET_CONF, load_usb_gadget_config, NULL);
+}
+
+void usb_state_retrieve_selected_mode(void)
+{
+       int mode_v;
+       unsigned int mode;
+       const unsigned int default_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM;
+
+       /* Never return here because deviced must never run in USB_FUNCTION_NONE mode */
+       if (vconf_get_int(VCONFKEY_USB_SEL_MODE, &mode_v) != VCONF_OK) {
+               mode_v = SET_USB_INVALID;
+               _E("Failed to get vconf value for USB sel mode: %d", vconf_get_ext_errno());
+       }
+
+       mode = get_mode_bitmap_from_vconf(mode_v);
+
+       /*
+        * Deviced must never run in USB_FUNCTION_NONE mode.
+        * So if vconf value is invalid, deviced uses the default usb mode internally.
+        * Keep the problematic vconf values in order to define the problem correctly.
+        */
+       switch (mode) {
+       case USB_FUNCTION_INVALID: /* Invalid vconf */
+               usb_selected_mode = default_mode;
+               _E("Failed to convert vconf to USB mode. There is no mode matches up with vconf %d. Use default mode=%#x.", mode_v, default_mode);
+               break;
+
+       case USB_FUNCTION_NONE: /* Invalid vconf */
+               usb_selected_mode = default_mode;
+               _E("There is USB_FUNCTION_NONE USB mode matches up with vconf %d. Use default mode=%#x.", mode_v, default_mode);
+               break;
+
+       default: /* Success */
+               usb_selected_mode = mode;
+               _I("Succeeded to convert vconf to USB mode. vconf=%d, mode=%#x.", mode_v, mode);
+               break;
+       }
+
+       /* To sync with vconf for debug mode */
+       set_usb_debug_state((bool)(usb_selected_mode & USB_FUNCTION_SDB));
+}
+
+/* Cache of vconf_get_int(VCONFKEY_USB_SEL_MODE) */
+unsigned int usb_state_get_selected_mode(void)
+{
+       return usb_selected_mode;
+}
+
+/* Since it is changed externally by dbus and vconf, it should be processed even if it has the same value as before. */
+int usb_state_set_selected_mode(unsigned int mode)
+{
+       int ret;
+       int mode_v;
+
+       usb_selected_mode = mode;
+
+       mode_v = get_mode_vconf_from_bitmap(mode);
+       if (mode_v == SET_USB_INVALID) {
+               _E("Failed to convert USB selected_mode to vconf. There is no vconf matches up with USB mode %#x", mode);
+               return -EINVAL;
+       }
+
+       ret = vconf_set_int(VCONFKEY_USB_SEL_MODE, mode_v);
+       if (ret != VCONF_OK)
+               _E("Failed to set vconf value for USB selected mode: %d", vconf_get_ext_errno());
+
+       return ret;
+}
+
+/* Cache of vconf_get_int(VCONFKEY_USB_CUR_MODE) */
+unsigned int usb_state_get_current_mode(void)
+{
+       return usb_current_mode;
+}
+
+/* Because it is only changed by deviced, it is only processed when the vconf actually changes. */
+int usb_state_set_current_mode(unsigned int mode)
+{
+       int ret = 0;
+       int mode_v;
+       static int old_mode_v = -1;
+
+       usb_current_mode = mode;
+
+       mode_v = get_mode_vconf_from_bitmap(mode);
+       if (mode_v == SET_USB_INVALID) {
+               _E("Failed to convert USB current_mode to vconf. There is no vconf matches up with mode %#x", mode);
+               return -EINVAL;
+       }
+
+       if (old_mode_v != mode_v) {
+               old_mode_v = mode_v;
+               ret = vconf_set_int(VCONFKEY_USB_CUR_MODE, mode_v);
+               if (ret < 0)
+                       _E("Failed to set vconf value for USB current mode: %d", vconf_get_ext_errno());
+       }
+
+       return ret;
+}
+
+extcon_usb_state_e usb_state_get_connection(void)
+{
+       return usb_connection;
+}
+
+void usb_state_set_connection(extcon_usb_state_e conn)
+{
+       usb_connection = conn;
+}
+
+static void media_noti_cb(GVariant *var, void *user_data, GError *err)
+{
+       int id = 0;
+
+       if (!var) {
+               if (err)
+                       _E("USB media notification error: %s", err->message);
+               return;
+       }
+
+       if (!g_variant_get_safe(var, "(i)", &id)) {
+               _E("Failed to get variant(%s): no USB notification message", g_variant_get_type_string(var));
+               goto out;
+       }
+
+       noti_id = id;
+       _D("USB media notification message(%d)", noti_id);
+
+out:
+       g_variant_unref(var);
+}
+
+static void add_notification_handler(void)
+{
+       int ret_val;
+
+       if (noti_id < 0) {
+               ret_val = add_async_notification("MediaDeviceNotiOn", media_noti_cb, NULL);
+               if (ret_val < 0)
+                       _E("Failed to add USB notification for usb connection: %d", ret_val);
+       }
+}
+
+static void remove_notification_handler(void)
+{
+       int ret_val;
+
+       if (noti_id >= 0) {
+               ret_val = remove_notification("MediaDeviceNotiOff", noti_id);
+               if (ret_val < 0)
+                       _E("Failed to remove USB notification for usb connection: %d", ret_val);
+               else
+                       noti_id = -1;
+       }
+}
+
+void change_usb_state_notification_handler(unsigned int mode)
+{
+       if (mode & USB_FUNCTION_MTP)
+               add_notification_handler();
+       else if (mode == USB_FUNCTION_NONE)
+               remove_notification_handler();
+}
+
+/*
+ * USB_DISCONNECTED                  : VCONFKEY_SYSMAN_USB_DISCONNECTED
+ * USB_CONNECTED + USB_FUNCTION_NONE : VCONFKEY_SYSMAN_USB_CONNECTED
+ * USB_CONNECTED + USB_FUNCTION_OOOO : VCONFKEY_SYSMAN_USB_AVAILABLE
+ *
+ * When connecting the usb cable     : "disconnected"(previous value) -> "connected" -> "available"
+ * When disconnecting the usb cable  : "available"(previous value) -> "dosconnected"
+ * When changing usb mode            : "available"(previous value) -> "connected" -> "available"
+ *
+ * When USB cable is connected but USB initialization fails : It stays "connected" without going to "available"
+ *
+ */
+void send_usb_state_changed_event(int status)
+{
+       static int old_status = -1;
+
+       if ((status != VCONFKEY_SYSMAN_USB_CONNECTED) &&
+               (status != VCONFKEY_SYSMAN_USB_AVAILABLE) &&
+               (status != VCONFKEY_SYSMAN_USB_DISCONNECTED)) {
+               _E("Invalid USB state changed event (%d)", status);
+               return;
+       }
+
+       if (old_status == status)
+               return;
+
+       old_status = status;
+
+       usb_state_send_system_event(status);
+
+       if (vconf_set_int(VCONFKEY_SYSMAN_USB_STATUS, status) != VCONF_OK)
+               _E("Failed to set vconf value for USB status: %d", vconf_get_ext_errno());
+
+       /* Caution: calls after vconf_set_int(VCONFKEY_SYSMAN_USB_STATUS) */
+       broadcast_usb_state_changed();
+}
+
diff --git a/src/usb-gadget/usb-tethering.c b/src/usb-gadget/usb-tethering.c
new file mode 100644 (file)
index 0000000..76dcb7d
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <stdbool.h>
+
+#include <vconf.h>
+
+#include "core/log.h"
+#include "shared/device-notifier.h"
+
+#include "usb.h"
+#include "usb-gadget.h"
+
+static bool tethering_state;
+
+static void usb_tethering_changed(keynode_t *key, void *data)
+{
+       int mode;
+       bool curr;
+
+       if (!key)
+               return;
+
+       mode = vconf_keynode_get_int(key);
+       curr = mode & VCONFKEY_MOBILE_HOTSPOT_MODE_USB;
+
+       if (curr == tethering_state) {
+               _I("USB tethering mode is already %s.", curr ? "ON" : "OFF");
+               return;
+       }
+
+       tethering_state = curr;
+
+       _I("USB tethering mode is changed to %s.", curr ? "ON" : "OFF");
+
+       device_notify(DEVICE_NOTIFIER_USB_TETHERING_MODE, (void *)curr);
+}
+
+static int usb_tethering_mode_changed(void *on)
+{
+       int ret;
+       unsigned new_mode;
+       static unsigned int saved_prev_mode = USB_FUNCTION_NONE;
+       const unsigned int curr_mode = usb_state_get_selected_mode();
+       const unsigned int predefined_rndis_mode_off = USB_FUNCTION_ACM | USB_FUNCTION_MTP;
+       const unsigned int predefined_rndis_mode_on = USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS;
+
+       /*
+        * On: Use predefined mode (USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS)
+        * Off: Use predefined mode (USB_FUNCTION_MTP | USB_FUNCTION_ACM) + USB_FUNCTION_SDB(conditional)
+        *
+        * Caution: If usb debug menu was enabled, add USB_FUNCTION_SDB to new mode to use.
+        *
+        * When tethering is enabled, additionally enable usb debug(USB_FUNCTION_SDB) unconditionally.
+        * Since usb debug is always enabled when you turn off usb tethering, there is no way to know if usb debug was enabled or not.
+        * So before enabling usb tethering, save the previous state.
+        * This saved value is used to check if the debug menu was enabled or not when you turn off usb tethering.
+        *
+        * In addition, if someone changes the usb mode while tethering on,
+        * use the latest usb mode to determine the usb debug mode instead of using the saved value.
+        *
+        */
+
+       if ((bool)on) {
+               new_mode = predefined_rndis_mode_on;
+               saved_prev_mode = curr_mode;
+       } else {
+               new_mode = predefined_rndis_mode_off;
+
+               if (curr_mode != predefined_rndis_mode_on) /* someone changes the usb mode while tethering on, use latest usb mode */
+                       saved_prev_mode = curr_mode;
+
+               if(saved_prev_mode & USB_FUNCTION_SDB)
+                       new_mode |= USB_FUNCTION_SDB;
+
+               saved_prev_mode = USB_FUNCTION_NONE;
+       }
+
+       ret = usb_change_mode(new_mode, true);
+       if (ret < 0)
+               _E("Failed to change USB mode to (%#x).", new_mode);
+
+       return ret;
+}
+
+void add_usb_tethering_handler(void)
+{
+       if (vconf_notify_key_changed(VCONFKEY_MOBILE_HOTSPOT_MODE, usb_tethering_changed, NULL) != VCONF_OK)
+               _E("Failed to add USB tethering handler.");
+
+       register_notifier(DEVICE_NOTIFIER_USB_TETHERING_MODE, usb_tethering_mode_changed);
+}
+
+void remove_usb_tethering_handler(void)
+{
+       vconf_ignore_key_changed(VCONFKEY_MOBILE_HOTSPOT_MODE, usb_tethering_changed);
+
+       unregister_notifier(DEVICE_NOTIFIER_USB_TETHERING_MODE, usb_tethering_mode_changed);
+}
diff --git a/src/usb-gadget/usb-tethering.h b/src/usb-gadget/usb-tethering.h
new file mode 100644 (file)
index 0000000..d7a40ec
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __USB_TETHERING_H__
+#define __USB_TETHERING_H__
+
+void add_usb_tethering_handler(void);
+void remove_usb_tethering_handler(void);
+
+#endif /* __USB_TETHERING_H__ */
diff --git a/src/usb-gadget/usb.c b/src/usb-gadget/usb.c
new file mode 100644 (file)
index 0000000..c71da85
--- /dev/null
@@ -0,0 +1,340 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#include <vconf.h>
+#include <libsyscommon/libsystemd.h>
+
+#include "core/log.h"
+#include "core/udev.h"
+#include "display/poll.h"
+#include "display/display-ops.h"
+#include "shared/plugin.h"
+
+#include "usb.h"
+#include "usb-gadget.h"
+#include "usb-debug.h"
+#include "usb-tethering.h"
+
+static int usb_change_gadget(unsigned mode);
+
+static struct display_plugin *disp_plgn;
+
+static int usb_config_init(void)
+{
+       unsigned int mode = usb_state_get_selected_mode();
+
+       return usb_change_gadget(mode);
+}
+
+/* Precondition: USB_FUNCTION_NONE */
+static int usb_change_gadget(unsigned mode)
+{
+       int ret;
+
+       ret = usb_gadget_change_mode(mode);
+       if (ret) {
+               /* because usb does not work properly */
+               (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
+               return ret;
+       }
+
+       _I("USB gadget changed to (%#x)", mode);
+
+       return 0;
+}
+
+/* Precondition: USB_CONNECTED, USB_FUNCTION_NONE */
+static int usb_enable(unsigned int mode)
+{
+       int ret;
+
+       ret = usb_gadget_enable();
+       if (ret < 0) {
+               _E("Failed to enable USB config: %d", ret);
+               goto out;
+       }
+
+       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_AVAILABLE);
+       (void)usb_state_set_current_mode(mode);
+       change_usb_state_notification_handler(mode);
+
+       return 0;
+
+out:
+       /* Although this function has a USB_FUNCTION_NONE precondition, it is to protect against coding mistakes. */
+       (void)usb_state_set_current_mode(USB_FUNCTION_NONE); /* because usb does not work properly */
+       return ret;
+}
+
+/* Precondition: N/A */
+static int usb_disable(void)
+{
+       int ret;
+
+       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
+       change_usb_state_notification_handler(USB_FUNCTION_NONE);
+
+       ret = usb_gadget_disable();
+       if (ret < 0) {
+               _E("Failed to disable USB config: %d", ret);
+               return ret;
+       }
+
+       return 0;
+}
+
+/* Precondition: USB_DISCONNECTED (Implicitly contains USB_FUNCTION_NONE) */
+static int usb_connected(void)
+{
+       int ret;
+       unsigned int mode = usb_state_get_selected_mode();
+
+       if (disp_plgn->pm_lock_internal)
+               disp_plgn->pm_lock_internal(INTERNAL_LOCK_USB, LCD_OFF, STAY_CUR_STATE, 0);
+
+       usb_state_set_connection(USB_CONNECTED);
+       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_CONNECTED);
+
+       ret = usb_enable(mode);
+       if (ret < 0) {
+               _E("Failed to enable USB gadget(%#x): %d", mode, ret);
+               return ret;
+       }
+
+       return 0;
+}
+
+/* Precondition: USB_CONNECTED */
+static int usb_disconnected(void)
+{
+       int ret;
+
+       usb_state_set_connection(USB_DISCONNECTED);
+       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
+
+       ret = usb_disable();
+       if(ret < 0) {
+               _E("Failed to disable USB gadget: %d", ret);
+               /* Important: You have to keep going to unlock disp_plgn->pm_unlock_internal */
+       }
+
+       if (disp_plgn->pm_unlock_internal)
+               disp_plgn->pm_unlock_internal(INTERNAL_LOCK_USB, LCD_OFF, STAY_CUR_STATE);
+
+       return ret;
+}
+
+/* Called by dbus signal and vconf change(tethering, debug mode) */
+int usb_change_mode(unsigned int new_mode, bool change_debug_mode)
+{
+       int ret;
+       const unsigned int curr_mode = usb_state_get_current_mode();
+       const unsigned int prev_mode = usb_state_get_selected_mode();
+
+       if (prev_mode == new_mode) {
+               _I("already using USB mode(%#x), current running mode (%#x)", prev_mode, curr_mode);
+               return 0;
+       }
+
+       _I("USB change mode (%#x) -> (%#x), current running mode (%#x)", prev_mode, new_mode, curr_mode);
+
+       /*
+        * When you change the gadget(usb_change_gadget) for new usb mode, you must disable the gadget first.
+        *
+        * Even if the usb cable is plugged in, the current mode may be NULL due to usb fail.
+        * So to find out which mode you are in, you should use the current mode, not the selected mode.
+       */
+       if (curr_mode != USB_FUNCTION_NONE) {
+               /* Special case: Because usb gadget is disabled, temporarily switch usb state from available to connected. */
+               send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_CONNECTED);
+
+               ret = usb_disable();
+               if (ret < 0) {
+                       _E("Failed to disable current USB mode.");
+                       return ret;
+               }
+       }
+
+       /*
+        * You should always change the gadget once when the usb mode is changed.
+        * In this state, usb_enable() is called when the usb cable is connected
+        * and usb_disable() is called when the usb cable is disconnected.
+        */
+       ret = usb_change_gadget(new_mode);
+       if (ret < 0) {
+               _E("Failed to change USB gadget: %d", ret);
+               return ret;
+       }
+
+       if (usb_state_get_connection() == USB_CONNECTED) {
+               ret = usb_enable(new_mode);
+               if (ret < 0) {
+                       _E("Failed to enable USB mode: %d", ret);
+                       return ret;
+               }
+       }
+
+       /* If you success to change the runtime usb configuration, do change the selected mode. */
+       (void)usb_state_set_selected_mode(new_mode);
+
+       /* To sync with vconf for debug mode */
+       if (change_debug_mode)
+               set_usb_debug_state((bool)(new_mode & USB_FUNCTION_SDB));
+
+       return 0;
+}
+
+/* Called by extcon udev event */
+static int usb_state_changed(const char *index, int new_status)
+{
+       int ret = -1;
+       static int old_status = -1; /* -1: Uninitialized, 0: disconnected, 1: connected */
+
+       /* For debugging. Do not move the location. */
+       _I("USB state is changed by extcon from (%d) to (%d).", old_status, new_status);
+
+       if (old_status == new_status)
+               return 0;
+
+       switch (new_status) {
+       case USB_CONNECTED:
+               ret = usb_connected();
+               break;
+
+       case USB_DISCONNECTED:
+               if (old_status == -1) {
+                       /* only initialize the internal data state and skip usb hal operation. */
+                       _I("USB is initialized without USB connection");
+
+                       /* From usb_disconnected() */
+                       usb_state_set_connection(USB_DISCONNECTED);
+                       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
+
+                       /*  From usb_disable() */
+                       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
+                       change_usb_state_notification_handler(USB_FUNCTION_NONE);
+
+                       ret = 0;
+               } else
+                       ret = usb_disconnected();
+               break;
+
+       default:
+               _E("Invalid USB state(%d).", new_status);
+               return -EINVAL;
+       }
+
+       if (ret < 0) {
+               _E("Failed to operate USB connection: %d", ret);
+               return ret;
+       }
+
+       old_status = new_status;
+
+       return ret;
+}
+
+static void uevent_usb_mode_handler(struct udev_device *dev)
+{
+       const char *state = NULL;
+
+       state = udev_device_get_property_value(dev, "USB_STATE");
+       if (!state)
+               return;
+
+       if (strncmp(state, "CONFIGURED", strlen(state) + 1))
+               return;
+
+       _I("USB udev event happend : CONFIGURED USB_STATE");
+
+       if (usb_state_get_selected_mode() & USB_FUNCTION_ACM)
+               systemd_start_unit_wait_started ("data-router.service", NULL, -1);
+
+       if (usb_state_get_selected_mode() & USB_FUNCTION_SDB)
+               systemd_start_unit_wait_started ("sdbd.service", NULL, -1);
+
+       if (usb_state_get_selected_mode() & USB_FUNCTION_MTP)
+               systemd_start_unit_wait_started ("mtp-responder.service", NULL, -1);
+}
+
+static struct uevent_handler uh = {
+       .subsystem = "usb_mode",
+       .uevent_func = uevent_usb_mode_handler,
+};
+
+static void usb_init(void *data)
+{
+       int ret;
+
+       usb_state_load_custom_mode();
+       usb_state_retrieve_selected_mode();
+
+       ret = usb_gadget_init();
+       if (ret < 0) {
+               _E("USB client cannot be used: %d", ret);
+               return;
+       }
+
+       ret = usb_config_init();
+       if (ret < 0)
+               _E("Failed to initialize USB configuation.");
+
+       ret = register_udev_uevent_control(&uh);
+       if (ret < 0)
+               _E("Failed to register udev event(%d) for USB", ret);
+
+       ret = usb_dbus_init();
+       if (ret < 0)
+               _E("Failed to init dbus(%d) for USB", ret);
+
+       add_usb_tethering_handler();
+       add_usb_debug_handler();
+}
+
+static void usb_exit(void *data)
+{
+       remove_usb_debug_handler();
+       remove_usb_tethering_handler();
+
+       usb_state_set_connection(USB_DISCONNECTED);
+       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
+       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
+       change_usb_state_notification_handler(USB_FUNCTION_NONE);
+
+       unregister_udev_uevent_control(&uh);
+       usb_gadget_disable();
+       usb_gadget_exit();
+
+}
+
+static struct extcon_ops extcon_usb_ops = {
+       .name   = EXTCON_CABLE_USB,
+       .init   = usb_init,
+       .exit   = usb_exit,
+       .update = usb_state_changed,
+};
+
+EXTCON_OPS_REGISTER(extcon_usb_ops)
+
+static void __CONSTRUCTOR__ initialize(void)
+{
+       disp_plgn = get_var_display_plugin();
+       if (!disp_plgn)
+               _E("Failed to get display plugin variable.");
+}
diff --git a/src/usb-gadget/usb.h b/src/usb-gadget/usb.h
new file mode 100644 (file)
index 0000000..0e30b2e
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __DEVICED_USB_H__
+#define __DEVICED_USB_H__
+
+#include <limits.h>
+#include <stdbool.h>
+#include "extcon/extcon.h"
+
+#define USB_FUNCTION_INVALID   UINT_MAX
+#define SET_USB_INVALID        INT_MAX
+
+int usb_dbus_init(void);
+
+void usb_state_load_custom_mode(void);
+
+int usb_change_mode(unsigned int mode, bool change_debug_mode);
+void usb_state_retrieve_selected_mode(void);
+unsigned int get_mode_bitmap_from_vconf(int mode_v);
+
+void broadcast_usb_state_changed(void);
+void send_usb_state_changed_event(int status);
+void change_usb_state_notification_handler(unsigned int mode);
+
+unsigned int usb_state_get_selected_mode(void);
+int usb_state_set_selected_mode(unsigned int mode);
+
+unsigned int usb_state_get_current_mode(void);
+int usb_state_set_current_mode(unsigned int mode);
+
+extcon_usb_state_e usb_state_get_connection(void);
+void usb_state_set_connection(extcon_usb_state_e conn);
+
+#endif /* __USB_CLIENT_H__ */
diff --git a/src/usb-host/usb-host.c b/src/usb-host/usb-host.c
new file mode 100644 (file)
index 0000000..9155fb5
--- /dev/null
@@ -0,0 +1,1224 @@
+/*
+ * deviced
+ *
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <stdio.h>
+#include <stdint.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <tzplatform_config.h>
+#include <libsyscommon/libgdbus.h>
+#include <libsyscommon/list.h>
+#include <dlfcn.h>
+
+#include "core/log.h"
+#include "shared/devices.h"
+#include "shared/device-notifier.h"
+#include "core/udev.h"
+#include "apps/apps.h"
+#include "extcon/extcon.h"
+#include "display/display-ops.h"
+#include "display/core.h"
+#include "dd-usbhost.h"
+#include "shared/plugin.h"
+
+#define USB_INTERFACE_CLASS     "bInterfaceClass"
+#define USB_INTERFACE_SUBCLASS  "bInterfaceSubClass"
+#define USB_INTERFACE_PROTOCOL  "bInterfaceProtocol"
+#define USB_VENDOR_ID           "idVendor"
+#define USB_PRODUCT_ID          "idProduct"
+#define USB_MANUFACTURER        "manufacturer"
+#define USB_PRODUCT             "product"
+#define USB_SERIAL              "serial"
+
+#define USB_HOST_RESULT_SIGNAL "USBHostResult"
+
+#define SIGNAL_USB_HOST_CHANGED "ChangedDevice"
+#define METHOD_GET_CONNECTION_CREDENTIALS "GetConnectionCredentials"
+
+#define ROOTPATH tzplatform_getenv(TZ_SYS_VAR)
+#define POLICY_FILENAME "usbhost-policy"
+
+static struct display_plugin *disp_plgn;
+static struct display_config *disp_conf;
+static struct display_config* (*fp_get_var_display_config)(void);
+static bool display_on_usb_conn_changed = true;
+static char *POLICY_FILEPATH;
+
+/**
+ * Below usb host class is defined by www.usb.org.
+ * Please refer to below site.
+ * http://www.usb.org/developers/defined_class
+ * You can find the detail class codes in linux/usb/ch9.h.
+ * Deviced uses kernel defines.
+ */
+#include <linux/usb/ch9.h>
+#define USB_CLASS_ALL   0xffffffff
+#define USB_DEVICE_MAJOR 189
+
+/**
+ * HID Standard protocol information.
+ * Please refer to below site.
+ * http://www.usb.org/developers/hidpage/HID1_11.pdf
+ * Below protocol only has meaning
+ * if the subclass is a boot interface subclass,
+ * otherwise it is 0.
+ */
+enum usbhost_hid_protocol {
+       USB_HOST_HID_KEYBOARD = 1,
+       USB_HOST_HID_MOUSE    = 2,
+};
+
+static GList *usbhost_list;
+
+enum policy_value {
+       POLICY_NONE,
+       POLICY_ALLOW_ALWAYS,
+       POLICY_ALLOW_NOW,
+       POLICY_DENY_ALWAYS,
+       POLICY_DENY_NOW,
+};
+
+#define UID_KEY "UnixUserID"
+#define PID_KEY "ProcessID"
+#define SEC_LABEL_KEY "LinuxSecurityLabel"
+#define ENTRY_LINE_SIZE 256
+
+struct user_credentials {
+       uint32_t uid;
+       uint32_t pid;
+       char *sec_label;
+};
+
+struct device_desc {
+       uint16_t bcdUSB;
+       uint8_t bDeviceClass;
+       uint8_t bDeviceSubClass;
+       uint8_t bDeviceProtocol;
+       uint16_t idVendor;
+       uint16_t idProduct;
+       uint16_t bcdDevice;
+};
+
+struct policy_entry {
+       struct user_credentials creds;
+       union {
+               struct usb_device_descriptor device;
+               /* for temporary policy */
+               char devpath[PATH_MAX];
+       };
+
+       enum policy_value value;
+};
+
+static inline int is_policy_temporary(struct policy_entry *entry)
+{
+       return entry->value == POLICY_ALLOW_NOW ||
+               entry->value == POLICY_DENY_NOW;
+}
+
+static GList *access_list;
+
+static struct usbhost_open_request {
+       GDBusMethodInvocation *invocation;
+       char *path;
+       //struct user_credentials cred;
+       GDBusCredentials cred;
+       struct usb_device_descriptor desc;
+       char devpath[PATH_MAX];
+} *current_request = NULL;
+
+static void print_usbhost(struct usbhost_device *usbhost)
+{
+       if (!usbhost)
+               return;
+
+       _I("devpath : %s", usbhost->devpath);
+       _I("interface baseclass : %#xh", usbhost->baseclass);
+       _I("interface subclass : %#xh", usbhost->subclass);
+       _I("interface protocol : %#xh", usbhost->protocol);
+       _I("vendor id : %#xh", usbhost->vendorid);
+       _I("product id : %#xh", usbhost->productid);
+       _I("manufacturer : %s", usbhost->manufacturer);
+       _I("product : %s", usbhost->product);
+       _I("serial : %s", usbhost->serial);
+}
+
+static void broadcast_usbhost_signal(enum usbhost_state state,
+               struct usbhost_device *usbhost)
+{
+       int ret;
+       GVariant *param;
+
+       if (!usbhost)
+               return;
+
+       param = g_variant_new("(isiiiiisss)", state,
+                                                                               usbhost->devpath,
+                                                                               usbhost->baseclass,
+                                                                               usbhost->subclass,
+                                                                               usbhost->protocol,
+                                                                               usbhost->vendorid,
+                                                                               usbhost->productid,
+                                                                               (usbhost->manufacturer ? usbhost->manufacturer : ""),
+                                                                               (usbhost->product ? usbhost->product : ""),
+                                                                               (usbhost->serial ? usbhost->serial : ""));
+
+       ret = gdbus_signal_emit(NULL,
+                       DEVICED_PATH_USBHOST,
+                       DEVICED_INTERFACE_USBHOST,
+                       SIGNAL_USB_HOST_CHANGED,
+                       param);
+       if (ret < 0)
+               _E("Failed to send dbus signal(%s)", SIGNAL_USB_HOST_CHANGED);
+}
+
+static int add_usbhost_list(struct udev_device *dev, const char *devpath)
+{
+       struct usbhost_device *usbhost;
+       const char *str;
+       struct udev_device *parent;
+
+       /* allocate new usbhost device */
+       usbhost = calloc(1, sizeof(struct usbhost_device));
+       if (!usbhost) {
+               _E("Fail to allocate usbhost memory: %d", errno);
+               return -errno;
+       }
+
+       /* save the devnode */
+       snprintf(usbhost->devpath, sizeof(usbhost->devpath),
+                       "%s", devpath);
+
+       /* get usb interface informations */
+       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_CLASS);
+       if (str)
+               usbhost->baseclass = (int)strtol(str, NULL, 16);
+       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_SUBCLASS);
+       if (str)
+               usbhost->subclass = (int)strtol(str, NULL, 16);
+       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_PROTOCOL);
+       if (str)
+               usbhost->protocol = (int)strtol(str, NULL, 16);
+
+       /* parent has a lot of information about usb_interface */
+       parent = udev_device_get_parent(dev);
+       if (!parent) {
+               _E("Failed to get parent.");
+               free(usbhost);
+               return -EPERM;
+       }
+
+       /* get usb device informations */
+       str = udev_device_get_sysattr_value(parent, USB_VENDOR_ID);
+       if (str)
+               usbhost->vendorid = (int)strtol(str, NULL, 16);
+       str = udev_device_get_sysattr_value(parent, USB_PRODUCT_ID);
+       if (str)
+               usbhost->productid = (int)strtol(str, NULL, 16);
+       str = udev_device_get_sysattr_value(parent, USB_MANUFACTURER);
+       if (str)
+               usbhost->manufacturer = strdup(str);
+       str = udev_device_get_sysattr_value(parent, USB_PRODUCT);
+       if (str)
+               usbhost->product = strdup(str);
+       str = udev_device_get_sysattr_value(parent, USB_SERIAL);
+       if (str)
+               usbhost->serial = strdup(str);
+
+       SYS_G_LIST_APPEND(usbhost_list, usbhost);
+
+       broadcast_usbhost_signal(USB_HOST_ADDED, usbhost);
+
+       if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
+               disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);
+
+       /* for debugging */
+       _I("USB HOST Added.");
+       print_usbhost(usbhost);
+
+       return 0;
+}
+
+static int remove_usbhost_list(const char *devpath)
+{
+       struct usbhost_device *usbhost;
+       GList *n, *next;
+
+       /* find the matched item */
+       SYS_G_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {
+               if (!strncmp(usbhost->devpath,
+                                       devpath, sizeof(usbhost->devpath)))
+                       break;
+       }
+
+       if (!usbhost) {
+               _E("Failed to find the matched usbhost device.");
+               return -ENODEV;
+       }
+
+       broadcast_usbhost_signal(USB_HOST_REMOVED, usbhost);
+
+       if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
+               disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);
+
+       /* for debugging */
+       _I("USB HOST Removed.");
+       _I("Devpath=%s", usbhost->devpath);
+
+       SYS_G_LIST_REMOVE(usbhost_list, usbhost);
+       free(usbhost->manufacturer);
+       free(usbhost->product);
+       free(usbhost->serial);
+       free(usbhost);
+
+       return 0;
+}
+
+static void remove_all_usbhost_list(void)
+{
+       struct usbhost_device *usbhost;
+       GList *n, *next;
+
+       SYS_G_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {
+
+               /* for debugging */
+               _I("USB HOST Removed.");
+               _I("Devpath=%s", usbhost->devpath);
+
+               SYS_G_LIST_REMOVE(usbhost_list, usbhost);
+               free(usbhost->manufacturer);
+               free(usbhost->product);
+               free(usbhost->serial);
+               free(usbhost);
+       }
+}
+
+static void uevent_usbhost_handler(struct udev_device *dev)
+{
+       const char *subsystem;
+       const char *devtype;
+       const char *devpath;
+       const char *action;
+       struct policy_entry *entry;
+       GList *n, *next;
+
+       /**
+        * Usb host device must have at least one interface.
+        * An interface is matched with a specific usb class.
+        */
+       subsystem = udev_device_get_subsystem(dev);
+       devtype = udev_device_get_devtype(dev);
+       if (!subsystem || !devtype) {
+               _E("Failed to get subsystem or devtype.");
+               return;
+       }
+
+       /* devpath is an unique information among usb host devices */
+       devpath = udev_device_get_devpath(dev);
+       if (!devpath) {
+               _E("Failed to get devpath from udev_device.");
+               return;
+       }
+
+       action = udev_device_get_action(dev);
+       _I("Subsystem=%s devtype=%s action=%s", subsystem, devtype, action);
+       /* Policy is valid for entire device, thus we check this devtype here */
+       if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) == 0 &&
+           strncmp(devtype, USB_DEVICE_DEVTYPE, sizeof(USB_DEVICE_DEVTYPE)) == 0 &&
+           strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)) == 0) {
+               SYS_G_LIST_FOREACH_SAFE(access_list, n, next, entry) {
+                       if (is_policy_temporary(entry) &&
+                                       strcmp(devpath, entry->devpath) == 0) {
+                               _I("Removed temporary policy for '%s'", devpath);
+                               SYS_G_LIST_REMOVE(access_list, entry);
+                               free(entry->creds.sec_label);
+                               free(entry);
+                       }
+               }
+       }
+
+       /**
+        * if devtype is not matched with usb subsystem
+        * and usb_interface devtype, skip.
+        */
+       if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) ||
+           strncmp(devtype, USB_INTERFACE_DEVTYPE, sizeof(USB_INTERFACE_DEVTYPE)))
+               return;
+
+       if (!strncmp(action, UDEV_ADD, sizeof(UDEV_ADD)))
+               add_usbhost_list(dev, devpath);
+       else if (!strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)))
+               remove_usbhost_list(devpath);
+}
+
+static int usbhost_init_from_udev_enumerate(void)
+{
+       struct udev *udev;
+       struct udev_enumerate *enumerate;
+       struct udev_list_entry *list_entry;
+       struct udev_device *dev;
+       const char *syspath;
+       const char *devpath;
+
+       udev = udev_new();
+       if (!udev) {
+               _E("Failed to create udev library context.");
+               return -EPERM;
+       }
+
+       /* create a list of the devices in the 'usb' subsystem */
+       enumerate = udev_enumerate_new(udev);
+       if (!enumerate) {
+               _E("Failed to create an enumeration context.");
+               return -EPERM;
+       }
+
+       udev_enumerate_add_match_subsystem(enumerate, USB_SUBSYSTEM);
+       udev_enumerate_add_match_property(enumerate,
+                       UDEV_DEVTYPE, USB_INTERFACE_DEVTYPE);
+       udev_enumerate_scan_devices(enumerate);
+
+       udev_list_entry_foreach(list_entry,
+                       udev_enumerate_get_list_entry(enumerate)) {
+               syspath = udev_list_entry_get_name(list_entry);
+               if (!syspath)
+                       continue;
+
+               dev = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
+                               syspath);
+               if (!dev)
+                       continue;
+
+               /* devpath is an unique information among usb host devices */
+               devpath = udev_device_get_devpath(dev);
+               if (!devpath) {
+                       _E("Failed to get devpath from '%s' device.", syspath);
+                       continue;
+               }
+
+               /* add usbhost list */
+               add_usbhost_list(dev, devpath);
+
+               udev_device_unref(dev);
+       }
+
+       udev_enumerate_unref(enumerate);
+       udev_unref(udev);
+       return 0;
+}
+
+static GVariant *print_device_list(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       GList *elem;
+       struct usbhost_device *usbhost;
+       int cnt = 0;
+
+       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
+               _I("== [%2d USB HOST DEVICE] ===============", cnt++);
+               print_usbhost(usbhost);
+       }
+
+       return gdbus_new_g_variant_tuple();
+}
+#define nullstr(x) (x ? x : "")
+static GVariant *get_device_list(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       GVariant *gvar = NULL;
+       GList *elem;
+       struct usbhost_device *usbhost;
+       int baseclass;
+       GVariantBuilder *builder = NULL;
+       const char *error = NULL;
+       int item_cnt = 0;
+
+       g_variant_get(param, "(i)", &baseclass);
+
+       builder = g_variant_builder_new(G_VARIANT_TYPE("a(siiiiisss)"));
+       if (!builder) {
+               _E("Failed to alloc memory for g_variant_builder.");
+               error = "Failed to alloc memory for g_variant_builder.";
+               goto out;
+       }
+
+       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
+               if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
+                       continue;
+
+               g_variant_builder_add(builder, "(siiiiisss)",
+                               nullstr(NULL),
+                               usbhost->baseclass,
+                               usbhost->subclass,
+                               usbhost->protocol,
+                               usbhost->vendorid,
+                               usbhost->productid,
+                               nullstr(usbhost->manufacturer),
+                               nullstr(usbhost->product),
+                               nullstr(usbhost->serial));
+               ++item_cnt;
+       }
+
+       if (item_cnt == 0) {
+               _E("Not found matched item");
+               error = "Not found matched item";
+               goto out;
+       }
+
+       gvar = g_variant_new("(a(siiiiisss))", builder);
+
+out:
+       if (builder)
+               g_variant_builder_unref(builder);
+       if (!gvar)
+               g_dbus_method_invocation_return_error(invocation,
+                                       G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
+                                       "%s", error);
+       return gvar;
+}
+
+static GVariant *get_device_list_count(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       GList *elem;
+       struct usbhost_device *usbhost;
+       int baseclass;
+       int ret = 0;
+
+       g_variant_get(param, "(i)", &baseclass);
+
+       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
+               if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
+                       continue;
+               ret++;
+       }
+
+       return g_variant_new("(i)", ret);
+}
+
+static struct uevent_handler uh = {
+       .subsystem = USB_SUBSYSTEM,
+       .uevent_func = uevent_usbhost_handler,
+};
+
+static const char *policy_value_str(enum policy_value value)
+{
+       switch (value) {
+       case POLICY_ALLOW_ALWAYS:
+               return "ALLOW";
+       case POLICY_ALLOW_NOW:
+               return "ALLOW_NOW";
+       case POLICY_DENY_ALWAYS:
+               return "DENY";
+       case POLICY_DENY_NOW:
+               return "DENY_NOW";
+       default:
+               return "UNKNOWN";
+       }
+}
+
+static int get_policy_value_from_str(const char *str)
+{
+       if (strncmp("ALLOW", str, 5) == 0)
+               return POLICY_ALLOW_ALWAYS;
+       if (strncmp("ALLOW_NOW", str, 5) == 0)
+               return POLICY_ALLOW_NOW;
+       if (strncmp("DENY", str, 4) == 0)
+               return POLICY_DENY_ALWAYS;
+       if (strncmp("DENY_NOW", str, 4) == 0)
+               return POLICY_DENY_NOW;
+       return POLICY_NONE;
+}
+
+static inline int marshal_policy_entry(char *buf, int len, struct policy_entry *entry)
+{
+       if (is_policy_temporary(entry))
+               return snprintf(buf, len, "%d %s %s %s\n",
+                               entry->creds.uid,
+                               entry->creds.sec_label,
+                               entry->devpath,
+                               policy_value_str(entry->value));
+       return snprintf(buf, len, "%d %s %04x %02x %02x %02x %04x %04x %04x %s\n",
+                       entry->creds.uid,
+                       entry->creds.sec_label,
+                       entry->device.bcdUSB,
+                       entry->device.bDeviceClass,
+                       entry->device.bDeviceSubClass,
+                       entry->device.bDeviceProtocol,
+                       entry->device.idVendor,
+                       entry->device.idProduct,
+                       entry->device.bcdDevice,
+                       policy_value_str(entry->value));
+}
+
+static GVariant *print_policy(GDBusConnection *conn,
+       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       char line[ENTRY_LINE_SIZE];
+       GList *elem;
+       struct policy_entry *entry;
+       int ret;
+
+       _I("USB access policy:");
+       SYS_G_LIST_FOREACH(access_list, elem, entry) {
+               ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
+               if (ret < 0)
+                       break;
+               _I("\t%s", line);
+       }
+
+       return gdbus_new_g_variant_tuple();
+}
+
+static int store_policy(void)
+{
+       int fd;
+       GList *elem;
+       struct policy_entry *entry;
+       char line[256];
+       int ret;
+
+       fd = open(POLICY_FILEPATH, O_WRONLY | O_CREAT, 0664);
+       if (fd < 0) {
+               _E("Could not open policy file for writing: %m");
+               return -errno;
+       }
+
+       SYS_G_LIST_FOREACH(access_list, elem, entry) {
+               if (is_policy_temporary(entry))
+                       continue;
+
+               ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
+               if (ret < 0) {
+                       _E("Serialization failed: %m");
+                       goto out;
+               }
+
+               ret = write(fd, line, ret);
+               if (ret < 0) {
+                       ret = -errno;
+                       _E("Error writing policy entry: %m");
+                       goto out;
+               }
+       }
+
+       _I("Policy stored in %s", POLICY_FILEPATH);
+
+       ret = 0;
+
+out:
+       close(fd);
+       return ret;
+}
+
+static int read_policy(void)
+{
+       FILE *fp;
+       struct policy_entry *entry;
+       char *line = NULL, value_str[256];
+       int ret = -1;
+       int count = 0;
+       size_t len;
+
+       fp = fopen(POLICY_FILEPATH, "r");
+       if (!fp) {
+               ret = -errno;
+               _E("Could not open policy file for reading: %m");
+               return ret;
+       }
+
+       while ((ret = getline(&line, &len, fp)) != -1) {
+               entry = malloc(sizeof(*entry));
+               if (!entry) {
+                       ret = -ENOMEM;
+                       _E("No memory: %m");
+                       goto out;
+               }
+
+               entry->creds.sec_label = calloc(ENTRY_LINE_SIZE, 1);
+               if (!entry->creds.sec_label) {
+                       _E("No memory: %m");
+                       free(entry);
+                       goto out;
+               }
+
+               ret = sscanf(line, "%d %255s %04hx %02hhx %02hhx %02hhx %04hx %04hx %04hx %255s\n",
+                               &entry->creds.uid,
+                               entry->creds.sec_label,
+                               &entry->device.bcdUSB,
+                               &entry->device.bDeviceClass,
+                               &entry->device.bDeviceSubClass,
+                               &entry->device.bDeviceProtocol,
+                               &entry->device.idVendor,
+                               &entry->device.idProduct,
+                               &entry->device.bcdDevice,
+                               value_str);
+               if (ret == EOF) {
+                       _E("Error reading line: %m");
+                       free(entry->creds.sec_label);
+                       free(entry);
+                       goto out;
+               }
+
+               entry->value = get_policy_value_from_str(value_str);
+               if (entry->value == POLICY_NONE) {
+                       _E("Invalid policy value=%s", value_str);
+                       ret = -EINVAL;
+                       free(entry->creds.sec_label);
+                       free(entry);
+                       goto out;
+               }
+
+               _I("%04x:%04x : %s", entry->device.idVendor, entry->device.idProduct,
+                               value_str);
+
+               SYS_G_LIST_APPEND(access_list, entry);
+               count++;
+       }
+
+       _I("Found %d policy entries.", count);
+       ret = 0;
+
+out:
+       fclose(fp);
+       free(line);
+
+       return ret;
+}
+
+static int get_device_desc(const char *filepath, struct usb_device_descriptor *desc, char *devpath)
+{
+       char *path = NULL;
+       const char *rdevpath;
+       struct stat st;
+       int ret;
+       int fd = -1;
+       struct udev *udev = NULL;
+       struct udev_device *udev_device = NULL;
+
+       ret = stat(filepath, &st);
+       if (ret < 0) {
+               ret = -errno;
+               _E("Could not stat %s: %m", filepath);
+               goto out;
+       }
+
+       if (!S_ISCHR(st.st_mode) ||
+           major(st.st_rdev) != USB_DEVICE_MAJOR) {
+               ret = -EINVAL;
+               _E("Not an USB device.");
+               goto out;
+       }
+
+       udev = udev_new();
+       if (!udev) {
+               _E("Could not create udev contect.");
+               ret =  -ENOMEM;
+               goto out;
+       }
+
+       udev_device = udev_device_new_from_devnum(udev, 'c', st.st_rdev);
+       if (!udev_device) {
+               _E("Udev could not find device.");
+               ret = -ENOENT;
+               goto out;
+       }
+
+       rdevpath = udev_device_get_devpath(udev_device);
+       if (!rdevpath) {
+               _E("Failed to get devpath from udev_device.");
+               ret = -errno;
+               goto out;
+       }
+       strncpy(devpath, rdevpath, PATH_MAX);
+
+       ret = asprintf(&path, "/sys/dev/char/%d:%d/descriptors", major(st.st_rdev), minor(st.st_rdev));
+       if (ret < 0) {
+               ret = -ENOMEM;
+               _E("Failed to asprintf.");
+               goto out;
+       }
+
+       _I("Opening descriptor at '%s'", path);
+       fd = open(path, O_RDONLY);
+       if (fd < 0) {
+               ret = -errno;
+               _E("Failed to open '%s': %m", path);
+               goto out;
+       }
+
+       ret = read(fd, desc, sizeof(*desc));
+       if (ret < 0) {
+               ret = -errno;
+               _E("Failed to read '%s': %m", path);
+               goto out;
+       }
+
+       ret = 0;
+
+out:
+       if (fd >= 0)
+               close(fd);
+       free(path);
+
+       udev_device_unref(udev_device);
+       udev_unref(udev);
+
+       return ret;
+}
+
+static gboolean store_idler_cb(gpointer data)
+{
+       store_policy();
+
+       return G_SOURCE_REMOVE;
+}
+
+static void destroy_open_request(struct usbhost_open_request *req)
+{
+       _D("Destroing request structure.");
+       free(req->path);
+       req->path = NULL;
+}
+
+static void finish_opening(struct usbhost_open_request *req, int policy)
+{
+       int ret;
+       int fd = -1;
+       const char *err;
+       GError *error = NULL;
+       GUnixFDList *fd_list;
+
+       if (req->path == NULL)
+               return;
+
+       switch (policy) {
+       case POLICY_ALLOW_NOW:
+       case POLICY_ALLOW_ALWAYS:
+               fd = open(req->path, O_RDWR);
+               if (fd < 0) {
+                       ret = -errno;
+                       err = "org.freedesktop.DBus.Error.Failed";//"org.freedesktop.DBus.Error.Failed";
+                       _E("Unable to open file(%s): %m", req->path);
+               } else
+                       ret = 0;
+               break;
+       case POLICY_DENY_NOW:
+       case POLICY_DENY_ALWAYS:
+               ret = -EACCES;
+               err = "org.freedesktop.DBus.Error.AccessDenied";//G_DBUS_ERROR_ACCESS_DENIED;
+               break;
+       default:
+               ret = -EINVAL;
+               err = "org.freedesktop.DBus.Error.Failed";
+               break;
+       }
+
+       if (ret < 0) {
+               g_dbus_method_invocation_return_dbus_error(req->invocation, err, "Cannot allocate memory for error message");
+               goto out;
+       }
+
+       /** send along the stdin in case
+        *  g_application_command_line_get_stdin_data() is called
+        */
+       fd_list = g_unix_fd_list_new();
+       if (g_unix_fd_list_append(fd_list, fd, &error) < 0) {
+               _E("Failed to append fd in unix fd list: %s\n", error->message);
+               g_error_free(error);
+               goto out;
+       }
+
+       g_dbus_method_invocation_return_value_with_unix_fd_list(req->invocation, g_variant_new("(ih)", ret, 0), fd_list);
+
+       g_object_unref(fd_list);
+
+out:
+       destroy_open_request(req);
+       if (fd >= 0)
+               close(fd);
+       _I("Popup destroyed.");
+}
+
+static int spawn_popup(struct usbhost_open_request *req)
+{
+       char pid_str[8];
+       int ret;
+
+       if (!req)
+               return -EINVAL;
+
+       /* Handle for the previous popup */
+       if (current_request) {
+               finish_opening(current_request, POLICY_DENY_NOW);
+               free(current_request);
+               current_request = NULL;
+       }
+
+       _I("Launching popup.");
+
+       snprintf(pid_str, sizeof(pid_str), "%d", req->cred.pid);
+       ret = launch_system_app(APP_DEFAULT, 4, APP_KEY_TYPE, "usbhost", "_APP_PID_", pid_str);
+       if (ret < 0) {
+               _E("Could not launch system popup.");
+               return ret;
+       }
+
+       return ret;
+}
+
+static void popup_result_signal_handler(GDBusConnection  *conn,
+       const gchar      *sender,
+       const gchar      *path,
+       const gchar      *iface,
+       const gchar      *name,
+       GVariant         *param,
+       gpointer          data)
+
+{
+       int allow = 0, always = 0;
+       struct policy_entry *entry;
+       int value;
+       struct usbhost_open_request *req;
+
+       req = current_request;
+       if (!req) {
+               _E("req is NULL");
+               return;
+       }
+
+       if (!g_variant_get_safe(param, "(ii)", &allow, &always)) {
+               _E("failed to get params from gvariant. expected:%s, type:%s", "(ii)", g_variant_get_type_string(param));
+               free(req);
+               return;
+       }
+
+       if (allow && always)
+               value = POLICY_ALLOW_ALWAYS;
+       else if (!allow && always)
+               value = POLICY_DENY_ALWAYS;
+       else if (allow && !always)
+               value = POLICY_ALLOW_NOW;
+       else
+               value = POLICY_DENY_NOW;
+
+       /* Save the policy */
+
+       entry = calloc(sizeof(*entry), 1);
+       if (!entry) {
+               _E("No memory.");
+               goto out;
+       }
+
+       entry->creds.uid = req->cred.uid;
+       entry->creds.sec_label = strdup(req->cred.sec_label);
+       if (!entry->creds.sec_label) {
+               _E("No memory.");
+               free(entry);
+               goto out;
+       }
+
+       switch (value) {
+       case POLICY_ALLOW_ALWAYS:
+       case POLICY_DENY_ALWAYS:
+               entry->device.bcdUSB = le16toh(req->desc.bcdUSB);
+               entry->device.bDeviceClass = req->desc.bDeviceClass;
+               entry->device.bDeviceSubClass = req->desc.bDeviceSubClass;
+               entry->device.bDeviceProtocol = req->desc.bDeviceProtocol;
+               entry->device.idVendor = le16toh(req->desc.idVendor);
+               entry->device.idProduct = le16toh(req->desc.idProduct);
+               entry->device.bcdDevice = le16toh(req->desc.bcdDevice);
+
+               _I("Added policy entry: %d %s %04x %02x %02x %02x %04x %04x %04x %s",
+                               entry->creds.uid,
+                               entry->creds.sec_label,
+                               entry->device.bcdUSB,
+                               entry->device.bDeviceClass,
+                               entry->device.bDeviceSubClass,
+                               entry->device.bDeviceProtocol,
+                               entry->device.idVendor,
+                               entry->device.idProduct,
+                               entry->device.bcdDevice,
+                               policy_value_str(value));
+               break;
+       case POLICY_ALLOW_NOW:
+       case POLICY_DENY_NOW:
+               strncpy(entry->devpath, req->devpath, sizeof(entry->devpath) - 1);
+               entry->devpath[sizeof(entry->devpath) - 1] = '\0';
+               _I("Added temporary policy entry: %d %s %s %s",
+                               entry->creds.uid,
+                               entry->creds.sec_label,
+                               entry->devpath,
+                               policy_value_str(value));
+               break;
+       }
+
+       entry->value = value;
+       SYS_G_LIST_APPEND(access_list, entry);
+
+       g_idle_add(store_idler_cb, NULL);
+
+out:
+       finish_opening(req, value);
+       free(current_request);
+       current_request = NULL;
+}
+
+static int get_policy_value(struct usbhost_open_request *req)
+{
+       int ret;
+       GList *elem;
+       struct policy_entry *entry;
+
+       memset(&req->desc, 0, sizeof(req->desc));
+
+       _I("Requested access from user %d to '%s'.", req->cred.uid, req->path);
+       ret = get_device_desc(req->path, &req->desc, req->devpath);
+       if (ret < 0) {
+               _E("Could not get device descriptor.");
+               return ret;
+       }
+
+       SYS_G_LIST_FOREACH(access_list, elem, entry) {
+               if (entry->creds.uid != req->cred.uid
+                       || strncmp(entry->creds.sec_label, req->cred.sec_label, strlen(req->cred.sec_label)) != 0)
+                       continue;
+
+               if (is_policy_temporary(entry) ? strncmp(entry->devpath, req->devpath, PATH_MAX) :
+                       (entry->device.bcdUSB && entry->device.bcdUSB != le16toh(req->desc.bcdUSB))
+                       || (entry->device.bDeviceClass && entry->device.bDeviceClass != req->desc.bDeviceClass)
+                       || (entry->device.bDeviceSubClass && entry->device.bDeviceSubClass != req->desc.bDeviceSubClass)
+                       || (entry->device.bDeviceProtocol && entry->device.bDeviceProtocol != req->desc.bDeviceProtocol)
+                       || (entry->device.idVendor && entry->device.idVendor != le16toh(req->desc.idVendor))
+                       || (entry->device.idProduct && entry->device.idProduct != le16toh(req->desc.idProduct))
+                       || (entry->device.bcdDevice && entry->device.bcdDevice != le16toh(req->desc.bcdDevice)))
+                       continue;
+
+               _I("Found matching policy entry(%s)", policy_value_str(entry->value));
+
+               return entry->value;
+       }
+
+       return POLICY_NONE;
+}
+
+static void remove_all_access_list(void)
+{
+       struct policy_entry *entry;
+       GList *n, *next;
+
+       SYS_G_LIST_FOREACH_SAFE(access_list, n, next, entry) {
+               SYS_G_LIST_REMOVE(access_list, entry);
+               free(entry->creds.sec_label);
+               free(entry);
+       }
+}
+
+static GVariant *open_device(GDBusConnection *conn,
+       const gchar *sender, const gchar *obj_path, const gchar *iface, const gchar *name,
+       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
+{
+       int ret = 0;
+       int policy;
+       char *path;
+       struct usbhost_open_request *req;
+
+       req = calloc(sizeof(*req), 1);
+       if (!req) {
+               _E("No memory.");
+               g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
+               return NULL;
+       }
+
+       req->invocation = invocation;
+
+       ret = gdbus_get_sender_credentials(NULL, sender, &req->cred);
+       if (ret < 0) {
+               _E("Unable to get credentials for caller: %d", ret);
+               goto out;
+       }
+
+       g_variant_get(param, "(s)", &path);
+
+       req->path = path;
+       policy = get_policy_value(req);
+       if (policy < 0) {
+               _E("Could not get policy value(%d).", policy);
+               ret = -1;
+               goto out;
+       }
+
+       /* Need to ask user */
+       if (policy == POLICY_NONE) {
+               ret = spawn_popup(req);
+               if (ret < 0) {
+                       finish_opening(req, POLICY_DENY_NOW);
+                       free(req->cred.sec_label);
+                       free(req);
+                       return NULL;
+               }
+
+               current_request = req;
+               return NULL;
+       }
+
+       /* The policy exists for the app */
+       _D("Policy exists.");
+       finish_opening(req, policy);
+       free(req->cred.sec_label);
+       free(req);
+       return NULL;
+
+out:
+       destroy_open_request(req);
+       free(req->cred.sec_label);
+       free(req);
+       g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
+       return NULL;
+}
+
+static const dbus_method_s dbus_methods[] = {
+       { "PrintDeviceList",   NULL,           NULL, print_device_list }, /* for debugging */
+       { "PrintPolicy",       NULL,           NULL, print_policy }, /* for debugging */
+       { "GetDeviceList",      "i", "a(siiiiisss)", get_device_list },
+       { "GetDeviceListCount", "i",            "i", get_device_list_count },
+       { "OpenDevice",         "s",           "ih", open_device },
+       /* Add methods here */
+};
+
+static const dbus_interface_u dbus_interface = {
+       .oh = NULL,
+       .name = DEVICED_INTERFACE_USBHOST,
+       .methods = dbus_methods,
+       .nr_methods = ARRAY_SIZE(dbus_methods),
+};
+
+
+static int delayed_init_done(void *data)
+{
+       /**
+        * To search the attched usb host device is not an urgent task.
+        * So deviced does not load while booting time.
+        * After booting task is done, it tries to find the attached devices.
+        */
+       usbhost_init_from_udev_enumerate();
+
+       /* unregister booting done notifier */
+       unregister_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_done);
+
+       return 0;
+}
+
+static void usbhost_init(void *data)
+{
+       int ret;
+
+       fp_get_var_display_config = dlsym(disp_plgn->handle, "get_var_display_config");
+       if (fp_get_var_display_config) {
+               disp_conf = fp_get_var_display_config();
+               if (!disp_conf)
+                       _E("Failed to get display config variable.");
+               else
+                       display_on_usb_conn_changed = disp_conf->display_on_usb_conn_changed;
+       } else {
+               _E("Failed to obtain address of get_var_display_config, %s.", dlerror());
+       }
+
+       /* register usbhost uevent */
+       ret = register_kernel_uevent_control(&uh);
+       if (ret < 0)
+               _E("Failed to register usb uevent: %d", ret);
+
+       /* register usbhost interface and method */
+       ret = gdbus_add_object(NULL, DEVICED_PATH_USBHOST, &dbus_interface);
+       if (ret < 0)
+               _E("Failed to register dbus interface and method: %d", ret);
+
+       /* register notifier */
+       register_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_done);
+
+       ret = asprintf(&POLICY_FILEPATH, "%s/%s", ROOTPATH, POLICY_FILENAME);
+       if (ret < 0) {
+               _E("No memory for policy path.");
+               return;
+       }
+
+       ret = gdbus_signal_subscribe(NULL, POPUP_PATH_SYSTEM,
+               POPUP_INTERFACE_SYSTEM, USB_HOST_RESULT_SIGNAL,
+               popup_result_signal_handler, NULL, NULL);
+       if (ret < 0) {
+               _E("Could not register popup signal handler.");
+               return;
+       }
+
+       read_policy();
+}
+
+static void usbhost_exit(void *data)
+{
+       int ret;
+
+       /* unregister usbhost uevent */
+       ret = unregister_kernel_uevent_control(&uh);
+       if (ret < 0)
+               _E("Failed to unregister usb uevent: %d", ret);
+
+       /* remove all usbhost list */
+       remove_all_usbhost_list();
+
+       store_policy();
+       remove_all_access_list();
+
+       free(POLICY_FILEPATH);
+}
+
+static const struct device_ops usbhost_device_ops = {
+       .name   = "usbhost",
+       .init   = usbhost_init,
+       .exit   = usbhost_exit,
+};
+
+DEVICE_OPS_REGISTER(&usbhost_device_ops)
+
+static int extcon_usbhost_state_changed(const char *index, int status)
+{
+       if (status == USBHOST_DISCONNECTED)
+               _I("USB host connector disconnected.");
+       else
+               _I("USB host connector connected.");
+
+       return 0;
+}
+
+static struct extcon_ops extcon_usbhost_ops = {
+       .name   = EXTCON_CABLE_USB_HOST,
+       .update = extcon_usbhost_state_changed,
+};
+
+EXTCON_OPS_REGISTER(extcon_usbhost_ops)
+
+static void __CONSTRUCTOR__ initialize(void)
+{
+       disp_plgn = get_var_display_plugin();
+       if (!disp_plgn)
+               _E("Failed to get display plugin variable.");
+}
diff --git a/src/usb/usb-dbus.c b/src/usb/usb-dbus.c
deleted file mode 100644 (file)
index 35eb16d..0000000
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <stdbool.h>
-
-#include <vconf.h>
-#include <libsyscommon/libgdbus.h>
-
-#include "core/log.h"
-
-#include "usb.h"
-#include "usb-gadget.h"
-#include "usb-debug.h"
-
-/* Legacy signals */
-#define SIGNAL_STATE_CHANGED  "StateChanged"
-#define SIGNAL_MODE_CHANGED   "ModeChanged"
-#define SIGNAL_CONFIG_ENABLED "ConfigEnabled"
-#define CHANGE_USB_MODE       "ChangeUsbMode"
-
-static int get_usb_state(void)
-{
-       int ret, val;
-       int result = 0;
-
-       ret = vconf_get_int(VCONFKEY_SYSMAN_USB_STATUS, &val);
-       if (ret != VCONF_OK) {
-               _E("Failed to get vconf value for USB status: %d", vconf_get_ext_errno());
-               return ret;
-       }
-
-       if (val == VCONFKEY_SYSMAN_USB_DISCONNECTED)
-               result = val;
-       else {
-               result = VCONFKEY_SYSMAN_USB_CONNECTED;
-               if (val == VCONFKEY_SYSMAN_USB_AVAILABLE)
-                       result |= VCONFKEY_SYSMAN_USB_AVAILABLE;
-       }
-
-       return result;
-}
-
-void broadcast_usb_state_changed(void)
-{
-       int ret;
-       unsigned int state;
-       static unsigned int prev_state = UINT_MAX;
-
-       state = get_usb_state();
-       if (state == prev_state)
-               return;
-       prev_state = state;
-
-       _I("USB state(%u) changed.", state);
-
-       ret = gdbus_signal_emit(NULL,
-                       DEVICED_PATH_USB,
-                       DEVICED_INTERFACE_USB,
-                       SIGNAL_STATE_CHANGED,
-                       g_variant_new("(u)", state));
-       if (ret < 0)
-               _E("Failed to send USB dbus signal.");
-}
-
-static void change_usb_client_mode(GDBusConnection  *conn,
-       const gchar      *sender,
-       const gchar      *path,
-       const gchar      *iface,
-       const gchar      *name,
-       GVariant         *param,
-       gpointer          data)
-
-{
-       int ret;
-       unsigned int mode;
-       int req_vconf = -1;
-
-       if (!g_variant_get_safe(param, "(i)", &req_vconf)) {
-               _E("failed to get params from gvariant. expected:%s, type:%s", "(i)", g_variant_get_type_string(param));
-               return;
-       }
-
-       if (req_vconf < 0) {
-               _E("Failed to get USB req_vconf.");
-               return;
-       }
-
-       _I("USB mode is changed by dbus signal to %d.", req_vconf);
-
-       mode = get_mode_bitmap_from_vconf(req_vconf);
-
-       if (mode == USB_FUNCTION_INVALID) {
-               _E("Failed to convert vconf to USB mode. There is no mode matches up with vconf %d.", req_vconf);
-               return;
-       }
-
-       /* Deviced must never run in USB_FUNCTION_NONE mode. */
-       if (mode == USB_FUNCTION_NONE) {
-               _E("Ignore this request. There is USB_FUNCTION_NONE mode matches up with vconf %d.", req_vconf);
-               return;
-       }
-
-       ret = usb_change_mode(mode, true);
-       if (ret < 0)
-               _E("Failed to change USB mode: %d", ret);
-}
-
-/* dbus methods */
-static GVariant *get_usb_client_state(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       unsigned int state;
-
-       state = get_usb_state();
-
-       return g_variant_new("(u)", state);
-}
-
-static GVariant *get_usb_client_mode(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       unsigned int mode;
-
-       mode = usb_state_get_current_mode();
-
-       return g_variant_new("(u)", mode);
-}
-
-static const dbus_method_s dbus_methods[] = {
-       { "GetState", NULL, "u", get_usb_client_state },  /* from Tizen 2.3 */
-       { "GetMode", NULL, "u", get_usb_client_mode  },   /* from Tizen 2.3 */
-       /* Add methods here */
-};
-
-static const dbus_interface_u dbus_interface = {
-       .oh = NULL,
-       .name = DEVICED_INTERFACE_USB,
-       .methods = dbus_methods,
-       .nr_methods = ARRAY_SIZE(dbus_methods),
-};
-
-
-int usb_dbus_init(void)
-{
-       int ret;
-
-       ret = gdbus_add_object(NULL, DEVICED_PATH_USB, &dbus_interface);
-       if (ret < 0)
-               _E("Failed to init dbus method for USB: %d", ret);
-
-       ret = gdbus_signal_subscribe(NULL, DEVICED_PATH_USB,
-               DEVICED_INTERFACE_USB, "ChangeUsbMode",
-               change_usb_client_mode, NULL, NULL);
-       if (ret <= 0) {
-               _E("Failed to subscribe dbus signal for USB: %d", ret);
-               return ret;
-       }
-
-       return 0;
-}
diff --git a/src/usb/usb-debug.c b/src/usb/usb-debug.c
deleted file mode 100644 (file)
index 22b5025..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <vconf.h>
-
-#include "core/log.h"
-#include "shared/device-notifier.h"
-
-#include "usb.h"
-#include "usb-gadget.h"
-
-static bool debug_state;
-
-int get_usb_debug_state(void)
-{
-       int state;
-
-       /* Never use debug_state variable, anyone other than deviced can change this vconf. */
-
-       if (vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &state) != VCONF_OK) {
-               _E("Failed to get vconf value for USB debug mode: %d", vconf_get_ext_errno());
-               return -1;
-       }
-
-       return state;
-}
-
-void set_usb_debug_state(bool on)
-{
-       int state = on ? 1 : 0;
-
-       /*
-        * VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL can also be written outside of deviced.
-        * So you should always write regardless of the internal debug_state of deviced.
-        */
-       if (vconf_set_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, state) == VCONF_OK)
-               debug_state = on;
-       else
-               _E("Failed to set vconf value for USB debug mode: %d", vconf_get_ext_errno());
-}
-
-static void usb_debug_changed(keynode_t *key, void *data)
-{
-       int mode;
-
-       if (!key)
-               return;
-
-       mode = vconf_keynode_get_bool(key);
-
-       /* This also prevents vconf self-loop by set_usb_debug_state(). */
-       if (mode == debug_state) {
-               _I("USB debug mode is already %s.", mode ? "ON" : "OFF");
-               return;
-       }
-
-       debug_state = mode;
-
-       _I("USB debug mode is changed to %s.", mode ? "ON" : "OFF");
-
-       device_notify(DEVICE_NOTIFIER_USB_DEBUG_MODE, (void *)(intptr_t) mode);
-}
-
-static int usb_debug_mode_changed(void *on)
-{
-       int ret;
-       unsigned int new_mode;
-       bool rndis_is_enabled = false;
-       const unsigned int curr_mode = usb_state_get_selected_mode();
-
-       if (curr_mode & USB_FUNCTION_RNDIS)
-               rndis_is_enabled = true;
-
-       /*
-        * debug  on + rndis  on : USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS
-        * debug  on + rndis off : USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB
-        * debug off + rndis  on : USB_FUNCTION_RNDIS
-        * debug off + rndis off : USB_FUNCTION_MTP | USB_FUNCTION_ACM
-        */
-
-       if ((int)(intptr_t) on) {
-               if (rndis_is_enabled)
-                       new_mode = USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS;
-               else
-                       new_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB;
-       } else {
-               if (rndis_is_enabled)
-                       new_mode = USB_FUNCTION_RNDIS;
-               else
-                       new_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM;
-       }
-
-       ret = usb_change_mode(new_mode, false);
-       if (ret < 0)
-               _E("Failed to change USB mode to (%d).", new_mode);
-
-       return ret;
-}
-
-void add_usb_debug_handler(void)
-{
-       int state = 0;
-
-       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL,
-                               usb_debug_changed, NULL) != VCONF_OK)
-               _E("Failed to add USB debug handler.");
-
-       register_notifier(DEVICE_NOTIFIER_USB_DEBUG_MODE, usb_debug_mode_changed);
-
-       if (vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &state) == VCONF_OK)
-               debug_state = (state == 0 ? false : true);
-       else
-               _E("Failed to get vconf value for USB debug mode: %d", vconf_get_ext_errno());
-}
-
-void remove_usb_debug_handler(void)
-{
-       vconf_ignore_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, usb_debug_changed);
-       unregister_notifier(DEVICE_NOTIFIER_USB_DEBUG_MODE, usb_debug_mode_changed);
-}
diff --git a/src/usb/usb-debug.h b/src/usb/usb-debug.h
deleted file mode 100644 (file)
index bab0392..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __USB_DEBUG_H__
-#define __USB_DEBUG_H__
-
-#include <stdbool.h>
-
-int get_usb_debug_state(void);
-void set_usb_debug_state(bool on);
-void add_usb_debug_handler(void);
-void remove_usb_debug_handler(void);
-
-#endif /* __USB_DEBUG_H__ */
diff --git a/src/usb/usb-gadget-cfs-gadget.c b/src/usb/usb-gadget-cfs-gadget.c
deleted file mode 100644 (file)
index 61583e0..0000000
+++ /dev/null
@@ -1,645 +0,0 @@
-#include <errno.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/mount.h>
-#include <linux/limits.h>
-
-#include <usbg/usbg.h>
-#include <usbg/function/net.h>
-
-#include <libsyscommon/libsystemd.h>
-
-#include <shared/log.h>
-#include "usb-gadget.h"
-
-#define CONFIGFS_PATH "/sys/kernel/config"
-
-#define CONFIGFS_GADGET_NAME "hal-gadget"
-#define CONFIGFS_CONFIG_LABEL "hal-config"
-
-#define NAME_INSTANCE_SEP '.'
-#define MAX_INSTANCE_LEN 512
-
-#define USB_FUNCS_PATH "/dev/usb-funcs"
-
-enum cfs_function_service_operation {
-       CFS_FUNCTION_SERVICE_START,
-       CFS_FUNCTION_SERVICE_STOP,
-       CFS_FUNCTION_SERVICE_POST_STOP,
-};
-
-struct cfs_client {
-       usbg_state *ctx;
-       usbg_gadget *gadget;
-       usbg_udc *udc;
-};
-
-/* Based on values in slp-gadget kernel module */
-struct usbg_gadget_attrs default_g_attrs = {
-       .idVendor = DEFAULT_VID,
-       .idProduct = DEFAULT_PID,
-       .bcdDevice = DEFAULT_BCD_DEVICE,
-};
-
-struct usbg_gadget_strs default_g_strs = {
-       .manufacturer = DEFAULT_MANUFACTURER,
-       .product = DEFAULT_PRODUCT,
-       .serial = DEFAULT_SERIAL,
-};
-
-struct cfs_client *g_cfs_client;
-
-static struct usb_function *cfs_find_usb_function(usbg_function *function)
-{
-       char *sep;
-       char buf[MAX_INSTANCE_LEN];
-       const char *instance = usbg_get_function_instance(function);
-       const char *name = usbg_get_function_type_str(usbg_get_function_type(function));
-
-       /* Ex. name:"ffs",  instance: "sdb.default" */
-       if (strcmp(name, usbg_get_function_type_str(USBG_F_FFS)) == 0) {
-               strncpy(buf, instance, sizeof(buf) - 1);
-               buf[sizeof(buf) - 1] = '\0';
-
-               /* Ex. "sdb.default" ==> "sdb" + "default" */
-               sep = strchr(buf, NAME_INSTANCE_SEP);
-               if (!sep || !sep[1])
-                       return NULL;
-               *sep = '\0';
-
-               name = buf;
-               instance = sep + 1;
-       }
-
-       return find_usb_function_by_name_instance(name, instance);
-}
-
-static bool cfs_is_function_supported(struct usb_function *func)
-{
-       char buf[PATH_MAX];
-
-       if (func->is_functionfs) {
-               /* functionfs must have a service */
-               if (!func->service)
-                       return false;
-
-               snprintf(buf, sizeof(buf), "/usr/lib/systemd/system/%s.socket", func->service);
-               if (access(buf, F_OK))
-                       return false;
-       } else {
-               if (usbg_lookup_function_type(func->name) < 0)
-                       return false;
-       }
-
-       return true;
-}
-
-static bool cfs_is_gadget_supported(struct usb_gadget *gadget)
-{
-       int i, j;
-       struct usb_configuration *config;
-
-       if (!gadget || !gadget->configs || !gadget->configs[0] || !gadget->configs[0]->funcs[0])
-               return false;
-
-       if (!gadget->attrs.idVendor || !gadget->attrs.idProduct || !gadget->attrs.bcdDevice)
-               return false;
-
-       /* only strings in US_en are allowed */
-       if (gadget->strs.lang_code != DEFAULT_LANG)
-               return false;
-
-       if (!gadget->strs.manufacturer || !gadget->strs.product || !gadget->strs.serial)
-               return false;
-
-       for (j = 0; gadget->configs[j]; ++j) {
-               config = gadget->configs[j];
-
-               if (!config->funcs)
-                       return false;
-
-               for (i = 0; config->funcs[i]; ++i)
-                       if (!cfs_is_function_supported(config->funcs[i]))
-                               return false;
-       }
-
-       return true;
-}
-
-static int cfs_set_gadget_attrs(struct cfs_client *cfs_client,
-                               struct usb_gadget_attrs *attrs)
-{
-       int ret;
-       struct usbg_gadget_attrs gadget_attrs;
-
-       ret = usbg_get_gadget_attrs(cfs_client->gadget, &gadget_attrs);
-       if (ret)
-               return ret;
-
-       gadget_attrs.bDeviceClass = attrs->bDeviceClass;
-       gadget_attrs.bDeviceSubClass = attrs->bDeviceSubClass;
-       gadget_attrs.bDeviceProtocol = attrs->bDeviceProtocol;
-       gadget_attrs.idVendor = attrs->idVendor;
-       gadget_attrs.idProduct = attrs->idProduct;
-       gadget_attrs.bcdDevice = attrs->bcdDevice;
-
-       ret = usbg_set_gadget_attrs(cfs_client->gadget, &gadget_attrs);
-
-       return ret;
-}
-
-static int cfs_set_gadget_strs(struct cfs_client *cfs_client, struct usb_gadget_strings *strs)
-{
-       int ret;
-
-       if (!strs->manufacturer || !strs->product || !strs->serial)
-               return -EINVAL;
-
-       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_MANUFACTURER, strs->lang_code, strs->manufacturer);
-       if (ret)
-               return ret;
-
-       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_PRODUCT, strs->lang_code, strs->product);
-       if (ret)
-               return ret;
-
-       ret = usbg_set_gadget_str(cfs_client->gadget, USBG_STR_SERIAL_NUMBER, strs->lang_code, strs->serial);
-       if (ret)
-               return ret;
-
-       return 0;
-}
-
-static int cfs_ensure_dir(char *path)
-{
-       if (mkdir(path, 0770) < 0)
-               return (errno == EEXIST) ? 0 : -errno;
-
-       return 0;
-}
-
-
-static int cfs_prep_ffs_service(struct usb_function *usb_func, usbg_function *function)
-{
-       int ret;
-       const char *name;
-       const char *service;
-       const char *instance;
-       const char *dev_name;
-       char buf[MAX_INSTANCE_LEN];
-
-       if (!usb_func || !function)
-               return -EINVAL;
-
-       if (usbg_get_function_type(function) != USBG_F_FFS)
-               return -EINVAL;
-
-       name = usb_func->name;
-       service = usb_func->service;
-       instance = usb_func->instance;
-       dev_name = usbg_get_function_instance(function);
-
-       /* "/dev/usb-funcs" + "/" + "sdb" + "/" + "default"  + '0' */
-       if (strlen(USB_FUNCS_PATH) + strlen(name) + strlen(instance) + 3  > sizeof(buf))
-               return -ENAMETOOLONG;
-
-       /* mkdir /dev/usb-funcs */
-       ret = cfs_ensure_dir(USB_FUNCS_PATH);
-       if (ret < 0)
-               return ret;
-
-       /* mkdir /dev/usb-funcs/sdb */
-       snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
-       ret = cfs_ensure_dir(buf);
-       if (ret < 0)
-               goto out_rmdir;
-
-       /* mkdir /dev/usb-funcs/sdb/default */
-       snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
-       ret = cfs_ensure_dir(buf);
-       if (ret < 0)
-               goto out_rmdir;
-
-       /* mount -t functionfs sdb.default /dev/usb-funcs/sdb/default */
-       ret = mount(dev_name, buf, "functionfs", 0, NULL);
-       if (ret < 0)
-               goto out_rmdir;
-
-       /* start sdbd.socket */
-       ret = systemd_start_unit_wait_started(service, ".socket", -1);
-       if (ret < 0)
-               goto out_unmount;
-
-       return 0;
-
-out_unmount:
-       umount(buf);
-
-out_rmdir:
-       snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, name, instance);
-       rmdir(buf);
-
-       snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, name);
-       rmdir(buf);
-
-       rmdir(USB_FUNCS_PATH);
-
-       return ret;
-}
-
-static int cfs_cleanup_ffs_service(usbg_function *function)
-{
-       int ret;
-       char buf[MAX_INSTANCE_LEN];
-       struct usb_function *usb_function;
-
-       if (!function)
-               return -EINVAL;
-
-       usb_function = cfs_find_usb_function(function);
-       if (!usb_function)
-               return -ENOENT;
-
-       /* stop .socket first and stop .service later becuase of socket activation */
-       if (usb_function->service) {
-               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".socket", -1);
-               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
-       }
-
-       /* umount /dev/usb-funcs/[sdb|mtp]/default and remove it's directory */
-       ret = snprintf(buf, sizeof(buf), "%s/%s/%s", USB_FUNCS_PATH, usb_function->name, usb_function->instance);
-       if (ret < 0)
-               return ret;
-
-       ret = umount(buf);
-       if (ret < 0)
-               return ret;
-
-       ret = rmdir(buf);
-       if (ret < 0)
-               return ret;
-
-       /* remove /dev/usb-funcs/[sdb|mtp] directory */
-       ret = snprintf(buf, sizeof(buf), "%s/%s", USB_FUNCS_PATH, usb_function->name);
-       if (ret < 0)
-               return ret;
-
-       ret = rmdir(buf);
-       if (ret < 0 && errno != ENOTEMPTY)
-               return ret;
-
-       /* remove /dev/usb-funcs/ directory */
-       ret = rmdir(USB_FUNCS_PATH);
-       if (ret < 0 && errno != ENOTEMPTY)
-               return ret;
-
-       return 0;
-}
-
-
-static int cfs_set_rndis_mac_addr(usbg_gadget *gadget, usbg_function *func)
-{
-       int i, ret;
-       struct ether_addr ethaddr;
-       struct usbg_gadget_strs strs;
-       struct usbg_f_net *nf = usbg_to_net_function(func);
-
-       if (!nf)
-               return -EINVAL;
-
-       ret = usbg_get_gadget_strs(gadget, LANG_US_ENG, &strs);
-       if (ret != USBG_SUCCESS)
-               return ret;
-
-       for (i = 0; i < ETHER_ADDR_LEN; i++)
-               ethaddr.ether_addr_octet[i] = 0;
-
-       for (i = 0; (i < 256) && strs.serial[i]; i++) {
-               ethaddr.ether_addr_octet[i % (ETHER_ADDR_LEN - 1) + 1] ^= strs.serial[i];
-       }
-       ethaddr.ether_addr_octet[0] &= 0xfe;     /* clear multicast bit */
-       ethaddr.ether_addr_octet[0] |= 0x02;     /* set local assignment bit (IEEE802) */
-
-       usbg_free_gadget_strs(&strs);
-
-       /* host_addr changes mac address */
-       ret = usbg_f_net_set_host_addr(nf, &ethaddr);
-
-       return ret;
-}
-
-static int cfs_cleanup_all_config_and_function(struct cfs_client *cfs_client)
-{
-       int ret;
-       usbg_config *config;
-       usbg_function *function;
-
-       /* delete all configs */
-restart_rm_config:
-       usbg_for_each_config(config, cfs_client->gadget) {
-               ret = usbg_rm_config(config, USBG_RM_RECURSE);
-               if (ret)
-                       return ret;
-
-               goto restart_rm_config; /* You cannot delete a config directly in an iterator. */
-       }
-
-       /* delete all functions */
-restart_rm_function:
-       usbg_for_each_function(function, cfs_client->gadget) {
-               if (usbg_get_function_type(function) == USBG_F_FFS) {
-                       ret = cfs_cleanup_ffs_service(function);
-                       if (ret)
-                               return ret;
-               }
-
-               ret = usbg_rm_function(function, USBG_RM_RECURSE);
-               if (ret)
-                       return ret;
-
-               goto restart_rm_function; /* You cannot delete a function directly in an iterator. */
-       }
-
-       return 0;
-}
-
-static int cfs_set_gadget_config(struct cfs_client *cfs_client, int config_id, struct usb_configuration *usb_config)
-{
-       int i;
-       int ret;
-       int function_type;
-       usbg_config *config;
-       usbg_function *function;
-       struct usb_function *usb_func;
-       char instance[MAX_INSTANCE_LEN];
-       struct usbg_config_attrs cattrs = {
-               .bmAttributes = usb_config->attrs.bmAttributs,
-               .bMaxPower = usb_config->attrs.MaxPower/2,
-       };
-
-       if (!usb_config->funcs || !usb_config->funcs[0])
-               return -EINVAL;
-
-       ret = usbg_create_config(cfs_client->gadget, config_id, CONFIGFS_CONFIG_LABEL, &cattrs, NULL, &config);
-       if (ret)
-               return ret;
-
-       if (usb_config->strs.config_str) {
-               ret = usbg_set_config_string(config, usb_config->strs.lang_code, usb_config->strs.config_str);
-               if (ret)
-                       return ret;
-       }
-
-       for (i = 0; usb_config->funcs[i]; ++i) {
-               usb_func = usb_config->funcs[i];
-
-               /* name("sdb") + NAME_INSTANCE_SEP(".") + instance("default") + '\0' */
-               if (strlen(usb_func->name) + strlen(usb_func->instance) + 2 > sizeof(instance))
-                       return -ENAMETOOLONG;
-
-               /* In functionfs, the instance is used in the format "[sdb|mtp].default" instead of "default" */
-               if (usb_func->is_functionfs) {
-                       function_type = USBG_F_FFS;
-                       snprintf(instance, sizeof(instance), "%s%c%s", usb_func->name, NAME_INSTANCE_SEP, usb_func->instance);
-               } else {
-                       function_type = usbg_lookup_function_type(usb_func->name);
-                       strncpy(instance, usb_func->instance, sizeof(instance) - 1);
-                       instance[sizeof(instance) - 1] = '\0';
-               }
-
-               function = usbg_get_function(cfs_client->gadget, function_type, instance);
-               if (!function) {
-                       ret = usbg_create_function(cfs_client->gadget, function_type, instance, NULL, &function);
-                       if (ret)
-                               return ret;
-
-                       /* Setting rndis mac address. This should be done at this point,
-                        * since the node host_addr changes to read only after the function
-                        * is added to config. */
-                       if (usbg_get_function_type(function) == USBG_F_RNDIS)
-                               (void)cfs_set_rndis_mac_addr(cfs_client->gadget, function); /* A random value is used if fails */
-
-                       if (usbg_get_function_type(function) == USBG_F_FFS) {
-                               ret = cfs_prep_ffs_service(usb_func, function);
-                               if (ret)
-                                       return ret;
-                       }
-               }
-
-               ret = usbg_add_config_function(config, NULL, function);
-               if (ret)
-                       return ret;
-       }
-
-       return 0;
-}
-
-static void cfs_start_stop_service_and_handler(usbg_gadget *gadget, enum cfs_function_service_operation operation)
-{
-       usbg_function *function;
-       struct usb_function *usb_function;
-
-       usbg_for_each_function(function, gadget) {
-               usb_function = cfs_find_usb_function(function);
-               if (!usb_function)
-                       continue;
-
-               switch(operation) {
-               case CFS_FUNCTION_SERVICE_START:
-                       if (usb_function->handler)
-                               usb_function->handler(1);
-
-                       /* functionfs service is automatically started by socket activation */
-                       if (!usb_function->is_functionfs && usb_function->service)
-                               (void)systemd_start_unit_wait_started(usb_function->service, ".service", -1);
-                       break;
-
-               case CFS_FUNCTION_SERVICE_STOP:
-                       if (!usb_function->is_functionfs && usb_function->service && !usb_function->remain_after_disable)
-                               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
-
-                       if (usb_function->handler)
-                               usb_function->handler(0);
-                       break;
-
-               case CFS_FUNCTION_SERVICE_POST_STOP:
-                       if (usb_function->is_functionfs && usb_function->service && !usb_function->remain_after_disable)
-                               (void)systemd_stop_unit_wait_stopped(usb_function->service, ".service", -1);
-                       break;
-
-               default:
-                       break;
-               }
-       }
-}
-
-static int usb_gadget_cfs_enable(void)
-{
-       int ret;
-
-       if (!g_cfs_client)
-               return -EINVAL;
-
-       ret = usbg_enable_gadget(g_cfs_client->gadget, g_cfs_client->udc);
-       if (ret)
-               return ret;
-
-       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_START);
-
-       return 0;
-}
-
-static int usb_gadget_cfs_disable(void)
-{
-       int ret;
-
-       if (!g_cfs_client)
-               return -EINVAL;
-
-       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_STOP);
-
-       ret = usbg_disable_gadget(g_cfs_client->gadget); /* ignore error checking */
-
-       /*
-        * Since functionfs service works with socket activation, you must stop it after disabling gadget.
-        * If usb data may come in after stopping functionfs service and before disabling gadget,
-        * functionfs service wakes up again by socket activation.
-        */
-       cfs_start_stop_service_and_handler(g_cfs_client->gadget, CFS_FUNCTION_SERVICE_POST_STOP);
-
-       return ret;
-}
-
-static int usb_gadget_cfs_reconfigure_gadget(struct usb_gadget *gadget)
-{
-       int i;
-       int ret;
-
-       if (!g_cfs_client || !gadget)
-               return -EINVAL;
-
-       /* Verify the gadget and check if function is supported */
-       if (!cfs_is_gadget_supported(gadget))
-               return -ENOTSUP;
-
-       ret = cfs_set_gadget_attrs(g_cfs_client, &gadget->attrs);
-       if (ret)
-               return ret;
-
-       ret = cfs_set_gadget_strs(g_cfs_client, &gadget->strs);
-       if (ret)
-               return ret;
-
-       ret = cfs_cleanup_all_config_and_function(g_cfs_client);
-       if (ret)
-               return ret;
-
-       for (i = 0; gadget->configs[i]; ++i) {
-               ret = cfs_set_gadget_config(g_cfs_client, i + 1, gadget->configs[i]);
-               if (ret)
-                       return ret;
-       }
-
-       return 0;
-}
-
-static int usb_gadget_cfs_open(void)
-{
-       int ret;
-
-       g_cfs_client = calloc(1, sizeof(*g_cfs_client));
-       if (!g_cfs_client)
-               return -ENOMEM;
-
-       ret = usbg_init(CONFIGFS_PATH, &g_cfs_client->ctx);
-       if (ret)
-               goto err_usbg_init;
-
-       g_cfs_client->udc = usbg_get_first_udc(g_cfs_client->ctx);
-       if (!g_cfs_client->udc) {
-               ret = -ENODEV;
-               goto err_no_udc;
-       }
-
-       ret = usbg_create_gadget(g_cfs_client->ctx, CONFIGFS_GADGET_NAME,
-                                &default_g_attrs, &default_g_strs, &g_cfs_client->gadget);
-       if (ret)
-               goto err_create_gadget;
-
-       return 0;
-
-err_create_gadget:
-err_no_udc:
-       usbg_cleanup(g_cfs_client->ctx);
-err_usbg_init:
-       free(g_cfs_client);
-
-       return ret;
-}
-
-static int usb_gadget_cfs_close(void)
-{
-       usbg_function *function;
-       struct usb_function *usb_func;
-
-       if (!g_cfs_client)
-               return -EINVAL;
-
-       usbg_for_each_function(function, g_cfs_client->gadget) {
-               usb_func = cfs_find_usb_function(function);
-               if (!usb_func)
-                       continue;
-
-               if (usb_func->is_functionfs && usb_func->service) {
-                       (void)systemd_stop_unit_wait_stopped(usb_func->service, ".socket", -1);
-                       (void)systemd_stop_unit_wait_stopped(usb_func->service, ".service", -1);
-               }
-       }
-
-       /*
-        * For now we don't check for errors
-        * but we should somehow handle them
-        */
-       usbg_rm_gadget(g_cfs_client->gadget, USBG_RM_RECURSE);
-       usbg_cleanup(g_cfs_client->ctx);
-       free(g_cfs_client);
-
-       return 0;
-}
-
-int usb_gadget_cfs_supported(void)
-{
-       FILE *fp;
-       char *line = NULL;
-       size_t len = 0;
-       int configfs = 0;
-
-       fp = fopen("/proc/filesystems", "r");
-       if (!fp)
-               return 0;
-
-       while (getline(&line, &len, fp) != -1) {
-               if (strstr(line, "configfs"))
-                       configfs = 1;
-       }
-
-       fclose(fp);
-       free(line);
-
-       if (configfs)
-               CRITICAL_LOG("Usb-gadget is supported via configfs.");
-
-       return configfs;
-}
-
-void usb_gadget_bind_cfs_gadget(int (**open) (void), int (**close) (void), int (**enable) (void),
-       int (**disable) (void), int (**reconfigure) (struct usb_gadget *))
-{
-       *open = usb_gadget_cfs_open;
-       *close = usb_gadget_cfs_close;
-       *enable = usb_gadget_cfs_enable;
-       *disable = usb_gadget_cfs_disable;
-       *reconfigure = usb_gadget_cfs_reconfigure_gadget;
-}
diff --git a/src/usb/usb-gadget-legacy-gadget.c b/src/usb/usb-gadget-legacy-gadget.c
deleted file mode 100644 (file)
index aa1f6b1..0000000
+++ /dev/null
@@ -1,358 +0,0 @@
-
-#include <stdio.h>
-#include <errno.h>
-#include <string.h>
-#include <stdbool.h>
-#include <linux/limits.h>
-
-#include <libsyscommon/file.h>
-#include <libsyscommon/libsystemd.h>
-
-#include <shared/log.h>
-#include "usb-gadget.h"
-
-#define MAX_GADGET_STR_LEN 256
-
-#define LEGACY_ROOTPATH        "/sys/class/usb_mode/usb0"
-
-/* Device descriptor values */
-#define LEGACY_ID_VENDOR_PATH       LEGACY_ROOTPATH"/idVendor"
-#define LEGACY_ID_PRODUCT_PATH      LEGACY_ROOTPATH"/idProduct"
-#define LEGACY_BCD_DEVICE_PATH      LEGACY_ROOTPATH"/bcdDevice"
-#define LEGACY_CLASS_PATH           LEGACY_ROOTPATH"/bDeviceClass"
-#define LEGACY_SUBCLASS_PATH        LEGACY_ROOTPATH"/bDeviceSubClass"
-#define LEGACY_PROTOCOL_PATH        LEGACY_ROOTPATH"/bDeviceProtocol"
-
-/* Strings */
-#define LEGACY_IMANUFACTURER_PATH   LEGACY_ROOTPATH"/iManufacturer"
-#define LEGACY_IPRODUCT_PATH        LEGACY_ROOTPATH"/iProduct"
-
-/* Functions in each config */
-#define LEGACY_CONFIG_1_PATH        LEGACY_ROOTPATH"/funcs_fconf"
-#define LEGACY_CONFIG_2_PATH        LEGACY_ROOTPATH"/funcs_sconf"
-
-/* should be single char */
-#define LEGACY_FUNC_SEP             ","
-
-/* ON/OFF switch */
-#define LEGACY_ENABLE_PATH          LEGACY_ROOTPATH"/enable"
-#define LEGACY_ENABLE               "1"
-#define LEGACY_DISABLE              "0"
-
-static bool legacy_is_function_supported(struct usb_function *func)
-{
-       char buf[PATH_MAX];
-
-       snprintf (buf, sizeof(buf), "%s/f_%s", LEGACY_ROOTPATH, func->name);
-       if (access(buf, F_OK))
-               return false;
-
-       return true;
-}
-
-static bool legacy_is_gadget_supported(struct usb_gadget *gadget)
-{
-       int i, j;
-       struct usb_configuration *config;
-
-       if (!gadget || !gadget->configs || !gadget->configs[0] || !gadget->configs[0]->funcs[0])
-               return false;
-
-       if (!gadget->attrs.idVendor || !gadget->attrs.idProduct || !gadget->attrs.bcdDevice)
-                       return false;
-
-       /* only strings in US_en are allowed */
-       if (gadget->strs.lang_code != DEFAULT_LANG)
-                       return false;
-
-       if (!gadget->strs.manufacturer || !gadget->strs.product)
-               return false;
-
-       for (j = 0; gadget->configs[j]; ++j) {
-               config = gadget->configs[j];
-
-               if (!config->funcs)
-                       return false;
-
-               for (i = 0; config->funcs[i]; ++i)
-                       if (!legacy_is_function_supported(config->funcs[i]))
-                               return false;
-       }
-
-       return true;
-}
-
-/* TODO. Maybe move this to sys ? */
-static int legacy_set_int_hex(char *path, int val)
-{
-       int r;
-       char buf[MAX_GADGET_STR_LEN];
-
-       if (!path)
-               return -EINVAL;
-
-       snprintf(buf, sizeof(buf), "%x", val);
-       r = sys_set_str(path, buf);
-       if (r < 0)
-               return r;
-
-       return 0;
-}
-
-static int legacy_set_gadget_attrs(struct usb_gadget_attrs *attrs)
-{
-       int ret;
-
-       ret = sys_set_int(LEGACY_CLASS_PATH, attrs->bDeviceClass);
-       if (ret)
-               return ret;
-
-       ret = sys_set_int(LEGACY_SUBCLASS_PATH, attrs->bDeviceSubClass);
-       if (ret)
-               return ret;
-
-       ret = sys_set_int(LEGACY_PROTOCOL_PATH, attrs->bDeviceProtocol);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_int_hex(LEGACY_ID_VENDOR_PATH, attrs->idVendor);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_int_hex(LEGACY_ID_PRODUCT_PATH, attrs->idProduct);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_int_hex(LEGACY_BCD_DEVICE_PATH, attrs->bcdDevice);
-       if (ret)
-               return ret;
-
-       return 0;
-}
-
-static int legacy_set_gadget_strs(struct usb_gadget_strings *strs)
-{
-       int ret;
-
-       if (!strs->manufacturer || !strs->product)
-               return -EINVAL;
-
-       ret = sys_set_str(LEGACY_IMANUFACTURER_PATH, strs->manufacturer);
-       if (ret)
-               return ret;
-
-       ret = sys_set_str(LEGACY_IPRODUCT_PATH, strs->product);
-       if (ret)
-               return ret;
-
-       /* The serial is written by the slp gadget kernel driver */
-
-       return 0;
-}
-
-static int legacy_set_gadget_config(char *cpath,
-                                   struct usb_configuration *config)
-{
-       char buf[MAX_GADGET_STR_LEN];
-       int left = sizeof(buf);
-       char *pos = buf;
-       int ret;
-       int i;
-
-       if (!config) {
-               buf[0] = '\n';
-               buf[1] = '\0';
-               goto empty_config;
-       }
-
-       for (i = 0; config->funcs[i]; ++i) {
-               ret = snprintf(pos, left, "%s" LEGACY_FUNC_SEP,
-                              config->funcs[i]->name);
-               if (ret >= left)
-                       return -EOVERFLOW;
-
-               pos += ret;
-               left -= ret;
-       }
-
-       /* eliminate last separator */
-       *(pos - 1) = '\0';
-
-empty_config:
-       return sys_set_str(cpath, buf);
-}
-
-static void legacy_start_stop_service_and_handler(bool start)
-{
-       int i;
-       int ret;
-       int n_func = 0;
-       char *ptr;
-       char *begin;
-       char *fname;
-       char *sep = LEGACY_FUNC_SEP;
-       char buf[MAX_GADGET_STR_LEN];
-       struct usb_function *func;
-       struct usb_function *funcs[USB_FUNCTION_IDX_MAX];
-
-       /* SLP gadget uses two USB configuration.
-        * (/sys/class/usb_mode/usb0/funcs_fconf and /sys/class/usb_mode/usb0/funcs_sconf)
-        *
-        * One usb function can be included in two configurations simultaneously.
-        * In this situation, a handler associated with function can be called twice for a usb function.
-        * To prevent duplicate calls,
-        * Collect all functions and remove duplicates and process them.
-        */
-
-       /* First configuration */
-       ret = sys_get_str(LEGACY_CONFIG_1_PATH, buf, sizeof(buf));
-       if (ret)
-               goto second_configuration;
-
-       /* Caution: buf ends with '\n' */
-       ptr = strchr(buf, '\n');
-       if (ptr)
-               *ptr = 0;
-
-       begin = buf;
-       for (fname = strsep(&begin, sep); fname; fname = strsep(&begin, sep)) {
-               func = find_usb_function_by_name(fname);
-               if (!func)
-                       continue;
-
-               for (i = 0; i < n_func; i++)
-                       if (funcs[i] == func)
-                               continue;
-
-               if(n_func >= USB_FUNCTION_IDX_MAX) /* What happen */
-                       break;
-
-               funcs[n_func] = func;
-               n_func++;
-       }
-
-       /* Second configuration */
-second_configuration:
-       ret = sys_get_str(LEGACY_CONFIG_2_PATH, buf, sizeof(buf));
-       if (ret)
-               return;
-
-       /* Caution: buf ends with '\n' */
-       ptr = strchr(buf, '\n');
-       if (ptr)
-               *ptr = 0;
-
-       begin = buf;
-       for (fname = strsep(&begin, sep); fname; fname = strsep(&begin, sep)) {
-               func = find_usb_function_by_name(fname);
-               if (!func)
-                       continue;
-
-               for (i = 0; i < n_func; i++)
-                       if (funcs[i] == func)
-                               continue;
-
-               if(n_func >= USB_FUNCTION_IDX_MAX) /* What happen */
-                       break;
-
-               funcs[n_func] = func;
-               n_func++;
-       }
-
-       for (i = 0; i < n_func; i++) {
-               if (start) {
-                       if (funcs[i]->handler)
-                               funcs[i]->handler(1);
-
-                       if (funcs[i]->service)
-                               (void)systemd_start_unit_wait_started(funcs[i]->service, ".service", -1);
-               } else {
-                       if (funcs[i]->service && !funcs[i]->remain_after_disable)
-                               (void)systemd_stop_unit_wait_stopped(funcs[i]->service, ".service", -1);
-
-                       if (funcs[i]->handler)
-                               funcs[i]->handler(0);
-               }
-       }
-}
-
-static int usb_gadget_legacy_enable(void)
-{
-       int ret;
-
-       ret = sys_set_str(LEGACY_ENABLE_PATH, LEGACY_ENABLE);
-       if (ret < 0)
-               return ret;
-
-       legacy_start_stop_service_and_handler(true);
-
-       return 0;
-}
-
-static int usb_gadget_legacy_disable(void)
-{
-       legacy_start_stop_service_and_handler(false);
-
-       return sys_set_str(LEGACY_ENABLE_PATH, LEGACY_DISABLE);
-}
-
-static int usb_gadget_legacy_reconfigure_gadget(struct usb_gadget *gadget)
-{
-       int ret;
-
-       if (!gadget)
-               return -EINVAL;
-
-       /* Verify the gadget and check if function is supported */
-       if (!legacy_is_gadget_supported(gadget))
-               return -ENOTSUP;
-
-       ret = legacy_set_gadget_attrs(&gadget->attrs);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_gadget_strs(&gadget->strs);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_gadget_config(LEGACY_CONFIG_1_PATH, gadget->configs[0]);
-       if (ret)
-               return ret;
-
-       ret = legacy_set_gadget_config(LEGACY_CONFIG_2_PATH, gadget->configs[1]);
-       if (ret)
-               return ret;
-
-       return 0;
-}
-
-static int usb_gadget_legacy_open(void)
-{
-       return 0;
-}
-
-static int usb_gadget_legacy_close(void)
-{
-       return 0;
-}
-
-int usb_gadget_legacy_supported(void)
-{
-       int ret;
-
-       ret = (access("/sys/class/usb_mode/usb0/enable", F_OK) == 0);
-       if (ret)
-               CRITICAL_LOG("Usb-gadget is supported via legacy samsung gadget.");
-
-       return ret;
-}
-
-void usb_gadget_bind_legacy_gadget(int (**open) (void), int (**close) (void), int (**enable) (void),
-       int (**disable) (void), int (**reconfigure) (struct usb_gadget *))
-{
-       *open = usb_gadget_legacy_open;
-       *close = usb_gadget_legacy_close;
-       *enable = usb_gadget_legacy_enable;
-       *disable = usb_gadget_legacy_disable;
-       *reconfigure = usb_gadget_legacy_reconfigure_gadget;
-}
diff --git a/src/usb/usb-gadget.c b/src/usb/usb-gadget.c
deleted file mode 100644 (file)
index efa1da8..0000000
+++ /dev/null
@@ -1,465 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-
-#include <libsyscommon/libsystemd.h>
-#include <libsyscommon/list.h>
-#include <vconf-internal-usb-keys.h>
-
-#include <shared/log.h>
-
-#include "usb-gadget.h"
-
-static int (*__usb_gadget_open) (void);
-static int (*__usb_gadget_close) (void);
-static int (*__usb_gadget_enable) (void);
-static int (*__usb_gadget_disable) (void);
-static int (*__usb_gadget_reconfigure) (struct usb_gadget *gadget);
-
-/* temporary extern access */
-struct _usb_mode_mapping_table {
-       int          mode_v; /* Integer defined by vconf */
-       unsigned int mode;   /* Bitmap of usb function combination */
-       struct usb_gadget_attrs attrs;
-};
-extern GList *usb_mode_mapping_table_custom;
-
-static void rndis_handler(int enable)
-{
-       if (enable)
-               (void)systemd_start_unit_wait_started("rndis.service", NULL, -1);
-       else
-               (void)systemd_stop_unit_wait_stopped("rndis.service", NULL, -1);
-}
-
-#define DEFINE_USB_FUNCTION(_id, _name, _is_functionfs, _service, _handler)  \
-       static struct usb_function _##_name##_function = {                   \
-               .id = _id,                                                   \
-               .name = #_name,                                              \
-               .instance = "default",                                       \
-               .is_functionfs = _is_functionfs,                             \
-               .service = _service,                                         \
-               .remain_after_disable = 0,                                   \
-               .handler = _handler,                                         \
-       }
-
-DEFINE_USB_FUNCTION(USB_FUNCTION_MTP,         mtp,         1, "mtp-responder", NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_ACM,         acm,         0, "data-router",   NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_SDB,         sdb,         1, "sdbd",          NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_RNDIS,       rndis,       0, "sshd",          rndis_handler);
-DEFINE_USB_FUNCTION(USB_FUNCTION_DIAG,        diag,        1, "diag",          NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_CONN_GADGET, conn_gadget, 0, NULL,            NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_DM,          dm,          0, NULL,            NULL);
-DEFINE_USB_FUNCTION(USB_FUNCTION_RMNET,       rmnet,       0, NULL,            NULL);
-
-#undef DEFINE_USB_FUNCTION
-
-/* Caution: index order of arrary is important, because simple_translator_open() uses it. */
-static struct usb_function *_available_funcs[] = {
-       [USB_FUNCTION_IDX_MTP]         = &_mtp_function,
-       [USB_FUNCTION_IDX_ACM]         = &_acm_function,
-       [USB_FUNCTION_IDX_SDB]         = &_sdb_function,
-       [USB_FUNCTION_IDX_RNDIS]       = &_rndis_function,
-       [USB_FUNCTION_IDX_DIAG]        = &_diag_function,
-       [USB_FUNCTION_IDX_CONN_GADGET] = &_conn_gadget_function,
-       [USB_FUNCTION_IDX_DM]          = &_dm_function,
-       [USB_FUNCTION_IDX_RMNET]       = &_rmnet_function,
-       [USB_FUNCTION_IDX_MAX]         = NULL /* An indicator to end the array */
-};
-static struct usb_function *find_usb_function_by_id(int id);
-
-struct usb_function *find_usb_function_by_name(const char *name)
-{
-       int i;
-
-       if(!name || !name[0])
-               return NULL;
-
-       for (i = 0; _available_funcs[i]; i++)
-               if (!strcmp(name, _available_funcs[i]->name))
-                       return _available_funcs[i];
-
-       return NULL;
-}
-
-struct usb_function *find_usb_function_by_name_instance(const char *name, const char *instance)
-{
-       int i;
-
-       if(!name || !name[0] || !instance || !instance[0])
-               return NULL;
-
-       for (i = 0; _available_funcs[i]; ++i)
-               if (!strcmp(name, _available_funcs[i]->name) && !strcmp(instance, _available_funcs[i]->instance))
-                       return _available_funcs[i];
-
-       return NULL;
-}
-
-static void simple_cleanup_config(struct usb_configuration *config)
-{
-       if (!config)
-               return;
-
-       free(config->strs.config_str);
-
-       if (config->funcs)
-               free(config->funcs);
-
-       free(config);
-}
-
-static void cleanup_gadget(struct usb_gadget *gadget)
-{
-       int i;
-
-       if (!gadget)
-               return;
-
-       free(gadget->strs.manufacturer);
-       free(gadget->strs.product);
-       free(gadget->strs.serial);
-
-       if (gadget->configs) {
-               for (i = 0; gadget->configs[i]; ++i)
-                       simple_cleanup_config(gadget->configs[i]);
-
-               free(gadget->configs);
-       }
-
-       free(gadget);
-}
-
-static int alloc_default_config(struct usb_configuration **_config)
-{
-       struct usb_configuration *config;
-
-       config = calloc(1, sizeof(*config));
-       if (!config)
-               return -ENOMEM;
-
-       config->attrs.bmAttributs = DEFAULT_BMATTRIBUTES;
-       config->attrs.MaxPower = DEFAULT_MAX_POWER;
-
-       /* TODO. Here is where to set the string used in config of configfs */
-
-       *_config = config;
-
-       return 0;
-}
-
-static int alloc_default_gadget(char *serial, struct usb_gadget **_gadget)
-{
-       struct usb_gadget *gadget;
-       struct usb_configuration **configs;
-
-       gadget = calloc(1, sizeof(*gadget));
-       if (!gadget)
-               goto out;
-
-       gadget->attrs.idVendor = DEFAULT_VID;
-       gadget->attrs.idProduct = DEFAULT_PID;
-       gadget->attrs.bcdDevice = DEFAULT_BCD_DEVICE;
-
-       gadget->strs.lang_code = DEFAULT_LANG;
-       gadget->strs.manufacturer = strdup(DEFAULT_MANUFACTURER);
-       gadget->strs.product = strdup(DEFAULT_PRODUCT);
-       gadget->strs.serial = strdup(serial);
-
-       if (!gadget->strs.manufacturer || !gadget->strs.product || !gadget->strs.serial)
-               goto free_strs;
-
-       /* slp-gadget use max 2 confiuration and NULL termination */
-       configs = calloc(3, sizeof(*configs));
-       if (!configs)
-               goto free_strs;
-
-       gadget->configs = configs;
-       *_gadget = gadget;
-
-       return 0;
-
-free_strs:
-       free(gadget->strs.manufacturer);
-       free(gadget->strs.product);
-       free(gadget->strs.serial);
-       free(gadget);
-out:
-       return -ENOMEM;
-}
-
-static int id_to_gadget(struct usb_gadget_id *gadget_id, char *serial, struct usb_gadget **_gadget)
-{
-       int ret;
-       int i, j;
-       int n_configs;
-       struct usb_gadget *gadget;
-       int functions[2][sizeof(gadget_id->function_mask)*8]; /* zero terminates */
-
-       GList *elem;
-       const struct _usb_mode_mapping_table *cm = NULL;
-
-       if (!gadget_id || !serial || !_gadget)
-               return -EINVAL;
-
-       ret = alloc_default_gadget(serial, &gadget);
-       if (ret)
-               goto out;
-
-       /* find custom mode */
-       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, cm) {
-               if (cm->mode == gadget_id->function_mask)
-                       break;
-       }
-
-       if (cm) {
-               int i, j;
-
-               j = 0;
-               n_configs = 1;
-               for (i = 0; i < USB_FUNCTION_IDX_MAX; ++i) {
-                       if (cm->mode & (1 << i))
-                               functions[0][j++] = (1 << i);
-               }
-               functions[0][j] = 0;
-
-               if (cm->attrs.idVendor)
-                       gadget->attrs.idVendor = cm->attrs.idVendor;
-               if (cm->attrs.idProduct)
-                       gadget->attrs.idProduct = cm->attrs.idProduct;
-
-       } else {
-               /*
-                * Currently all gadgets use inly single configuration but
-                * slp-gadget is capable to handle two of them
-                *
-                * Order of interfaces in configuration is significant
-                * so in this switch we sort our functions in a correct order
-                */
-               switch (gadget_id->function_mask) {
-                       /* MTP, ACM, SDB */
-                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_MTP;
-                               functions[0][1] = USB_FUNCTION_ACM;
-                               functions[0][2] = 0;
-                               gadget->attrs.idProduct = 0x6860;
-                               break;
-
-                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_MTP;
-                               functions[0][1] = USB_FUNCTION_ACM;
-                               functions[0][2] = USB_FUNCTION_SDB;
-                               functions[0][3] = 0;
-                               gadget->attrs.idProduct = 0x6860;
-                               break;
-
-                               /* DIAG */
-                       case USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_MTP;
-                               functions[0][1] = USB_FUNCTION_ACM;
-                               functions[0][2] = USB_FUNCTION_SDB;
-                               functions[0][3] = USB_FUNCTION_DIAG;
-                               functions[0][4] = 0;
-                               gadget->attrs.idProduct = 0x6860;
-                               break;
-
-                               /* RNDIS */
-                       case USB_FUNCTION_RNDIS:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_RNDIS;
-                               functions[0][1] = 0;
-                               gadget->attrs.idProduct = 0x6863;
-                               break;
-
-                       case USB_FUNCTION_RNDIS | USB_FUNCTION_DIAG:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_RNDIS;
-                               functions[0][1] = USB_FUNCTION_DIAG;
-                               functions[0][2] = 0;
-                               gadget->attrs.idProduct = 0x6864;
-                               break;
-
-                       case USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_RNDIS;
-                               functions[0][1] = USB_FUNCTION_ACM;
-                               functions[0][2] = USB_FUNCTION_SDB;
-                               functions[0][3] = 0;
-                               gadget->attrs.idProduct = 0x6864;
-                               break;
-
-                               /* RMNET */
-                       case USB_FUNCTION_DIAG | USB_FUNCTION_RMNET:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_DIAG;
-                               functions[0][1] = USB_FUNCTION_RMNET;
-                               functions[0][2] = 0;
-                               gadget->attrs.idProduct = 0x685d;
-                               break;
-
-                               /* DM */
-                       case USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DM:
-                               n_configs = 1;
-                               functions[0][0] = USB_FUNCTION_ACM;
-                               functions[0][1] = USB_FUNCTION_SDB;
-                               functions[0][2] = USB_FUNCTION_DM;
-                               functions[0][3] = 0;
-                               gadget->attrs.idProduct = 0x6860;
-                               break;
-
-                       default:
-                               ret = -EINVAL;
-                               goto free_gadget;
-               };
-       }
-
-       for (j = 0; j < n_configs; ++j) {
-               int n_funcs_in_config;
-               struct usb_configuration *config;
-
-               for (i = 0; functions[j][i]; ++i);
-               n_funcs_in_config = i;
-
-               ret = alloc_default_config(&config);
-               if (ret)
-                       goto free_configs;
-
-               gadget->configs[j] = config;
-               config->funcs = calloc(n_funcs_in_config + 1, sizeof(void *));
-               if (!config->funcs)
-                       goto free_configs;
-
-               for (i = 0; functions[j][i]; ++i) {
-                       config->funcs[i] = find_usb_function_by_id(functions[j][i]);
-                       if (!config->funcs[i])
-                               goto free_configs;
-               }
-       }
-
-       *_gadget = gadget;
-
-       return 0;
-
-free_configs:
-free_gadget:
-       cleanup_gadget(gadget);
-out:
-       return ret;
-}
-
-
-static struct usb_function *find_usb_function_by_id(int id)
-{
-       int i;
-
-       for (i = 0; _available_funcs[i]; i++)
-               if (_available_funcs[i]->id == id)
-                       return _available_funcs[i];
-
-       return NULL;
-}
-
-
-int usb_gadget_enable(void)
-{
-       if (!__usb_gadget_enable) {
-               _E("Not supported usb_gadget_enable.");
-               return -ENOTSUP;
-       }
-
-       return __usb_gadget_enable();
-}
-
-int usb_gadget_disable(void)
-{
-       if (!__usb_gadget_disable) {
-               _E("Not supported usb_gadget_disable.");
-               return -ENOTSUP;
-       }
-
-       return __usb_gadget_disable();
-}
-
-int usb_gadget_change_mode(unsigned int mode)
-{
-       struct usb_gadget *gadget;
-       struct usb_gadget_id gadget_id = {0, };
-       char serial[] = "123456";
-       int ret;
-
-       if (!__usb_gadget_reconfigure) {
-               _E("Not supported usb_gadget_reconfigure.");
-               return -ENOTSUP;
-       }
-
-       gadget_id.function_mask = mode;
-
-       ret = id_to_gadget(&gadget_id, serial, &gadget);
-       if (ret) {
-               _E("Failed to id_to_gadget, %d", ret);
-               return ret;
-       }
-
-       ret = __usb_gadget_reconfigure(gadget);
-       cleanup_gadget(gadget);
-       if (ret) {
-               _E("Failed to reconfigure gadget, %d", ret);
-               return ret;
-       }
-
-       return 0;
-}
-
-int usb_gadget_init(void)
-{
-       if (usb_gadget_legacy_supported()) {
-               /* legacy samsung gadget */
-               usb_gadget_bind_legacy_gadget(&__usb_gadget_open,
-                       &__usb_gadget_close,
-                       &__usb_gadget_enable,
-                       &__usb_gadget_disable,
-                       &__usb_gadget_reconfigure);
-       } else if (usb_gadget_cfs_supported()) {
-               /* configfs/functionfs gadget */
-               usb_gadget_bind_cfs_gadget(&__usb_gadget_open,
-                       &__usb_gadget_close,
-                       &__usb_gadget_enable,
-                       &__usb_gadget_disable,
-                       &__usb_gadget_reconfigure);
-       } else {
-               CRITICAL_LOG("Usb-gadget is not supported.");
-               return -ENOTSUP;
-       }
-
-       /* open supported usb-gadget */
-       __usb_gadget_open();
-
-       /* Use mtp-responder-dummy.socket when there is no mtp-responser.socket.
-        *
-        * The mtp-responder.socket is special in the configfs environment.
-        * If mtp-responder.socket is missing, gadget configuration will fail.
-        * As a result, all usb operations do not work properly.
-        * So in environments that mtp doesn't support, use dummy mtp.
-        */
-       if (access("/usr/lib/systemd/system/mtp-responder.socket", F_OK)) {
-               _available_funcs[USB_FUNCTION_IDX_MTP]->service = "mtp-responder-dummy";
-       }
-
-       return 0;
-}
-
-int usb_gadget_exit(void)
-{
-       if (__usb_gadget_close)
-               __usb_gadget_close();
-
-       __usb_gadget_open = NULL;
-       __usb_gadget_close = NULL;
-       __usb_gadget_enable = NULL;
-       __usb_gadget_disable = NULL;
-       __usb_gadget_reconfigure = NULL;
-
-       return 0;
-}
diff --git a/src/usb/usb-gadget.h b/src/usb/usb-gadget.h
deleted file mode 100644 (file)
index e98442f..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-#ifndef __USB_GADGET_H__
-#define __USB_GADGET_H__
-
-#include <stdint.h>
-#include <device/usb-gadget.h>
-
-/*The default USB configuration */
-#define DEFAULT_VID 0x04e8
-#define DEFAULT_PID 0x6860
-#define DEFAULT_BCD_DEVICE 0x0100
-
-#define DEFAULT_LANG 0x409 /* US_en */
-#define DEFAULT_MANUFACTURER "Samsung"
-#define DEFAULT_PRODUCT "TIZEN"
-#define DEFAULT_SERIAL "01234TEST"
-
-#define DEFAULT_BMATTRIBUTES ((1 << 7) | (1 << 6))
-#define DEFAULT_MAX_POWER 500
-
-struct usb_function {
-       int id;
-       const char *name;
-       const char *instance;
-
-       int is_functionfs;
-       const char *service;
-
-       /* do not stop the service on disabling usb-gadget function */
-       int remain_after_disable;
-
-       void (*handler)(int enable);
-};
-
-struct usb_configuration_attributes {
-       uint8_t bmAttributs;
-       int MaxPower;
-};
-
-struct usb_configuration_strings {
-       uint16_t lang_code;
-       char *config_str;
-};
-
-struct usb_configuration {
-       struct usb_configuration_attributes attrs;
-       struct usb_configuration_strings strs;
-       struct usb_function **funcs;
-};
-
-struct usb_gadget_attrs {
-       uint8_t bDeviceClass;
-       uint8_t bDeviceSubClass;
-       uint8_t bDeviceProtocol;
-       uint16_t idVendor;
-       uint16_t idProduct;
-       uint16_t bcdDevice;
-};
-
-struct usb_gadget_strings {
-       uint16_t lang_code;
-       char *manufacturer;
-       char *product;
-       char *serial;
-};
-
-struct usb_gadget {
-       struct usb_gadget_attrs attrs;
-       struct usb_gadget_strings strs;
-       struct usb_configuration **configs;
-};
-
-struct usb_gadget_id {
-       unsigned int function_mask;
-};
-
-enum {
-       USB_FUNCTION_IDX_MTP         = 0,
-       USB_FUNCTION_IDX_ACM         = 1,
-       USB_FUNCTION_IDX_SDB         = 2,
-       USB_FUNCTION_IDX_RNDIS       = 3,
-       USB_FUNCTION_IDX_DIAG        = 4,
-       USB_FUNCTION_IDX_CONN_GADGET = 5,
-       USB_FUNCTION_IDX_DM          = 6,
-       USB_FUNCTION_IDX_RMNET       = 7,
-       USB_FUNCTION_IDX_MAX         = USB_FUNCTION_IDX_RMNET + 1
-};
-
-
-struct usb_function *find_usb_function_by_name(const char *name);
-struct usb_function *find_usb_function_by_name_instance(const char *name, const char *instance);
-
-int usb_gadget_enable(void);
-int usb_gadget_disable(void);
-int usb_gadget_change_mode(unsigned int mode);
-int usb_gadget_init(void);
-int usb_gadget_exit(void);
-
-/* legacy samsung gadget */
-int usb_gadget_legacy_supported(void);
-void usb_gadget_bind_legacy_gadget(int (**open) (void),
-       int (**close) (void),
-       int (**enable) (void),
-       int (**disable) (void),
-       int (**reconfigure) (struct usb_gadget *));
-
-/* configfs/functionfs gadget */
-int usb_gadget_cfs_supported(void);
-void usb_gadget_bind_cfs_gadget(int (**open) (void),
-       int (**close) (void),
-       int (**enable) (void),
-       int (**disable) (void),
-       int (**reconfigure) (struct usb_gadget *));
-
-#endif //__USB_GADGET_H__
diff --git a/src/usb/usb-state.c b/src/usb/usb-state.c
deleted file mode 100644 (file)
index d05f9a3..0000000
+++ /dev/null
@@ -1,503 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <string.h>
-#include <vconf.h>
-#include <bundle.h>
-#include <eventsystem.h>
-#include <libsyscommon/ini-parser.h>
-
-#include "core/log.h"
-#include "apps/apps.h"
-#include "extcon/extcon.h"
-
-#include "usb.h"
-#include "usb-debug.h"
-#include "usb-gadget.h"
-
-#define PATH_USB_GADGET_CONF    "/hal/etc/deviced/usb_gadget.conf"
-
-static int noti_id = -1;
-
-static unsigned int usb_current_mode = USB_FUNCTION_NONE;
-static unsigned int usb_selected_mode = USB_FUNCTION_NONE;
-
-static extcon_usb_state_e usb_connection = USB_DISCONNECTED;
-
-/**
- * Important
- * You must keep the order for the specific items.
- *
- * There may be several mode_v for a mode.
- * In this case, the representative value should be placed on top.
- *
- * In case of SET_USB_SDB_DIAG and SET_USB_DIAG_SDB, the SET_USB_SDB_DIAG should be above.
- * As another example, SET_USB_RNDIS_SDB should be at the top of them.
- */
-static const struct _usb_mode_mapping_table {
-       int          mode_v; /* Integer defined by vconf */
-       unsigned int mode;   /* Bitmap of usb function combination */
-       struct usb_gadget_attrs attrs;
-} usb_mode_mapping_table[] = {
-       /* Hack for performance. In most cases this is the value. */
-       {SET_USB_DEFAULT,         USB_FUNCTION_MTP | USB_FUNCTION_ACM},
-       {SET_USB_SDB,             USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB},
-
-       {SET_USB_NONE,            USB_FUNCTION_NONE},
-       {SET_USB_RNDIS,           USB_FUNCTION_RNDIS},
-       {SET_USB_RNDIS_DIAG,      USB_FUNCTION_RNDIS | USB_FUNCTION_DIAG},
-       {SET_USB_DIAG_RMNET,      USB_FUNCTION_DIAG | USB_FUNCTION_RMNET},
-       {SET_USB_ACM_SDB_DM,      USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DM},
-
-       {SET_USB_SDB_DIAG,        USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG},
-       {SET_USB_DIAG_SDB,        USB_FUNCTION_MTP | USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_DIAG},
-
-       {SET_USB_RNDIS_SDB,       USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
-       {SET_USB_RNDIS_TETHERING, USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
-       {SET_USB_RNDIS_SDB_ACM,   USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS},
-};
-
-static const int mapping_table_len = sizeof(usb_mode_mapping_table) / sizeof(usb_mode_mapping_table[0]);
-
-/*
- * Private, custom defined mode mapping.
- * You can define custom mode_v with mode from /hal/etc/deviced/usb_gadget.conf
- * A custom mapping precedes the above default mapping if the custom mode_v overlaps
- * default mode_v.
- *
- * Do not declare it with static storage class as it will be exported as dynamic symbol
- * so that dlopen-ed device-common can refer it.
- */
-GList *usb_mode_mapping_table_custom;
-
-/*
- * Do not declare it with static storage class as it will be exported as dynamic symbol
- * so that dlopen-ed device-common can refer it.
- */
-struct service_config {
-       char name[128];
-       int remain_after_disable; /* do not stop the service on disabling usb-gadget function */
-};
-GList *service_config_list;
-
-unsigned int get_mode_bitmap_from_vconf(int mode_v)
-{
-       int i;
-       GList *elem;
-       struct _usb_mode_mapping_table *table;
-
-       /* lookup from custom mapping table first */
-       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, table) {
-               if (table->mode_v == mode_v)
-                       return table->mode;
-       }
-
-       /* and then lookup the default mapping table */
-       for (i = 0; i < mapping_table_len; i++) {
-               if (usb_mode_mapping_table[i].mode_v == mode_v)
-                       return usb_mode_mapping_table[i].mode;
-       }
-
-       return USB_FUNCTION_INVALID;
-}
-
-static int get_mode_vconf_from_bitmap(unsigned int mode)
-{
-       int i;
-       GList *elem;
-       struct _usb_mode_mapping_table *table;
-
-       /* lookup from custom mapping table first */
-       SYS_G_LIST_FOREACH(usb_mode_mapping_table_custom, elem, table) {
-               if (table->mode == mode)
-                       return table->mode_v;
-       }
-
-       /* Caution: The order to search the usb_mode_mapping_table must start with a low index. */
-       for (i = 0; i < mapping_table_len; i++) {
-               if (usb_mode_mapping_table[i].mode == mode)
-                       return usb_mode_mapping_table[i].mode_v;
-       }
-
-       return SET_USB_INVALID;
-}
-
-static void usb_state_send_system_event(int status)
-{
-       bundle *b;
-       const char *str;
-
-       switch (status) {
-       case VCONFKEY_SYSMAN_USB_DISCONNECTED:
-               str = EVT_VAL_USB_DISCONNECTED;
-               break;
-
-       case VCONFKEY_SYSMAN_USB_CONNECTED:
-               str = EVT_VAL_USB_CONNECTED;
-               break;
-
-       case VCONFKEY_SYSMAN_USB_AVAILABLE:
-               str = EVT_VAL_USB_AVAILABLE;
-               break;
-
-       default:
-               return;
-       }
-
-       _I("USB system_event (%s)", str);
-
-       b = bundle_create();
-       bundle_add_str(b, EVT_KEY_USB_STATUS, str);
-       eventsystem_send_system_event(SYS_EVENT_USB_STATUS, b);
-       bundle_free(b);
-}
-
-static void parse_property_systemd_unit(gpointer data, gpointer udata)
-{
-       struct section_property *prop = (struct section_property *) data;
-       struct service_config *svc = (struct service_config *) udata;
-
-       if (MATCH(prop->key, "Service")) {
-               strncpy(svc->name, prop->value, sizeof(svc->name) - 1);
-               svc->name[sizeof(svc->name) - 1] = '\0';
-       } else if (MATCH(prop->key, "RemainAfterDisable")) {
-               svc->remain_after_disable = MATCH(prop->value, "yes");
-       }
-}
-
-static unsigned int parse_usb_function(char *fstr)
-{
-       // Parse Function=, e.g., "Function=diag,acm"
-       unsigned int ret = USB_FUNCTION_NONE;
-       char *p, *saveptr;
-
-       if (!fstr)
-               return ret;
-
-       p = strtok_r(fstr, ",", &saveptr);
-       if (!p)
-               return ret;
-
-       do {
-               if (strncasecmp(p, "mtp", sizeof("mtp")) == 0) {
-                       ret |= USB_FUNCTION_MTP;
-               } else if (strncasecmp(p, "acm", sizeof("acm")) == 0) {
-                       ret |= USB_FUNCTION_ACM;
-               } else if(strncasecmp(p, "sdb", sizeof("sdb")) == 0) {
-                       ret |= USB_FUNCTION_SDB;
-               } else if (strncasecmp(p, "rndis", sizeof("rndis")) == 0) {
-                       ret |= USB_FUNCTION_RNDIS;
-               } else if (strncasecmp(p, "diag", sizeof("diag")) == 0) {
-                       ret |= USB_FUNCTION_DIAG;
-               } else if (strncasecmp(p, "conngadget", sizeof("conngadget")) == 0) {
-                       ret |= USB_FUNCTION_CONN_GADGET;
-               } else if (strncasecmp(p, "dm", sizeof("dm")) == 0) {
-                       ret |= USB_FUNCTION_DM;
-               } else if (strncasecmp(p, "rmnet", sizeof("rmnet")) == 0) {
-                       ret |= USB_FUNCTION_RMNET;
-               }
-       } while ((p = strtok_r(NULL, ",", &saveptr)));
-
-       return ret;
-}
-
-static void parse_property_attribute(gpointer data, gpointer udata)
-{
-       struct section_property *prop = (struct section_property *) data;
-       struct _usb_mode_mapping_table *table = (struct _usb_mode_mapping_table *) udata;
-       unsigned int value;
-
-       if (MATCH(prop->key, "Mode")) {
-               sscanf(prop->value, "%d", &table->mode_v);
-       } else if (MATCH(prop->key, "Function")) {
-               table->mode = parse_usb_function(prop->value);
-       } else if (MATCH(prop->key, "bDeviceClass")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.bDeviceClass = (uint8_t) value;
-       } else if (MATCH(prop->key, "bDeviceSubClass")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.bDeviceSubClass = (uint8_t) value;
-       } else if (MATCH(prop->key, "bDeviceProtocol")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.bDeviceProtocol = (uint8_t) value;
-       } else if (MATCH(prop->key, "idVendor")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.idVendor = (uint16_t) value;
-       } else if (MATCH(prop->key, "idProduct")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.idProduct = (uint16_t) value;
-       } else if (MATCH(prop->key, "bcdDevice")) {
-               sscanf(prop->value, "%x", &value);
-               table->attrs.bcdDevice = (uint16_t) value;
-       }
-}
-
-static int load_usb_gadget_config(const struct parse_result *result, void *data)
-{
-       if (MATCH(result->section, "SystemdUnit")) {
-               struct service_config svc = { 0, };
-               void *entry = NULL;
-
-               g_list_foreach(result->props, parse_property_systemd_unit, &svc);
-
-               entry = malloc(sizeof(struct service_config));
-               if (!entry) {
-                       _E("Failed to alloc service config");
-                       return 0;
-               }
-
-               _I("usb-gadget service config: name=%s, remain_after_disable=%d",
-                       svc.name, svc.remain_after_disable);
-               service_config_list = g_list_prepend(service_config_list, memcpy(entry, &svc, sizeof(svc)));
-
-       } else if (MATCH(result->section, "Attribute")) {
-               struct _usb_mode_mapping_table table = { 0, };
-               void *entry = NULL;
-
-               g_list_foreach(result->props, parse_property_attribute, &table);
-
-               // if it hasn't defined mode, use default or pre-defined one
-               if (table.mode == USB_FUNCTION_NONE)
-                       table.mode = get_mode_bitmap_from_vconf(table.mode_v);
-
-               if (table.mode == USB_FUNCTION_INVALID)
-                       return 0;
-
-               if (table.mode_v >= SET_USB_NONE && table.mode_v <= SET_USB_RNDIS_SDB_ACM)
-                       _W("The custom mode=%d replaces the predefined usb-gadget configuration", table.mode_v);
-
-               entry = malloc(sizeof(struct _usb_mode_mapping_table));
-               if (!entry) {
-                       _E("Failed to alloc mapping table");
-                       return 0;
-               }
-
-               _I("Custom usb-gadget: mode=%d, function=%#x, idVendor=%#x, idProduct=%#x",
-                       table.mode_v, table.mode, table.attrs.idVendor, table.attrs.idProduct);
-
-               usb_mode_mapping_table_custom = g_list_prepend(usb_mode_mapping_table_custom, memcpy(entry, &table, sizeof(table)));
-       }
-
-       return 0;
-}
-
-void usb_state_load_custom_mode(void)
-{
-       libsys_config_parse_by_section(PATH_USB_GADGET_CONF, load_usb_gadget_config, NULL);
-}
-
-void usb_state_retrieve_selected_mode(void)
-{
-       int mode_v;
-       unsigned int mode;
-       const unsigned int default_mode = USB_FUNCTION_MTP | USB_FUNCTION_ACM;
-
-       /* Never return here because deviced must never run in USB_FUNCTION_NONE mode */
-       if (vconf_get_int(VCONFKEY_USB_SEL_MODE, &mode_v) != VCONF_OK) {
-               mode_v = SET_USB_INVALID;
-               _E("Failed to get vconf value for USB sel mode: %d", vconf_get_ext_errno());
-       }
-
-       mode = get_mode_bitmap_from_vconf(mode_v);
-
-       /*
-        * Deviced must never run in USB_FUNCTION_NONE mode.
-        * So if vconf value is invalid, deviced uses the default usb mode internally.
-        * Keep the problematic vconf values in order to define the problem correctly.
-        */
-       switch (mode) {
-       case USB_FUNCTION_INVALID: /* Invalid vconf */
-               usb_selected_mode = default_mode;
-               _E("Failed to convert vconf to USB mode. There is no mode matches up with vconf %d. Use default mode=%#x.", mode_v, default_mode);
-               break;
-
-       case USB_FUNCTION_NONE: /* Invalid vconf */
-               usb_selected_mode = default_mode;
-               _E("There is USB_FUNCTION_NONE USB mode matches up with vconf %d. Use default mode=%#x.", mode_v, default_mode);
-               break;
-
-       default: /* Success */
-               usb_selected_mode = mode;
-               _I("Succeeded to convert vconf to USB mode. vconf=%d, mode=%#x.", mode_v, mode);
-               break;
-       }
-
-       /* To sync with vconf for debug mode */
-       set_usb_debug_state((bool)(usb_selected_mode & USB_FUNCTION_SDB));
-}
-
-/* Cache of vconf_get_int(VCONFKEY_USB_SEL_MODE) */
-unsigned int usb_state_get_selected_mode(void)
-{
-       return usb_selected_mode;
-}
-
-/* Since it is changed externally by dbus and vconf, it should be processed even if it has the same value as before. */
-int usb_state_set_selected_mode(unsigned int mode)
-{
-       int ret;
-       int mode_v;
-
-       usb_selected_mode = mode;
-
-       mode_v = get_mode_vconf_from_bitmap(mode);
-       if (mode_v == SET_USB_INVALID) {
-               _E("Failed to convert USB selected_mode to vconf. There is no vconf matches up with USB mode %#x", mode);
-               return -EINVAL;
-       }
-
-       ret = vconf_set_int(VCONFKEY_USB_SEL_MODE, mode_v);
-       if (ret != VCONF_OK)
-               _E("Failed to set vconf value for USB selected mode: %d", vconf_get_ext_errno());
-
-       return ret;
-}
-
-/* Cache of vconf_get_int(VCONFKEY_USB_CUR_MODE) */
-unsigned int usb_state_get_current_mode(void)
-{
-       return usb_current_mode;
-}
-
-/* Because it is only changed by deviced, it is only processed when the vconf actually changes. */
-int usb_state_set_current_mode(unsigned int mode)
-{
-       int ret = 0;
-       int mode_v;
-       static int old_mode_v = -1;
-
-       usb_current_mode = mode;
-
-       mode_v = get_mode_vconf_from_bitmap(mode);
-       if (mode_v == SET_USB_INVALID) {
-               _E("Failed to convert USB current_mode to vconf. There is no vconf matches up with mode %#x", mode);
-               return -EINVAL;
-       }
-
-       if (old_mode_v != mode_v) {
-               old_mode_v = mode_v;
-               ret = vconf_set_int(VCONFKEY_USB_CUR_MODE, mode_v);
-               if (ret < 0)
-                       _E("Failed to set vconf value for USB current mode: %d", vconf_get_ext_errno());
-       }
-
-       return ret;
-}
-
-extcon_usb_state_e usb_state_get_connection(void)
-{
-       return usb_connection;
-}
-
-void usb_state_set_connection(extcon_usb_state_e conn)
-{
-       usb_connection = conn;
-}
-
-static void media_noti_cb(GVariant *var, void *user_data, GError *err)
-{
-       int id = 0;
-
-       if (!var) {
-               if (err)
-                       _E("USB media notification error: %s", err->message);
-               return;
-       }
-
-       if (!g_variant_get_safe(var, "(i)", &id)) {
-               _E("Failed to get variant(%s): no USB notification message", g_variant_get_type_string(var));
-               goto out;
-       }
-
-       noti_id = id;
-       _D("USB media notification message(%d)", noti_id);
-
-out:
-       g_variant_unref(var);
-}
-
-static void add_notification_handler(void)
-{
-       int ret_val;
-
-       if (noti_id < 0) {
-               ret_val = add_async_notification("MediaDeviceNotiOn", media_noti_cb, NULL);
-               if (ret_val < 0)
-                       _E("Failed to add USB notification for usb connection: %d", ret_val);
-       }
-}
-
-static void remove_notification_handler(void)
-{
-       int ret_val;
-
-       if (noti_id >= 0) {
-               ret_val = remove_notification("MediaDeviceNotiOff", noti_id);
-               if (ret_val < 0)
-                       _E("Failed to remove USB notification for usb connection: %d", ret_val);
-               else
-                       noti_id = -1;
-       }
-}
-
-void change_usb_state_notification_handler(unsigned int mode)
-{
-       if (mode & USB_FUNCTION_MTP)
-               add_notification_handler();
-       else if (mode == USB_FUNCTION_NONE)
-               remove_notification_handler();
-}
-
-/*
- * USB_DISCONNECTED                  : VCONFKEY_SYSMAN_USB_DISCONNECTED
- * USB_CONNECTED + USB_FUNCTION_NONE : VCONFKEY_SYSMAN_USB_CONNECTED
- * USB_CONNECTED + USB_FUNCTION_OOOO : VCONFKEY_SYSMAN_USB_AVAILABLE
- *
- * When connecting the usb cable     : "disconnected"(previous value) -> "connected" -> "available"
- * When disconnecting the usb cable  : "available"(previous value) -> "dosconnected"
- * When changing usb mode            : "available"(previous value) -> "connected" -> "available"
- *
- * When USB cable is connected but USB initialization fails : It stays "connected" without going to "available"
- *
- */
-void send_usb_state_changed_event(int status)
-{
-       static int old_status = -1;
-
-       if ((status != VCONFKEY_SYSMAN_USB_CONNECTED) &&
-               (status != VCONFKEY_SYSMAN_USB_AVAILABLE) &&
-               (status != VCONFKEY_SYSMAN_USB_DISCONNECTED)) {
-               _E("Invalid USB state changed event (%d)", status);
-               return;
-       }
-
-       if (old_status == status)
-               return;
-
-       old_status = status;
-
-       usb_state_send_system_event(status);
-
-       if (vconf_set_int(VCONFKEY_SYSMAN_USB_STATUS, status) != VCONF_OK)
-               _E("Failed to set vconf value for USB status: %d", vconf_get_ext_errno());
-
-       /* Caution: calls after vconf_set_int(VCONFKEY_SYSMAN_USB_STATUS) */
-       broadcast_usb_state_changed();
-}
-
diff --git a/src/usb/usb-tethering.c b/src/usb/usb-tethering.c
deleted file mode 100644 (file)
index 76dcb7d..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <stdbool.h>
-
-#include <vconf.h>
-
-#include "core/log.h"
-#include "shared/device-notifier.h"
-
-#include "usb.h"
-#include "usb-gadget.h"
-
-static bool tethering_state;
-
-static void usb_tethering_changed(keynode_t *key, void *data)
-{
-       int mode;
-       bool curr;
-
-       if (!key)
-               return;
-
-       mode = vconf_keynode_get_int(key);
-       curr = mode & VCONFKEY_MOBILE_HOTSPOT_MODE_USB;
-
-       if (curr == tethering_state) {
-               _I("USB tethering mode is already %s.", curr ? "ON" : "OFF");
-               return;
-       }
-
-       tethering_state = curr;
-
-       _I("USB tethering mode is changed to %s.", curr ? "ON" : "OFF");
-
-       device_notify(DEVICE_NOTIFIER_USB_TETHERING_MODE, (void *)curr);
-}
-
-static int usb_tethering_mode_changed(void *on)
-{
-       int ret;
-       unsigned new_mode;
-       static unsigned int saved_prev_mode = USB_FUNCTION_NONE;
-       const unsigned int curr_mode = usb_state_get_selected_mode();
-       const unsigned int predefined_rndis_mode_off = USB_FUNCTION_ACM | USB_FUNCTION_MTP;
-       const unsigned int predefined_rndis_mode_on = USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS;
-
-       /*
-        * On: Use predefined mode (USB_FUNCTION_ACM | USB_FUNCTION_SDB | USB_FUNCTION_RNDIS)
-        * Off: Use predefined mode (USB_FUNCTION_MTP | USB_FUNCTION_ACM) + USB_FUNCTION_SDB(conditional)
-        *
-        * Caution: If usb debug menu was enabled, add USB_FUNCTION_SDB to new mode to use.
-        *
-        * When tethering is enabled, additionally enable usb debug(USB_FUNCTION_SDB) unconditionally.
-        * Since usb debug is always enabled when you turn off usb tethering, there is no way to know if usb debug was enabled or not.
-        * So before enabling usb tethering, save the previous state.
-        * This saved value is used to check if the debug menu was enabled or not when you turn off usb tethering.
-        *
-        * In addition, if someone changes the usb mode while tethering on,
-        * use the latest usb mode to determine the usb debug mode instead of using the saved value.
-        *
-        */
-
-       if ((bool)on) {
-               new_mode = predefined_rndis_mode_on;
-               saved_prev_mode = curr_mode;
-       } else {
-               new_mode = predefined_rndis_mode_off;
-
-               if (curr_mode != predefined_rndis_mode_on) /* someone changes the usb mode while tethering on, use latest usb mode */
-                       saved_prev_mode = curr_mode;
-
-               if(saved_prev_mode & USB_FUNCTION_SDB)
-                       new_mode |= USB_FUNCTION_SDB;
-
-               saved_prev_mode = USB_FUNCTION_NONE;
-       }
-
-       ret = usb_change_mode(new_mode, true);
-       if (ret < 0)
-               _E("Failed to change USB mode to (%#x).", new_mode);
-
-       return ret;
-}
-
-void add_usb_tethering_handler(void)
-{
-       if (vconf_notify_key_changed(VCONFKEY_MOBILE_HOTSPOT_MODE, usb_tethering_changed, NULL) != VCONF_OK)
-               _E("Failed to add USB tethering handler.");
-
-       register_notifier(DEVICE_NOTIFIER_USB_TETHERING_MODE, usb_tethering_mode_changed);
-}
-
-void remove_usb_tethering_handler(void)
-{
-       vconf_ignore_key_changed(VCONFKEY_MOBILE_HOTSPOT_MODE, usb_tethering_changed);
-
-       unregister_notifier(DEVICE_NOTIFIER_USB_TETHERING_MODE, usb_tethering_mode_changed);
-}
diff --git a/src/usb/usb-tethering.h b/src/usb/usb-tethering.h
deleted file mode 100644 (file)
index d7a40ec..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __USB_TETHERING_H__
-#define __USB_TETHERING_H__
-
-void add_usb_tethering_handler(void);
-void remove_usb_tethering_handler(void);
-
-#endif /* __USB_TETHERING_H__ */
diff --git a/src/usb/usb.c b/src/usb/usb.c
deleted file mode 100644 (file)
index c71da85..0000000
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#include <vconf.h>
-#include <libsyscommon/libsystemd.h>
-
-#include "core/log.h"
-#include "core/udev.h"
-#include "display/poll.h"
-#include "display/display-ops.h"
-#include "shared/plugin.h"
-
-#include "usb.h"
-#include "usb-gadget.h"
-#include "usb-debug.h"
-#include "usb-tethering.h"
-
-static int usb_change_gadget(unsigned mode);
-
-static struct display_plugin *disp_plgn;
-
-static int usb_config_init(void)
-{
-       unsigned int mode = usb_state_get_selected_mode();
-
-       return usb_change_gadget(mode);
-}
-
-/* Precondition: USB_FUNCTION_NONE */
-static int usb_change_gadget(unsigned mode)
-{
-       int ret;
-
-       ret = usb_gadget_change_mode(mode);
-       if (ret) {
-               /* because usb does not work properly */
-               (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
-               return ret;
-       }
-
-       _I("USB gadget changed to (%#x)", mode);
-
-       return 0;
-}
-
-/* Precondition: USB_CONNECTED, USB_FUNCTION_NONE */
-static int usb_enable(unsigned int mode)
-{
-       int ret;
-
-       ret = usb_gadget_enable();
-       if (ret < 0) {
-               _E("Failed to enable USB config: %d", ret);
-               goto out;
-       }
-
-       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_AVAILABLE);
-       (void)usb_state_set_current_mode(mode);
-       change_usb_state_notification_handler(mode);
-
-       return 0;
-
-out:
-       /* Although this function has a USB_FUNCTION_NONE precondition, it is to protect against coding mistakes. */
-       (void)usb_state_set_current_mode(USB_FUNCTION_NONE); /* because usb does not work properly */
-       return ret;
-}
-
-/* Precondition: N/A */
-static int usb_disable(void)
-{
-       int ret;
-
-       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
-       change_usb_state_notification_handler(USB_FUNCTION_NONE);
-
-       ret = usb_gadget_disable();
-       if (ret < 0) {
-               _E("Failed to disable USB config: %d", ret);
-               return ret;
-       }
-
-       return 0;
-}
-
-/* Precondition: USB_DISCONNECTED (Implicitly contains USB_FUNCTION_NONE) */
-static int usb_connected(void)
-{
-       int ret;
-       unsigned int mode = usb_state_get_selected_mode();
-
-       if (disp_plgn->pm_lock_internal)
-               disp_plgn->pm_lock_internal(INTERNAL_LOCK_USB, LCD_OFF, STAY_CUR_STATE, 0);
-
-       usb_state_set_connection(USB_CONNECTED);
-       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_CONNECTED);
-
-       ret = usb_enable(mode);
-       if (ret < 0) {
-               _E("Failed to enable USB gadget(%#x): %d", mode, ret);
-               return ret;
-       }
-
-       return 0;
-}
-
-/* Precondition: USB_CONNECTED */
-static int usb_disconnected(void)
-{
-       int ret;
-
-       usb_state_set_connection(USB_DISCONNECTED);
-       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
-
-       ret = usb_disable();
-       if(ret < 0) {
-               _E("Failed to disable USB gadget: %d", ret);
-               /* Important: You have to keep going to unlock disp_plgn->pm_unlock_internal */
-       }
-
-       if (disp_plgn->pm_unlock_internal)
-               disp_plgn->pm_unlock_internal(INTERNAL_LOCK_USB, LCD_OFF, STAY_CUR_STATE);
-
-       return ret;
-}
-
-/* Called by dbus signal and vconf change(tethering, debug mode) */
-int usb_change_mode(unsigned int new_mode, bool change_debug_mode)
-{
-       int ret;
-       const unsigned int curr_mode = usb_state_get_current_mode();
-       const unsigned int prev_mode = usb_state_get_selected_mode();
-
-       if (prev_mode == new_mode) {
-               _I("already using USB mode(%#x), current running mode (%#x)", prev_mode, curr_mode);
-               return 0;
-       }
-
-       _I("USB change mode (%#x) -> (%#x), current running mode (%#x)", prev_mode, new_mode, curr_mode);
-
-       /*
-        * When you change the gadget(usb_change_gadget) for new usb mode, you must disable the gadget first.
-        *
-        * Even if the usb cable is plugged in, the current mode may be NULL due to usb fail.
-        * So to find out which mode you are in, you should use the current mode, not the selected mode.
-       */
-       if (curr_mode != USB_FUNCTION_NONE) {
-               /* Special case: Because usb gadget is disabled, temporarily switch usb state from available to connected. */
-               send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_CONNECTED);
-
-               ret = usb_disable();
-               if (ret < 0) {
-                       _E("Failed to disable current USB mode.");
-                       return ret;
-               }
-       }
-
-       /*
-        * You should always change the gadget once when the usb mode is changed.
-        * In this state, usb_enable() is called when the usb cable is connected
-        * and usb_disable() is called when the usb cable is disconnected.
-        */
-       ret = usb_change_gadget(new_mode);
-       if (ret < 0) {
-               _E("Failed to change USB gadget: %d", ret);
-               return ret;
-       }
-
-       if (usb_state_get_connection() == USB_CONNECTED) {
-               ret = usb_enable(new_mode);
-               if (ret < 0) {
-                       _E("Failed to enable USB mode: %d", ret);
-                       return ret;
-               }
-       }
-
-       /* If you success to change the runtime usb configuration, do change the selected mode. */
-       (void)usb_state_set_selected_mode(new_mode);
-
-       /* To sync with vconf for debug mode */
-       if (change_debug_mode)
-               set_usb_debug_state((bool)(new_mode & USB_FUNCTION_SDB));
-
-       return 0;
-}
-
-/* Called by extcon udev event */
-static int usb_state_changed(const char *index, int new_status)
-{
-       int ret = -1;
-       static int old_status = -1; /* -1: Uninitialized, 0: disconnected, 1: connected */
-
-       /* For debugging. Do not move the location. */
-       _I("USB state is changed by extcon from (%d) to (%d).", old_status, new_status);
-
-       if (old_status == new_status)
-               return 0;
-
-       switch (new_status) {
-       case USB_CONNECTED:
-               ret = usb_connected();
-               break;
-
-       case USB_DISCONNECTED:
-               if (old_status == -1) {
-                       /* only initialize the internal data state and skip usb hal operation. */
-                       _I("USB is initialized without USB connection");
-
-                       /* From usb_disconnected() */
-                       usb_state_set_connection(USB_DISCONNECTED);
-                       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
-
-                       /*  From usb_disable() */
-                       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
-                       change_usb_state_notification_handler(USB_FUNCTION_NONE);
-
-                       ret = 0;
-               } else
-                       ret = usb_disconnected();
-               break;
-
-       default:
-               _E("Invalid USB state(%d).", new_status);
-               return -EINVAL;
-       }
-
-       if (ret < 0) {
-               _E("Failed to operate USB connection: %d", ret);
-               return ret;
-       }
-
-       old_status = new_status;
-
-       return ret;
-}
-
-static void uevent_usb_mode_handler(struct udev_device *dev)
-{
-       const char *state = NULL;
-
-       state = udev_device_get_property_value(dev, "USB_STATE");
-       if (!state)
-               return;
-
-       if (strncmp(state, "CONFIGURED", strlen(state) + 1))
-               return;
-
-       _I("USB udev event happend : CONFIGURED USB_STATE");
-
-       if (usb_state_get_selected_mode() & USB_FUNCTION_ACM)
-               systemd_start_unit_wait_started ("data-router.service", NULL, -1);
-
-       if (usb_state_get_selected_mode() & USB_FUNCTION_SDB)
-               systemd_start_unit_wait_started ("sdbd.service", NULL, -1);
-
-       if (usb_state_get_selected_mode() & USB_FUNCTION_MTP)
-               systemd_start_unit_wait_started ("mtp-responder.service", NULL, -1);
-}
-
-static struct uevent_handler uh = {
-       .subsystem = "usb_mode",
-       .uevent_func = uevent_usb_mode_handler,
-};
-
-static void usb_init(void *data)
-{
-       int ret;
-
-       usb_state_load_custom_mode();
-       usb_state_retrieve_selected_mode();
-
-       ret = usb_gadget_init();
-       if (ret < 0) {
-               _E("USB client cannot be used: %d", ret);
-               return;
-       }
-
-       ret = usb_config_init();
-       if (ret < 0)
-               _E("Failed to initialize USB configuation.");
-
-       ret = register_udev_uevent_control(&uh);
-       if (ret < 0)
-               _E("Failed to register udev event(%d) for USB", ret);
-
-       ret = usb_dbus_init();
-       if (ret < 0)
-               _E("Failed to init dbus(%d) for USB", ret);
-
-       add_usb_tethering_handler();
-       add_usb_debug_handler();
-}
-
-static void usb_exit(void *data)
-{
-       remove_usb_debug_handler();
-       remove_usb_tethering_handler();
-
-       usb_state_set_connection(USB_DISCONNECTED);
-       send_usb_state_changed_event(VCONFKEY_SYSMAN_USB_DISCONNECTED);
-       (void)usb_state_set_current_mode(USB_FUNCTION_NONE);
-       change_usb_state_notification_handler(USB_FUNCTION_NONE);
-
-       unregister_udev_uevent_control(&uh);
-       usb_gadget_disable();
-       usb_gadget_exit();
-
-}
-
-static struct extcon_ops extcon_usb_ops = {
-       .name   = EXTCON_CABLE_USB,
-       .init   = usb_init,
-       .exit   = usb_exit,
-       .update = usb_state_changed,
-};
-
-EXTCON_OPS_REGISTER(extcon_usb_ops)
-
-static void __CONSTRUCTOR__ initialize(void)
-{
-       disp_plgn = get_var_display_plugin();
-       if (!disp_plgn)
-               _E("Failed to get display plugin variable.");
-}
diff --git a/src/usb/usb.h b/src/usb/usb.h
deleted file mode 100644 (file)
index 0e30b2e..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __DEVICED_USB_H__
-#define __DEVICED_USB_H__
-
-#include <limits.h>
-#include <stdbool.h>
-#include "extcon/extcon.h"
-
-#define USB_FUNCTION_INVALID   UINT_MAX
-#define SET_USB_INVALID        INT_MAX
-
-int usb_dbus_init(void);
-
-void usb_state_load_custom_mode(void);
-
-int usb_change_mode(unsigned int mode, bool change_debug_mode);
-void usb_state_retrieve_selected_mode(void);
-unsigned int get_mode_bitmap_from_vconf(int mode_v);
-
-void broadcast_usb_state_changed(void);
-void send_usb_state_changed_event(int status);
-void change_usb_state_notification_handler(unsigned int mode);
-
-unsigned int usb_state_get_selected_mode(void);
-int usb_state_set_selected_mode(unsigned int mode);
-
-unsigned int usb_state_get_current_mode(void);
-int usb_state_set_current_mode(unsigned int mode);
-
-extcon_usb_state_e usb_state_get_connection(void);
-void usb_state_set_connection(extcon_usb_state_e conn);
-
-#endif /* __USB_CLIENT_H__ */
diff --git a/src/usbhost/usb-host.c b/src/usbhost/usb-host.c
deleted file mode 100644 (file)
index 9155fb5..0000000
+++ /dev/null
@@ -1,1224 +0,0 @@
-/*
- * deviced
- *
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <stdio.h>
-#include <stdint.h>
-#include <limits.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <tzplatform_config.h>
-#include <libsyscommon/libgdbus.h>
-#include <libsyscommon/list.h>
-#include <dlfcn.h>
-
-#include "core/log.h"
-#include "shared/devices.h"
-#include "shared/device-notifier.h"
-#include "core/udev.h"
-#include "apps/apps.h"
-#include "extcon/extcon.h"
-#include "display/display-ops.h"
-#include "display/core.h"
-#include "dd-usbhost.h"
-#include "shared/plugin.h"
-
-#define USB_INTERFACE_CLASS     "bInterfaceClass"
-#define USB_INTERFACE_SUBCLASS  "bInterfaceSubClass"
-#define USB_INTERFACE_PROTOCOL  "bInterfaceProtocol"
-#define USB_VENDOR_ID           "idVendor"
-#define USB_PRODUCT_ID          "idProduct"
-#define USB_MANUFACTURER        "manufacturer"
-#define USB_PRODUCT             "product"
-#define USB_SERIAL              "serial"
-
-#define USB_HOST_RESULT_SIGNAL "USBHostResult"
-
-#define SIGNAL_USB_HOST_CHANGED "ChangedDevice"
-#define METHOD_GET_CONNECTION_CREDENTIALS "GetConnectionCredentials"
-
-#define ROOTPATH tzplatform_getenv(TZ_SYS_VAR)
-#define POLICY_FILENAME "usbhost-policy"
-
-static struct display_plugin *disp_plgn;
-static struct display_config *disp_conf;
-static struct display_config* (*fp_get_var_display_config)(void);
-static bool display_on_usb_conn_changed = true;
-static char *POLICY_FILEPATH;
-
-/**
- * Below usb host class is defined by www.usb.org.
- * Please refer to below site.
- * http://www.usb.org/developers/defined_class
- * You can find the detail class codes in linux/usb/ch9.h.
- * Deviced uses kernel defines.
- */
-#include <linux/usb/ch9.h>
-#define USB_CLASS_ALL   0xffffffff
-#define USB_DEVICE_MAJOR 189
-
-/**
- * HID Standard protocol information.
- * Please refer to below site.
- * http://www.usb.org/developers/hidpage/HID1_11.pdf
- * Below protocol only has meaning
- * if the subclass is a boot interface subclass,
- * otherwise it is 0.
- */
-enum usbhost_hid_protocol {
-       USB_HOST_HID_KEYBOARD = 1,
-       USB_HOST_HID_MOUSE    = 2,
-};
-
-static GList *usbhost_list;
-
-enum policy_value {
-       POLICY_NONE,
-       POLICY_ALLOW_ALWAYS,
-       POLICY_ALLOW_NOW,
-       POLICY_DENY_ALWAYS,
-       POLICY_DENY_NOW,
-};
-
-#define UID_KEY "UnixUserID"
-#define PID_KEY "ProcessID"
-#define SEC_LABEL_KEY "LinuxSecurityLabel"
-#define ENTRY_LINE_SIZE 256
-
-struct user_credentials {
-       uint32_t uid;
-       uint32_t pid;
-       char *sec_label;
-};
-
-struct device_desc {
-       uint16_t bcdUSB;
-       uint8_t bDeviceClass;
-       uint8_t bDeviceSubClass;
-       uint8_t bDeviceProtocol;
-       uint16_t idVendor;
-       uint16_t idProduct;
-       uint16_t bcdDevice;
-};
-
-struct policy_entry {
-       struct user_credentials creds;
-       union {
-               struct usb_device_descriptor device;
-               /* for temporary policy */
-               char devpath[PATH_MAX];
-       };
-
-       enum policy_value value;
-};
-
-static inline int is_policy_temporary(struct policy_entry *entry)
-{
-       return entry->value == POLICY_ALLOW_NOW ||
-               entry->value == POLICY_DENY_NOW;
-}
-
-static GList *access_list;
-
-static struct usbhost_open_request {
-       GDBusMethodInvocation *invocation;
-       char *path;
-       //struct user_credentials cred;
-       GDBusCredentials cred;
-       struct usb_device_descriptor desc;
-       char devpath[PATH_MAX];
-} *current_request = NULL;
-
-static void print_usbhost(struct usbhost_device *usbhost)
-{
-       if (!usbhost)
-               return;
-
-       _I("devpath : %s", usbhost->devpath);
-       _I("interface baseclass : %#xh", usbhost->baseclass);
-       _I("interface subclass : %#xh", usbhost->subclass);
-       _I("interface protocol : %#xh", usbhost->protocol);
-       _I("vendor id : %#xh", usbhost->vendorid);
-       _I("product id : %#xh", usbhost->productid);
-       _I("manufacturer : %s", usbhost->manufacturer);
-       _I("product : %s", usbhost->product);
-       _I("serial : %s", usbhost->serial);
-}
-
-static void broadcast_usbhost_signal(enum usbhost_state state,
-               struct usbhost_device *usbhost)
-{
-       int ret;
-       GVariant *param;
-
-       if (!usbhost)
-               return;
-
-       param = g_variant_new("(isiiiiisss)", state,
-                                                                               usbhost->devpath,
-                                                                               usbhost->baseclass,
-                                                                               usbhost->subclass,
-                                                                               usbhost->protocol,
-                                                                               usbhost->vendorid,
-                                                                               usbhost->productid,
-                                                                               (usbhost->manufacturer ? usbhost->manufacturer : ""),
-                                                                               (usbhost->product ? usbhost->product : ""),
-                                                                               (usbhost->serial ? usbhost->serial : ""));
-
-       ret = gdbus_signal_emit(NULL,
-                       DEVICED_PATH_USBHOST,
-                       DEVICED_INTERFACE_USBHOST,
-                       SIGNAL_USB_HOST_CHANGED,
-                       param);
-       if (ret < 0)
-               _E("Failed to send dbus signal(%s)", SIGNAL_USB_HOST_CHANGED);
-}
-
-static int add_usbhost_list(struct udev_device *dev, const char *devpath)
-{
-       struct usbhost_device *usbhost;
-       const char *str;
-       struct udev_device *parent;
-
-       /* allocate new usbhost device */
-       usbhost = calloc(1, sizeof(struct usbhost_device));
-       if (!usbhost) {
-               _E("Fail to allocate usbhost memory: %d", errno);
-               return -errno;
-       }
-
-       /* save the devnode */
-       snprintf(usbhost->devpath, sizeof(usbhost->devpath),
-                       "%s", devpath);
-
-       /* get usb interface informations */
-       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_CLASS);
-       if (str)
-               usbhost->baseclass = (int)strtol(str, NULL, 16);
-       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_SUBCLASS);
-       if (str)
-               usbhost->subclass = (int)strtol(str, NULL, 16);
-       str = udev_device_get_sysattr_value(dev, USB_INTERFACE_PROTOCOL);
-       if (str)
-               usbhost->protocol = (int)strtol(str, NULL, 16);
-
-       /* parent has a lot of information about usb_interface */
-       parent = udev_device_get_parent(dev);
-       if (!parent) {
-               _E("Failed to get parent.");
-               free(usbhost);
-               return -EPERM;
-       }
-
-       /* get usb device informations */
-       str = udev_device_get_sysattr_value(parent, USB_VENDOR_ID);
-       if (str)
-               usbhost->vendorid = (int)strtol(str, NULL, 16);
-       str = udev_device_get_sysattr_value(parent, USB_PRODUCT_ID);
-       if (str)
-               usbhost->productid = (int)strtol(str, NULL, 16);
-       str = udev_device_get_sysattr_value(parent, USB_MANUFACTURER);
-       if (str)
-               usbhost->manufacturer = strdup(str);
-       str = udev_device_get_sysattr_value(parent, USB_PRODUCT);
-       if (str)
-               usbhost->product = strdup(str);
-       str = udev_device_get_sysattr_value(parent, USB_SERIAL);
-       if (str)
-               usbhost->serial = strdup(str);
-
-       SYS_G_LIST_APPEND(usbhost_list, usbhost);
-
-       broadcast_usbhost_signal(USB_HOST_ADDED, usbhost);
-
-       if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
-               disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);
-
-       /* for debugging */
-       _I("USB HOST Added.");
-       print_usbhost(usbhost);
-
-       return 0;
-}
-
-static int remove_usbhost_list(const char *devpath)
-{
-       struct usbhost_device *usbhost;
-       GList *n, *next;
-
-       /* find the matched item */
-       SYS_G_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {
-               if (!strncmp(usbhost->devpath,
-                                       devpath, sizeof(usbhost->devpath)))
-                       break;
-       }
-
-       if (!usbhost) {
-               _E("Failed to find the matched usbhost device.");
-               return -ENODEV;
-       }
-
-       broadcast_usbhost_signal(USB_HOST_REMOVED, usbhost);
-
-       if (display_on_usb_conn_changed && disp_plgn->pm_change_internal)
-               disp_plgn->pm_change_internal(INTERNAL_LOCK_USB_HOST, LCD_NORMAL);
-
-       /* for debugging */
-       _I("USB HOST Removed.");
-       _I("Devpath=%s", usbhost->devpath);
-
-       SYS_G_LIST_REMOVE(usbhost_list, usbhost);
-       free(usbhost->manufacturer);
-       free(usbhost->product);
-       free(usbhost->serial);
-       free(usbhost);
-
-       return 0;
-}
-
-static void remove_all_usbhost_list(void)
-{
-       struct usbhost_device *usbhost;
-       GList *n, *next;
-
-       SYS_G_LIST_FOREACH_SAFE(usbhost_list, n, next, usbhost) {
-
-               /* for debugging */
-               _I("USB HOST Removed.");
-               _I("Devpath=%s", usbhost->devpath);
-
-               SYS_G_LIST_REMOVE(usbhost_list, usbhost);
-               free(usbhost->manufacturer);
-               free(usbhost->product);
-               free(usbhost->serial);
-               free(usbhost);
-       }
-}
-
-static void uevent_usbhost_handler(struct udev_device *dev)
-{
-       const char *subsystem;
-       const char *devtype;
-       const char *devpath;
-       const char *action;
-       struct policy_entry *entry;
-       GList *n, *next;
-
-       /**
-        * Usb host device must have at least one interface.
-        * An interface is matched with a specific usb class.
-        */
-       subsystem = udev_device_get_subsystem(dev);
-       devtype = udev_device_get_devtype(dev);
-       if (!subsystem || !devtype) {
-               _E("Failed to get subsystem or devtype.");
-               return;
-       }
-
-       /* devpath is an unique information among usb host devices */
-       devpath = udev_device_get_devpath(dev);
-       if (!devpath) {
-               _E("Failed to get devpath from udev_device.");
-               return;
-       }
-
-       action = udev_device_get_action(dev);
-       _I("Subsystem=%s devtype=%s action=%s", subsystem, devtype, action);
-       /* Policy is valid for entire device, thus we check this devtype here */
-       if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) == 0 &&
-           strncmp(devtype, USB_DEVICE_DEVTYPE, sizeof(USB_DEVICE_DEVTYPE)) == 0 &&
-           strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)) == 0) {
-               SYS_G_LIST_FOREACH_SAFE(access_list, n, next, entry) {
-                       if (is_policy_temporary(entry) &&
-                                       strcmp(devpath, entry->devpath) == 0) {
-                               _I("Removed temporary policy for '%s'", devpath);
-                               SYS_G_LIST_REMOVE(access_list, entry);
-                               free(entry->creds.sec_label);
-                               free(entry);
-                       }
-               }
-       }
-
-       /**
-        * if devtype is not matched with usb subsystem
-        * and usb_interface devtype, skip.
-        */
-       if (strncmp(subsystem, USB_SUBSYSTEM, sizeof(USB_SUBSYSTEM)) ||
-           strncmp(devtype, USB_INTERFACE_DEVTYPE, sizeof(USB_INTERFACE_DEVTYPE)))
-               return;
-
-       if (!strncmp(action, UDEV_ADD, sizeof(UDEV_ADD)))
-               add_usbhost_list(dev, devpath);
-       else if (!strncmp(action, UDEV_REMOVE, sizeof(UDEV_REMOVE)))
-               remove_usbhost_list(devpath);
-}
-
-static int usbhost_init_from_udev_enumerate(void)
-{
-       struct udev *udev;
-       struct udev_enumerate *enumerate;
-       struct udev_list_entry *list_entry;
-       struct udev_device *dev;
-       const char *syspath;
-       const char *devpath;
-
-       udev = udev_new();
-       if (!udev) {
-               _E("Failed to create udev library context.");
-               return -EPERM;
-       }
-
-       /* create a list of the devices in the 'usb' subsystem */
-       enumerate = udev_enumerate_new(udev);
-       if (!enumerate) {
-               _E("Failed to create an enumeration context.");
-               return -EPERM;
-       }
-
-       udev_enumerate_add_match_subsystem(enumerate, USB_SUBSYSTEM);
-       udev_enumerate_add_match_property(enumerate,
-                       UDEV_DEVTYPE, USB_INTERFACE_DEVTYPE);
-       udev_enumerate_scan_devices(enumerate);
-
-       udev_list_entry_foreach(list_entry,
-                       udev_enumerate_get_list_entry(enumerate)) {
-               syspath = udev_list_entry_get_name(list_entry);
-               if (!syspath)
-                       continue;
-
-               dev = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
-                               syspath);
-               if (!dev)
-                       continue;
-
-               /* devpath is an unique information among usb host devices */
-               devpath = udev_device_get_devpath(dev);
-               if (!devpath) {
-                       _E("Failed to get devpath from '%s' device.", syspath);
-                       continue;
-               }
-
-               /* add usbhost list */
-               add_usbhost_list(dev, devpath);
-
-               udev_device_unref(dev);
-       }
-
-       udev_enumerate_unref(enumerate);
-       udev_unref(udev);
-       return 0;
-}
-
-static GVariant *print_device_list(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       GList *elem;
-       struct usbhost_device *usbhost;
-       int cnt = 0;
-
-       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
-               _I("== [%2d USB HOST DEVICE] ===============", cnt++);
-               print_usbhost(usbhost);
-       }
-
-       return gdbus_new_g_variant_tuple();
-}
-#define nullstr(x) (x ? x : "")
-static GVariant *get_device_list(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       GVariant *gvar = NULL;
-       GList *elem;
-       struct usbhost_device *usbhost;
-       int baseclass;
-       GVariantBuilder *builder = NULL;
-       const char *error = NULL;
-       int item_cnt = 0;
-
-       g_variant_get(param, "(i)", &baseclass);
-
-       builder = g_variant_builder_new(G_VARIANT_TYPE("a(siiiiisss)"));
-       if (!builder) {
-               _E("Failed to alloc memory for g_variant_builder.");
-               error = "Failed to alloc memory for g_variant_builder.";
-               goto out;
-       }
-
-       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
-               if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
-                       continue;
-
-               g_variant_builder_add(builder, "(siiiiisss)",
-                               nullstr(NULL),
-                               usbhost->baseclass,
-                               usbhost->subclass,
-                               usbhost->protocol,
-                               usbhost->vendorid,
-                               usbhost->productid,
-                               nullstr(usbhost->manufacturer),
-                               nullstr(usbhost->product),
-                               nullstr(usbhost->serial));
-               ++item_cnt;
-       }
-
-       if (item_cnt == 0) {
-               _E("Not found matched item");
-               error = "Not found matched item";
-               goto out;
-       }
-
-       gvar = g_variant_new("(a(siiiiisss))", builder);
-
-out:
-       if (builder)
-               g_variant_builder_unref(builder);
-       if (!gvar)
-               g_dbus_method_invocation_return_error(invocation,
-                                       G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
-                                       "%s", error);
-       return gvar;
-}
-
-static GVariant *get_device_list_count(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       GList *elem;
-       struct usbhost_device *usbhost;
-       int baseclass;
-       int ret = 0;
-
-       g_variant_get(param, "(i)", &baseclass);
-
-       SYS_G_LIST_FOREACH(usbhost_list, elem, usbhost) {
-               if (baseclass != USB_CLASS_ALL && usbhost->baseclass != baseclass)
-                       continue;
-               ret++;
-       }
-
-       return g_variant_new("(i)", ret);
-}
-
-static struct uevent_handler uh = {
-       .subsystem = USB_SUBSYSTEM,
-       .uevent_func = uevent_usbhost_handler,
-};
-
-static const char *policy_value_str(enum policy_value value)
-{
-       switch (value) {
-       case POLICY_ALLOW_ALWAYS:
-               return "ALLOW";
-       case POLICY_ALLOW_NOW:
-               return "ALLOW_NOW";
-       case POLICY_DENY_ALWAYS:
-               return "DENY";
-       case POLICY_DENY_NOW:
-               return "DENY_NOW";
-       default:
-               return "UNKNOWN";
-       }
-}
-
-static int get_policy_value_from_str(const char *str)
-{
-       if (strncmp("ALLOW", str, 5) == 0)
-               return POLICY_ALLOW_ALWAYS;
-       if (strncmp("ALLOW_NOW", str, 5) == 0)
-               return POLICY_ALLOW_NOW;
-       if (strncmp("DENY", str, 4) == 0)
-               return POLICY_DENY_ALWAYS;
-       if (strncmp("DENY_NOW", str, 4) == 0)
-               return POLICY_DENY_NOW;
-       return POLICY_NONE;
-}
-
-static inline int marshal_policy_entry(char *buf, int len, struct policy_entry *entry)
-{
-       if (is_policy_temporary(entry))
-               return snprintf(buf, len, "%d %s %s %s\n",
-                               entry->creds.uid,
-                               entry->creds.sec_label,
-                               entry->devpath,
-                               policy_value_str(entry->value));
-       return snprintf(buf, len, "%d %s %04x %02x %02x %02x %04x %04x %04x %s\n",
-                       entry->creds.uid,
-                       entry->creds.sec_label,
-                       entry->device.bcdUSB,
-                       entry->device.bDeviceClass,
-                       entry->device.bDeviceSubClass,
-                       entry->device.bDeviceProtocol,
-                       entry->device.idVendor,
-                       entry->device.idProduct,
-                       entry->device.bcdDevice,
-                       policy_value_str(entry->value));
-}
-
-static GVariant *print_policy(GDBusConnection *conn,
-       const gchar *sender, const gchar *path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       char line[ENTRY_LINE_SIZE];
-       GList *elem;
-       struct policy_entry *entry;
-       int ret;
-
-       _I("USB access policy:");
-       SYS_G_LIST_FOREACH(access_list, elem, entry) {
-               ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
-               if (ret < 0)
-                       break;
-               _I("\t%s", line);
-       }
-
-       return gdbus_new_g_variant_tuple();
-}
-
-static int store_policy(void)
-{
-       int fd;
-       GList *elem;
-       struct policy_entry *entry;
-       char line[256];
-       int ret;
-
-       fd = open(POLICY_FILEPATH, O_WRONLY | O_CREAT, 0664);
-       if (fd < 0) {
-               _E("Could not open policy file for writing: %m");
-               return -errno;
-       }
-
-       SYS_G_LIST_FOREACH(access_list, elem, entry) {
-               if (is_policy_temporary(entry))
-                       continue;
-
-               ret = marshal_policy_entry(line, ENTRY_LINE_SIZE, entry);
-               if (ret < 0) {
-                       _E("Serialization failed: %m");
-                       goto out;
-               }
-
-               ret = write(fd, line, ret);
-               if (ret < 0) {
-                       ret = -errno;
-                       _E("Error writing policy entry: %m");
-                       goto out;
-               }
-       }
-
-       _I("Policy stored in %s", POLICY_FILEPATH);
-
-       ret = 0;
-
-out:
-       close(fd);
-       return ret;
-}
-
-static int read_policy(void)
-{
-       FILE *fp;
-       struct policy_entry *entry;
-       char *line = NULL, value_str[256];
-       int ret = -1;
-       int count = 0;
-       size_t len;
-
-       fp = fopen(POLICY_FILEPATH, "r");
-       if (!fp) {
-               ret = -errno;
-               _E("Could not open policy file for reading: %m");
-               return ret;
-       }
-
-       while ((ret = getline(&line, &len, fp)) != -1) {
-               entry = malloc(sizeof(*entry));
-               if (!entry) {
-                       ret = -ENOMEM;
-                       _E("No memory: %m");
-                       goto out;
-               }
-
-               entry->creds.sec_label = calloc(ENTRY_LINE_SIZE, 1);
-               if (!entry->creds.sec_label) {
-                       _E("No memory: %m");
-                       free(entry);
-                       goto out;
-               }
-
-               ret = sscanf(line, "%d %255s %04hx %02hhx %02hhx %02hhx %04hx %04hx %04hx %255s\n",
-                               &entry->creds.uid,
-                               entry->creds.sec_label,
-                               &entry->device.bcdUSB,
-                               &entry->device.bDeviceClass,
-                               &entry->device.bDeviceSubClass,
-                               &entry->device.bDeviceProtocol,
-                               &entry->device.idVendor,
-                               &entry->device.idProduct,
-                               &entry->device.bcdDevice,
-                               value_str);
-               if (ret == EOF) {
-                       _E("Error reading line: %m");
-                       free(entry->creds.sec_label);
-                       free(entry);
-                       goto out;
-               }
-
-               entry->value = get_policy_value_from_str(value_str);
-               if (entry->value == POLICY_NONE) {
-                       _E("Invalid policy value=%s", value_str);
-                       ret = -EINVAL;
-                       free(entry->creds.sec_label);
-                       free(entry);
-                       goto out;
-               }
-
-               _I("%04x:%04x : %s", entry->device.idVendor, entry->device.idProduct,
-                               value_str);
-
-               SYS_G_LIST_APPEND(access_list, entry);
-               count++;
-       }
-
-       _I("Found %d policy entries.", count);
-       ret = 0;
-
-out:
-       fclose(fp);
-       free(line);
-
-       return ret;
-}
-
-static int get_device_desc(const char *filepath, struct usb_device_descriptor *desc, char *devpath)
-{
-       char *path = NULL;
-       const char *rdevpath;
-       struct stat st;
-       int ret;
-       int fd = -1;
-       struct udev *udev = NULL;
-       struct udev_device *udev_device = NULL;
-
-       ret = stat(filepath, &st);
-       if (ret < 0) {
-               ret = -errno;
-               _E("Could not stat %s: %m", filepath);
-               goto out;
-       }
-
-       if (!S_ISCHR(st.st_mode) ||
-           major(st.st_rdev) != USB_DEVICE_MAJOR) {
-               ret = -EINVAL;
-               _E("Not an USB device.");
-               goto out;
-       }
-
-       udev = udev_new();
-       if (!udev) {
-               _E("Could not create udev contect.");
-               ret =  -ENOMEM;
-               goto out;
-       }
-
-       udev_device = udev_device_new_from_devnum(udev, 'c', st.st_rdev);
-       if (!udev_device) {
-               _E("Udev could not find device.");
-               ret = -ENOENT;
-               goto out;
-       }
-
-       rdevpath = udev_device_get_devpath(udev_device);
-       if (!rdevpath) {
-               _E("Failed to get devpath from udev_device.");
-               ret = -errno;
-               goto out;
-       }
-       strncpy(devpath, rdevpath, PATH_MAX);
-
-       ret = asprintf(&path, "/sys/dev/char/%d:%d/descriptors", major(st.st_rdev), minor(st.st_rdev));
-       if (ret < 0) {
-               ret = -ENOMEM;
-               _E("Failed to asprintf.");
-               goto out;
-       }
-
-       _I("Opening descriptor at '%s'", path);
-       fd = open(path, O_RDONLY);
-       if (fd < 0) {
-               ret = -errno;
-               _E("Failed to open '%s': %m", path);
-               goto out;
-       }
-
-       ret = read(fd, desc, sizeof(*desc));
-       if (ret < 0) {
-               ret = -errno;
-               _E("Failed to read '%s': %m", path);
-               goto out;
-       }
-
-       ret = 0;
-
-out:
-       if (fd >= 0)
-               close(fd);
-       free(path);
-
-       udev_device_unref(udev_device);
-       udev_unref(udev);
-
-       return ret;
-}
-
-static gboolean store_idler_cb(gpointer data)
-{
-       store_policy();
-
-       return G_SOURCE_REMOVE;
-}
-
-static void destroy_open_request(struct usbhost_open_request *req)
-{
-       _D("Destroing request structure.");
-       free(req->path);
-       req->path = NULL;
-}
-
-static void finish_opening(struct usbhost_open_request *req, int policy)
-{
-       int ret;
-       int fd = -1;
-       const char *err;
-       GError *error = NULL;
-       GUnixFDList *fd_list;
-
-       if (req->path == NULL)
-               return;
-
-       switch (policy) {
-       case POLICY_ALLOW_NOW:
-       case POLICY_ALLOW_ALWAYS:
-               fd = open(req->path, O_RDWR);
-               if (fd < 0) {
-                       ret = -errno;
-                       err = "org.freedesktop.DBus.Error.Failed";//"org.freedesktop.DBus.Error.Failed";
-                       _E("Unable to open file(%s): %m", req->path);
-               } else
-                       ret = 0;
-               break;
-       case POLICY_DENY_NOW:
-       case POLICY_DENY_ALWAYS:
-               ret = -EACCES;
-               err = "org.freedesktop.DBus.Error.AccessDenied";//G_DBUS_ERROR_ACCESS_DENIED;
-               break;
-       default:
-               ret = -EINVAL;
-               err = "org.freedesktop.DBus.Error.Failed";
-               break;
-       }
-
-       if (ret < 0) {
-               g_dbus_method_invocation_return_dbus_error(req->invocation, err, "Cannot allocate memory for error message");
-               goto out;
-       }
-
-       /** send along the stdin in case
-        *  g_application_command_line_get_stdin_data() is called
-        */
-       fd_list = g_unix_fd_list_new();
-       if (g_unix_fd_list_append(fd_list, fd, &error) < 0) {
-               _E("Failed to append fd in unix fd list: %s\n", error->message);
-               g_error_free(error);
-               goto out;
-       }
-
-       g_dbus_method_invocation_return_value_with_unix_fd_list(req->invocation, g_variant_new("(ih)", ret, 0), fd_list);
-
-       g_object_unref(fd_list);
-
-out:
-       destroy_open_request(req);
-       if (fd >= 0)
-               close(fd);
-       _I("Popup destroyed.");
-}
-
-static int spawn_popup(struct usbhost_open_request *req)
-{
-       char pid_str[8];
-       int ret;
-
-       if (!req)
-               return -EINVAL;
-
-       /* Handle for the previous popup */
-       if (current_request) {
-               finish_opening(current_request, POLICY_DENY_NOW);
-               free(current_request);
-               current_request = NULL;
-       }
-
-       _I("Launching popup.");
-
-       snprintf(pid_str, sizeof(pid_str), "%d", req->cred.pid);
-       ret = launch_system_app(APP_DEFAULT, 4, APP_KEY_TYPE, "usbhost", "_APP_PID_", pid_str);
-       if (ret < 0) {
-               _E("Could not launch system popup.");
-               return ret;
-       }
-
-       return ret;
-}
-
-static void popup_result_signal_handler(GDBusConnection  *conn,
-       const gchar      *sender,
-       const gchar      *path,
-       const gchar      *iface,
-       const gchar      *name,
-       GVariant         *param,
-       gpointer          data)
-
-{
-       int allow = 0, always = 0;
-       struct policy_entry *entry;
-       int value;
-       struct usbhost_open_request *req;
-
-       req = current_request;
-       if (!req) {
-               _E("req is NULL");
-               return;
-       }
-
-       if (!g_variant_get_safe(param, "(ii)", &allow, &always)) {
-               _E("failed to get params from gvariant. expected:%s, type:%s", "(ii)", g_variant_get_type_string(param));
-               free(req);
-               return;
-       }
-
-       if (allow && always)
-               value = POLICY_ALLOW_ALWAYS;
-       else if (!allow && always)
-               value = POLICY_DENY_ALWAYS;
-       else if (allow && !always)
-               value = POLICY_ALLOW_NOW;
-       else
-               value = POLICY_DENY_NOW;
-
-       /* Save the policy */
-
-       entry = calloc(sizeof(*entry), 1);
-       if (!entry) {
-               _E("No memory.");
-               goto out;
-       }
-
-       entry->creds.uid = req->cred.uid;
-       entry->creds.sec_label = strdup(req->cred.sec_label);
-       if (!entry->creds.sec_label) {
-               _E("No memory.");
-               free(entry);
-               goto out;
-       }
-
-       switch (value) {
-       case POLICY_ALLOW_ALWAYS:
-       case POLICY_DENY_ALWAYS:
-               entry->device.bcdUSB = le16toh(req->desc.bcdUSB);
-               entry->device.bDeviceClass = req->desc.bDeviceClass;
-               entry->device.bDeviceSubClass = req->desc.bDeviceSubClass;
-               entry->device.bDeviceProtocol = req->desc.bDeviceProtocol;
-               entry->device.idVendor = le16toh(req->desc.idVendor);
-               entry->device.idProduct = le16toh(req->desc.idProduct);
-               entry->device.bcdDevice = le16toh(req->desc.bcdDevice);
-
-               _I("Added policy entry: %d %s %04x %02x %02x %02x %04x %04x %04x %s",
-                               entry->creds.uid,
-                               entry->creds.sec_label,
-                               entry->device.bcdUSB,
-                               entry->device.bDeviceClass,
-                               entry->device.bDeviceSubClass,
-                               entry->device.bDeviceProtocol,
-                               entry->device.idVendor,
-                               entry->device.idProduct,
-                               entry->device.bcdDevice,
-                               policy_value_str(value));
-               break;
-       case POLICY_ALLOW_NOW:
-       case POLICY_DENY_NOW:
-               strncpy(entry->devpath, req->devpath, sizeof(entry->devpath) - 1);
-               entry->devpath[sizeof(entry->devpath) - 1] = '\0';
-               _I("Added temporary policy entry: %d %s %s %s",
-                               entry->creds.uid,
-                               entry->creds.sec_label,
-                               entry->devpath,
-                               policy_value_str(value));
-               break;
-       }
-
-       entry->value = value;
-       SYS_G_LIST_APPEND(access_list, entry);
-
-       g_idle_add(store_idler_cb, NULL);
-
-out:
-       finish_opening(req, value);
-       free(current_request);
-       current_request = NULL;
-}
-
-static int get_policy_value(struct usbhost_open_request *req)
-{
-       int ret;
-       GList *elem;
-       struct policy_entry *entry;
-
-       memset(&req->desc, 0, sizeof(req->desc));
-
-       _I("Requested access from user %d to '%s'.", req->cred.uid, req->path);
-       ret = get_device_desc(req->path, &req->desc, req->devpath);
-       if (ret < 0) {
-               _E("Could not get device descriptor.");
-               return ret;
-       }
-
-       SYS_G_LIST_FOREACH(access_list, elem, entry) {
-               if (entry->creds.uid != req->cred.uid
-                       || strncmp(entry->creds.sec_label, req->cred.sec_label, strlen(req->cred.sec_label)) != 0)
-                       continue;
-
-               if (is_policy_temporary(entry) ? strncmp(entry->devpath, req->devpath, PATH_MAX) :
-                       (entry->device.bcdUSB && entry->device.bcdUSB != le16toh(req->desc.bcdUSB))
-                       || (entry->device.bDeviceClass && entry->device.bDeviceClass != req->desc.bDeviceClass)
-                       || (entry->device.bDeviceSubClass && entry->device.bDeviceSubClass != req->desc.bDeviceSubClass)
-                       || (entry->device.bDeviceProtocol && entry->device.bDeviceProtocol != req->desc.bDeviceProtocol)
-                       || (entry->device.idVendor && entry->device.idVendor != le16toh(req->desc.idVendor))
-                       || (entry->device.idProduct && entry->device.idProduct != le16toh(req->desc.idProduct))
-                       || (entry->device.bcdDevice && entry->device.bcdDevice != le16toh(req->desc.bcdDevice)))
-                       continue;
-
-               _I("Found matching policy entry(%s)", policy_value_str(entry->value));
-
-               return entry->value;
-       }
-
-       return POLICY_NONE;
-}
-
-static void remove_all_access_list(void)
-{
-       struct policy_entry *entry;
-       GList *n, *next;
-
-       SYS_G_LIST_FOREACH_SAFE(access_list, n, next, entry) {
-               SYS_G_LIST_REMOVE(access_list, entry);
-               free(entry->creds.sec_label);
-               free(entry);
-       }
-}
-
-static GVariant *open_device(GDBusConnection *conn,
-       const gchar *sender, const gchar *obj_path, const gchar *iface, const gchar *name,
-       GVariant *param, GDBusMethodInvocation *invocation, gpointer user_data)
-{
-       int ret = 0;
-       int policy;
-       char *path;
-       struct usbhost_open_request *req;
-
-       req = calloc(sizeof(*req), 1);
-       if (!req) {
-               _E("No memory.");
-               g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
-               return NULL;
-       }
-
-       req->invocation = invocation;
-
-       ret = gdbus_get_sender_credentials(NULL, sender, &req->cred);
-       if (ret < 0) {
-               _E("Unable to get credentials for caller: %d", ret);
-               goto out;
-       }
-
-       g_variant_get(param, "(s)", &path);
-
-       req->path = path;
-       policy = get_policy_value(req);
-       if (policy < 0) {
-               _E("Could not get policy value(%d).", policy);
-               ret = -1;
-               goto out;
-       }
-
-       /* Need to ask user */
-       if (policy == POLICY_NONE) {
-               ret = spawn_popup(req);
-               if (ret < 0) {
-                       finish_opening(req, POLICY_DENY_NOW);
-                       free(req->cred.sec_label);
-                       free(req);
-                       return NULL;
-               }
-
-               current_request = req;
-               return NULL;
-       }
-
-       /* The policy exists for the app */
-       _D("Policy exists.");
-       finish_opening(req, policy);
-       free(req->cred.sec_label);
-       free(req);
-       return NULL;
-
-out:
-       destroy_open_request(req);
-       free(req->cred.sec_label);
-       free(req);
-       g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.DBus.Error.Failed", "no memory");
-       return NULL;
-}
-
-static const dbus_method_s dbus_methods[] = {
-       { "PrintDeviceList",   NULL,           NULL, print_device_list }, /* for debugging */
-       { "PrintPolicy",       NULL,           NULL, print_policy }, /* for debugging */
-       { "GetDeviceList",      "i", "a(siiiiisss)", get_device_list },
-       { "GetDeviceListCount", "i",            "i", get_device_list_count },
-       { "OpenDevice",         "s",           "ih", open_device },
-       /* Add methods here */
-};
-
-static const dbus_interface_u dbus_interface = {
-       .oh = NULL,
-       .name = DEVICED_INTERFACE_USBHOST,
-       .methods = dbus_methods,
-       .nr_methods = ARRAY_SIZE(dbus_methods),
-};
-
-
-static int delayed_init_done(void *data)
-{
-       /**
-        * To search the attched usb host device is not an urgent task.
-        * So deviced does not load while booting time.
-        * After booting task is done, it tries to find the attached devices.
-        */
-       usbhost_init_from_udev_enumerate();
-
-       /* unregister booting done notifier */
-       unregister_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_done);
-
-       return 0;
-}
-
-static void usbhost_init(void *data)
-{
-       int ret;
-
-       fp_get_var_display_config = dlsym(disp_plgn->handle, "get_var_display_config");
-       if (fp_get_var_display_config) {
-               disp_conf = fp_get_var_display_config();
-               if (!disp_conf)
-                       _E("Failed to get display config variable.");
-               else
-                       display_on_usb_conn_changed = disp_conf->display_on_usb_conn_changed;
-       } else {
-               _E("Failed to obtain address of get_var_display_config, %s.", dlerror());
-       }
-
-       /* register usbhost uevent */
-       ret = register_kernel_uevent_control(&uh);
-       if (ret < 0)
-               _E("Failed to register usb uevent: %d", ret);
-
-       /* register usbhost interface and method */
-       ret = gdbus_add_object(NULL, DEVICED_PATH_USBHOST, &dbus_interface);
-       if (ret < 0)
-               _E("Failed to register dbus interface and method: %d", ret);
-
-       /* register notifier */
-       register_notifier(DEVICE_NOTIFIER_DELAYED_INIT, delayed_init_done);
-
-       ret = asprintf(&POLICY_FILEPATH, "%s/%s", ROOTPATH, POLICY_FILENAME);
-       if (ret < 0) {
-               _E("No memory for policy path.");
-               return;
-       }
-
-       ret = gdbus_signal_subscribe(NULL, POPUP_PATH_SYSTEM,
-               POPUP_INTERFACE_SYSTEM, USB_HOST_RESULT_SIGNAL,
-               popup_result_signal_handler, NULL, NULL);
-       if (ret < 0) {
-               _E("Could not register popup signal handler.");
-               return;
-       }
-
-       read_policy();
-}
-
-static void usbhost_exit(void *data)
-{
-       int ret;
-
-       /* unregister usbhost uevent */
-       ret = unregister_kernel_uevent_control(&uh);
-       if (ret < 0)
-               _E("Failed to unregister usb uevent: %d", ret);
-
-       /* remove all usbhost list */
-       remove_all_usbhost_list();
-
-       store_policy();
-       remove_all_access_list();
-
-       free(POLICY_FILEPATH);
-}
-
-static const struct device_ops usbhost_device_ops = {
-       .name   = "usbhost",
-       .init   = usbhost_init,
-       .exit   = usbhost_exit,
-};
-
-DEVICE_OPS_REGISTER(&usbhost_device_ops)
-
-static int extcon_usbhost_state_changed(const char *index, int status)
-{
-       if (status == USBHOST_DISCONNECTED)
-               _I("USB host connector disconnected.");
-       else
-               _I("USB host connector connected.");
-
-       return 0;
-}
-
-static struct extcon_ops extcon_usbhost_ops = {
-       .name   = EXTCON_CABLE_USB_HOST,
-       .update = extcon_usbhost_state_changed,
-};
-
-EXTCON_OPS_REGISTER(extcon_usbhost_ops)
-
-static void __CONSTRUCTOR__ initialize(void)
-{
-       disp_plgn = get_var_display_plugin();
-       if (!disp_plgn)
-               _E("Failed to get display plugin variable.");
-}