usbmodeswitch: Updated to v.1.2.6 from shibby's branch.
[tomato.git] / release / src / router / rc / usb.c
blob64a140dfd3f03539c9d0f4fb9d09a0b51fcfc32d
1 /*
3 USB Support
5 */
6 #include "rc.h"
8 #include <sys/types.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <arpa/inet.h>
13 #include <time.h>
14 #include <sys/time.h>
15 #include <errno.h>
17 #include <sys/mount.h>
18 #include <mntent.h>
19 #include <dirent.h>
20 #include <sys/file.h>
21 #include <sys/swap.h>
23 /* Adjust bdflush parameters.
24 * Do this here, because Tomato doesn't have the sysctl command.
25 * With these values, a disk block should be written to disk within 2 seconds.
27 #ifdef LINUX26
28 void tune_bdflush(void)
30 f_write_string("/proc/sys/vm/dirty_expire_centisecs", "200", 0, 0);
31 f_write_string("/proc/sys/vm/dirty_writeback_centisecs", "200", 0, 0);
33 #else
34 #include <sys/kdaemon.h>
35 #define SET_PARM(n) (n * 2 | 1)
36 void tune_bdflush(void)
38 bdflush(SET_PARM(5), 100);
39 bdflush(SET_PARM(6), 100);
40 bdflush(SET_PARM(8), 0);
42 #endif // LINUX26
44 #define USBCORE_MOD "usbcore"
45 #define USB20_MOD "ehci-hcd"
46 #define USBSTORAGE_MOD "usb-storage"
47 #define SCSI_MOD "scsi_mod"
48 #define SD_MOD "sd_mod"
49 #ifdef LINUX26
50 #define USBOHCI_MOD "ohci-hcd"
51 #define USBUHCI_MOD "uhci-hcd"
52 #define USBPRINTER_MOD "usblp"
53 #define SCSI_WAIT_MOD "scsi_wait_scan"
54 #define USBFS "usbfs"
55 #else
56 #define USBOHCI_MOD "usb-ohci"
57 #define USBUHCI_MOD "usb-uhci"
58 #define USBPRINTER_MOD "printer"
59 #define USBFS "usbdevfs"
60 #endif
62 static int p9100d_sig(int sig)
64 const char p910pid[] = "/var/run/p9100d.pid";
65 char s[32];
66 int pid;
68 if (f_read_string(p910pid, s, sizeof(s)) > 0) {
69 if ((pid = atoi(s)) > 1) {
70 if (kill(pid, sig) == 0) {
71 if (sig == SIGTERM) {
72 sleep(1);
73 unlink(p910pid);
75 return 0;
79 return -1;
82 void start_usb(void)
84 char param[32];
85 int i;
87 if (nvram_match("boardtype", "0x052b")) { // Netgear WNR3500L v2 - initialize USB port
88 xstart("gpio", "enable", "20");
91 _dprintf("%s\n", __FUNCTION__);
92 tune_bdflush();
94 if (nvram_get_int("usb_enable")) {
95 modprobe(USBCORE_MOD);
97 /* mount usb device filesystem */
98 mount(USBFS, "/proc/bus/usb", USBFS, MS_MGC_VAL, NULL);
100 #ifdef LINUX26
101 i = do_led(LED_USB, LED_PROBE);
102 if (i != 255) {
103 modprobe("ledtrig-usbdev");
104 modprobe("leds-usb");
105 sprintf(param, "%d", i);
106 f_write_string("/proc/leds-usb/gpio_pin", param, 0, 0);
108 #endif
109 #ifdef TCONFIG_USBAP
110 char instance[20];
111 sprintf(instance, "instance_base=1");
112 modprobe("wl_high", instance );
113 #endif
115 if (nvram_get_int("usb_storage")) {
116 /* insert scsi and storage modules before usb drivers */
117 modprobe(SCSI_MOD);
118 #ifdef LINUX26
119 modprobe(SCSI_WAIT_MOD);
120 #endif
121 modprobe(SD_MOD);
122 modprobe(USBSTORAGE_MOD);
124 if (nvram_get_int("usb_fs_ext3")) {
125 #ifdef LINUX26
126 modprobe("mbcache"); // used by ext2/ext3
127 #endif
128 /* insert ext3 first so that lazy mount tries ext3 before ext2 */
129 modprobe("jbd");
130 modprobe("ext3");
131 modprobe("ext2");
134 if (nvram_get_int("usb_fs_fat")) {
135 modprobe("fat");
136 modprobe("vfat");
139 if (nvram_get_int("usb_fs_hfs")) {
140 modprobe("hfs");
143 if (nvram_get_int("usb_fs_hfsplus")) {
144 modprobe("hfsplus");
147 #if defined(LINUX26) && defined(TCONFIG_USB_EXTRAS)
148 if (nvram_get_int("usb_mmc") == 1) {
149 /* insert SD/MMC modules if present */
150 modprobe("mmc_core");
151 modprobe("mmc_block");
152 modprobe("sdhci");
154 #endif
157 /* if enabled, force USB2 before USB1.1 */
158 if (nvram_get_int("usb_usb2") == 1) {
159 i = nvram_get_int("usb_irq_thresh");
160 if ((i < 0) || (i > 6))
161 i = 0;
162 sprintf(param, "log2_irq_thresh=%d", i);
163 modprobe(USB20_MOD, param);
166 if (nvram_get_int("usb_uhci") == 1) {
167 modprobe(USBUHCI_MOD);
170 if (nvram_get_int("usb_ohci") == 1) {
171 modprobe(USBOHCI_MOD);
174 if (nvram_get_int("usb_printer")) {
175 symlink("/dev/usb", "/dev/printers");
176 modprobe(USBPRINTER_MOD);
178 /* start printer server only if not already running */
179 if (p9100d_sig(0) != 0) {
180 eval("p910nd",
181 nvram_get_int("usb_printer_bidirect") ? "-b" : "", //bidirectional
182 "-f", "/dev/usb/lp0", // device
183 "0" // listen port
188 #ifdef LINUX26
189 if (nvram_get_int("idle_enable") == 1) {
190 xstart( "sd-idle" );
192 #endif
193 #ifdef TCONFIG_USBAP
194 //enable eth2 after detect new iface by wl_high module
195 sleep(5);
196 xstart("service", "wireless", "restart");
197 #endif
201 void stop_usb(void)
203 int disabled = !nvram_get_int("usb_enable");
205 // only find and kill the printer server we started (port 0)
206 p9100d_sig(SIGTERM);
207 modprobe_r(USBPRINTER_MOD);
209 // only stop storage services if disabled
210 if (disabled || !nvram_get_int("usb_storage")) {
211 // Unmount all partitions
212 remove_storage_main(0);
214 // Stop storage services
215 modprobe_r("ext2");
216 modprobe_r("ext3");
217 modprobe_r("jbd");
218 #ifdef LINUX26
219 modprobe_r("mbcache");
220 #endif
221 modprobe_r("vfat");
222 modprobe_r("fat");
223 modprobe_r("fuse");
224 #ifdef TCONFIG_HFS
225 modprobe_r("hfs");
226 modprobe_r("hfsplus");
227 #endif
228 sleep(1);
229 #ifdef TCONFIG_SAMBASRV
230 modprobe_r("nls_cp437");
231 modprobe_r("nls_cp850");
232 modprobe_r("nls_cp852");
233 modprobe_r("nls_cp866");
234 #ifdef LINUX26
235 modprobe_r("nls_cp932");
236 modprobe_r("nls_cp936");
237 modprobe_r("nls_cp949");
238 modprobe_r("nls_cp950");
239 #endif
240 #endif
241 modprobe_r(USBSTORAGE_MOD);
242 modprobe_r(SD_MOD);
243 #ifdef LINUX26
244 modprobe_r(SCSI_WAIT_MOD);
245 #endif
246 modprobe_r(SCSI_MOD);
249 #if defined(LINUX26) && defined(TCONFIG_USB_EXTRAS)
250 if (disabled || !nvram_get_int("usb_storage") || nvram_get_int("usb_mmc") != 1) {
251 modprobe_r("sdhci");
252 modprobe_r("mmc_block");
253 modprobe_r("mmc_core");
255 #endif
257 if (disabled || nvram_get_int("usb_ohci") != 1) modprobe_r(USBOHCI_MOD);
258 if (disabled || nvram_get_int("usb_uhci") != 1) modprobe_r(USBUHCI_MOD);
259 if (disabled || nvram_get_int("usb_usb2") != 1) modprobe_r(USB20_MOD);
261 #ifdef LINUX26
262 modprobe_r("leds-usb");
263 modprobe_r("ledtrig-usbdev");
264 led(LED_USB, LED_OFF);
265 #endif
267 // only unload core modules if usb is disabled
268 if (disabled) {
269 umount("/proc/bus/usb"); // unmount usb device filesystem
270 modprobe_r(USBOHCI_MOD);
271 modprobe_r(USBUHCI_MOD);
272 modprobe_r(USB20_MOD);
273 modprobe_r(USBCORE_MOD);
276 #ifdef LINUX26
277 if (nvram_get_int("idle_enable") == 0) {
278 killall("sd-idle", SIGTERM);
281 if (nvram_match("3g_usb", "0") ) {
282 if (nvram_match("3g_module", "sierra") ) {
283 modprobe_r("sierra");
284 modprobe_r("usbserial");
286 if (nvram_match("3g_module", "option") ) {
287 modprobe_r("option");
288 modprobe_r("usbserial");
291 // shibby
292 // when modem use usbserial module and we will try remove module, module will crash
293 // the only solution at the moment is reboot router
294 // FIX THIS
295 if (nvram_match("3g_module", "usbserial") ) {
296 modprobe_r("usbserial");
300 if (nvram_match("boardtype", "0x052b")) { // Netgear WNR3500L v2 - disable USB port
301 xstart("gpio", "disable", "20");
305 #endif
309 #define MOUNT_VAL_FAIL 0
310 #define MOUNT_VAL_RONLY 1
311 #define MOUNT_VAL_RW 2
312 #define MOUNT_VAL_EXIST 3
314 int mount_r(char *mnt_dev, char *mnt_dir, char *type)
316 struct mntent *mnt;
317 int ret;
318 char options[140];
319 char flagfn[128];
320 int dir_made;
322 if ((mnt = findmntents(mnt_dev, 0, NULL, 0))) {
323 syslog(LOG_INFO, "USB partition at %s already mounted on %s",
324 mnt_dev, mnt->mnt_dir);
325 return MOUNT_VAL_EXIST;
328 options[0] = 0;
330 if (type) {
331 unsigned long flags = MS_NOATIME | MS_NODEV;
333 if (strcmp(type, "swap") == 0 || strcmp(type, "mbr") == 0) {
334 /* not a mountable partition */
335 flags = 0;
337 else if (strcmp(type, "ext2") == 0 || strcmp(type, "ext3") == 0) {
338 if (nvram_invmatch("usb_ext_opt", ""))
339 sprintf(options, nvram_safe_get("usb_ext_opt"));
341 else if (strcmp(type, "vfat") == 0) {
342 if (nvram_invmatch("smbd_cset", ""))
343 sprintf(options, "iocharset=%s%s",
344 isdigit(nvram_get("smbd_cset")[0]) ? "cp" : "",
345 nvram_get("smbd_cset"));
346 if (nvram_invmatch("smbd_cpage", "")) {
347 char *cp = nvram_safe_get("smbd_cpage");
348 sprintf(options + strlen(options), ",codepage=%s" + (options[0] ? 0 : 1), cp);
349 sprintf(flagfn, "nls_cp%s", cp);
351 cp = nvram_get("smbd_nlsmod");
352 if ((cp) && (*cp != 0) && (strcmp(cp, flagfn) != 0))
353 modprobe_r(cp);
355 modprobe(flagfn);
356 nvram_set("smbd_nlsmod", flagfn);
358 sprintf(options + strlen(options), ",shortname=winnt" + (options[0] ? 0 : 1));
359 #ifdef LINUX26
360 sprintf(options + strlen(options), ",flush" + (options[0] ? 0 : 1));
361 #endif
362 if (nvram_invmatch("usb_fat_opt", ""))
363 sprintf(options + strlen(options), "%s%s", options[0] ? "," : "", nvram_safe_get("usb_fat_opt"));
365 else if (strncmp(type, "ntfs", 4) == 0) {
366 if (nvram_invmatch("smbd_cset", ""))
367 sprintf(options, "iocharset=%s%s",
368 isdigit(nvram_get("smbd_cset")[0]) ? "cp" : "",
369 nvram_get("smbd_cset"));
370 if (nvram_invmatch("usb_ntfs_opt", ""))
371 sprintf(options + strlen(options), "%s%s", options[0] ? "," : "", nvram_safe_get("usb_ntfs_opt"));
374 if (flags) {
375 if ((dir_made = mkdir_if_none(mnt_dir))) {
376 /* Create the flag file for remove the directory on dismount. */
377 sprintf(flagfn, "%s/.autocreated-dir", mnt_dir);
378 f_write(flagfn, NULL, 0, 0, 0);
381 ret = mount(mnt_dev, mnt_dir, type, flags, options[0] ? options : "");
383 /* try ntfs-3g in case it's installed */
384 if (ret != 0 && strncmp(type, "ntfs", 4) == 0) {
385 sprintf(options + strlen(options), ",noatime,nodev" + (options[0] ? 0 : 1));
386 #ifdef TCONFIG_NTFS
387 if (nvram_get_int("usb_fs_ntfs"))
388 #endif
389 ret = eval("ntfs-3g", "-o", options, mnt_dev, mnt_dir);
392 if (ret != 0 && strncmp(type, "hfs", "") == 0) {
393 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
396 if (ret != 0 && strncmp(type, "hfsplus", "") == 0) {
397 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
400 if (ret != 0) /* give it another try - guess fs */
401 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
403 if (ret == 0) {
404 syslog(LOG_INFO, "USB %s%s fs at %s mounted on %s",
405 type, (flags & MS_RDONLY) ? " (ro)" : "", mnt_dev, mnt_dir);
406 return (flags & MS_RDONLY) ? MOUNT_VAL_RONLY : MOUNT_VAL_RW;
409 if (dir_made) {
410 unlink(flagfn);
411 rmdir(mnt_dir);
415 return MOUNT_VAL_FAIL;
419 struct mntent *mount_fstab(char *dev_name, char *type, char *label, char *uuid)
421 struct mntent *mnt = NULL;
422 #if 0
423 if (eval("mount", "-a") == 0)
424 mnt = findmntents(dev_name, 0, NULL, 0);
425 #else
426 char spec[PATH_MAX+1];
428 if (label && *label) {
429 sprintf(spec, "LABEL=%s", label);
430 if (eval("mount", spec) == 0)
431 mnt = findmntents(dev_name, 0, NULL, 0);
434 if (!mnt && uuid && *uuid) {
435 sprintf(spec, "UUID=%s", uuid);
436 if (eval("mount", spec) == 0)
437 mnt = findmntents(dev_name, 0, NULL, 0);
440 if (!mnt) {
441 if (eval("mount", dev_name) == 0)
442 mnt = findmntents(dev_name, 0, NULL, 0);
445 if (!mnt) {
446 /* Still did not find what we are looking for, try absolute path */
447 if (realpath(dev_name, spec)) {
448 if (eval("mount", spec) == 0)
449 mnt = findmntents(dev_name, 0, NULL, 0);
452 #endif
454 if (mnt)
455 syslog(LOG_INFO, "USB %s fs at %s mounted on %s", type, dev_name, mnt->mnt_dir);
456 return (mnt);
460 /* Check if the UFD is still connected because the links created in /dev/discs
461 * are not removed when the UFD is unplugged.
462 * The file to read is: /proc/scsi/usb-storage-#/#, where # is the host no.
463 * We are looking for "Attached: Yes".
465 static int usb_ufd_connected(int host_no)
467 char proc_file[128];
468 #ifndef LINUX26
469 char line[256];
470 #endif
471 FILE *fp;
473 sprintf(proc_file, "%s/%s-%d/%d", PROC_SCSI_ROOT, USB_STORAGE, host_no, host_no);
474 fp = fopen(proc_file, "r");
476 if (!fp) {
477 /* try the way it's implemented in newer kernels: /proc/scsi/usb-storage/[host] */
478 sprintf(proc_file, "%s/%s/%d", PROC_SCSI_ROOT, USB_STORAGE, host_no);
479 fp = fopen(proc_file, "r");
482 if (fp) {
483 #ifdef LINUX26
484 fclose(fp);
485 return 1;
486 #else
487 while (fgets(line, sizeof(line), fp) != NULL) {
488 if (strstr(line, "Attached: Yes")) {
489 fclose(fp);
490 return 1;
493 fclose(fp);
494 #endif
497 return 0;
501 #ifndef MNT_DETACH
502 #define MNT_DETACH 0x00000002 /* from linux/fs.h - just detach from the tree */
503 #endif
504 int umount_mountpoint(struct mntent *mnt, uint flags);
505 int uswap_mountpoint(struct mntent *mnt, uint flags);
507 /* Unmount this partition from all its mountpoints. Note that it may
508 * actually be mounted several times, either with different names or
509 * with "-o bind" flag.
510 * If the special flagfile is now revealed, delete it and [attempt to] delete
511 * the directory.
513 int umount_partition(char *dev_name, int host_num, char *dsc_name, char *pt_name, uint flags)
515 sync(); /* This won't matter if the device is unplugged, though. */
517 if (flags & EFH_HUNKNOWN) {
518 /* EFH_HUNKNOWN flag is passed if the host was unknown.
519 * Only unmount disconnected drives in this case.
521 if (usb_ufd_connected(host_num))
522 return 0;
525 /* Find all the active swaps that are on this device and stop them. */
526 findmntents(dev_name, 1, uswap_mountpoint, flags);
528 /* Find all the mountpoints that are for this device and unmount them. */
529 findmntents(dev_name, 0, umount_mountpoint, flags);
530 return 0;
533 int uswap_mountpoint(struct mntent *mnt, uint flags)
535 swapoff(mnt->mnt_fsname);
536 return 0;
539 int umount_mountpoint(struct mntent *mnt, uint flags)
541 int ret = 1, count;
542 char flagfn[128];
544 sprintf(flagfn, "%s/.autocreated-dir", mnt->mnt_dir);
546 /* Run user pre-unmount scripts if any. It might be too late if
547 * the drive has been disconnected, but we'll try it anyway.
549 if (nvram_get_int("usb_automount"))
550 run_nvscript("script_usbumount", mnt->mnt_dir, 3);
551 /* Run *.autostop scripts located in the root of the partition being unmounted if any. */
552 run_userfile(mnt->mnt_dir, ".autostop", mnt->mnt_dir, 5);
553 run_nvscript("script_autostop", mnt->mnt_dir, 5);
555 count = 0;
556 while ((ret = umount(mnt->mnt_dir)) && (count < 2)) {
557 count++;
558 /* If we could not unmount the drive on the 1st try,
559 * kill all NAS applications so they are not keeping the device busy -
560 * unless it's an unmount request from the Web GUI.
562 if ((count == 1) && ((flags & EFH_USER) == 0))
563 restart_nas_services(1, 0);
564 sleep(1);
567 if (ret == 0)
568 syslog(LOG_INFO, "USB partition unmounted from %s", mnt->mnt_dir);
570 if (ret && ((flags & EFH_SHUTDN) != 0)) {
571 /* If system is stopping (not restarting), and we couldn't unmount the
572 * partition, try to remount it as read-only. Ignore the return code -
573 * we can still try to do a lazy unmount.
575 eval("mount", "-o", "remount,ro", mnt->mnt_dir);
578 if (ret && ((flags & EFH_USER) == 0)) {
579 /* Make one more try to do a lazy unmount unless it's an unmount
580 * request from the Web GUI.
581 * MNT_DETACH will expose the underlying mountpoint directory to all
582 * except whatever has cd'ed to the mountpoint (thereby making it busy).
583 * So the unmount can't actually fail. It disappears from the ken of
584 * everyone else immediately, and from the ken of whomever is keeping it
585 * busy when they move away from it. And then it disappears for real.
587 ret = umount2(mnt->mnt_dir, MNT_DETACH);
588 syslog(LOG_INFO, "USB partition busy - will unmount ASAP from %s", mnt->mnt_dir);
591 if (ret == 0) {
592 if ((unlink(flagfn) == 0)) {
593 // Only delete the directory if it was auto-created
594 rmdir(mnt->mnt_dir);
597 return (ret == 0);
601 /* Mount this partition on this disc.
602 * If the device is already mounted on any mountpoint, don't mount it again.
603 * If this is a swap partition, try swapon -a.
604 * If this is a regular partition, try mount -a.
606 * Before we mount any partitions:
607 * If the type is swap and /etc/fstab exists, do "swapon -a"
608 * If /etc/fstab exists, try mounting using fstab.
609 * We delay invoking mount because mount will probe all the partitions
610 * to read the labels, and we don't want it to do that early on.
611 * We don't invoke swapon until we actually find a swap partition.
613 * If the mount succeeds, execute the *.autorun scripts in the top
614 * directory of the newly mounted partition.
615 * Returns NZ for success, 0 if we did not mount anything.
617 int mount_partition(char *dev_name, int host_num, char *dsc_name, char *pt_name, uint flags)
619 char the_label[128], mountpoint[128], uuid[40];
620 int ret;
621 char *type, *p;
622 static char *swp_argv[] = { "swapon", "-a", NULL };
623 struct mntent *mnt;
625 if ((type = find_label_or_uuid(dev_name, the_label, uuid)) == NULL)
626 return 0;
628 if (f_exists("/etc/fstab")) {
629 if (strcmp(type, "swap") == 0) {
630 _eval(swp_argv, NULL, 0, NULL);
631 return 0;
634 if (mount_r(dev_name, NULL, NULL) == MOUNT_VAL_EXIST)
635 return 0;
637 if ((mnt = mount_fstab(dev_name, type, the_label, uuid))) {
638 strcpy(mountpoint, mnt->mnt_dir);
639 ret = MOUNT_VAL_RW;
640 goto done;
644 if (*the_label != 0) {
645 for (p = the_label; *p; p++) {
646 if (!isalnum(*p) && !strchr("+-&.@", *p))
647 *p = '_';
649 sprintf(mountpoint, "%s/%s", MOUNT_ROOT, the_label);
650 if ((ret = mount_r(dev_name, mountpoint, type)))
651 goto done;
654 /* Can't mount to /mnt/LABEL, so try mounting to /mnt/discDN_PN */
655 sprintf(mountpoint, "%s/%s", MOUNT_ROOT, pt_name);
656 ret = mount_r(dev_name, mountpoint, type);
657 done:
658 if (ret == MOUNT_VAL_RONLY || ret == MOUNT_VAL_RW)
660 /* Run user *.autorun and post-mount scripts if any. */
661 run_userfile(mountpoint, ".autorun", mountpoint, 3);
662 if (nvram_get_int("usb_automount"))
663 run_nvscript("script_usbmount", mountpoint, 3);
665 return (ret == MOUNT_VAL_RONLY || ret == MOUNT_VAL_RW);
669 #if 0 /* LINUX26 */
672 * Finds SCSI Host number. Returns the host number >=0 if found, or (-1) otherwise.
673 * The name and host number of scsi block device in kernel 2.6 (for attached devices) can be found as
674 * /sys($DEVPATH)/host<host_no>/target<*>/<id>/block:[sda|sdb|...]
675 * where $DEVPATH is passed to hotplug events, and looks like
676 * /devices/pci0000:00/0000:00:04.1/usb1/1-1/1-1:1.2
678 * For printers this function finds a minor assigned to a printer
679 * /sys($DEVPATH)/usb:lp[0|1|2|...]
681 int find_dev_host(const char *devpath)
683 DIR *usb_devpath;
684 struct dirent *dp;
685 char buf[256];
686 int host = -1; /* Scsi Host */
688 sprintf(buf, "/sys%s", devpath);
689 if ((usb_devpath = opendir(buf))) {
690 while ((dp = readdir(usb_devpath))) {
691 errno = 0;
692 if (strncmp(dp->d_name, "host", 4) == 0) {
693 host = strtol(dp->d_name + 4, (char **)NULL, 10);
694 if (errno)
695 host = -1;
696 else
697 break;
699 else if (strncmp(dp->d_name, "usb:lp", 6) == 0) {
700 host = strtol(dp->d_name + 6, (char **)NULL, 10);
701 if (errno)
702 host = -1;
703 else
704 break;
706 else
707 continue;
709 closedir(usb_devpath);
711 return (host);
714 #endif /* LINUX26 */
716 int dir_is_mountpoint(const char *root, const char *dir)
718 char path[256];
719 struct stat sb;
720 int thisdev;
722 snprintf(path, sizeof(path), "%s%s%s", root ? : "", root ? "/" : "", dir);
724 /* Check if this is a directory */
725 sb.st_mode = S_IFDIR; /* failsafe */
726 stat(path, &sb);
728 if (S_ISDIR(sb.st_mode)) {
730 /* If this dir & its parent dir are on the same device, it is not a mountpoint */
731 strcat(path, "/.");
732 stat(path, &sb);
733 thisdev = sb.st_dev;
734 strcat(path, ".");
735 ++sb.st_dev; /* failsafe */
736 stat(path, &sb);
738 return (thisdev != sb.st_dev);
741 return 0;
744 /* Mount or unmount all partitions on this controller.
745 * Parameter: action_add:
746 * 0 = unmount
747 * >0 = mount only if automount config option is enabled.
748 * <0 = mount regardless of config option.
750 void hotplug_usb_storage_device(int host_no, int action_add, uint flags)
752 if (!nvram_get_int("usb_enable"))
753 return;
754 _dprintf("%s: host %d action: %d\n", __FUNCTION__, host_no, action_add);
756 if (action_add) {
757 if (nvram_get_int("usb_storage") && (nvram_get_int("usb_automount") || action_add < 0)) {
758 /* Do not probe the device here. It's either initiated by user,
759 * or hotplug_usb() already did.
761 if (exec_for_host(host_no, 0x00, flags, mount_partition)) {
762 restart_nas_services(0, 1); // restart all NAS applications
766 else {
767 if (nvram_get_int("usb_storage") || ((flags & EFH_USER) == 0)) {
768 /* When unplugged, unmount the device even if
769 * usb storage is disabled in the GUI.
771 exec_for_host(host_no, (flags & EFH_USER) ? 0x00 : 0x02, flags, umount_partition);
772 /* Restart NAS applications (they could be killed by umount_mountpoint),
773 * or just re-read the configuration.
775 restart_nas_services(0, 1);
781 /* This gets called at reboot or upgrade. The system is stopping. */
782 void remove_storage_main(int shutdn)
784 if (shutdn)
785 restart_nas_services(1, 0);
786 /* Unmount all partitions */
787 exec_for_host(-1, 0x02, shutdn ? EFH_SHUTDN : 0, umount_partition);
791 /*******
792 * All the complex locking & checking code was removed when the kernel USB-storage
793 * bugs were fixed.
794 * The crash bug was with overlapped I/O to different USB drives, not specifically
795 * with mount processing.
797 * And for USB devices that are slow to come up. The kernel now waits until the
798 * USB drive has settled, and it correctly reads the partition table before calling
799 * the hotplug agent.
801 * The kernel patch was cleaning up data structures on an unplug. It
802 * needs to wait until the disk is unmounted. We have 20 seconds to do
803 * the unmounts.
804 *******/
806 #ifdef LINUX26
807 static inline void usbled_proc(char *device, int add)
809 char *p;
810 char param[32];
812 if (do_led(LED_USB, LED_PROBE) != 255) {
813 strncpy(param, device, sizeof(param));
814 if ((p = strchr(param, ':')) != NULL)
815 *p = 0;
817 /* verify if we need to ignore this device (i.e. an internal SD/MMC slot ) */
818 p = nvram_safe_get("usb_noled");
819 if (strcmp(p, param) == 0)
820 return;
822 f_write_string(add ? "/proc/leds-usb/add" : "/proc/leds-usb/remove", param, 0, 0);
825 #endif
827 /* Plugging or removing usb device
829 * On an occurrance, multiple hotplug events may be fired off.
830 * For example, if a hub is plugged or unplugged, an event
831 * will be generated for everything downstream of it, plus one for
832 * the hub itself. These are fired off simultaneously, not serially.
833 * This means that many many hotplug processes will be running at
834 * the same time.
836 * The hotplug event generated by the kernel gives us several pieces
837 * of information:
838 * PRODUCT is vendorid/productid/rev#.
839 * DEVICE is /proc/bus/usb/bus#/dev#
840 * ACTION is add or remove
841 * SCSI_HOST is the host (controller) number (this relies on the custom kernel patch)
843 * Note that when we get a hotplug add event, the USB susbsystem may
844 * or may not have yet tried to read the partition table of the
845 * device. For a new controller that has never been seen before,
846 * generally yes. For a re-plug of a controller that has been seen
847 * before, generally no.
849 * On a remove, the partition info has not yet been expunged. The
850 * partitions show up as /dev/discs/disc#/part#, and /proc/partitions.
851 * It appears that doing a "stat" for a non-existant partition will
852 * causes the kernel to re-validate the device and update the
853 * partition table info. However, it won't re-validate if the disc is
854 * mounted--you'll get a "Device busy for revalidation (usage=%d)" in
855 * syslog.
857 * The $INTERFACE is "class/subclass/protocol"
858 * Some interesting classes:
859 * 8 = mass storage
860 * 7 = printer
861 * 3 = HID. 3/1/2 = mouse.
862 * 6 = still image (6/1/1 = Digital camera Camera)
863 * 9 = Hub
864 * 255 = scanner (255/255/255)
866 * Observed:
867 * Hub seems to have no INTERFACE (null), and TYPE of "9/0/0"
868 * Flash disk seems to have INTERFACE of "8/6/80", and TYPE of "0/0/0"
870 * When a hub is unplugged, a hotplug event is generated for it and everything
871 * downstream from it. You cannot depend on getting these events in any
872 * particular order, since there will be many hotplug programs all fired off
873 * at almost the same time.
874 * On a remove, don't try to access the downstream devices right away, give the
875 * kernel time to finish cleaning up all the data structures, which will be
876 * in the process of being torn down.
878 * On the initial plugin, the first time the kernel usb-storage subsystem sees
879 * the host (identified by GUID), it automatically reads the partition table.
880 * On subsequent plugins, it does not.
882 * Special values for Web Administration to unmount or remount
883 * all partitions of the host:
884 * INTERFACE=TOMATO/...
885 * ACTION=add/remove
886 * SCSI_HOST=<host_no>
887 * If host_no is negative, we unmount all partions of *all* hosts.
889 void hotplug_usb(void)
891 int add;
892 int host = -1;
893 char *interface = getenv("INTERFACE");
894 char *action = getenv("ACTION");
895 char *product = getenv("PRODUCT");
896 #ifdef LINUX26
897 char *device = getenv("DEVICENAME");
898 int is_block = strcmp(getenv("SUBSYSTEM") ? : "", "block") == 0;
899 #else
900 char *device = getenv("DEVICE");
901 #endif
902 char *scsi_host = getenv("SCSI_HOST");
904 _dprintf("%s hotplug INTERFACE=%s ACTION=%s PRODUCT=%s HOST=%s DEVICE=%s\n",
905 getenv("SUBSYSTEM") ? : "USB", interface, action, product, scsi_host, device);
907 if (!nvram_get_int("usb_enable")) return;
908 #ifdef LINUX26
909 if (!action || ((!interface || !product) && !is_block))
910 #else
911 if (!interface || !action || !product) /* Hubs bail out here. */
912 #endif
913 return;
915 if (scsi_host)
916 host = atoi(scsi_host);
918 if (!wait_action_idle(10)) return;
920 add = (strcmp(action, "add") == 0);
921 if (add && (strncmp(interface ? : "", "TOMATO/", 7) != 0)) {
922 #ifdef LINUX26
923 if (!is_block && device)
924 #endif
925 syslog(LOG_DEBUG, "Attached USB device %s [INTERFACE=%s PRODUCT=%s]",
926 device, interface, product);
927 #ifndef LINUX26
928 /* To allow automount to be blocked on startup.
929 * In kernel 2.6 we still need to serialize mount/umount calls -
930 * so the lock is down below in the "block" hotplug processing.
932 file_unlock(file_lock("usb"));
933 #endif
936 if (strncmp(interface ? : "", "TOMATO/", 7) == 0) { /* web admin */
937 if (scsi_host == NULL)
938 host = atoi(product); // for backward compatibility
939 /* If host is negative, unmount all partitions of *all* hosts.
940 * If host == -1, execute "soft" unmount (do not kill NAS apps, no "lazy" umount).
941 * If host == -2, run "hard" unmount, as if the drive is unplugged.
942 * This feature can be used in custom scripts as following:
944 * # INTERFACE=TOMATO/1 ACTION=remove PRODUCT=-1 SCSI_HOST=-1 hotplug usb
946 * PRODUCT is required to pass the env variables verification.
948 /* Unmount or remount all partitions of the host. */
949 hotplug_usb_storage_device(host < 0 ? -1 : host, add ? -1 : 0,
950 host == -2 ? 0 : EFH_USER);
952 #ifdef LINUX26
953 else if (is_block && strcmp(getenv("MAJOR") ? : "", "8") == 0 && strcmp(getenv("PHYSDEVBUS") ? : "", "scsi") == 0) {
954 /* scsi partition */
955 char devname[64];
956 int lock;
958 sprintf(devname, "/dev/%s", device);
959 lock = file_lock("usb");
960 if (add) {
961 if (nvram_get_int("usb_storage") && nvram_get_int("usb_automount")) {
962 int minor = atoi(getenv("MINOR") ? : "0");
963 if ((minor % 16) == 0 && !is_no_partition(device)) {
964 /* This is a disc, and not a "no-partition" device,
965 * like APPLE iPOD shuffle. We can't mount it.
967 return;
969 if (mount_partition(devname, host, NULL, device, EFH_HP_ADD)) {
970 restart_nas_services(0, 1); // restart all NAS applications
974 else {
975 /* When unplugged, unmount the device even if usb storage is disabled in the GUI */
976 umount_partition(devname, host, NULL, device, EFH_HP_REMOVE);
977 /* Restart NAS applications (they could be killed by umount_mountpoint),
978 * or just re-read the configuration.
980 restart_nas_services(0, 1);
982 file_unlock(lock);
984 #endif
985 else if (strncmp(interface ? : "", "8/", 2) == 0) { /* usb storage */
986 #ifdef LINUX26
987 usbled_proc(device, add);
988 #endif
989 run_nvscript("script_usbhotplug", NULL, 2);
990 #ifndef LINUX26
991 hotplug_usb_storage_device(host, add, (add ? EFH_HP_ADD : EFH_HP_REMOVE) | (host < 0 ? EFH_HUNKNOWN : 0));
992 #endif
994 else { /* It's some other type of USB device, not storage. */
995 #ifdef LINUX26
996 if (is_block) return;
997 #endif
998 #ifdef LINUX26
999 if (strncmp(interface ? : "", "7/", 2) == 0) /* printer */
1000 usbled_proc(device, add);
1001 #endif
1002 /* Do nothing. The user's hotplug script must do it all. */
1003 run_nvscript("script_usbhotplug", NULL, 2);