Linux remount usb device

How to disconnect a specific USB device using musb_hdrc Linux driver?

First, i am new to the Linux USB stack and i am trying to understand it a little bit more in order to achieve the following result : i need to reconnect/disconnect a specific USB device because sometimes, tough not often, this device does not respond anymore and the only solution is to physically disconnect/reconnect the USB cable from the device.

On my board (AM33x Sitara), there are 2 usb controllers with musb-hdrc drivers bind to them :

From dmesg, i can see that my device is using driver musb-hdrc :

But looking at the device node, i cannot find this driver :

According to https://www.kernel.org/doc/Documentation/usb/power-management.txt, it is possible to suspend usb devices by doing : echo «auto» > /sys/bus/usb/devices/2-1.4/power/control and echo 0 > /sys/bus/usb/devices/2-1.4/power/autosuspend_delay_ms , plus unbinding the driver with echo «2-1.4:1.0» > /sys/bus/usb/devices/2-1.4:1.0/driver/unbind

I can see in dmesg that the device is disconnected, but for some reason the device is automatically bind just after that.

However, when i do the same procedure using musb-hdrc driver on musb-hdrc.1.auto and musb-hdrc.0.auto devices, it works well except that all my usb devices are turned off/on. and i would like to be more specific about the 2-1.4:1.0 usb devices interface.

An idea is to use the musb-hdrc driver to unbind the 2-1.4:1.0 usb device interface but it says that there is no such device.

I am a bit confused about that because i can see that the device is inside the device tree of musb-hdrc.1.auto :

Why the unbind command say that the device does not exist then ? Maybe there is a way to indicate, a kind of path inside the device tree to indicate to the driver that i want to unbind to this specific device interface 2-1.4:1.0 ?

Источник

Как перезагрузить USB-устройство из командной строки?

Можно ли сбросить подключение USB-устройства без физического отключения / подключения от ПК?

В частности, мое устройство представляет собой цифровую камеру. Я использую gphoto2 , но в последнее время я получаю «ошибки чтения устройства», поэтому я хотел бы попытаться выполнить программный сброс соединения.

Из того, что я могу сказать, нет никаких модулей ядра, загружаемых для камеры. Единственный, который выглядит связанным, это usbhid .

Сохранить следующее как usbreset.c

Выполните следующие команды в терминале:

Получите идентификатор шины и устройства USB-устройства, которое вы хотите сбросить:

Сделайте нашу скомпилированную программу исполняемой:

Запустите программу с привилегией sudo; сделать необходимые замены и идентификаторы, найденные с помощью lsusb команды:

Я раньше не сталкивался с вашими конкретными обстоятельствами, поэтому я не уверен, что этого будет достаточно, но я нашел самый простой способ перезагрузить USB-устройство с помощью этой команды: (Внешние приложения не нужны)

Это именно то, что я использую для сброса моего Kinect, поскольку у libfreenect, похоже, нет API для возврата его в спящий режим. Он у меня на Gentoo box, но ядро ​​должно быть достаточно новым, чтобы использовать ту же структуру пути для sysfs.

Ваш, очевидно, не будет, 1-4.6 но вы можете либо извлечь этот путь устройства из журнала ядра ( dmesg ), либо использовать что-то вроде lsusb получения идентификатора производителя и продукта, а затем использовать быструю команду, подобную этой, чтобы увидеть, как эти пути связаны с другим поставщиком. / пары идентификаторов продукта:

Читайте также:  Виртуальный хостинг windows server

Это сбросит все подключенные порты USB1 / 2/3 [1]:

Я верю, что это решит вашу проблему. Если вы не хотите сбрасывать все конечные точки USB, вы можете использовать соответствующий идентификатор устройства из /sys/bus/pci/drivers/ehci_hcd

Примечания: [1]: *hci_hcd драйверы ядра обычно управляют портами USB. ohci_hcd и uhci_hcd для портов USB1.1, ehci_hcd для портов USB2 и xhci_hcd для портов USB3. (см. https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire) )

Мне нужно было автоматизировать это в скрипте Python, поэтому я адаптировал чрезвычайно полезный ответ LiLo к следующему:

В моем случае это был драйвер cp210x (о котором я мог сказать lsmod | grep usbserial ), так что вы можете сохранить приведенный фрагмент как reset_usb.py, а затем сделать это:

Это также может быть полезно, если у вас еще нет настройки компилятора переменного тока в вашей системе, но у вас есть Python.

Я создал скрипт Python, который упрощает весь процесс на основе ответов здесь.

Сохраните приведенный ниже скрипт как reset_usb.py или клонируйте этот репозиторий .

Поскольку частный случай вопроса — это проблема связи gphoto2 с камерой по USB, в gphoto2 есть возможность сбросить USB-соединение:

Возможно, этот вариант не существовал в 2010 году, когда был задан вопрос.

Самым быстрым способом сброса будет сброс самого контроллера USB. Это заставит udev отменить регистрацию устройства при отключении, и регистрация вернется после того, как вы его включите.

Это должно работать для большинства компьютерных сред. Однако, если вы используете какое-то нестандартное оборудование, вы можете просто перебирать имена устройств. С помощью этого метода вам не нужно узнавать имя устройства по lsusb. Вы также можете включить в автоматизированный скрипт.

Я использую кувалду, перезагружая модули. Это мой скрипт usb_reset.sh:

И это мой файл службы systemd /usr/lib/systemd/system/usbreset.service, который запускает usb_reset.sh после запуска моего менеджера diplay:

Я сделал скрипт Python, который будет сбрасывать определенное устройство USB на основе номера устройства. Вы можете узнать номер устройства из команды lsusb.

В этой строке 004 номер устройства

Вот скрипт, который будет сбрасывать только соответствующий идентификатор продукта / поставщика.

Кто-нибудь заказывал кувалду? Это воедино из различных других ответов здесь.

Иногда я хочу выполнить эту операцию на определенном устройстве, как указано VID (идентификатор поставщика) и PID (идентификатор продукта). Это скрипт, который я нашел полезным для этой цели, который использует изящную библиотеку libusb.

Затем этот c ++ файл resetDeviceConnection должен выполнить эту задачу сброса подключения устройства, как указано в vid и pid.

Я сделал простой скрипт для перезагрузки определенного USB-устройства.

Возможно, это работает и для камеры:

После я восстановил голодный USB 3.0 HDD на 3.4.42 (kernel.org) Linux на моей стороне. dmesg сказал, что это было время ожидания команд после 360 секунд (извините, я не могу скопировать системный журнал здесь, не подключенные сети), и диск завис полностью. Процессы доступа к устройству были заблокированы в ядре и не могут быть уничтожены. NFS висел, ZFS висел, dd висел.

После этого все снова заработало. dmesg рассказал только одну строчку о USB найденном устройстве.

Я действительно понятия не имею, что делает следующее подробно. Но это сработало.

Следующий пример выводится из Debian Squeeze с 2.6.32-5-686 ядром, поэтому я думаю, что он работает для 2.6 и выше:

Если это не работает, возможно, кто-то еще может выяснить, как отправить реальный сброс на устройство.

Попробуйте, это отключение программного обеспечения (Eject).

Иногда не работает просто отсоединить устройство для некоторых устройств.

Я хочу удалить или извлечь мой «Genius NetScroll 120».

Читайте также:  Игровой режим windows 10 тесты

Тогда я сначала проверь мое подключенное USB-устройство

Хорошо, я нашел свою мышь, она имеет шину 002, устройство 009, idVendor 0458 и idProduct 003a, так что это справочная информация об устройстве мыши.

Это важно, номер шины — это начальный путь к устройству, и я проверю идентификатор продукта и поставщика, чтобы убедиться, что устройство удаляется.

Обратите внимание на папки, проверьте начало с папкой номер 2, я проверю эту, потому что мой Bus — 002, и одну за другой я проверяю каждую папку, содержащую правильные idVendor и idProduct, о моей информации о мыши.

В этом случае я получу информацию с помощью этой команды:

Хорошо, путь /sys/bus/usb/drivers/usb/2-1.3/ совпадает с моей информационной мышью! XDDD.

Пришло время удалить устройство!

Подключите снова USB-устройство, и оно снова работает!

Источник

How to Manually Mount/UnMount a USB Device on Ubuntu

When you plug in a USB drive on our system, it usually mounts automatically; creating a directory by your username under the media folder. You can also access it through the file manager running on your system. Unfortunately, this is not always the case; sometimes, you need to mount the USB manually to your system in order to access it.

In this tutorial, we will explain how to manually mount and unmount a USB drive to and from your system. The commands and steps described in this article have been run on an Ubuntu 18.04 LTS system.

How to mount a USB drive on Ubuntu

Let us follow these steps to mount a USB drive manually to your system:

Step1: Plug in the USB drive to an available port.

Step2: Run the following command as sudo in your Terminal application in order to check the available storage devices on your system and the file system they are using:

Your USB device will usually be listed at the end of the output mostly as sdb-(number). In our case it is listed as sdb1, running a FAT32 file system.

Step3: Create a mount point for your USB device through the following command:

Note: The name of your mount point can not include spaces; you can seperate the words through an underscore ‘_’.

Advertisement

The mount point will now be created.

Step4: Now we shall mount the USB storage device to the mount point that we created. We will use the following command in order to mount a FAT32 device:

The security option is mandatory and allows you to give/gain access to the USB by specifying one of the following values for permission;

In this example, I am giving access control to a user(current user) by specifying the user id:

For NTFS, use the following command:

Step5: Your USB has now been mounted. You can access it through your media folder.

You can also access USB through the file manager. In the following image, the 16 GB Volume listed right above Other Locations is my mounted USB storage.

How to unmount a USB drive on Ubuntu

If you have mounted a USB manually, it is best to even unmount it manually.

Step1: Use the following command in order to unmount your USB:

In the above command, specify the mount point if it is something other than the ‘USB’ mount point I have used.

Your USB will be unmounted from your system:

Step2: You will need to remove the USB mount point directory manually as follows if you don’t plan to reuse it in future:

Читайте также:  Нет task view windows 10

Step3: Unplug the USB from your system.

After following the steps described in this article, you will be successfully able to mount and unmount a USB storage device to and from your system. This will help you if your system fails to automatically make the USB available for access and use.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

How to reconnect a logically disconnected USB device?

It is possible for a USB storage device to become logically disconnected: the device is still plugged in, but is invisible from the operating system (e.g. it’s not listed under /proc/bus/usb ). Maybe this can happen to other kinds of USB or other removable devices as well. This can happen for example:

  • after Nautilus has unmounted a USB storage device;
  • after VirtualBox has claimed a USB storage device (the device disappears from the Linux host when it is attached in the guest, and does not automatically reappear if it is detached from the guest).

What is going on in the driver or in the hardware, and most importantly, (how) can the device be logically reconnected (without physically plugging it out and back in)?

Note that this question is not about mounting. In the “logically disconnected” state, the kernel believes there is nothing on the USB bus (and so of course there is no entry under /dev ).

9 Answers 9

It is sometimes possible to do a power cycle on branch of the USB bus where the device is plugged :

The 1-1 should be adjusted to your configuration. You can see to which part of the USB tree your device is plugged by running lsusb -t before ejecting it.

You can find detailed information on the linux-usb mailing-list, this thread for example.

Now check for Kernel. E.g. if it is connected to Port 2 of Front UIP then it would be 1-1.2 and if it is connected to Port 1 of Front UIP then it would be 1-1.1.

For Port 2 : To disconnect USB :

Reset the device, or the hub it is connected to, and the device should reappear. Here is a small program to do that:

It works for most USB drives I’ve tried, but there are exceptions, like my Kingston DT 101 II 4GB, which fails INQUIRY and READ CAPACITY commands after reset, and remains unusable until power-cycled.

You can power-cycle the device without unplugging if it gets power from the port, and your USB hub supports per-port power control. Here is a small program to control the power:

Unfortunately, almost no USB hubs support this feature, and it’s very difficult to find one that supports it. Manufacturers do not advertise it. Many hubs also lie about it, for example if you do «lsusb -v» you can see «Per-port power switching» advertised in «wHubCharacteristic», but in reality it does not work. The chipset may support it, but it was easier/cheaper for the manufacturer to connect port power pins directly to the power supply instead of going through the chipset.

Источник

Оцените статью