allow coexistance of N build and AC build.
[tomato.git] / release / src / router / rc / usb.c
blobc89da803b04b64e97e7fa941585c3f738efb1fc5
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");
138 #ifdef TCONFIG_HFS
139 if (nvram_get_int("usb_fs_hfs")) {
140 modprobe("hfs");
141 modprobe("hfsplus");
143 #endif
145 #if defined(LINUX26) && defined(TCONFIG_MICROSD)
146 if (nvram_get_int("usb_mmc") == 1) {
147 /* insert SD/MMC modules if present */
148 modprobe("mmc_core");
149 modprobe("mmc_block");
150 modprobe("sdhci");
152 #endif
155 /* if enabled, force USB2 before USB1.1 */
156 if (nvram_get_int("usb_usb2") == 1) {
157 i = nvram_get_int("usb_irq_thresh");
158 if ((i < 0) || (i > 6))
159 i = 0;
160 sprintf(param, "log2_irq_thresh=%d", i);
161 modprobe(USB20_MOD, param);
164 if (nvram_get_int("usb_uhci") == 1) {
165 modprobe(USBUHCI_MOD);
168 if (nvram_get_int("usb_ohci") == 1) {
169 modprobe(USBOHCI_MOD);
172 if (nvram_get_int("usb_printer")) {
173 symlink("/dev/usb", "/dev/printers");
174 modprobe(USBPRINTER_MOD);
176 /* start printer server only if not already running */
177 if (p9100d_sig(0) != 0) {
178 eval("p910nd",
179 nvram_get_int("usb_printer_bidirect") ? "-b" : "", //bidirectional
180 "-f", "/dev/usb/lp0", // device
181 "0" // listen port
185 #ifdef LINUX26
186 if (nvram_get_int("idle_enable") == 1) {
187 xstart( "sd-idle" );
189 #endif
191 #ifdef TCONFIG_UPS
192 start_ups();
193 #endif
195 #ifdef TCONFIG_USBAP
196 //enable eth2 after detect new iface by wl_high module
197 sleep(5);
198 xstart("service", "wireless", "restart");
199 #endif
201 // shibby
202 // If we want restore backup of webmon from USB device,
203 // we have to wait for mount USB devices by hotplug
204 // and then reboot firewall service (webmon iptables rules) one more time.
205 if( nvram_match( "log_wm", "1" ) && nvram_match( "webmon_bkp", "1" ) )
206 xstart( "service", "firewall", "restart" );
211 void stop_usb(void)
213 int disabled = !nvram_get_int("usb_enable");
215 // only find and kill the printer server we started (port 0)
216 p9100d_sig(SIGTERM);
217 modprobe_r(USBPRINTER_MOD);
219 // only stop storage services if disabled
220 if (disabled || !nvram_get_int("usb_storage")) {
221 // Unmount all partitions
222 remove_storage_main(0);
224 // Stop storage services
225 modprobe_r("ext2");
226 modprobe_r("ext3");
227 modprobe_r("jbd");
228 #ifdef LINUX26
229 modprobe_r("mbcache");
230 #endif
231 modprobe_r("vfat");
232 modprobe_r("fat");
233 modprobe_r("fuse");
234 #ifdef TCONFIG_HFS
235 modprobe_r("hfs");
236 modprobe_r("hfsplus");
237 #endif
238 sleep(1);
240 #ifdef TCONFIG_SAMBASRV
241 modprobe_r("nls_cp437");
242 modprobe_r("nls_cp850");
243 modprobe_r("nls_cp852");
244 modprobe_r("nls_cp866");
245 #ifdef LINUX26
246 modprobe_r("nls_cp932");
247 modprobe_r("nls_cp936");
248 modprobe_r("nls_cp949");
249 modprobe_r("nls_cp950");
250 #endif
251 #endif
252 modprobe_r(USBSTORAGE_MOD);
253 modprobe_r(SD_MOD);
254 #ifdef LINUX26
255 modprobe_r(SCSI_WAIT_MOD);
256 #endif
257 modprobe_r(SCSI_MOD);
260 #if defined(LINUX26) && defined(TCONFIG_MICROSD)
261 if (disabled || !nvram_get_int("usb_storage") || nvram_get_int("usb_mmc") != 1) {
262 modprobe_r("sdhci");
263 modprobe_r("mmc_block");
264 modprobe_r("mmc_core");
266 #endif
268 if (disabled || nvram_get_int("usb_ohci") != 1) modprobe_r(USBOHCI_MOD);
269 if (disabled || nvram_get_int("usb_uhci") != 1) modprobe_r(USBUHCI_MOD);
270 if (disabled || nvram_get_int("usb_usb2") != 1) modprobe_r(USB20_MOD);
272 #ifdef LINUX26
273 modprobe_r("leds-usb");
274 modprobe_r("ledtrig-usbdev");
275 led(LED_USB, LED_OFF);
276 #endif
278 // only unload core modules if usb is disabled
279 if (disabled) {
280 umount("/proc/bus/usb"); // unmount usb device filesystem
281 modprobe_r(USBOHCI_MOD);
282 modprobe_r(USBUHCI_MOD);
283 modprobe_r(USB20_MOD);
284 modprobe_r(USBCORE_MOD);
287 #ifdef LINUX26
288 if (nvram_get_int("idle_enable") == 0) {
289 killall("sd-idle", SIGTERM);
292 #ifdef TCONFIG_UPS
293 stop_ups();
294 #endif
296 if (nvram_match("3g_usb", "0") ) {
297 if (nvram_match("3g_module", "sierra") ) {
298 modprobe_r("sierra");
299 modprobe_r("usbserial");
302 if (nvram_match("3g_module", "option") ) {
303 modprobe_r("option");
304 modprobe_r("usbserial");
307 // shibby
308 // when modem use usbserial module and we will try remove module, module will crash
309 // the only solution at the moment is reboot router
310 // FIX THIS
311 if (nvram_match("3g_module", "usbserial") ) {
312 modprobe_r("usbserial");
316 if (nvram_match("boardtype", "0x052b")) { // Netgear WNR3500L v2 - disable USB port
317 xstart("gpio", "disable", "20");
321 #endif
326 #define MOUNT_VAL_FAIL 0
327 #define MOUNT_VAL_RONLY 1
328 #define MOUNT_VAL_RW 2
329 #define MOUNT_VAL_EXIST 3
331 int mount_r(char *mnt_dev, char *mnt_dir, char *type)
333 struct mntent *mnt;
334 int ret;
335 char options[140];
336 char flagfn[128];
337 int dir_made;
339 if ((mnt = findmntents(mnt_dev, 0, NULL, 0))) {
340 syslog(LOG_INFO, "USB partition at %s already mounted on %s",
341 mnt_dev, mnt->mnt_dir);
342 return MOUNT_VAL_EXIST;
345 options[0] = 0;
347 if (type) {
348 unsigned long flags = MS_NOATIME | MS_NODEV;
350 if (strcmp(type, "swap") == 0 || strcmp(type, "mbr") == 0) {
351 /* not a mountable partition */
352 flags = 0;
354 else if (strcmp(type, "ext2") == 0 || strcmp(type, "ext3") == 0) {
355 if (nvram_invmatch("usb_ext_opt", ""))
356 sprintf(options, nvram_safe_get("usb_ext_opt"));
358 else if (strcmp(type, "vfat") == 0) {
359 if (nvram_invmatch("smbd_cset", ""))
360 sprintf(options, "iocharset=%s%s",
361 isdigit(nvram_get("smbd_cset")[0]) ? "cp" : "",
362 nvram_get("smbd_cset"));
363 if (nvram_invmatch("smbd_cpage", "")) {
364 char *cp = nvram_safe_get("smbd_cpage");
365 sprintf(options + strlen(options), ",codepage=%s" + (options[0] ? 0 : 1), cp);
366 sprintf(flagfn, "nls_cp%s", cp);
368 cp = nvram_get("smbd_nlsmod");
369 if ((cp) && (*cp != 0) && (strcmp(cp, flagfn) != 0))
370 modprobe_r(cp);
372 modprobe(flagfn);
373 nvram_set("smbd_nlsmod", flagfn);
375 sprintf(options + strlen(options), ",shortname=winnt" + (options[0] ? 0 : 1));
376 #ifdef LINUX26
377 sprintf(options + strlen(options), ",flush" + (options[0] ? 0 : 1));
378 #endif
379 if (nvram_invmatch("usb_fat_opt", ""))
380 sprintf(options + strlen(options), "%s%s", options[0] ? "," : "", nvram_safe_get("usb_fat_opt"));
382 else if (strncmp(type, "ntfs", 4) == 0) {
383 if (nvram_invmatch("smbd_cset", ""))
384 sprintf(options, "iocharset=%s%s",
385 isdigit(nvram_get("smbd_cset")[0]) ? "cp" : "",
386 nvram_get("smbd_cset"));
387 if (nvram_invmatch("usb_ntfs_opt", ""))
388 sprintf(options + strlen(options), "%s%s", options[0] ? "," : "", nvram_safe_get("usb_ntfs_opt"));
391 if (flags) {
392 if ((dir_made = mkdir_if_none(mnt_dir))) {
393 /* Create the flag file for remove the directory on dismount. */
394 sprintf(flagfn, "%s/.autocreated-dir", mnt_dir);
395 f_write(flagfn, NULL, 0, 0, 0);
398 ret = mount(mnt_dev, mnt_dir, type, flags, options[0] ? options : "");
400 /* try ntfs-3g in case it's installed */
401 if (ret != 0 && strncmp(type, "ntfs", 4) == 0) {
402 sprintf(options + strlen(options), ",noatime,nodev" + (options[0] ? 0 : 1));
403 #ifdef TCONFIG_NTFS
404 if (nvram_get_int("usb_fs_ntfs"))
405 #endif
406 ret = eval("ntfs-3g", "-o", options, mnt_dev, mnt_dir);
409 #ifdef TCONFIG_HFS
410 if (ret != 0 && strncmp(type, "hfs", "") == 0) {
411 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
414 if (ret != 0 && strncmp(type, "hfsplus", "") == 0) {
415 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
417 #endif
419 if (ret != 0) /* give it another try - guess fs */
420 ret = eval("mount", "-o", "noatime,nodev", mnt_dev, mnt_dir);
422 if (ret == 0) {
423 syslog(LOG_INFO, "USB %s%s fs at %s mounted on %s",
424 type, (flags & MS_RDONLY) ? " (ro)" : "", mnt_dev, mnt_dir);
425 return (flags & MS_RDONLY) ? MOUNT_VAL_RONLY : MOUNT_VAL_RW;
428 if (dir_made) {
429 unlink(flagfn);
430 rmdir(mnt_dir);
434 return MOUNT_VAL_FAIL;
438 struct mntent *mount_fstab(char *dev_name, char *type, char *label, char *uuid)
440 struct mntent *mnt = NULL;
441 #if 0
442 if (eval("mount", "-a") == 0)
443 mnt = findmntents(dev_name, 0, NULL, 0);
444 #else
445 char spec[PATH_MAX+1];
447 if (label && *label) {
448 sprintf(spec, "LABEL=%s", label);
449 if (eval("mount", spec) == 0)
450 mnt = findmntents(dev_name, 0, NULL, 0);
453 if (!mnt && uuid && *uuid) {
454 sprintf(spec, "UUID=%s", uuid);
455 if (eval("mount", spec) == 0)
456 mnt = findmntents(dev_name, 0, NULL, 0);
459 if (!mnt) {
460 if (eval("mount", dev_name) == 0)
461 mnt = findmntents(dev_name, 0, NULL, 0);
464 if (!mnt) {
465 /* Still did not find what we are looking for, try absolute path */
466 if (realpath(dev_name, spec)) {
467 if (eval("mount", spec) == 0)
468 mnt = findmntents(dev_name, 0, NULL, 0);
471 #endif
473 if (mnt)
474 syslog(LOG_INFO, "USB %s fs at %s mounted on %s", type, dev_name, mnt->mnt_dir);
475 return (mnt);
479 /* Check if the UFD is still connected because the links created in /dev/discs
480 * are not removed when the UFD is unplugged.
481 * The file to read is: /proc/scsi/usb-storage-#/#, where # is the host no.
482 * We are looking for "Attached: Yes".
484 static int usb_ufd_connected(int host_no)
486 char proc_file[128];
487 #ifndef LINUX26
488 char line[256];
489 #endif
490 FILE *fp;
492 sprintf(proc_file, "%s/%s-%d/%d", PROC_SCSI_ROOT, USB_STORAGE, host_no, host_no);
493 fp = fopen(proc_file, "r");
495 if (!fp) {
496 /* try the way it's implemented in newer kernels: /proc/scsi/usb-storage/[host] */
497 sprintf(proc_file, "%s/%s/%d", PROC_SCSI_ROOT, USB_STORAGE, host_no);
498 fp = fopen(proc_file, "r");
501 if (fp) {
502 #ifdef LINUX26
503 fclose(fp);
504 return 1;
505 #else
506 while (fgets(line, sizeof(line), fp) != NULL) {
507 if (strstr(line, "Attached: Yes")) {
508 fclose(fp);
509 return 1;
512 fclose(fp);
513 #endif
516 return 0;
520 #ifndef MNT_DETACH
521 #define MNT_DETACH 0x00000002 /* from linux/fs.h - just detach from the tree */
522 #endif
523 int umount_mountpoint(struct mntent *mnt, uint flags);
524 int uswap_mountpoint(struct mntent *mnt, uint flags);
526 /* Unmount this partition from all its mountpoints. Note that it may
527 * actually be mounted several times, either with different names or
528 * with "-o bind" flag.
529 * If the special flagfile is now revealed, delete it and [attempt to] delete
530 * the directory.
532 int umount_partition(char *dev_name, int host_num, char *dsc_name, char *pt_name, uint flags)
534 sync(); /* This won't matter if the device is unplugged, though. */
536 if (flags & EFH_HUNKNOWN) {
537 /* EFH_HUNKNOWN flag is passed if the host was unknown.
538 * Only unmount disconnected drives in this case.
540 if (usb_ufd_connected(host_num))
541 return 0;
544 /* Find all the active swaps that are on this device and stop them. */
545 findmntents(dev_name, 1, uswap_mountpoint, flags);
547 /* Find all the mountpoints that are for this device and unmount them. */
548 findmntents(dev_name, 0, umount_mountpoint, flags);
549 return 0;
552 int uswap_mountpoint(struct mntent *mnt, uint flags)
554 swapoff(mnt->mnt_fsname);
555 return 0;
558 int umount_mountpoint(struct mntent *mnt, uint flags)
560 int ret = 1, count;
561 char flagfn[128];
563 sprintf(flagfn, "%s/.autocreated-dir", mnt->mnt_dir);
565 /* Run user pre-unmount scripts if any. It might be too late if
566 * the drive has been disconnected, but we'll try it anyway.
568 if (nvram_get_int("usb_automount"))
569 run_nvscript("script_usbumount", mnt->mnt_dir, 3);
570 /* Run *.autostop scripts located in the root of the partition being unmounted if any. */
571 run_userfile(mnt->mnt_dir, ".autostop", mnt->mnt_dir, 5);
572 run_nvscript("script_autostop", mnt->mnt_dir, 5);
574 count = 0;
575 while ((ret = umount(mnt->mnt_dir)) && (count < 2)) {
576 count++;
577 /* If we could not unmount the drive on the 1st try,
578 * kill all NAS applications so they are not keeping the device busy -
579 * unless it's an unmount request from the Web GUI.
581 if ((count == 1) && ((flags & EFH_USER) == 0))
582 restart_nas_services(1, 0);
583 sleep(1);
586 if (ret == 0)
587 syslog(LOG_INFO, "USB partition unmounted from %s", mnt->mnt_dir);
589 if (ret && ((flags & EFH_SHUTDN) != 0)) {
590 /* If system is stopping (not restarting), and we couldn't unmount the
591 * partition, try to remount it as read-only. Ignore the return code -
592 * we can still try to do a lazy unmount.
594 eval("mount", "-o", "remount,ro", mnt->mnt_dir);
597 if (ret && ((flags & EFH_USER) == 0)) {
598 /* Make one more try to do a lazy unmount unless it's an unmount
599 * request from the Web GUI.
600 * MNT_DETACH will expose the underlying mountpoint directory to all
601 * except whatever has cd'ed to the mountpoint (thereby making it busy).
602 * So the unmount can't actually fail. It disappears from the ken of
603 * everyone else immediately, and from the ken of whomever is keeping it
604 * busy when they move away from it. And then it disappears for real.
606 ret = umount2(mnt->mnt_dir, MNT_DETACH);
607 syslog(LOG_INFO, "USB partition busy - will unmount ASAP from %s", mnt->mnt_dir);
610 if (ret == 0) {
611 if ((unlink(flagfn) == 0)) {
612 // Only delete the directory if it was auto-created
613 rmdir(mnt->mnt_dir);
616 return (ret == 0);
620 /* Mount this partition on this disc.
621 * If the device is already mounted on any mountpoint, don't mount it again.
622 * If this is a swap partition, try swapon -a.
623 * If this is a regular partition, try mount -a.
625 * Before we mount any partitions:
626 * If the type is swap and /etc/fstab exists, do "swapon -a"
627 * If /etc/fstab exists, try mounting using fstab.
628 * We delay invoking mount because mount will probe all the partitions
629 * to read the labels, and we don't want it to do that early on.
630 * We don't invoke swapon until we actually find a swap partition.
632 * If the mount succeeds, execute the *.autorun scripts in the top
633 * directory of the newly mounted partition.
634 * Returns NZ for success, 0 if we did not mount anything.
636 int mount_partition(char *dev_name, int host_num, char *dsc_name, char *pt_name, uint flags)
638 char the_label[128], mountpoint[128], uuid[40];
639 int ret;
640 char *type, *p;
641 static char *swp_argv[] = { "swapon", "-a", NULL };
642 struct mntent *mnt;
644 if ((type = find_label_or_uuid(dev_name, the_label, uuid)) == NULL)
645 return 0;
647 if (f_exists("/etc/fstab")) {
648 if (strcmp(type, "swap") == 0) {
649 _eval(swp_argv, NULL, 0, NULL);
650 return 0;
653 if (mount_r(dev_name, NULL, NULL) == MOUNT_VAL_EXIST)
654 return 0;
656 if ((mnt = mount_fstab(dev_name, type, the_label, uuid))) {
657 strcpy(mountpoint, mnt->mnt_dir);
658 ret = MOUNT_VAL_RW;
659 goto done;
663 if (*the_label != 0) {
664 for (p = the_label; *p; p++) {
665 if (!isalnum(*p) && !strchr("+-&.@", *p))
666 *p = '_';
668 sprintf(mountpoint, "%s/%s", MOUNT_ROOT, the_label);
669 if ((ret = mount_r(dev_name, mountpoint, type)))
670 goto done;
673 /* Can't mount to /mnt/LABEL, so try mounting to /mnt/discDN_PN */
674 sprintf(mountpoint, "%s/%s", MOUNT_ROOT, pt_name);
675 ret = mount_r(dev_name, mountpoint, type);
676 done:
677 if (ret == MOUNT_VAL_RONLY || ret == MOUNT_VAL_RW)
679 /* Run user *.autorun and post-mount scripts if any. */
680 run_userfile(mountpoint, ".autorun", mountpoint, 3);
681 if (nvram_get_int("usb_automount"))
682 run_nvscript("script_usbmount", mountpoint, 3);
684 return (ret == MOUNT_VAL_RONLY || ret == MOUNT_VAL_RW);
688 #if 0 /* LINUX26 */
691 * Finds SCSI Host number. Returns the host number >=0 if found, or (-1) otherwise.
692 * The name and host number of scsi block device in kernel 2.6 (for attached devices) can be found as
693 * /sys($DEVPATH)/host<host_no>/target<*>/<id>/block:[sda|sdb|...]
694 * where $DEVPATH is passed to hotplug events, and looks like
695 * /devices/pci0000:00/0000:00:04.1/usb1/1-1/1-1:1.2
697 * For printers this function finds a minor assigned to a printer
698 * /sys($DEVPATH)/usb:lp[0|1|2|...]
700 int find_dev_host(const char *devpath)
702 DIR *usb_devpath;
703 struct dirent *dp;
704 char buf[256];
705 int host = -1; /* Scsi Host */
707 sprintf(buf, "/sys%s", devpath);
708 if ((usb_devpath = opendir(buf))) {
709 while ((dp = readdir(usb_devpath))) {
710 errno = 0;
711 if (strncmp(dp->d_name, "host", 4) == 0) {
712 host = strtol(dp->d_name + 4, (char **)NULL, 10);
713 if (errno)
714 host = -1;
715 else
716 break;
718 else if (strncmp(dp->d_name, "usb:lp", 6) == 0) {
719 host = strtol(dp->d_name + 6, (char **)NULL, 10);
720 if (errno)
721 host = -1;
722 else
723 break;
725 else
726 continue;
728 closedir(usb_devpath);
730 return (host);
733 #endif /* LINUX26 */
735 int dir_is_mountpoint(const char *root, const char *dir)
737 char path[256];
738 struct stat sb;
739 int thisdev;
741 snprintf(path, sizeof(path), "%s%s%s", root ? : "", root ? "/" : "", dir);
743 /* Check if this is a directory */
744 sb.st_mode = S_IFDIR; /* failsafe */
745 stat(path, &sb);
747 if (S_ISDIR(sb.st_mode)) {
749 /* If this dir & its parent dir are on the same device, it is not a mountpoint */
750 strcat(path, "/.");
751 stat(path, &sb);
752 thisdev = sb.st_dev;
753 strcat(path, ".");
754 ++sb.st_dev; /* failsafe */
755 stat(path, &sb);
757 return (thisdev != sb.st_dev);
760 return 0;
763 /* Mount or unmount all partitions on this controller.
764 * Parameter: action_add:
765 * 0 = unmount
766 * >0 = mount only if automount config option is enabled.
767 * <0 = mount regardless of config option.
769 void hotplug_usb_storage_device(int host_no, int action_add, uint flags)
771 if (!nvram_get_int("usb_enable"))
772 return;
773 _dprintf("%s: host %d action: %d\n", __FUNCTION__, host_no, action_add);
775 if (action_add) {
776 if (nvram_get_int("usb_storage") && (nvram_get_int("usb_automount") || action_add < 0)) {
777 /* Do not probe the device here. It's either initiated by user,
778 * or hotplug_usb() already did.
780 if (exec_for_host(host_no, 0x00, flags, mount_partition)) {
781 restart_nas_services(0, 1); // restart all NAS applications
785 else {
786 if (nvram_get_int("usb_storage") || ((flags & EFH_USER) == 0)) {
787 /* When unplugged, unmount the device even if
788 * usb storage is disabled in the GUI.
790 exec_for_host(host_no, (flags & EFH_USER) ? 0x00 : 0x02, flags, umount_partition);
791 /* Restart NAS applications (they could be killed by umount_mountpoint),
792 * or just re-read the configuration.
794 restart_nas_services(0, 1);
800 /* This gets called at reboot or upgrade. The system is stopping. */
801 void remove_storage_main(int shutdn)
803 if (shutdn)
804 restart_nas_services(1, 0);
805 /* Unmount all partitions */
806 exec_for_host(-1, 0x02, shutdn ? EFH_SHUTDN : 0, umount_partition);
810 /*******
811 * All the complex locking & checking code was removed when the kernel USB-storage
812 * bugs were fixed.
813 * The crash bug was with overlapped I/O to different USB drives, not specifically
814 * with mount processing.
816 * And for USB devices that are slow to come up. The kernel now waits until the
817 * USB drive has settled, and it correctly reads the partition table before calling
818 * the hotplug agent.
820 * The kernel patch was cleaning up data structures on an unplug. It
821 * needs to wait until the disk is unmounted. We have 20 seconds to do
822 * the unmounts.
823 *******/
825 #ifdef LINUX26
826 static inline void usbled_proc(char *device, int add)
828 char *p;
829 char param[32];
831 if (do_led(LED_USB, LED_PROBE) != 255) {
832 strncpy(param, device, sizeof(param));
833 if ((p = strchr(param, ':')) != NULL)
834 *p = 0;
836 /* verify if we need to ignore this device (i.e. an internal SD/MMC slot ) */
837 p = nvram_safe_get("usb_noled");
838 if (strcmp(p, param) == 0)
839 return;
841 f_write_string(add ? "/proc/leds-usb/add" : "/proc/leds-usb/remove", param, 0, 0);
844 #endif
846 /* Plugging or removing usb device
848 * On an occurrance, multiple hotplug events may be fired off.
849 * For example, if a hub is plugged or unplugged, an event
850 * will be generated for everything downstream of it, plus one for
851 * the hub itself. These are fired off simultaneously, not serially.
852 * This means that many many hotplug processes will be running at
853 * the same time.
855 * The hotplug event generated by the kernel gives us several pieces
856 * of information:
857 * PRODUCT is vendorid/productid/rev#.
858 * DEVICE is /proc/bus/usb/bus#/dev#
859 * ACTION is add or remove
860 * SCSI_HOST is the host (controller) number (this relies on the custom kernel patch)
862 * Note that when we get a hotplug add event, the USB susbsystem may
863 * or may not have yet tried to read the partition table of the
864 * device. For a new controller that has never been seen before,
865 * generally yes. For a re-plug of a controller that has been seen
866 * before, generally no.
868 * On a remove, the partition info has not yet been expunged. The
869 * partitions show up as /dev/discs/disc#/part#, and /proc/partitions.
870 * It appears that doing a "stat" for a non-existant partition will
871 * causes the kernel to re-validate the device and update the
872 * partition table info. However, it won't re-validate if the disc is
873 * mounted--you'll get a "Device busy for revalidation (usage=%d)" in
874 * syslog.
876 * The $INTERFACE is "class/subclass/protocol"
877 * Some interesting classes:
878 * 8 = mass storage
879 * 7 = printer
880 * 3 = HID. 3/1/2 = mouse.
881 * 6 = still image (6/1/1 = Digital camera Camera)
882 * 9 = Hub
883 * 255 = scanner (255/255/255)
885 * Observed:
886 * Hub seems to have no INTERFACE (null), and TYPE of "9/0/0"
887 * Flash disk seems to have INTERFACE of "8/6/80", and TYPE of "0/0/0"
889 * When a hub is unplugged, a hotplug event is generated for it and everything
890 * downstream from it. You cannot depend on getting these events in any
891 * particular order, since there will be many hotplug programs all fired off
892 * at almost the same time.
893 * On a remove, don't try to access the downstream devices right away, give the
894 * kernel time to finish cleaning up all the data structures, which will be
895 * in the process of being torn down.
897 * On the initial plugin, the first time the kernel usb-storage subsystem sees
898 * the host (identified by GUID), it automatically reads the partition table.
899 * On subsequent plugins, it does not.
901 * Special values for Web Administration to unmount or remount
902 * all partitions of the host:
903 * INTERFACE=TOMATO/...
904 * ACTION=add/remove
905 * SCSI_HOST=<host_no>
906 * If host_no is negative, we unmount all partions of *all* hosts.
908 void hotplug_usb(void)
910 int add;
911 int host = -1;
912 char *interface = getenv("INTERFACE");
913 char *action = getenv("ACTION");
914 char *product = getenv("PRODUCT");
915 #ifdef LINUX26
916 char *device = getenv("DEVICENAME");
917 int is_block = strcmp(getenv("SUBSYSTEM") ? : "", "block") == 0;
918 #else
919 char *device = getenv("DEVICE");
920 #endif
921 char *scsi_host = getenv("SCSI_HOST");
923 _dprintf("%s hotplug INTERFACE=%s ACTION=%s PRODUCT=%s HOST=%s DEVICE=%s\n",
924 getenv("SUBSYSTEM") ? : "USB", interface, action, product, scsi_host, device);
926 if (!nvram_get_int("usb_enable")) return;
927 #ifdef LINUX26
928 if (!action || ((!interface || !product) && !is_block))
929 #else
930 if (!interface || !action || !product) /* Hubs bail out here. */
931 #endif
932 return;
934 if (scsi_host)
935 host = atoi(scsi_host);
937 if (!wait_action_idle(10)) return;
939 add = (strcmp(action, "add") == 0);
940 if (add && (strncmp(interface ? : "", "TOMATO/", 7) != 0)) {
941 #ifdef LINUX26
942 if (!is_block && device)
943 #endif
944 syslog(LOG_DEBUG, "Attached USB device %s [INTERFACE=%s PRODUCT=%s]",
945 device, interface, product);
946 #ifndef LINUX26
947 /* To allow automount to be blocked on startup.
948 * In kernel 2.6 we still need to serialize mount/umount calls -
949 * so the lock is down below in the "block" hotplug processing.
951 file_unlock(file_lock("usb"));
952 #endif
955 if (strncmp(interface ? : "", "TOMATO/", 7) == 0) { /* web admin */
956 if (scsi_host == NULL)
957 host = atoi(product); // for backward compatibility
958 /* If host is negative, unmount all partitions of *all* hosts.
959 * If host == -1, execute "soft" unmount (do not kill NAS apps, no "lazy" umount).
960 * If host == -2, run "hard" unmount, as if the drive is unplugged.
961 * This feature can be used in custom scripts as following:
963 * # INTERFACE=TOMATO/1 ACTION=remove PRODUCT=-1 SCSI_HOST=-1 hotplug usb
965 * PRODUCT is required to pass the env variables verification.
967 /* Unmount or remount all partitions of the host. */
968 hotplug_usb_storage_device(host < 0 ? -1 : host, add ? -1 : 0,
969 host == -2 ? 0 : EFH_USER);
971 #ifdef LINUX26
972 else if (is_block && strcmp(getenv("MAJOR") ? : "", "8") == 0 && strcmp(getenv("PHYSDEVBUS") ? : "", "scsi") == 0) {
973 /* scsi partition */
974 char devname[64];
975 int lock;
977 sprintf(devname, "/dev/%s", device);
978 lock = file_lock("usb");
979 if (add) {
980 if (nvram_get_int("usb_storage") && nvram_get_int("usb_automount")) {
981 int minor = atoi(getenv("MINOR") ? : "0");
982 if ((minor % 16) == 0 && !is_no_partition(device)) {
983 /* This is a disc, and not a "no-partition" device,
984 * like APPLE iPOD shuffle. We can't mount it.
986 return;
988 if (mount_partition(devname, host, NULL, device, EFH_HP_ADD)) {
989 restart_nas_services(0, 1); // restart all NAS applications
993 else {
994 /* When unplugged, unmount the device even if usb storage is disabled in the GUI */
995 umount_partition(devname, host, NULL, device, EFH_HP_REMOVE);
996 /* Restart NAS applications (they could be killed by umount_mountpoint),
997 * or just re-read the configuration.
999 restart_nas_services(0, 1);
1001 file_unlock(lock);
1003 #endif
1004 else if (strncmp(interface ? : "", "8/", 2) == 0) { /* usb storage */
1005 #ifdef LINUX26
1006 usbled_proc(device, add);
1007 #endif
1008 run_nvscript("script_usbhotplug", NULL, 2);
1009 #ifndef LINUX26
1010 hotplug_usb_storage_device(host, add, (add ? EFH_HP_ADD : EFH_HP_REMOVE) | (host < 0 ? EFH_HUNKNOWN : 0));
1011 #endif
1013 else { /* It's some other type of USB device, not storage. */
1014 #ifdef LINUX26
1015 if (is_block) return;
1016 #endif
1017 #ifdef LINUX26
1018 if (strncmp(interface ? : "", "7/", 2) == 0) /* printer */
1019 usbled_proc(device, add);
1020 #endif
1021 /* Do nothing. The user's hotplug script must do it all. */
1022 run_nvscript("script_usbhotplug", NULL, 2);