diff options
author | Andreas Baumann <mail@andreasbaumann.cc> | 2015-01-03 12:04:58 +0100 |
---|---|---|
committer | Andreas Baumann <mail@andreasbaumann.cc> | 2015-01-03 12:04:58 +0100 |
commit | 008d0be72b2f160382c6e880765e96b64a050c65 (patch) | |
tree | 36f48a98a3815a408e2ce1693dd182af90f80305 /release/src/router/busybox/miscutils | |
parent | 611becfb8726c60cb060368541ad98191d4532f5 (diff) | |
download | tomato-008d0be72b2f160382c6e880765e96b64a050c65.tar.gz tomato-008d0be72b2f160382c6e880765e96b64a050c65.tar.bz2 |
imported original firmware WRT54GL_v4.30.11_11_US
Diffstat (limited to 'release/src/router/busybox/miscutils')
-rwxr-xr-x | release/src/router/busybox/miscutils/Config.in | 147 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/Makefile | 30 | ||||
-rwxr-xr-x | release/src/router/busybox/miscutils/Makefile.in | 43 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/adjtimex.c | 167 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/crond.c | 1100 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/crontab.c | 391 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/dc.c | 215 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/dutmp.c | 66 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/hdparm.c | 2665 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/makedevs.c | 92 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/mt.c | 121 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/strings.c | 160 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/time.c | 502 | ||||
-rw-r--r-- | release/src/router/busybox/miscutils/watchdog.c | 81 |
14 files changed, 5780 insertions, 0 deletions
diff --git a/release/src/router/busybox/miscutils/Config.in b/release/src/router/busybox/miscutils/Config.in new file mode 100755 index 00000000..0c56f0ee --- /dev/null +++ b/release/src/router/busybox/miscutils/Config.in @@ -0,0 +1,147 @@ +# +# For a description of the syntax of this configuration file, +# see scripts/kbuild/config-language.txt. +# + +menu "Miscellaneous Utilities" + +config CONFIG_ADJTIMEX + bool "adjtimex" + default n + help + Adjtimex reads and optionally sets adjustment parameters for + the Linux clock adjustment algorithm. + +config CONFIG_CROND + bool "crond" + default n + help + Crond is a background daemon that parses individual crontab + files and executes commands on behalf of the users in question. + +config CONFIG_FEATURE_CROND_CALL_SENDMAIL + bool " Using /usr/sbin/sendmail?" + default n + depends on CONFIG_CROND + help + Support call /usr/sbin/sendmail for send cmd outputs. + +config CONFIG_CRONTAB + bool "crontab" + default n + help + Crontab manipulates the crontab for a particular user. Only + the superuser may specify a different user and/or crontab directory. + +config CONFIG_DC + bool "dc" + default n + help + Dc is a reverse-polish desk calculator which supports unlimited + precision arithmetic. + +config CONFIG_DUTMP + bool "dutmp" + default n + help + 'dutmp' is a utility used by the Linux Router Project (as far as I + know nobody else uses it). It dumps the contents of the utmp file to + STDOUT with each field seperated by a colon. IP addresses are are + given in hex in native byte order. It is intended that this format + can then be parsed by shell scripts. + +config CONFIG_HDPARM + bool "hdparm" + default n + help + Get/Set hard drive parameters. Primarily intended for ATA + drives. Adds about 13k (or around 30k if you enable the + CONFIG_FEATURE_HDPARM_GET_IDENTITY option).... + +config CONFIG_FEATURE_HDPARM_GET_IDENTITY + bool " Support obtaining detailed information directly from drives" + default y + depends on CONFIG_HDPARM + help + Enables the -I and -Istdin options to obtain detailed information + directly from drives about their capabilities and supported ATA + feature set. Enabling this option will add about 16k... + +config CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + bool " Register an IDE interface (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -R' option to register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + bool " Un-register an IDE interface (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -U' option to un-register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + bool " perform device reset (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -w' option to perform a device reset. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + bool " tristate device for hotswap (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -x' option to tristate device for hotswap, + and the '-b' option to get/set bus state. This is dangerous + stuff, so you should probably say N. + +config CONFIG_MAKEDEVS + bool "makedevs" + default n + help + 'makedevs' is a utility used and created by the Linux Router Project. + It creates a large number of device special files (/dev devices) + rather quickly, and can be considerably faster then running mknod a + zillion times. + +config CONFIG_MT + bool "mt" + default n + help + Mt is used to control tape devices. You can use the mt utility + to advance or rewind a tape past a specified number of archive + files on the tape. + +config CONFIG_STRINGS + bool "strings" + default n + help + Strings prints the printable character sequences for each file + specified. + +config CONFIG_TIME + bool "time" + default n + help + The time command runs the specified program with the given arguments. + When the command finishes, time writes a message to standard output + giving timing statistics about this program run. + +config CONFIG_WATCHDOG + bool "watchdog" + default n + help + The watchdog utility is used with hardware or softwate watchdog + device drivers. It opens the specified watchdog device special file + and periodically writes a magic character to the device. If the + watchdog applet ever fails to write the magic character within a + certain amount of time, the watchdog device assumes the system has + hung, and will cause the hardware to reboot. + +endmenu + diff --git a/release/src/router/busybox/miscutils/Makefile b/release/src/router/busybox/miscutils/Makefile new file mode 100644 index 00000000..374ce68f --- /dev/null +++ b/release/src/router/busybox/miscutils/Makefile @@ -0,0 +1,30 @@ +# Makefile for busybox +# +# Copyright (C) 1999-2003 by Erik Andersen <andersen@codepoet.org> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +TOPDIR:= ../ +MISCUTILS_DIR:=./ +include $(TOPDIR).config +include $(TOPDIR)Rules.mak +include Makefile.in +all: $(libraries-y) +-include $(TOPDIR).depend + +clean: + rm -f *.o *.a $(AR_TARGET) + diff --git a/release/src/router/busybox/miscutils/Makefile.in b/release/src/router/busybox/miscutils/Makefile.in new file mode 100755 index 00000000..0f200f4f --- /dev/null +++ b/release/src/router/busybox/miscutils/Makefile.in @@ -0,0 +1,43 @@ +# Makefile for busybox +# +# Copyright (C) 1999-2003 by Erik Andersen <andersen@codepoet.org> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +MISCUTILS_AR:=miscutils.a +ifndef $(MISCUTILS_DIR) +MISCUTILS_DIR:=$(TOPDIR)miscutils/ +endif + + +MISCUTILS-y:= +MISCUTILS-$(CONFIG_ADJTIMEX) += adjtimex.o +MISCUTILS-$(CONFIG_CROND) += crond.o +MISCUTILS-$(CONFIG_CRONTAB) += crontab.o +MISCUTILS-$(CONFIG_DC) += dc.o +MISCUTILS-$(CONFIG_DUTMP) += dutmp.o +MISCUTILS-$(CONFIG_HDPARM) += hdparm.o +MISCUTILS-$(CONFIG_MAKEDEVS) += makedevs.o +MISCUTILS-$(CONFIG_MT) += mt.o +MISCUTILS-$(CONFIG_STRINGS) += strings.o +MISCUTILS-$(CONFIG_TIME) += time.o +MISCUTILS-$(CONFIG_WATCHDOG) += watchdog.o + +libraries-y+=$(MISCUTILS_DIR)$(MISCUTILS_AR) + +$(MISCUTILS_DIR)$(MISCUTILS_AR): $(patsubst %,$(MISCUTILS_DIR)%, $(MISCUTILS-y)) + $(AR) -ro $@ $(patsubst %,$(MISCUTILS_DIR)%, $(MISCUTILS-y)) + diff --git a/release/src/router/busybox/miscutils/adjtimex.c b/release/src/router/busybox/miscutils/adjtimex.c new file mode 100644 index 00000000..e941f6b4 --- /dev/null +++ b/release/src/router/busybox/miscutils/adjtimex.c @@ -0,0 +1,167 @@ +/* + * adjtimex.c - read, and possibly modify, the Linux kernel `timex' variables. + * + * Originally written: October 1997 + * Last hack: March 2001 + * Copyright 1997, 2000, 2001 Larry Doolittle <LRDoolittle@lbl.gov> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License (Version 2, + * June 1991) as published by the Free Software Foundation. At the + * time of writing, that license was published by the FSF with the URL + * http://www.gnu.org/copyleft/gpl.html, and is incorporated herein by + * reference. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * This adjtimex(1) is very similar in intent to adjtimex(8) by Steven + * Dick <ssd@nevets.oau.org> and Jim Van Zandt <jrv@vanzandt.mv.com> + * (see http://metalab.unc.edu/pub/Linux/system/admin/time/adjtimex*). + * That version predates this one, and is _much_ bigger and more + * featureful. My independently written version was very similar to + * Steven's from the start, because they both follow the kernel timex + * structure. I further tweaked this version to be equivalent to Steven's + * where possible, but I don't like getopt_long, so the actual usage + * syntax is incompatible. + * + * Amazingly enough, my Red Hat 5.2 sys/timex (and sub-includes) + * don't actually give a prototype for adjtimex(2), so building + * this code (with -Wall) gives a warning. Later versions of + * glibc fix this issue. + * + * This program is too simple for a Makefile, just build with: + * gcc -Wall -O adjtimex.c -o adjtimex + * + * busyboxed 20 March 2001, Larry Doolittle <ldoolitt@recycle.lbl.gov> + * It will autosense if it is built in a busybox environment, based + * on the BB_VER preprocessor macro. + */ + +#include <stdio.h> +#include <sys/types.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/timex.h> +#include "busybox.h" + +static struct {int bit; char *name;} statlist[] = { + { STA_PLL, "PLL" }, + { STA_PPSFREQ, "PPSFREQ" }, + { STA_PPSTIME, "PPSTIME" }, + { STA_FLL, "FFL" }, + { STA_INS, "INS" }, + { STA_DEL, "DEL" }, + { STA_UNSYNC, "UNSYNC" }, + { STA_FREQHOLD, "FREQHOLD" }, + { STA_PPSSIGNAL, "PPSSIGNAL" }, + { STA_PPSJITTER, "PPSJITTER" }, + { STA_PPSWANDER, "PPSWANDER" }, + { STA_PPSERROR, "PPSERROR" }, + { STA_CLOCKERR, "CLOCKERR" }, + { 0, NULL } }; + +static char *ret_code_descript[] = { + "clock synchronized", + "insert leap second", + "delete leap second", + "leap second in progress", + "leap second has occurred", + "clock not synchronized" }; + +#ifdef BB_VER +#define main adjtimex_main +#else +void usage(char *prog) +{ + fprintf(stderr, + "Usage: %s [ -q ] [ -o offset ] [ -f frequency ] [ -p timeconstant ] [ -t tick ]\n", + prog); +} +#define bb_show_usage() usage(argv[0]) +#endif + +int main(int argc, char ** argv) +{ + struct timex txc; + int quiet=0; + int c, i, ret, sep; + char *descript; + txc.modes=0; + for (;;) { + c = getopt( argc, argv, "qo:f:p:t:"); + if (c == EOF) break; + switch (c) { + case 'q': + quiet=1; + break; + case 'o': + txc.offset = atoi(optarg); + txc.modes |= ADJ_OFFSET_SINGLESHOT; + break; + case 'f': + txc.freq = atoi(optarg); + txc.modes |= ADJ_FREQUENCY; + break; + case 'p': + txc.constant = atoi(optarg); + txc.modes |= ADJ_TIMECONST; + break; + case 't': + txc.tick = atoi(optarg); + txc.modes |= ADJ_TICK; + break; + default: + bb_show_usage(); + exit(1); + } + } + if (argc != optind) { /* no valid non-option parameters */ + bb_show_usage(); + exit(1); + } + + ret = adjtimex(&txc); + + if (ret < 0) perror("adjtimex"); + + if (!quiet && ret>=0) { + printf( + " mode: %d\n" + "-o offset: %ld\n" + "-f frequency: %ld\n" + " maxerror: %ld\n" + " esterror: %ld\n" + " status: %d ( ", + txc.modes, txc.offset, txc.freq, txc.maxerror, + txc.esterror, txc.status); + + /* representative output of next code fragment: + "PLL | PPSTIME" */ + sep=0; + for (i=0; statlist[i].name; i++) { + if (txc.status & statlist[i].bit) { + if (sep) fputs(" | ",stdout); + fputs(statlist[i].name,stdout); + sep=1; + } + } + + descript = "error"; + if (ret >= 0 && ret <= 5) descript = ret_code_descript[ret]; + printf(" )\n" + "-p timeconstant: %ld\n" + " precision: %ld\n" + " tolerance: %ld\n" + "-t tick: %ld\n" + " time.tv_sec: %ld\n" + " time.tv_usec: %ld\n" + " return value: %d (%s)\n", + txc.constant, + txc.precision, txc.tolerance, txc.tick, + (long)txc.time.tv_sec, (long)txc.time.tv_usec, ret, descript); + } + return (ret<0); +} diff --git a/release/src/router/busybox/miscutils/crond.c b/release/src/router/busybox/miscutils/crond.c new file mode 100644 index 00000000..f0920136 --- /dev/null +++ b/release/src/router/busybox/miscutils/crond.c @@ -0,0 +1,1100 @@ +/* + * crond -d[#] -c <crondir> -f -b + * + * run as root, but NOT setuid root + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * May be distributed under the GNU General Public License + * + * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 to be used in busybox + */ + +#define VERSION "2.3.2" + +#undef FEATURE_DEBUG_OPT + + +#include <stdio.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <errno.h> +#include <time.h> +#include <dirent.h> +#include <fcntl.h> +#include <unistd.h> +#include <syslog.h> +#include <signal.h> +#include <getopt.h> +#include <sys/ioctl.h> +#include <sys/wait.h> +#include <sys/stat.h> +#include <sys/resource.h> + +#include "busybox.h" + +#define arysize(ary) (sizeof(ary)/sizeof((ary)[0])) + +#ifndef CRONTABS +#define CRONTABS "/var/spool/cron/crontabs" +#endif +#ifndef TMPDIR +#define TMPDIR "/var/spool/cron" +#endif +#ifndef SENDMAIL +#define SENDMAIL "/usr/sbin/sendmail" +#endif +#ifndef SENDMAIL_ARGS +#define SENDMAIL_ARGS "-ti", "oem" +#endif +#ifndef CRONUPDATE +#define CRONUPDATE "cron.update" +#endif +#ifndef MAXLINES +#define MAXLINES 256 /* max lines in non-root crontabs */ +#endif + +static const char def_sh[] = "/bin/sh"; + + +typedef struct CronFile { + struct CronFile *cf_Next; + struct CronLine *cf_LineBase; + char *cf_User; /* username */ + int cf_Ready; /* bool: one or more jobs ready */ + int cf_Running; /* bool: one or more jobs running */ + int cf_Deleted; /* marked for deletion, ignore */ +} CronFile; + +typedef struct CronLine { + struct CronLine *cl_Next; + char *cl_Shell; /* shell command */ + pid_t cl_Pid; /* running pid, 0, or armed (-1) */ + int cl_MailFlag; /* running pid is for mail */ + int cl_MailPos; /* 'empty file' size */ + char cl_Mins[60]; /* 0-59 */ + char cl_Hrs[24]; /* 0-23 */ + char cl_Days[32]; /* 1-31 */ + char cl_Mons[12]; /* 0-11 */ + char cl_Dow[7]; /* 0-6, beginning sunday */ +} CronLine; + +#define RUN_RANOUT 1 +#define RUN_RUNNING 2 +#define RUN_FAILED 3 + +#define DaemonUid 0 + +#ifdef FEATURE_DEBUG_OPT +static short DebugOpt; +#endif + +static short LogLevel = 8; +static const char *LogFile; +static const char *CDir = CRONTABS; + +static void startlogger(void); + +static void CheckUpdates(void); +static void SynchronizeDir(void); +static int TestJobs(time_t t1, time_t t2); +static void RunJobs(void); +static int CheckJobs(void); + +static void RunJob(const char *user, CronLine *line); +#ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL +static void EndJob(const char *user, CronLine *line); +#else +#define EndJob(user, line) line->cl_Pid = 0 +#endif + +static void DeleteFile(const char *userName); + +static CronFile *FileBase; + + +static void +crondlog(const char *ctl, ...) +{ + va_list va; + int level = (int)(ctl[0] & 0xf); + int type = level == 20 ? + LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE); + + + va_start(va, ctl); + if (level >= LogLevel) { + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) vfprintf(stderr, ctl, va); + else +#endif + if (LogFile == 0) vsyslog(type, ctl, va); + else { + int logfd; + + if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0) { + vdprintf(logfd, ctl, va); + close(logfd); +#ifdef FEATURE_DEBUG_OPT + } else { + bb_perror_msg("Can't open log file"); +#endif + } + } + } + va_end(va); + if(ctl[0] & 0200) + exit(20); +} + +int +crond_main(int ac, char **av) +{ + unsigned long opt; + char *lopt, *Lopt, *copt; +#ifdef FEATURE_DEBUG_OPT + char *dopt; + bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l"; +#else + bb_opt_complementaly = "f-b:b-f:S-L:L-S"; +#endif + + opterr = 0; /* disable getopt 'errors' message.*/ + opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:" +#ifdef FEATURE_DEBUG_OPT + "d:" +#endif + , &lopt, &Lopt, &copt +#ifdef FEATURE_DEBUG_OPT + , &dopt +#endif + ); + if(opt & 1) + LogLevel = atoi(lopt); + if(opt & 2) + if (*Lopt != 0) LogFile = Lopt; + if(opt & 32) { + if (*copt != 0) CDir = copt; + } +#ifdef FEATURE_DEBUG_OPT + if(opt & 64) { + DebugOpt = atoi(dopt); + LogLevel = 0; + } +#endif + + /* + * change directory + */ + + if (chdir(CDir) != 0) + bb_perror_msg_and_die("%s", CDir); + + signal(SIGHUP,SIG_IGN); /* hmm.. but, if kill -HUP original + * version - his died. ;( + */ + /* + * close stdin and stdout, stderr. + * close unused descriptors - don't need. + * optional detach from controlling terminal + */ + + if (!(opt & 4)) { + if(daemon(1, 0) < 0) { + bb_perror_msg_and_die("daemon"); + } +#if defined(__uClinux__) + else { + /* reexec for vfork() do continue parent */ + vfork_daemon_rexec(ac, av, "-f"); + } +#endif /* uClinux */ + } + + (void)startlogger(); /* need if syslog mode selected */ + + /* + * main loop - synchronize to 1 second after the minute, minimum sleep + * of 1 second. + */ + + crondlog("\011%s " VERSION " dillon, started, log level %d\n", bb_applet_name, + LogLevel); + + SynchronizeDir(); + + { + time_t t1 = time(NULL); + time_t t2; + long dt; + short rescan = 60; + short sleep_time = 60; + + for (;;) { + sleep((sleep_time + 1) - (short)(time(NULL) % sleep_time)); + + t2 = time(NULL); + dt = t2 - t1; + + /* + * The file 'cron.update' is checked to determine new cron + * jobs. The directory is rescanned once an hour to deal + * with any screwups. + * + * check for disparity. Disparities over an hour either way + * result in resynchronization. A reverse-indexed disparity + * less then an hour causes us to effectively sleep until we + * match the original time (i.e. no re-execution of jobs that + * have just been run). A forward-indexed disparity less then + * an hour causes intermediate jobs to be run, but only once + * in the worst case. + * + * when running jobs, the inequality used is greater but not + * equal to t1, and less then or equal to t2. + */ + + if (--rescan == 0) { + rescan = 60; + SynchronizeDir(); + } + CheckUpdates(); +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005Wakeup dt=%d\n", dt); +#endif + if (dt < -60*60 || dt > 60*60) { + t1 = t2; + crondlog("\111time disparity of %d minutes detected\n", dt / 60); + } else if (dt > 0) { + TestJobs(t1, t2); + RunJobs(); + sleep(5); + if (CheckJobs() > 0) + sleep_time = 10; + else + sleep_time = 60; + t1 = t2; + } + } + } + /* not reached */ +} + + +#if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL) +/* + write to temp file.. +*/ +static void +fdprintf(int fd, const char *ctl, ...) +{ + va_list va; + + va_start(va, ctl); + vdprintf(fd, ctl, va); + va_end(va); +} +#endif + + +static int +ChangeUser(const char *user) +{ + struct passwd *pas; + + /* + * Obtain password entry and change privilages + */ + + if ((pas = getpwnam(user)) == 0) { + crondlog("\011failed to get uid for %s", user); + return(-1); + } + setenv("USER", pas->pw_name, 1); + setenv("HOME", pas->pw_dir, 1); + setenv("SHELL", def_sh, 1); + + /* + * Change running state to the user in question + */ + + if (initgroups(user, pas->pw_gid) < 0) { + crondlog("\011initgroups failed: %s %m", user); + return(-1); + } + /* drop all priviledges */ + if (setgid(pas->pw_gid) < 0) { + crondlog("\011setgid failed: %s %d", user, pas->pw_gid); + return(-1); + } + if (setuid(pas->pw_uid) < 0) { + crondlog("\011setuid failed: %s %d", user, pas->pw_uid); + return(-1); + } + if (chdir(pas->pw_dir) < 0) { + crondlog("\011chdir failed: %s: %m", pas->pw_dir); + if (chdir(TMPDIR) < 0) { + crondlog("\011chdir failed: %s: %m", TMPDIR); + return(-1); + } + } + return(pas->pw_uid); +} + +static void +startlogger(void) +{ + if (LogFile == 0) + openlog(bb_applet_name, LOG_CONS|LOG_PID, LOG_CRON); +#ifdef FEATURE_DEBUG_OPT + else { /* test logfile */ + int logfd; + + if ((logfd = open(LogFile, O_WRONLY|O_CREAT|O_APPEND, 600)) >= 0) + close(logfd); + else + bb_perror_msg("Failed to open log file '%s' reason", LogFile); + } +#endif +} + + +static const char * const DowAry[] = { + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat", + + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat", + NULL +}; + +static const char * const MonAry[] = { + "jan", + "feb", + "mar", + "apr", + "may", + "jun", + "jul", + "aug", + "sep", + "oct", + "nov", + "dec", + + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + NULL +}; + +static char * +ParseField(char *user, char *ary, int modvalue, int off, + const char * const *names, char *ptr) +{ + char *base = ptr; + int n1 = -1; + int n2 = -1; + + if (base == NULL) + return(NULL); + + while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') { + int skip = 0; + + /* + * Handle numeric digit or symbol or '*' + */ + + if (*ptr == '*') { + n1 = 0; /* everything will be filled */ + n2 = modvalue - 1; + skip = 1; + ++ptr; + } else if (*ptr >= '0' && *ptr <= '9') { + if (n1 < 0) + n1 = strtol(ptr, &ptr, 10) + off; + else + n2 = strtol(ptr, &ptr, 10) + off; + skip = 1; + } else if (names) { + int i; + + for (i = 0; names[i]; ++i) { + if (strncmp(ptr, names[i], strlen(names[i])) == 0) { + break; + } + } + if (names[i]) { + ptr += strlen(names[i]); + if (n1 < 0) + n1 = i; + else + n2 = i; + skip = 1; + } + } + + /* + * handle optional range '-' + */ + + if (skip == 0) { + crondlog("\111failed user %s parsing %s\n", user, base); + return(NULL); + } + if (*ptr == '-' && n2 < 0) { + ++ptr; + continue; + } + + /* + * collapse single-value ranges, handle skipmark, and fill + * in the character array appropriately. + */ + + if (n2 < 0) + n2 = n1; + + if (*ptr == '/') + skip = strtol(ptr + 1, &ptr, 10); + + /* + * fill array, using a failsafe is the easiest way to prevent + * an endless loop + */ + + { + int s0 = 1; + int failsafe = 1024; + + --n1; + do { + n1 = (n1 + 1) % modvalue; + + if (--s0 == 0) { + ary[n1 % modvalue] = 1; + s0 = skip; + } + } while (n1 != n2 && --failsafe); + + if (failsafe == 0) { + crondlog("\111failed user %s parsing %s\n", user, base); + return(NULL); + } + } + if (*ptr != ',') + break; + ++ptr; + n1 = -1; + n2 = -1; + } + + if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') { + crondlog("\111failed user %s parsing %s\n", user, base); + return(NULL); + } + + while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') + ++ptr; + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + int i; + + for (i = 0; i < modvalue; ++i) + crondlog("\005%d", ary[i]); + crondlog("\005\n"); + } +#endif + + return(ptr); +} + +static void +FixDayDow(CronLine *line) +{ + short i; + short weekUsed = 0; + short daysUsed = 0; + + for (i = 0; i < arysize(line->cl_Dow); ++i) { + if (line->cl_Dow[i] == 0) { + weekUsed = 1; + break; + } + } + for (i = 0; i < arysize(line->cl_Days); ++i) { + if (line->cl_Days[i] == 0) { + daysUsed = 1; + break; + } + } + if (weekUsed && !daysUsed) { + memset(line->cl_Days, 0, sizeof(line->cl_Days)); + } + if (daysUsed && !weekUsed) { + memset(line->cl_Dow, 0, sizeof(line->cl_Dow)); + } +} + + + +static void +SynchronizeFile(const char *fileName) +{ + int maxEntries = MAXLINES; + int maxLines; + char buf[1024]; + + if (strcmp(fileName, "root") == 0) + maxEntries = 65535; + maxLines = maxEntries * 10; + + if (fileName) { + FILE *fi; + + DeleteFile(fileName); + + if ((fi = fopen(fileName, "r")) != NULL) { + struct stat sbuf; + + if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) { + CronFile *file = calloc(1, sizeof(CronFile)); + CronLine **pline; + + file->cf_User = strdup(fileName); + pline = &file->cf_LineBase; + + while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) { + CronLine line; + char *ptr; + + if (buf[0]) + buf[strlen(buf)-1] = 0; + + if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t') + continue; + + if (--maxEntries == 0) + break; + + memset(&line, 0, sizeof(line)); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\111User %s Entry %s\n", fileName, buf); +#endif + + /* + * parse date ranges + */ + + ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf); + ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr); + ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr); + ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr); + ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr); + + /* + * check failure + */ + + if (ptr == NULL) + continue; + + /* + * fix days and dow - if one is not * and the other + * is *, the other is set to 0, and vise-versa + */ + + FixDayDow(&line); + + *pline = calloc(1, sizeof(CronLine)); + **pline = line; + + /* + * copy command + */ + + (*pline)->cl_Shell = strdup(ptr); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\111 Command %s\n", ptr); + } +#endif + + pline = &((*pline)->cl_Next); + } + *pline = NULL; + + file->cf_Next = FileBase; + FileBase = file; + + if (maxLines == 0 || maxEntries == 0) + crondlog("\111Maximum number of lines reached for user %s\n", fileName); + } + fclose(fi); + } + } +} + +static void +CheckUpdates(void) +{ + FILE *fi; + char buf[256]; + + if ((fi = fopen(CRONUPDATE, "r")) != NULL) { + remove(CRONUPDATE); + while (fgets(buf, sizeof(buf), fi) != NULL) { + SynchronizeFile(strtok(buf, " \t\r\n")); + } + fclose(fi); + } +} + +static void +SynchronizeDir(void) +{ + /* + * Attempt to delete the database. + */ + + for (;;) { + CronFile *file; + + for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next) + ; + if (file == NULL) + break; + DeleteFile(file->cf_User); + } + + /* + * Remove cron update file + * + * Re-chdir, in case directory was renamed & deleted, or otherwise + * screwed up. + * + * scan directory and add associated users + */ + + remove(CRONUPDATE); + if (chdir(CDir) < 0) { + crondlog("\311unable to find %s\n", CDir); + } + { + DIR *dir; + struct dirent *den; + + if ((dir = opendir("."))) { + while ((den = readdir(dir))) { + if (strchr(den->d_name, '.') != NULL) + continue; + if (getpwnam(den->d_name)) + SynchronizeFile(den->d_name); + else + crondlog("\007ignoring %s\n", den->d_name); + } + closedir(dir); + } else { + crondlog("\311Unable to open current dir!\n"); + } + } +} + + +/* + * DeleteFile() - delete user database + * + * Note: multiple entries for same user may exist if we were unable to + * completely delete a database due to running processes. + */ + +static void +DeleteFile(const char *userName) +{ + CronFile **pfile = &FileBase; + CronFile *file; + + while ((file = *pfile) != NULL) { + if (strcmp(userName, file->cf_User) == 0) { + CronLine **pline = &file->cf_LineBase; + CronLine *line; + + file->cf_Running = 0; + file->cf_Deleted = 1; + + while ((line = *pline) != NULL) { + if (line->cl_Pid > 0) { + file->cf_Running = 1; + pline = &line->cl_Next; + } else { + *pline = line->cl_Next; + free(line->cl_Shell); + free(line); + } + } + if (file->cf_Running == 0) { + *pfile = file->cf_Next; + free(file->cf_User); + free(file); + } else { + pfile = &file->cf_Next; + } + } else { + pfile = &file->cf_Next; + } + } +} + +/* + * TestJobs() + * + * determine which jobs need to be run. Under normal conditions, the + * period is about a minute (one scan). Worst case it will be one + * hour (60 scans). + */ + +static int +TestJobs(time_t t1, time_t t2) +{ + short nJobs = 0; + time_t t; + + /* + * Find jobs > t1 and <= t2 + */ + + for (t = t1 - t1 % 60; t <= t2; t += 60) { + if (t > t1) { + struct tm *tp = localtime(&t); + CronFile *file; + CronLine *line; + + for (file = FileBase; file; file = file->cf_Next) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005FILE %s:\n", file->cf_User); +#endif + if (file->cf_Deleted) + continue; + for (line = file->cf_LineBase; line; line = line->cl_Next) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005 LINE %s\n", line->cl_Shell); +#endif + if (line->cl_Mins[tp->tm_min] && + line->cl_Hrs[tp->tm_hour] && + (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) && + line->cl_Mons[tp->tm_mon] + ) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005 JobToDo: %d %s\n", line->cl_Pid, line->cl_Shell); +#endif + if (line->cl_Pid > 0) { + crondlog("\010 process already running: %s %s\n", + file->cf_User, + line->cl_Shell + ); + } else if (line->cl_Pid == 0) { + line->cl_Pid = -1; + file->cf_Ready = 1; + ++nJobs; + } + } + } + } + } + } + return(nJobs); +} + +static void +RunJobs(void) +{ + CronFile *file; + CronLine *line; + + for (file = FileBase; file; file = file->cf_Next) { + if (file->cf_Ready) { + file->cf_Ready = 0; + + for (line = file->cf_LineBase; line; line = line->cl_Next) { + if (line->cl_Pid < 0) { + + RunJob(file->cf_User, line); + + crondlog("\010USER %s pid %3d cmd %s\n", + file->cf_User, + line->cl_Pid, + line->cl_Shell + ); + if (line->cl_Pid < 0) + file->cf_Ready = 1; + else if (line->cl_Pid > 0) + file->cf_Running = 1; + } + } + } + } +} + +/* + * CheckJobs() - check for job completion + * + * Check for job completion, return number of jobs still running after + * all done. + */ + +static int +CheckJobs(void) +{ + CronFile *file; + CronLine *line; + int nStillRunning = 0; + + for (file = FileBase; file; file = file->cf_Next) { + if (file->cf_Running) { + file->cf_Running = 0; + + for (line = file->cf_LineBase; line; line = line->cl_Next) { + if (line->cl_Pid > 0) { + int status; + int r = wait4(line->cl_Pid, &status, WNOHANG, NULL); + + if (r < 0 || r == line->cl_Pid) { + EndJob(file->cf_User, line); + if (line->cl_Pid) + file->cf_Running = 1; + } else if (r == 0) { + file->cf_Running = 1; + } + } + } + } + nStillRunning += file->cf_Running; + } + return(nStillRunning); +} + + +#ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL +static void +ForkJob(const char *user, CronLine *line, int mailFd, + const char *prog, const char *cmd, const char *arg, const char *mailf) +{ + /* + * Fork as the user in question and run program + */ + pid_t pid = fork(); + + line->cl_Pid = pid; + if (pid == 0) { + /* + * CHILD + */ + + /* + * Change running state to the user in question + */ + + if (ChangeUser(user) < 0) + exit(0); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005Child Running %s\n", prog); +#endif + + if (mailFd >= 0) { + dup2(mailFd, mailf != NULL); + dup2((mailf ? mailFd : 1), 2); + close(mailFd); + } + execl(prog, prog, cmd, arg, NULL); + crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, + prog, cmd, arg); + if(mailf) + fdprintf(1, "Exec failed: %s -c %s\n", prog, arg); + exit(0); + } else if (pid < 0) { + /* + * FORK FAILED + */ + crondlog("\024couldn't fork, user %s\n", user); + line->cl_Pid = 0; + if(mailf) + remove(mailf); + } else if(mailf) { + /* + * PARENT, FORK SUCCESS + * + * rename mail-file based on pid of process + */ + char mailFile2[128]; + + snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", + user, pid); + rename(mailf, mailFile2); + } + /* + * Close the mail file descriptor.. we can't just leave it open in + * a structure, closing it later, because we might run out of descriptors + */ + + if (mailFd >= 0) + close(mailFd); +} + +static void +RunJob(const char *user, CronLine *line) +{ + char mailFile[128]; + int mailFd; + + line->cl_Pid = 0; + line->cl_MailFlag = 0; + + /* + * open mail file - owner root so nobody can screw with it. + */ + + snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", + user, getpid()); + mailFd = open(mailFile, O_CREAT|O_TRUNC|O_WRONLY|O_EXCL|O_APPEND, 0600); + + if (mailFd >= 0) { + line->cl_MailFlag = 1; + fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user, + line->cl_Shell); + line->cl_MailPos = lseek(mailFd, 0, 1); + } else { + crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", + user, mailFile); + } + + ForkJob(user, line, mailFd, def_sh, "-c", line->cl_Shell, mailFile); +} + +/* + * EndJob - called when job terminates and when mail terminates + */ + +static void +EndJob(const char *user, CronLine *line) +{ + int mailFd; + char mailFile[128]; + struct stat sbuf; + + /* + * No job + */ + + if (line->cl_Pid <= 0) { + line->cl_Pid = 0; + return; + } + + /* + * End of job and no mail file + * End of sendmail job + */ + + snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", + user, line->cl_Pid); + line->cl_Pid = 0; + + if (line->cl_MailFlag != 1) + return; + + line->cl_MailFlag = 0; + + /* + * End of primary job - check for mail file. If size has increased and + * the file is still valid, we sendmail it. + */ + + mailFd = open(mailFile, O_RDONLY); + remove(mailFile); + if (mailFd < 0) { + return; + } + + if (fstat(mailFd, &sbuf) < 0 || + sbuf.st_uid != DaemonUid || + sbuf.st_nlink != 0 || + sbuf.st_size == line->cl_MailPos || + !S_ISREG(sbuf.st_mode) + ) { + close(mailFd); + return; + } + ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL); +} +#else +/* crond whithout sendmail */ + +static void +RunJob(const char *user, CronLine *line) +{ + /* + * Fork as the user in question and run program + */ + pid_t pid = fork(); + + if (pid == 0) { + /* + * CHILD + */ + + /* + * Change running state to the user in question + */ + + if (ChangeUser(user) < 0) + exit(0); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005Child Running %s\n", def_sh); +#endif + + execl(def_sh, def_sh, "-c", line->cl_Shell, NULL); + crondlog("\024unable to exec, user %s cmd %s -c %s\n", user, + def_sh, line->cl_Shell); + exit(0); + } else if (pid < 0) { + /* + * FORK FAILED + */ + crondlog("\024couldn't fork, user %s\n", user); + pid = 0; + } + line->cl_Pid = pid; +} +#endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */ diff --git a/release/src/router/busybox/miscutils/crontab.c b/release/src/router/busybox/miscutils/crontab.c new file mode 100644 index 00000000..6b944646 --- /dev/null +++ b/release/src/router/busybox/miscutils/crontab.c @@ -0,0 +1,391 @@ +/* + * CRONTAB + * + * usually setuid root, -c option only works if getuid() == geteuid() + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * May be distributed under the GNU General Public License + * + * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 to be used in busybox + * + */ + +#include <stdio.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <errno.h> +#include <time.h> +#include <dirent.h> +#include <fcntl.h> +#include <unistd.h> +#include <syslog.h> +#include <signal.h> +#include <getopt.h> +#include <sys/ioctl.h> +#include <sys/wait.h> +#include <sys/stat.h> +#include <sys/resource.h> + +#ifndef CRONTABS +#define CRONTABS "/var/spool/cron/crontabs" +#endif +#ifndef TMPDIR +#define TMPDIR "/var/spool/cron" +#endif +#ifndef CRONUPDATE +#define CRONUPDATE "cron.update" +#endif +#ifndef PATH_VI +#define PATH_VI "/bin/vi" /* location of vi */ +#endif + +#include "busybox.h" + +static const char *CDir = CRONTABS; + +static void EditFile(const char *user, const char *file); +static int GetReplaceStream(const char *user, const char *file); +static int ChangeUser(const char *user, short dochdir); + +int +crontab_main(int ac, char **av) +{ + enum { NONE, EDIT, LIST, REPLACE, DELETE } option = NONE; + const struct passwd *pas; + const char *repFile = NULL; + int repFd = 0; + int i; + char caller[256]; /* user that ran program */ + int UserId; + + UserId = getuid(); + if ((pas = getpwuid(UserId)) == NULL) + bb_perror_msg_and_die("getpwuid"); + + strncpy(caller, pas->pw_name, sizeof(caller)); + + i = 1; + if (ac > 1) { + if (av[1][0] == '-' && av[1][1] == 0) { + option = REPLACE; + ++i; + } else if (av[1][0] != '-') { + option = REPLACE; + ++i; + repFile = av[1]; + } + } + + for (; i < ac; ++i) { + char *ptr = av[i]; + + if (*ptr != '-') + break; + ptr += 2; + + switch(ptr[-1]) { + case 'l': + if (ptr[-1] == 'l') + option = LIST; + /* fall through */ + case 'e': + if (ptr[-1] == 'e') + option = EDIT; + /* fall through */ + case 'd': + if (ptr[-1] == 'd') + option = DELETE; + /* fall through */ + case 'u': + if (i + 1 < ac && av[i+1][0] != '-') { + ++i; + if (getuid() == geteuid()) { + pas = getpwnam(av[i]); + if (pas) { + UserId = pas->pw_uid; + } else { + bb_error_msg_and_die("user %s unknown", av[i]); + } + } else { + bb_error_msg_and_die("only the superuser may specify a user"); + } + } + break; + case 'c': + if (getuid() == geteuid()) { + CDir = (*ptr) ? ptr : av[++i]; + } else { + bb_error_msg_and_die("-c option: superuser only"); + } + break; + default: + i = ac; + break; + } + } + if (i != ac || option == NONE) + bb_show_usage(); + + /* + * Get password entry + */ + + if ((pas = getpwuid(UserId)) == NULL) + bb_perror_msg_and_die("getpwuid"); + + /* + * If there is a replacement file, obtain a secure descriptor to it. + */ + + if (repFile) { + repFd = GetReplaceStream(caller, repFile); + if (repFd < 0) + bb_error_msg_and_die("unable to read replacement file"); + } + + /* + * Change directory to our crontab directory + */ + + if (chdir(CDir) < 0) + bb_perror_msg_and_die("cannot change dir to %s", CDir); + + /* + * Handle options as appropriate + */ + + switch(option) { + case LIST: + { + FILE *fi; + char buf[1024]; + + if ((fi = fopen(pas->pw_name, "r"))) { + while (fgets(buf, sizeof(buf), fi) != NULL) + fputs(buf, stdout); + fclose(fi); + } else { + bb_error_msg("no crontab for %s", pas->pw_name); + } + } + break; + case EDIT: + { + FILE *fi; + int fd; + int n; + char tmp[128]; + char buf[1024]; + + snprintf(tmp, sizeof(tmp), TMPDIR "/crontab.%d", getpid()); + if ((fd = open(tmp, O_RDWR|O_CREAT|O_TRUNC|O_EXCL, 0600)) >= 0) { + chown(tmp, getuid(), getgid()); + if ((fi = fopen(pas->pw_name, "r"))) { + while ((n = fread(buf, 1, sizeof(buf), fi)) > 0) + write(fd, buf, n); + } + EditFile(caller, tmp); + remove(tmp); + lseek(fd, 0L, 0); + repFd = fd; + } else { + bb_error_msg_and_die("unable to create %s", tmp); + } + + } + option = REPLACE; + /* fall through */ + case REPLACE: + { + char buf[1024]; + char path[1024]; + int fd; + int n; + + snprintf(path, sizeof(path), "%s.new", pas->pw_name); + if ((fd = open(path, O_CREAT|O_TRUNC|O_APPEND|O_WRONLY, 0600)) >= 0) { + while ((n = read(repFd, buf, sizeof(buf))) > 0) { + write(fd, buf, n); + } + close(fd); + rename(path, pas->pw_name); + } else { + bb_error_msg("unable to create %s/%s", CDir, path); + } + close(repFd); + } + break; + case DELETE: + remove(pas->pw_name); + break; + case NONE: + default: + break; + } + + /* + * Bump notification file. Handle window where crond picks file up + * before we can write our entry out. + */ + + if (option == REPLACE || option == DELETE) { + FILE *fo; + struct stat st; + + while ((fo = fopen(CRONUPDATE, "a"))) { + fprintf(fo, "%s\n", pas->pw_name); + fflush(fo); + if (fstat(fileno(fo), &st) != 0 || st.st_nlink != 0) { + fclose(fo); + break; + } + fclose(fo); + /* loop */ + } + if (fo == NULL) { + bb_error_msg("unable to append to %s/%s", CDir, CRONUPDATE); + } + } + return 0; +} + +static int +GetReplaceStream(const char *user, const char *file) +{ + int filedes[2]; + int pid; + int fd; + int n; + char buf[1024]; + + if (pipe(filedes) < 0) { + perror("pipe"); + return(-1); + } + if ((pid = fork()) < 0) { + perror("fork"); + return(-1); + } + if (pid > 0) { + /* + * PARENT + */ + + close(filedes[1]); + if (read(filedes[0], buf, 1) != 1) { + close(filedes[0]); + filedes[0] = -1; + } + return(filedes[0]); + } + + /* + * CHILD + */ + + close(filedes[0]); + + if (ChangeUser(user, 0) < 0) + exit(0); + + fd = open(file, O_RDONLY); + if (fd < 0) { + bb_error_msg("unable to open %s", file); + exit(0); + } + buf[0] = 0; + write(filedes[1], buf, 1); + while ((n = read(fd, buf, sizeof(buf))) > 0) { + write(filedes[1], buf, n); + } + exit(0); +} + +static void +EditFile(const char *user, const char *file) +{ + int pid; + + if ((pid = fork()) == 0) { + /* + * CHILD - change user and run editor + */ + char *ptr; + char visual[1024]; + + if (ChangeUser(user, 1) < 0) + exit(0); + if ((ptr = getenv("VISUAL")) == NULL || strlen(ptr) > 256) + ptr = PATH_VI; + + snprintf(visual, sizeof(visual), "%s %s", ptr, file); + execl("/bin/sh", "/bin/sh", "-c", visual, NULL); + perror("exec"); + exit(0); + } + if (pid < 0) { + /* + * PARENT - failure + */ + bb_perror_msg_and_die("fork"); + } + wait4(pid, NULL, 0, NULL); +} + +static void +log(const char *ctl, ...) +{ + va_list va; + char buf[1024]; + + va_start(va, ctl); + vsnprintf(buf, sizeof(buf), ctl, va); + syslog(LOG_NOTICE, "%s",buf ); + va_end(va); +} + +static int +ChangeUser(const char *user, short dochdir) +{ + struct passwd *pas; + + /* + * Obtain password entry and change privilages + */ + + if ((pas = getpwnam(user)) == 0) { + log("failed to get uid for %s", user); + return(-1); + } + setenv("USER", pas->pw_name, 1); + setenv("HOME", pas->pw_dir, 1); + setenv("SHELL", "/bin/sh", 1); + + /* + * Change running state to the user in question + */ + + if (initgroups(user, pas->pw_gid) < 0) { + log("initgroups failed: %s %m", user); + return(-1); + } + if (setregid(pas->pw_gid, pas->pw_gid) < 0) { + log("setregid failed: %s %d", user, pas->pw_gid); + return(-1); + } + if (setreuid(pas->pw_uid, pas->pw_uid) < 0) { + log("setreuid failed: %s %d", user, pas->pw_uid); + return(-1); + } + if (dochdir) { + if (chdir(pas->pw_dir) < 0) { + if (chdir(TMPDIR) < 0) { + log("chdir failed: %s %s", user, pas->pw_dir); + log("chdir failed: %s " TMPDIR, user); + return(-1); + } + } + } + return(pas->pw_uid); +} diff --git a/release/src/router/busybox/miscutils/dc.c b/release/src/router/busybox/miscutils/dc.c new file mode 100644 index 00000000..5e367fe6 --- /dev/null +++ b/release/src/router/busybox/miscutils/dc.c @@ -0,0 +1,215 @@ +/* vi: set sw=4 ts=4: */ +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <math.h> +#include "busybox.h" + +/* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */ + +static double stack[100]; +static unsigned int pointer; +static unsigned char base; + +static void push(double a) +{ + if (pointer >= (sizeof(stack) / sizeof(*stack))) + bb_error_msg_and_die("stack overflow"); + stack[pointer++] = a; +} + +static double pop(void) +{ + if (pointer == 0) + bb_error_msg_and_die("stack underflow"); + return stack[--pointer]; +} + +static void add(void) +{ + push(pop() + pop()); +} + +static void sub(void) +{ + double subtrahend = pop(); + + push(pop() - subtrahend); +} + +static void mul(void) +{ + push(pop() * pop()); +} + +static void divide(void) +{ + double divisor = pop(); + + push(pop() / divisor); +} + +static void and(void) +{ + push((unsigned int) pop() & (unsigned int) pop()); +} + +static void or(void) +{ + push((unsigned int) pop() | (unsigned int) pop()); +} + +static void eor(void) +{ + push((unsigned int) pop() ^ (unsigned int) pop()); +} + +static void not(void) +{ + push(~(unsigned int) pop()); +} + +static void set_output_base(void) +{ + base=(unsigned char)pop(); + if ((base != 10) && (base != 16)) { + fprintf(stderr, "Error: base = %d is not supported.\n", base); + base=10; + } +} + +static void print_base(double print) +{ + if (base == 16) + printf("%x\n", (unsigned int)print); + else + printf("%g\n", print); +} + +static void print_stack_no_pop(void) +{ + unsigned int i=pointer; + while (i) + print_base(stack[--i]); +} + +static void print_no_pop(void) +{ + print_base(stack[pointer-1]); +} + +static void print(void) +{ + print_base(pop()); +} + +struct op { + const char *name; + void (*function) (void); +}; + +static const struct op operators[] = { + {"+", add}, + {"add", add}, + {"-", sub}, + {"sub", sub}, + {"*", mul}, + {"mul", mul}, + {"/", divide}, + {"div", divide}, + {"and", and}, + {"or", or}, + {"not", not}, + {"eor", eor}, + {"p", print_no_pop}, + {"f", print_stack_no_pop}, + {"o", set_output_base}, + {0, 0} +}; + +static void stack_machine(const char *argument) +{ + char *endPointer = 0; + double d; + const struct op *o = operators; + + if (argument == 0) { + print(); + return; + } + + d = strtod(argument, &endPointer); + + if (endPointer != argument) { + push(d); + return; + } + + while (o->name != 0) { + if (strcmp(o->name, argument) == 0) { + (*(o->function)) (); + return; + } + o++; + } + bb_error_msg_and_die("%s: syntax error.", argument); +} + +/* return pointer to next token in buffer and set *buffer to one char + * past the end of the above mentioned token + */ +static char *get_token(char **buffer) +{ + char *start = NULL; + char *current = *buffer; + + while (isspace(*current)) { current++; } + if (*current != 0) { + start = current; + while (!isspace(*current) && current != 0) { current++; } + *buffer = current; + } + return start; +} + +/* In Perl one might say, scalar m|\s*(\S+)\s*|g */ +static int number_of_tokens(char *buffer) +{ + int i = 0; + char *b = buffer; + while (get_token(&b)) { i++; } + return i; +} + +int dc_main(int argc, char **argv) +{ + /* take stuff from stdin if no args are given */ + if (argc <= 1) { + int i, len; + char *line = NULL; + char *cursor = NULL; + char *token = NULL; + while ((line = bb_get_chomped_line_from_file(stdin))) { + cursor = line; + len = number_of_tokens(line); + for (i = 0; i < len; i++) { + token = get_token(&cursor); + *cursor++ = 0; + stack_machine(token); + } + free(line); + } + } else { + if (*argv[1]=='-') + bb_show_usage(); + while (argc >= 2) { + stack_machine(argv[1]); + argv++; + argc--; + } + } + stack_machine(0); + return EXIT_SUCCESS; +} diff --git a/release/src/router/busybox/miscutils/dutmp.c b/release/src/router/busybox/miscutils/dutmp.c new file mode 100644 index 00000000..86d7ce4b --- /dev/null +++ b/release/src/router/busybox/miscutils/dutmp.c @@ -0,0 +1,66 @@ +/* vi: set sw=4 ts=4: */ +/* + * public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com> + * + * dutmp + * Takes utmp formated file on stdin and dumps it's contents + * out in colon delimited fields. Easy to 'cut' for shell based + * versions of 'who', 'last', etc. IP Addr is output in hex, + * little endian on x86. + * + */ + +/* Mar 13, 2003 Manuel Novoa III + * + * 1) Added proper error checking. + * 2) Allow '-' arg for stdin. + * 3) For modern libcs, take into account that utmp char[] members + * need not be nul-terminated. + */ + +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <utmp.h> +#include "busybox.h" + +/* Grr... utmp char[] members do not have to be nul-terminated. + * Do what we can while still keeping this reasonably small. + * Note: We are assuming the ut_id[] size is fixed at 4. */ + +#if (UT_LINESIZE != 32) || (UT_NAMESIZE != 32) || (UT_HOSTSIZE != 256) +#error struct utmp member char[] size(s) have changed! +#endif + +extern int dutmp_main(int argc, char **argv) +{ + int file = STDIN_FILENO; + ssize_t n; + struct utmp ut; + + if (argc > 2) { + bb_show_usage(); + } + ++argv; + if ((argc == 2) && ((argv[0][0] != '-') || argv[0][1])) { + file = bb_xopen(*argv, O_RDONLY); + } + + + while ((n = safe_read(file, (void*)&ut, sizeof(struct utmp))) != 0) { + + if (n != sizeof(struct utmp)) { + bb_perror_msg_and_die("short read"); + } + + bb_printf("%d|%d|%.32s|%.4s|%.32s|%.256s|%d|%d|%ld|%ld|%ld|%x\n", + ut.ut_type, ut.ut_pid, ut.ut_line, + ut.ut_id, ut.ut_user, ut.ut_host, + ut.ut_exit.e_termination, ut.ut_exit.e_exit, + ut.ut_session, + ut.ut_tv.tv_sec, ut.ut_tv.tv_usec, + ut.ut_addr); + } + + bb_fflush_stdout_and_exit(EXIT_SUCCESS); +} diff --git a/release/src/router/busybox/miscutils/hdparm.c b/release/src/router/busybox/miscutils/hdparm.c new file mode 100644 index 00000000..1e34f4f4 --- /dev/null +++ b/release/src/router/busybox/miscutils/hdparm.c @@ -0,0 +1,2665 @@ +/* vi: set sw=4 ts=4: */ +/* + * hdparm implementation for busybox + * + * + * Copyright (C) [2003] by [Matteo Croce] <pinnolo@tin.it> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA + * + * + * This program is based on the source code of hdparm: see below... + * hdparm.c - Command line interface to get/set hard disk parameters + * - by Mark Lord (C) 1994-2002 -- freely distributable + */ + +#include <unistd.h> +#include <string.h> +#include <stdlib.h> +#include <fcntl.h> +#include <errno.h> +#include <ctype.h> +#include <endian.h> +#include <sys/ioctl.h> +#include <sys/shm.h> +#include <sys/sysmacros.h> +#include <sys/time.h> +#include <sys/times.h> +#include <sys/mount.h> +#include "busybox.h" +#include <linux/types.h> +#include <linux/hdreg.h> +#include <linux/major.h> +#include <asm/byteorder.h> + + +#if __BYTE_ORDER == __BIG_ENDIAN +#define __USE_XOPEN +#endif + +/* device types */ +/* ------------ */ +#define NO_DEV 0xffff +#define ATA_DEV 0x0000 +#define ATAPI_DEV 0x0001 + +/* word definitions */ +/* ---------------- */ +#define GEN_CONFIG 0 /* general configuration */ +#define LCYLS 1 /* number of logical cylinders */ +#define CONFIG 2 /* specific configuration */ +#define LHEADS 3 /* number of logical heads */ +#define TRACK_BYTES 4 /* number of bytes/track (ATA-1) */ +#define SECT_BYTES 5 /* number of bytes/sector (ATA-1) */ +#define LSECTS 6 /* number of logical sectors/track */ +#define START_SERIAL 10 /* ASCII serial number */ +#define LENGTH_SERIAL 10 /* 10 words (20 bytes or characters) */ +#define BUF_TYPE 20 /* buffer type (ATA-1) */ +#define BUFFER__SIZE 21 /* buffer size (ATA-1) */ +#define RW_LONG 22 /* extra bytes in R/W LONG cmd ( < ATA-4)*/ +#define START_FW_REV 23 /* ASCII firmware revision */ +#define LENGTH_FW_REV 4 /* 4 words (8 bytes or characters) */ +#define START_MODEL 27 /* ASCII model number */ +#define LENGTH_MODEL 20 /* 20 words (40 bytes or characters) */ +#define SECTOR_XFER_MAX 47 /* r/w multiple: max sectors xfered */ +#define DWORD_IO 48 /* can do double-word IO (ATA-1 only) */ +#define CAPAB_0 49 /* capabilities */ +#define CAPAB_1 50 +#define PIO_MODE 51 /* max PIO mode supported (obsolete)*/ +#define DMA_MODE 52 /* max Singleword DMA mode supported (obs)*/ +#define WHATS_VALID 53 /* what fields are valid */ +#define LCYLS_CUR 54 /* current logical cylinders */ +#define LHEADS_CUR 55 /* current logical heads */ +#define LSECTS_CUR 56 /* current logical sectors/track */ +#define CAPACITY_LSB 57 /* current capacity in sectors */ +#define CAPACITY_MSB 58 +#define SECTOR_XFER_CUR 59 /* r/w multiple: current sectors xfered */ +#define LBA_SECTS_LSB 60 /* LBA: total number of user */ +#define LBA_SECTS_MSB 61 /* addressable sectors */ +#define SINGLE_DMA 62 /* singleword DMA modes */ +#define MULTI_DMA 63 /* multiword DMA modes */ +#define ADV_PIO_MODES 64 /* advanced PIO modes supported */ + /* multiword DMA xfer cycle time: */ +#define DMA_TIME_MIN 65 /* - minimum */ +#define DMA_TIME_NORM 66 /* - manufacturer's recommended */ + /* minimum PIO xfer cycle time: */ +#define PIO_NO_FLOW 67 /* - without flow control */ +#define PIO_FLOW 68 /* - with IORDY flow control */ +#define PKT_REL 71 /* typical #ns from PKT cmd to bus rel */ +#define SVC_NBSY 72 /* typical #ns from SERVICE cmd to !BSY */ +#define CDR_MAJOR 73 /* CD ROM: major version number */ +#define CDR_MINOR 74 /* CD ROM: minor version number */ +#define QUEUE_DEPTH 75 /* queue depth */ +#define MAJOR 80 /* major version number */ +#define MINOR 81 /* minor version number */ +#define CMDS_SUPP_0 82 /* command/feature set(s) supported */ +#define CMDS_SUPP_1 83 +#define CMDS_SUPP_2 84 +#define CMDS_EN_0 85 /* command/feature set(s) enabled */ +#define CMDS_EN_1 86 +#define CMDS_EN_2 87 +#define ULTRA_DMA 88 /* ultra DMA modes */ + /* time to complete security erase */ +#define ERASE_TIME 89 /* - ordinary */ +#define ENH_ERASE_TIME 90 /* - enhanced */ +#define ADV_PWR 91 /* current advanced power management level + in low byte, 0x40 in high byte. */ +#define PSWD_CODE 92 /* master password revision code */ +#define HWRST_RSLT 93 /* hardware reset result */ +#define ACOUSTIC 94 /* acoustic mgmt values ( >= ATA-6) */ +#define LBA_LSB 100 /* LBA: maximum. Currently only 48 */ +#define LBA_MID 101 /* bits are used, but addr 103 */ +#define LBA_48_MSB 102 /* has been reserved for LBA in */ +#define LBA_64_MSB 103 /* the future. */ +#define RM_STAT 127 /* removable media status notification feature set support */ +#define SECU_STATUS 128 /* security status */ +#define CFA_PWR_MODE 160 /* CFA power mode 1 */ +#define START_MEDIA 176 /* media serial number */ +#define LENGTH_MEDIA 20 /* 20 words (40 bytes or characters)*/ +#define START_MANUF 196 /* media manufacturer I.D. */ +#define LENGTH_MANUF 10 /* 10 words (20 bytes or characters) */ +#define INTEGRITY 255 /* integrity word */ + +/* bit definitions within the words */ +/* -------------------------------- */ + +/* many words are considered valid if bit 15 is 0 and bit 14 is 1 */ +#define VALID 0xc000 +#define VALID_VAL 0x4000 +/* many words are considered invalid if they are either all-0 or all-1 */ +#define NOVAL_0 0x0000 +#define NOVAL_1 0xffff + +/* word 0: gen_config */ +#define NOT_ATA 0x8000 +#define NOT_ATAPI 0x4000 /* (check only if bit 15 == 1) */ +#define MEDIA_REMOVABLE 0x0080 +#define DRIVE_NOT_REMOVABLE 0x0040 /* bit obsoleted in ATA 6 */ +#define INCOMPLETE 0x0004 +#define CFA_SUPPORT_VAL 0x848a /* 848a=CFA feature set support */ +#define DRQ_RESPONSE_TIME 0x0060 +#define DRQ_3MS_VAL 0x0000 +#define DRQ_INTR_VAL 0x0020 +#define DRQ_50US_VAL 0x0040 +#define PKT_SIZE_SUPPORTED 0x0003 +#define PKT_SIZE_12_VAL 0x0000 +#define PKT_SIZE_16_VAL 0x0001 +#define EQPT_TYPE 0x1f00 +#define SHIFT_EQPT 8 + +#define CDROM 0x0005 + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *pkt_str[] = { + "Direct-access device", /* word 0, bits 12-8 = 00 */ + "Sequential-access device", /* word 0, bits 12-8 = 01 */ + "Printer", /* word 0, bits 12-8 = 02 */ + "Processor", /* word 0, bits 12-8 = 03 */ + "Write-once device", /* word 0, bits 12-8 = 04 */ + "CD-ROM", /* word 0, bits 12-8 = 05 */ + "Scanner", /* word 0, bits 12-8 = 06 */ + "Optical memory", /* word 0, bits 12-8 = 07 */ + "Medium changer", /* word 0, bits 12-8 = 08 */ + "Communications device", /* word 0, bits 12-8 = 09 */ + "ACS-IT8 device", /* word 0, bits 12-8 = 0a */ + "ACS-IT8 device", /* word 0, bits 12-8 = 0b */ + "Array controller", /* word 0, bits 12-8 = 0c */ + "Enclosure services", /* word 0, bits 12-8 = 0d */ + "Reduced block command device", /* word 0, bits 12-8 = 0e */ + "Optical card reader/writer", /* word 0, bits 12-8 = 0f */ + "", /* word 0, bits 12-8 = 10 */ + "", /* word 0, bits 12-8 = 11 */ + "", /* word 0, bits 12-8 = 12 */ + "", /* word 0, bits 12-8 = 13 */ + "", /* word 0, bits 12-8 = 14 */ + "", /* word 0, bits 12-8 = 15 */ + "", /* word 0, bits 12-8 = 16 */ + "", /* word 0, bits 12-8 = 17 */ + "", /* word 0, bits 12-8 = 18 */ + "", /* word 0, bits 12-8 = 19 */ + "", /* word 0, bits 12-8 = 1a */ + "", /* word 0, bits 12-8 = 1b */ + "", /* word 0, bits 12-8 = 1c */ + "", /* word 0, bits 12-8 = 1d */ + "", /* word 0, bits 12-8 = 1e */ + "Unknown", /* word 0, bits 12-8 = 1f */ +}; +static const char *ata1_cfg_str[] = { /* word 0 in ATA-1 mode */ + "reserved", /* bit 0 */ + "hard sectored", /* bit 1 */ + "soft sectored", /* bit 2 */ + "not MFM encoded ", /* bit 3 */ + "head switch time > 15us", /* bit 4 */ + "spindle motor control option", /* bit 5 */ + "fixed drive", /* bit 6 */ + "removable drive", /* bit 7 */ + "disk xfer rate <= 5Mbs", /* bit 8 */ + "disk xfer rate > 5Mbs, <= 10Mbs", /* bit 9 */ + "disk xfer rate > 5Mbs", /* bit 10 */ + "rotational speed tol.", /* bit 11 */ + "data strobe offset option", /* bit 12 */ + "track offset option", /* bit 13 */ + "format speed tolerance gap reqd", /* bit 14 */ + "ATAPI" /* bit 14 */ +}; +#endif + +/* word 1: number of logical cylinders */ +#define LCYLS_MAX 0x3fff /* maximum allowable value */ + +/* word 2: specific configureation + * (a) require SET FEATURES to spin-up + * (b) require spin-up to fully reply to IDENTIFY DEVICE + */ +#define STBY_NID_VAL 0x37c8 /* (a) and (b) */ +#define STBY_ID_VAL 0x738c /* (a) and not (b) */ +#define PWRD_NID_VAL 0x8c73 /* not (a) and (b) */ +#define PWRD_ID_VAL 0xc837 /* not (a) and not (b) */ + +/* words 47 & 59: sector_xfer_max & sector_xfer_cur */ +#define SECTOR_XFER 0x00ff /* sectors xfered on r/w multiple cmds*/ +#define MULTIPLE_SETTING_VALID 0x0100 /* 1=multiple sector setting is valid */ + +/* word 49: capabilities 0 */ +#define STD_STBY 0x2000 /* 1=standard values supported (ATA); + 0=vendor specific values */ +#define IORDY_SUP 0x0800 /* 1=support; 0=may be supported */ +#define IORDY_OFF 0x0400 /* 1=may be disabled */ +#define LBA_SUP 0x0200 /* 1=Logical Block Address support */ +#define DMA_SUP 0x0100 /* 1=Direct Memory Access support */ +#define DMA_IL_SUP 0x8000 /* 1=interleaved DMA support (ATAPI) */ +#define CMD_Q_SUP 0x4000 /* 1=command queuing support (ATAPI) */ +#define OVLP_SUP 0x2000 /* 1=overlap operation support (ATAPI) */ +#define SWRST_REQ 0x1000 /* 1=ATA SW reset required (ATAPI, obsolete */ + +/* word 50: capabilities 1 */ +#define MIN_STANDBY_TIMER 0x0001 /* 1=device specific standby timer value minimum */ + +/* words 51 & 52: PIO & DMA cycle times */ +#define MODE 0xff00 /* the mode is in the MSBs */ + +/* word 53: whats_valid */ +#define OK_W88 0x0004 /* the ultra_dma info is valid */ +#define OK_W64_70 0x0002 /* see above for word descriptions */ +#define OK_W54_58 0x0001 /* current cyl, head, sector, cap. info valid */ + +/*word 63,88: dma_mode, ultra_dma_mode*/ +#define MODE_MAX 7 /* bit definitions force udma <=7 (when + * udma >=8 comes out it'll have to be + * defined in a new dma_mode word!) */ + +/* word 64: PIO transfer modes */ +#define PIO_SUP 0x00ff /* only bits 0 & 1 are used so far, */ +#define PIO_MODE_MAX 8 /* but all 8 bits are defined */ + +/* word 75: queue_depth */ +#define DEPTH_BITS 0x001f /* bits used for queue depth */ + +/* words 80-81: version numbers */ +/* NOVAL_0 or NOVAL_1 means device does not report version */ + +/* word 81: minor version number */ +#define MINOR_MAX 0x1C +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *minor_str[] = { /* word 81 value: */ + "device does not report version", /* 0x0000 */ + "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */ + "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */ + "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */ + "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */ + "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */ + "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ + "ATA-2 X3T10 948D revision 2k", /* 0x0007 */ + "ATA-3 X3T10 2008D revision 0", /* 0x0008 */ + "ATA-2 X3T10 948D revision 3", /* 0x0009 */ + "ATA-3 published, ANSI X3.298-199x", /* 0x000a */ + "ATA-3 X3T10 2008D revision 6", /* 0x000b */ + "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */ + "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */ + "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */ + "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */ + "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */ + "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */ + "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */ + "ATA/ATAPI-5 T13 1321D revision 3", + "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */ + "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */ + "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */ + "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */ + "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */ + "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */ + "Reserved", /* 0x001a */ + "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */ + "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */ + "reserved" /* 0x001d */ + "reserved" /* 0x001e */ + "reserved" /* 0x001f-0xfffe*/ +}; +#endif +static const char actual_ver[] = { + /* word 81 value: */ + 0, /* 0x0000 WARNING: */ + 1, /* 0x0001 WARNING: */ + 1, /* 0x0002 WARNING: */ + 1, /* 0x0003 WARNING: */ + 2, /* 0x0004 WARNING: This array */ + 2, /* 0x0005 WARNING: corresponds */ + 3, /* 0x0006 WARNING: *exactly* */ + 2, /* 0x0007 WARNING: to the ATA/ */ + 3, /* 0x0008 WARNING: ATAPI version */ + 2, /* 0x0009 WARNING: listed in */ + 3, /* 0x000a WARNING: the */ + 3, /* 0x000b WARNING: minor_str */ + 3, /* 0x000c WARNING: array */ + 4, /* 0x000d WARNING: above. */ + 4, /* 0x000e WARNING: */ + 4, /* 0x000f WARNING: if you change */ + 4, /* 0x0010 WARNING: that one, */ + 4, /* 0x0011 WARNING: change this one */ + 4, /* 0x0012 WARNING: too!!! */ + 5, /* 0x0013 WARNING: */ + 4, /* 0x0014 WARNING: */ + 5, /* 0x0015 WARNING: */ + 5, /* 0x0016 WARNING: */ + 4, /* 0x0017 WARNING: */ + 6, /* 0x0018 WARNING: */ + 6, /* 0x0019 WARNING: */ + 0, /* 0x001a WARNING: */ + 6, /* 0x001b WARNING: */ + 6, /* 0x001c WARNING: */ + 0 /* 0x001d-0xfffe */ +}; + +/* words 82-84: cmds/feats supported */ +#define CMDS_W82 0x77ff /* word 82: defined command locations*/ +#define CMDS_W83 0x3fff /* word 83: defined command locations*/ +#define CMDS_W84 0x002f /* word 83: defined command locations*/ +#define SUPPORT_48_BIT 0x0400 +#define NUM_CMD_FEAT_STR 48 + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *cmd_feat_str[] = { + "", /* word 82 bit 15: obsolete */ + "NOP cmd", /* word 82 bit 14 */ + "READ BUFFER cmd", /* word 82 bit 13 */ + "WRITE BUFFER cmd", /* word 82 bit 12 */ + "", /* word 82 bit 11: obsolete */ + "Host Protected Area feature set", /* word 82 bit 10 */ + "DEVICE RESET cmd", /* word 82 bit 9 */ + "SERVICE interrupt", /* word 82 bit 8 */ + "Release interrupt", /* word 82 bit 7 */ + "Look-ahead", /* word 82 bit 6 */ + "Write cache", /* word 82 bit 5 */ + "PACKET command feature set", /* word 82 bit 4 */ + "Power Management feature set", /* word 82 bit 3 */ + "Removable Media feature set", /* word 82 bit 2 */ + "Security Mode feature set", /* word 82 bit 1 */ + "SMART feature set", /* word 82 bit 0 */ + /* --------------*/ + "", /* word 83 bit 15: !valid bit */ + "", /* word 83 bit 14: valid bit */ + "FLUSH CACHE EXT command", /* word 83 bit 13 */ + "Mandatory FLUSH CACHE command ", /* word 83 bit 12 */ + "Device Configuration Overlay feature set ", + "48-bit Address feature set ", /* word 83 bit 10 */ + "", + "SET MAX security extension", /* word 83 bit 8 */ + "Address Offset Reserved Area Boot", /* word 83 bit 7 */ + "SET FEATURES subcommand required to spinup after power up", + "Power-Up In Standby feature set", /* word 83 bit 5 */ + "Removable Media Status Notification feature set", + "Advanced Power Management feature set",/* word 83 bit 3 */ + "CFA feature set", /* word 83 bit 2 */ + "READ/WRITE DMA QUEUED", /* word 83 bit 1 */ + "DOWNLOAD MICROCODE cmd", /* word 83 bit 0 */ + /* --------------*/ + "", /* word 84 bit 15: !valid bit */ + "", /* word 84 bit 14: valid bit */ + "", /* word 84 bit 13: reserved */ + "", /* word 84 bit 12: reserved */ + "", /* word 84 bit 11: reserved */ + "", /* word 84 bit 10: reserved */ + "", /* word 84 bit 9: reserved */ + "", /* word 84 bit 8: reserved */ + "", /* word 84 bit 7: reserved */ + "", /* word 84 bit 6: reserved */ + "General Purpose Logging feature set", /* word 84 bit 5 */ + "", /* word 84 bit 4: reserved */ + "Media Card Pass Through Command feature set ", + "Media serial number ", /* word 84 bit 2 */ + "SMART self-test ", /* word 84 bit 1 */ + "SMART error logging " /* word 84 bit 0 */ +}; +#endif + + +/* words 85-87: cmds/feats enabled */ +/* use cmd_feat_str[] to display what commands and features have + * been enabled with words 85-87 + */ + +/* words 89, 90, SECU ERASE TIME */ +#define ERASE_BITS 0x00ff + +/* word 92: master password revision */ +/* NOVAL_0 or NOVAL_1 means no support for master password revision */ + +/* word 93: hw reset result */ +#define CBLID 0x2000 /* CBLID status */ +#define RST0 0x0001 /* 1=reset to device #0 */ +#define DEV_DET 0x0006 /* how device num determined */ +#define JUMPER_VAL 0x0002 /* device num determined by jumper */ +#define CSEL_VAL 0x0004 /* device num determined by CSEL_VAL */ + +/* word 127: removable media status notification feature set support */ +#define RM_STAT_BITS 0x0003 +#define RM_STAT_SUP 0x0001 + +/* word 128: security */ +#define SECU_ENABLED 0x0002 +#define SECU_LEVEL 0x0010 +#define NUM_SECU_STR 6 +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *secu_str[] = { + "supported", /* word 128, bit 0 */ + "enabled", /* word 128, bit 1 */ + "locked", /* word 128, bit 2 */ + "frozen", /* word 128, bit 3 */ + "expired: security count", /* word 128, bit 4 */ + "supported: enhanced erase" /* word 128, bit 5 */ +}; +#endif + +/* word 160: CFA power mode */ +#define VALID_W160 0x8000 /* 1=word valid */ +#define PWR_MODE_REQ 0x2000 /* 1=CFA power mode req'd by some cmds*/ +#define PWR_MODE_OFF 0x1000 /* 1=CFA power moded disabled */ +#define MAX_AMPS 0x0fff /* value = max current in ma */ + +/* word 255: integrity */ +#define SIG 0x00ff /* signature location */ +#define SIG_VAL 0x00A5 /* signature value */ + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static uint8_t mode_loop(uint16_t mode_sup, uint16_t mode_sel, int cc, uint8_t *have_mode) { + uint16_t ii; + uint8_t err_dma = 0; + for(ii = 0; ii <= MODE_MAX; ii++) { + if(mode_sel & 0x0001) { + printf("*%cdma%u ",cc,ii); + if(*have_mode) err_dma = 1; + *have_mode = 1; + } else if(mode_sup & 0x0001) { + printf("%cdma%u ",cc,ii); + } + mode_sup >>=1; mode_sel >>=1; + } + return err_dma; +} +static void print_ascii(uint16_t *p, uint8_t length) { + uint8_t ii; + char cl; + + /* find first non-space & print it */ + for(ii = 0; ii< length; ii++) { + if(((char) 0x00ff&((*p)>>8)) != ' ') break; + if((cl = (char) 0x00ff&(*p)) != ' ') { + if(cl != '\0') printf("%c",cl); + p++; ii++; + break; + } + p++; + } + /* print the rest */ + for(; ii< length; ii++) { + if(!(*p)) break; /* some older devices have NULLs */ + printf("%c%c",(char)0x00ff&((*p)>>8),(char)(*p)&0x00ff); + p++; + } + printf("\n"); +} + +/* identify() is the only extern function used across two source files. The + others, though, were declared in hdparm.c with global scope; since other + functions in that file have static (file) scope, I assume the difference is + intentional. */ +static void identify (uint16_t *id_supplied, const char *devname) +{ + + char *id_file = NULL, fmt[]="/proc/ide/%s/identify"; + FILE *fl; + uint16_t val[256], ii, jj, kk; + uint16_t like_std = 1, std = 0, min_std = 0xffff; + uint16_t dev = NO_DEV, eqpt = NO_DEV; + uint8_t have_mode = 0, err_dma = 0; + uint8_t chksum = 0; + uint32_t ll, mm, nn, oo; + __u64 bbbig; /* (:) */ + + if (id_supplied) { +#if __BYTE_ORDER == __BIG_ENDIAN + swab(id_supplied, val, sizeof(val)); +#else + memcpy(val, id_supplied, sizeof(val)); +#endif + } else { + id_file = xcalloc(1, strlen(devname)+1+strlen(fmt)); + sprintf(id_file, fmt, devname); + + /* open the file, read in all the info and close it */ + if (id_file == NULL) { + fl = stdin; + } else if(NULL == (fl = fopen(id_file, "r"))) + bb_perror_msg_and_die(id_file); + /* calculate checksum over all bytes */ + for(ii = GEN_CONFIG; ii<=INTEGRITY; ii++) { + unsigned int scratch; + if(1 != fscanf(fl,"%04x",&scratch)) break; + val[ii] = (uint16_t)scratch; + chksum += val[ii] + (val[ii] >> 8); + } + fclose(fl); + if(ii < (INTEGRITY+1)) + bb_error_msg_and_die("Input file wrong format or length"); + } + chksum &= 0xff; + + /* check if we recognise the device type */ + printf("\n"); + if(!(val[GEN_CONFIG] & NOT_ATA)) { + dev = ATA_DEV; + printf("ATA device, with "); + } else if(val[GEN_CONFIG]==CFA_SUPPORT_VAL) { + dev = ATA_DEV; + like_std = 4; + printf("CompactFlash ATA device, with "); + } else if(!(val[GEN_CONFIG] & NOT_ATAPI)) { + dev = ATAPI_DEV; + eqpt = (val[GEN_CONFIG] & EQPT_TYPE) >> SHIFT_EQPT; + printf("ATAPI %s, with ", pkt_str[eqpt]); + like_std = 3; + } else { + bb_error_msg_and_die("Unknown device type:\n\tbits 15&14 of general configuration word 0 both set to 1.\n"); + } + if(!(val[GEN_CONFIG] & MEDIA_REMOVABLE)) + printf("non-"); + printf("removable media\n"); + + + /* Info from the specific configuration word says whether or not the + * ID command completed correctly. It is only defined, however in + * ATA/ATAPI-5 & 6; it is reserved (value theoretically 0) in prior + * standards. Since the values allowed for this word are extremely + * specific, it should be safe to check it now, even though we don't + * know yet what standard this device is using. + */ + if((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL) || + (val[CONFIG]==PWRD_NID_VAL) || (val[CONFIG]==PWRD_ID_VAL) ) { + like_std = 5; + if((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL)) + printf("powers-up in standby; SET FEATURES subcmd spins-up.\n"); + if(((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==PWRD_NID_VAL)) && + (val[GEN_CONFIG] & INCOMPLETE)) + printf("\n\tWARNING: ID response incomplete.\n\tWARNING: Following data may be incorrect.\n\n"); + } + + /* output the model and serial numbers and the fw revision */ + if(val[START_MODEL]) { + printf("\t%-20s","Model Number:"); + print_ascii(&val[START_MODEL], LENGTH_MODEL); + } + if(val[START_SERIAL]) { + printf("\t%-20s","Serial Number:"); + print_ascii( &val[START_SERIAL], LENGTH_SERIAL); + } + if(val[START_FW_REV]) { + printf("\t%-20s","Firmware Revision:"); + print_ascii(&val[START_FW_REV], LENGTH_FW_REV); + } + if(val[START_MEDIA]) { + printf("\t%-20s","Media Serial Num:"); + print_ascii(&val[START_MEDIA], LENGTH_MEDIA); + } + if(val[START_MANUF]) { + printf("\t%-20s","Media Manufacturer:"); + print_ascii(&val[START_MANUF], LENGTH_MANUF); + } + + /* major & minor standards version number (Note: these words were not + * defined until ATA-3 & the CDROM std uses different words.) */ + printf("Standards:"); + if(eqpt != CDROM) { + if(val[MINOR] && (val[MINOR] <= MINOR_MAX)){ + if(like_std < 3) like_std = 3; + std = actual_ver[val[MINOR]]; + if(std) { + printf("\n\tUsed: "); + printf("%s ",minor_str[val[MINOR]]); + } + } + /* looks like when they up-issue the std, they obsolete one; + * thus, only the newest 4 issues need be supported. (That's + * what "kk" and "min_std" are all about.) */ + if(val[MAJOR] && (val[MAJOR] !=NOVAL_1)) { + printf("\n\tSupported: "); + jj = val[MAJOR] << 1; + kk = like_std >4 ? like_std-4: 0; + for(ii = 14; (ii >0)&&(ii>kk); ii--) { + if(jj & 0x8000) { + printf("%u ", ii); + if(like_std < ii) { + like_std = ii; + kk = like_std >4 ? like_std-4: 0; + } + if(min_std > ii) min_std = ii; + } + jj <<= 1; + } + if(like_std < 3) like_std = 3; + } + /* Figure out what standard the device is using if it hasn't told + * us. If we know the std, check if the device is using any of + * the words from the next level up. It happens. + */ + if(like_std < std) like_std = std; + if(((std == 5) || (!std && (like_std < 6))) && + ( (((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + ((val[CMDS_SUPP_1] & CMDS_W83) > 0x00ff)) || + (((val[CMDS_SUPP_2] & VALID) == VALID_VAL) && + (val[CMDS_SUPP_2] & CMDS_W84) ) ) ) { + like_std = 6; + } else if(((std == 4) || (!std && (like_std < 5))) && + ((((val[INTEGRITY] & SIG) == SIG_VAL) && !chksum) || + ((val[HWRST_RSLT] & VALID) == VALID_VAL) || + (((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + ((val[CMDS_SUPP_1] & CMDS_W83) > 0x001f)) ) ) { + like_std = 5; + } else if(((std == 3) || (!std && (like_std < 4))) && + ((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + (((val[CMDS_SUPP_1] & CMDS_W83) > 0x0000) || + ((val[CMDS_SUPP_0] & CMDS_W82) > 0x000f))) || + ((val[CAPAB_1] & VALID) == VALID_VAL) || + ((val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) || + ((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) ) ) { + like_std = 4; + } else if(((std == 2) || (!std && (like_std < 3))) && + ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) ) { + like_std = 3; + } else if(((std == 1) || (!std && (like_std < 2))) && + ((val[CAPAB_0] & (IORDY_SUP | IORDY_OFF)) || + (val[WHATS_VALID] & OK_W64_70)) ) { + like_std = 2; + } + if(!std) { + printf("\n\tLikely used: %u\n",like_std); + } else if(like_std > std) { + printf("& some of %u\n",like_std); + } else printf("\n"); + } else { + /* TBD: do CDROM stuff more thoroughly. For now... */ + kk = 0; + if(val[CDR_MINOR] == 9) { + kk = 1; + printf("\n\tUsed: ATAPI for CD-ROMs, SFF-8020i, r2.5"); + } + if(val[CDR_MAJOR] && (val[CDR_MAJOR] !=NOVAL_1)) { + kk = 1; + printf("\n\tSupported: CD-ROM ATAPI"); + jj = val[CDR_MAJOR] >> 1; + for(ii = 1; ii <15; ii++) { + if(jj & 0x0001) { + printf("-%u ", ii); + } + jj >>= 1; + } + } + if(!kk) printf("\n\tLikely used CD-ROM ATAPI-1\n"); + else printf("\n"); + /* the cdrom stuff is more like ATA-2 than anything else, so: */ + like_std = 2; + } + + if(min_std == 0xffff) min_std = like_std > 4 ? like_std - 3 : 1; + + printf("Configuration:\n"); + /* more info from the general configuration word */ + if((eqpt != CDROM) && (like_std == 1)) { + jj = val[GEN_CONFIG] >> 1; + for(ii = 1; ii < 15; ii++) { + if(jj & 0x0001) printf("\t%s\n",ata1_cfg_str[ii]); + jj >>=1; + } + } + if(dev == ATAPI_DEV) { + printf("\tDRQ response: "); /* Data Request (DRQ) */ + switch(val[GEN_CONFIG] & DRQ_RESPONSE_TIME) { + case DRQ_3MS_VAL : printf("3ms.\n"); break; + case DRQ_INTR_VAL : printf("<=10ms with INTRQ\n"); break; + case DRQ_50US_VAL : printf("50us.\n"); break; + default : printf("unknown.\n"); break; + } + printf("\tPacket size: "); + switch(val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) { + case PKT_SIZE_12_VAL : printf("12 bytes\n"); break; + case PKT_SIZE_16_VAL : printf("16 bytes\n"); break; + default : printf("Unknown\n"); break; + } + } else { + /* addressing...CHS? See section 6.2 of ATA specs 4 or 5 */ + ll = (uint32_t)val[LBA_SECTS_MSB] << 16 | val[LBA_SECTS_LSB]; + mm = 0; bbbig = 0; + if ( (ll > 0x00FBFC10) && (!val[LCYLS])) { + printf("\tCHS addressing not supported\n"); + } else { + jj = val[WHATS_VALID] & OK_W54_58; + printf("\tLogical\t\tmax\tcurrent\n"); + printf("\tcylinders\t%u\t%u\n",val[LCYLS],jj?val[LCYLS_CUR]:0); + printf("\theads\t\t%u\t%u\n",val[LHEADS],jj?val[LHEADS_CUR]:0); + printf("\tsectors/track\t%u\t%u\n",val[LSECTS],jj?val[LSECTS_CUR]:0); + printf("\t--\n"); + if((min_std == 1) && (val[TRACK_BYTES] || val[SECT_BYTES])) { + printf("\tbytes/track: %u",val[TRACK_BYTES]); + printf("\tbytes/sector: %u\n",val[SECT_BYTES]); + } + if(jj) { + mm = (uint32_t)val[CAPACITY_MSB] << 16 | val[CAPACITY_LSB]; + if(like_std < 3) { /* check Endian of capacity bytes */ + nn = val[LCYLS_CUR] * val[LHEADS_CUR] * val[LSECTS_CUR]; + oo = (uint32_t)val[CAPACITY_LSB] << 16 | val[CAPACITY_MSB]; + if(abs(mm - nn) > abs(oo - nn)) + mm = oo; + } + printf("\tCHS current addressable sectors:%11u\n",mm); + } + } + /* LBA addressing */ + printf("\tLBA user addressable sectors:%11u\n",ll); + if( ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + (val[CMDS_SUPP_1] & SUPPORT_48_BIT) ) { + bbbig = (__u64)val[LBA_64_MSB] << 48 | + (__u64)val[LBA_48_MSB] << 32 | + (__u64)val[LBA_MID] << 16 | + val[LBA_LSB] ; + printf("\tLBA48 user addressable sectors:%11llu\n",bbbig); + } + if (!bbbig) bbbig = (__u64)(ll>mm ? ll : mm); /* # 512 byte blocks */ + printf("\tdevice size with M = 1024*1024: %11llu MBytes\n",bbbig>>11); + bbbig = (bbbig<<9)/1000000; + printf("\tdevice size with M = 1000*1000: %11llu MBytes ",bbbig); + if(bbbig > 1000) printf("(%llu GB)\n",bbbig/1000); + else printf("\n"); + + } + + /* hw support of commands (capabilities) */ + printf("Capabilities:\n"); + printf("\t"); + if(dev == ATAPI_DEV) { + if(eqpt != CDROM) { + if(val[CAPAB_0] & CMD_Q_SUP) printf("Cmd queuing, "); + } + if(val[CAPAB_0] & OVLP_SUP) printf("Cmd overlap, "); + } + if(val[CAPAB_0] & LBA_SUP) printf("LBA, "); + if(like_std != 1) { + printf("IORDY"); + if(!(val[CAPAB_0] & IORDY_SUP)) printf("(may be)"); + if(val[CAPAB_0] & IORDY_OFF) printf("(can"); + else printf("(cannot"); + printf(" be disabled)"); + } else printf("no IORDY"); + printf("\n"); + if((like_std == 1) && val[BUF_TYPE]) { + kk = val[BUF_TYPE]; + printf("\tBuffer type: %04x: ",kk); + if (kk < 2) printf("single port, single-sector"); + else printf("dual port, multi-sector"); + if (kk > 2) printf(" with read caching ability"); + printf("\n"); + } + jj = 0; + if((min_std == 1) && (val[BUFFER__SIZE] && (val[BUFFER__SIZE] != NOVAL_1))) { + printf("\tBuffer size: %.1fkB",(float)val[BUFFER__SIZE]/2); + jj = 1; + } + if((min_std < 4) && (val[RW_LONG])) { + printf("\tbytes avail on r/w long: %u",val[RW_LONG]); + jj = 1; + } + if((eqpt != CDROM) && (like_std > 3)) { + printf("\tQueue depth: %u",(val[QUEUE_DEPTH] & DEPTH_BITS)+1); + jj = 1; + } + if(jj) printf("\n"); + if(dev == ATA_DEV) { + if(like_std == 1) { + printf("\tCan"); + if(!val[DWORD_IO]) printf("not"); + printf(" perform double-word IO\n"); + } else { + printf("\tStandby timer values: spec'd by "); + if(val[CAPAB_0] & STD_STBY) printf("Standard"); + else printf("Vendor"); + if((like_std > 3) && ((val[CAPAB_1] & VALID) == VALID_VAL)) { + if(val[CAPAB_1] & MIN_STANDBY_TIMER) printf(", with "); + else printf(", no "); + printf("device specific minimum\n"); + } else printf("\n"); + } + printf("\tR/W multiple sector transfer: "); + if((like_std < 3) && !(val[SECTOR_XFER_MAX] & SECTOR_XFER)) { + printf("not supported\n"); + } else { + printf("Max = %u\t",val[SECTOR_XFER_MAX] & SECTOR_XFER); + printf("Current = "); + if(val[SECTOR_XFER_CUR] & MULTIPLE_SETTING_VALID) + printf("%u\n",val[SECTOR_XFER_CUR] & SECTOR_XFER); + else printf("?\n"); + } + if((like_std > 3) && (val[CMDS_SUPP_1] & 0x0008)) { + /* We print out elsewhere whether the APM feature is enabled or + not. If it's not enabled, let's not repeat the info; just print + nothing here. */ + printf("\tAdvanced power management level: "); + if ( (val[ADV_PWR] & 0xFF00) == 0x4000 ) { + uint8_t apm_level = val[ADV_PWR] & 0x00FF; + + printf("%u (0x%x)\n", apm_level, apm_level); + } else { + printf("unknown setting (0x%04x)\n", val[ADV_PWR]); + } + } + if(like_std > 5) { + if(val[ACOUSTIC]) { + printf("\tRecommended acoustic management value: %u, current value: %u\n", (val[ACOUSTIC] >> 8) & 0x00ff, val[ACOUSTIC] & 0x00ff); + } + } + } else { /* ATAPI */ + if(eqpt != CDROM) { + if(val[CAPAB_0] & SWRST_REQ) printf("\tATA sw reset required\n"); + } + if(val[PKT_REL] || val[SVC_NBSY]) { + printf("\tOverlap support:"); + if(val[PKT_REL]) printf(" %uus to release bus.",val[PKT_REL]); + if(val[SVC_NBSY]) printf(" %uus to clear BSY after SERVICE cmd.",val[SVC_NBSY]); + printf("\n"); + } + } + + /* DMA stuff. Check that only one DMA mode is selected. */ + printf("\tDMA: "); + if(!(val[CAPAB_0] & DMA_SUP)) { + printf("not supported\n"); + } else { + if(val[DMA_MODE] && !val[SINGLE_DMA] && !val[MULTI_DMA]) + printf(" sdma%u\n",(val[DMA_MODE] & MODE) >> 8); + if(val[SINGLE_DMA]) { + jj = val[SINGLE_DMA]; kk = val[SINGLE_DMA] >> 8; + err_dma += mode_loop(jj,kk,'s',&have_mode); + } + if(val[MULTI_DMA]) { + jj = val[MULTI_DMA]; kk = val[MULTI_DMA] >> 8; + err_dma += mode_loop(jj,kk,'m',&have_mode); + } + if((val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) { + jj = val[ULTRA_DMA]; kk = val[ULTRA_DMA] >> 8; + err_dma += mode_loop(jj,kk,'u',&have_mode); + } + if(err_dma || !have_mode) printf("(?)"); + printf("\n"); + + if((dev == ATAPI_DEV) && (eqpt != CDROM) && (val[CAPAB_0] & DMA_IL_SUP)) + printf("\t Interleaved DMA support\n"); + + if((val[WHATS_VALID] & OK_W64_70) && + (val[DMA_TIME_MIN] || val[DMA_TIME_NORM])) { + printf("\t Cycle time:"); + if(val[DMA_TIME_MIN]) + printf(" min=%uns",val[DMA_TIME_MIN]); + if(val[DMA_TIME_NORM]) + printf(" recommended=%uns",val[DMA_TIME_NORM]); + printf("\n"); + } + } + + /* Programmed IO stuff */ + printf("\tPIO: "); + /* If a drive supports mode n (e.g. 3), it also supports all modes less + * than n (e.g. 3, 2, 1 and 0). Print all the modes. */ + if((val[WHATS_VALID] & OK_W64_70) && (val[ADV_PIO_MODES] & PIO_SUP)) { + jj = ((val[ADV_PIO_MODES] & PIO_SUP) << 3) | 0x0007; + for(ii = 0; ii <= PIO_MODE_MAX ; ii++) { + if(jj & 0x0001) + printf("pio%d ",ii); + jj >>=1; + } + printf("\n"); + } else if(((min_std < 5) || (eqpt == CDROM)) && (val[PIO_MODE] & MODE) ) { + for(ii = 0; ii <= val[PIO_MODE]>>8; ii++) { + printf("pio%d ",ii); + } + printf("\n"); + } else printf("unknown\n"); + if(val[WHATS_VALID] & OK_W64_70) { + if(val[PIO_NO_FLOW] || val[PIO_FLOW]) { + printf("\t Cycle time:"); + if(val[PIO_NO_FLOW]) + printf(" no flow control=%uns", val[PIO_NO_FLOW]); + if(val[PIO_FLOW]) + printf(" IORDY flow control=%uns", val[PIO_FLOW]); + printf("\n"); + } + } + + if((val[CMDS_SUPP_1] & VALID) == VALID_VAL){ + printf("Commands/features:\n\tEnabled\tSupported:\n"); + jj = val[CMDS_SUPP_0]; + kk = val[CMDS_EN_0]; + for(ii = 0; ii < NUM_CMD_FEAT_STR; ii++) { + if((jj & 0x8000) && (*cmd_feat_str[ii] != '\0')) { + if(kk & 0x8000) printf("\t *"); + else printf("\t"); + printf("\t%s\n",cmd_feat_str[ii]); + } + jj <<=1; kk<<=1; + if(ii%16 == 15) { + jj = val[CMDS_SUPP_0+1+(ii/16)]; + kk = val[CMDS_EN_0+1+(ii/16)]; + } + if(ii == 31) { + if((val[CMDS_SUPP_2] & VALID) != VALID_VAL) ii +=16; + } + } + } + if((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) + printf("\tRemovable Media Status Notification feature set supported\n"); + + + /* security */ + if((eqpt != CDROM) && (like_std > 3) && + (val[SECU_STATUS] || val[ERASE_TIME] || val[ENH_ERASE_TIME])) { + printf("Security: \n"); + if(val[PSWD_CODE] && (val[PSWD_CODE] != NOVAL_1)) + printf("\tMaster password revision code = %u\n",val[PSWD_CODE]); + jj = val[SECU_STATUS]; + if(jj) { + for(ii = 0; ii < NUM_SECU_STR; ii++) { + if(!(jj & 0x0001)) printf("\tnot\t"); + else printf("\t\t"); + printf("%s\n",secu_str[ii]); + jj >>=1; + } + if(val[SECU_STATUS] & SECU_ENABLED) { + printf("\tSecurity level "); + if(val[SECU_STATUS] & SECU_LEVEL) printf("maximum\n"); + else printf("high\n"); + } + } + jj = val[ERASE_TIME] & ERASE_BITS; + kk = val[ENH_ERASE_TIME] & ERASE_BITS; + if(jj || kk) { + printf("\t"); + if(jj) printf("%umin for SECURITY ERASE UNIT. ", jj==ERASE_BITS ? 508 : jj<<1); + if(kk) printf("%umin for ENHANCED SECURITY ERASE UNIT.", kk==ERASE_BITS ? 508 : kk<<1); + printf("\n"); + } + } + + /* reset result */ + if((val[HWRST_RSLT] & VALID) == VALID_VAL) { + printf("HW reset results:\n"); + if(val[HWRST_RSLT] & CBLID) printf("\tCBLID- above Vih\n"); + else printf("\tCBLID- below Vih\n"); + if(val[HWRST_RSLT] & RST0) { + printf("\tDevice num = 0"); + jj = val[HWRST_RSLT]; + } else { + printf("\tDevice num = 1"); + jj = val[HWRST_RSLT] >> 8; + } + if((jj & DEV_DET) == JUMPER_VAL) + printf(" determined by the jumper"); + else if((jj & DEV_DET) == CSEL_VAL) + printf(" determined by CSEL"); + printf("\n"); + } + + /* more stuff from std 5 */ + if((like_std > 4) && (eqpt != CDROM)) { + if(val[CFA_PWR_MODE] & VALID_W160) { + printf("CFA power mode 1:\n\t"); + if(val[CFA_PWR_MODE] & PWR_MODE_OFF) printf("dis"); + else printf("en"); + printf("abled"); + if(val[CFA_PWR_MODE] & PWR_MODE_REQ) + printf(" and required by some commands"); + printf("\n"); + if(val[CFA_PWR_MODE] & MAX_AMPS) + printf("\tMaximum current = %uma\n",val[CFA_PWR_MODE] & MAX_AMPS); + } + if((val[INTEGRITY] & SIG) == SIG_VAL) { + printf("Checksum: "); + if(chksum) printf("in"); + printf("correct\n"); + } + } + + exit(0); +} +#endif + +#define VERSION "v5.4" + +#undef DO_FLUSHCACHE /* under construction: force cache flush on -W0 */ +#define TIMING_BUF_MB 2 +#define TIMING_BUF_BYTES (TIMING_BUF_MB * 1024 * 1024) +#define BUFCACHE_FACTOR 2 + +static int verbose = 0, get_identity = 0, get_geom = 0, noisy = 1, quiet = 0; +static int flagcount = 0, do_flush = 0, is_scsi_hd = 0, is_xt_hd = 0; +static int do_ctimings, do_timings = 0; + +static unsigned long set_readahead= 0, get_readahead= 0, readahead= 0; +static unsigned long set_readonly = 0, get_readonly = 0, readonly = 0; +static unsigned long set_unmask = 0, get_unmask = 0, unmask = 0; +static unsigned long set_mult = 0, get_mult = 0, mult = 0; +static unsigned long set_dma = 0, get_dma = 0, dma = 0; +static unsigned long set_dma_q = 0, get_dma_q = 0, dma_q = 0; +static unsigned long set_nowerr = 0, get_nowerr = 0, nowerr = 0; +static unsigned long set_keep = 0, get_keep = 0, keep = 0; +static unsigned long set_io32bit = 0, get_io32bit = 0, io32bit = 0; +static unsigned long set_piomode = 0, noisy_piomode= 0; +static int piomode = 0; +#ifdef HDIO_DRIVE_CMD +static unsigned long set_dkeep = 0, get_dkeep = 0, dkeep = 0; +static unsigned long set_standby = 0, get_standby = 0, standby_requested= 0; +static unsigned long set_xfermode = 0, get_xfermode = 0; +static int xfermode_requested= 0; +static unsigned long set_lookahead= 0, get_lookahead= 0, lookahead= 0; +static unsigned long set_prefetch = 0, get_prefetch = 0, prefetch = 0; +static unsigned long set_defects = 0, get_defects = 0, defects = 0; +static unsigned long set_wcache = 0, get_wcache = 0, wcache = 0; +static unsigned long set_doorlock = 0, get_doorlock = 0, doorlock = 0; +static unsigned long set_seagate = 0, get_seagate = 0; +static unsigned long set_standbynow = 0, get_standbynow = 0; +static unsigned long set_sleepnow = 0, get_sleepnow = 0; +static unsigned long get_powermode = 0; +static unsigned long set_apmmode = 0, get_apmmode= 0, apmmode = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static int get_IDentity = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF +static int unregister_hwif = 0; +static int hwif = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF +static int scan_hwif = 0; +static int hwif_data = 0; +static int hwif_ctrl = 0; +static int hwif_irq = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static int set_busstate = 0, get_busstate = 0, busstate = 0; +#endif +static int reread_partn = 0; + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET +static int perform_reset = 0; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static int perform_tristate = 0, tristate = 0; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ + +// Historically, if there was no HDIO_OBSOLETE_IDENTITY, then +// then the HDIO_GET_IDENTITY only returned 142 bytes. +// Otherwise, HDIO_OBSOLETE_IDENTITY returns 142 bytes, +// and HDIO_GET_IDENTITY returns 512 bytes. But the latest +// 2.5.xx kernels no longer define HDIO_OBSOLETE_IDENTITY +// (which they should, but they should just return -EINVAL). +// +// So.. we must now assume that HDIO_GET_IDENTITY returns 512 bytes. +// On a really old system, it will not, and we will be confused. +// Too bad, really. + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *cfg_str[] = +{ "", " HardSect", " SoftSect", " NotMFM", + " HdSw>15uSec", " SpinMotCtl", " Fixed", " Removeable", + " DTR<=5Mbs", " DTR>5Mbs", " DTR>10Mbs", " RotSpdTol>.5%", + " dStbOff", " TrkOff", " FmtGapReq", " nonMagnetic" +}; + +static const char *BuffType[] = {"unknown", "1Sect", "DualPort", "DualPortCache"}; + +#define YN(b) (((b)==0)?"no":"yes") + +static void dmpstr (const char *prefix, unsigned int i, const char *s[], unsigned int maxi) +{ + if (i > maxi) + printf("%s%u", prefix, i); + else + printf("%s%s", prefix, s[i]); +} + +static void dump_identity (const struct hd_driveid *id) +{ + int i; + char pmodes[64] = {0,}, dmodes[128]={0,}, umodes[128]={0,}; + const unsigned short int *id_regs= (const void*) id; + unsigned long capacity; + + printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s", + id->model, id->fw_rev, id->serial_no); + printf("\n Config={"); + for (i=0; i<=15; i++) { + if (id->config & (1<<i)) + printf("%s", cfg_str[i]); + } + printf(" }\n"); + printf(" RawCHS=%u/%u/%u, TrkSize=%u, SectSize=%u, ECCbytes=%u\n", + id->cyls, id->heads, id->sectors, + id->track_bytes, id->sector_bytes, id->ecc_bytes); + dmpstr(" BuffType=",id->buf_type,BuffType,3); + printf(", BuffSize=%ukB, MaxMultSect=%u", id->buf_size/2, id->max_multsect); + if (id->max_multsect) { + printf(", MultSect="); + if (!(id->multsect_valid&1)) + printf("?%u?", id->multsect); + else if (id->multsect) + printf("%u", id->multsect); + else + printf("off"); + } + putchar('\n'); + if (id->tPIO <= 5) { + strcat(pmodes, "pio0 "); + if (id->tPIO >= 1) strcat(pmodes, "pio1 "); + if (id->tPIO >= 2) strcat(pmodes, "pio2 "); + } + if (!(id->field_valid&1)) + printf(" (maybe):"); +#if __BYTE_ORDER == __BIG_ENDIAN + capacity = (id->cur_capacity0 << 16) | id->cur_capacity1; +#else + capacity = (id->cur_capacity1 << 16) | id->cur_capacity0; +#endif + printf(" CurCHS=%u/%u/%u, CurSects=%lu", id->cur_cyls, id->cur_heads, id->cur_sectors, capacity); + printf(", LBA=%s", YN(id->capability&2)); + if (id->capability&2) + printf(", LBAsects=%u", id->lba_capacity); + + if (id->capability&1) { + if (id->dma_1word | id->dma_mword) { + if (id->dma_1word & 0x100) strcat(dmodes,"*"); + if (id->dma_1word & 1) strcat(dmodes,"sdma0 "); + if (id->dma_1word & 0x200) strcat(dmodes,"*"); + if (id->dma_1word & 2) strcat(dmodes,"sdma1 "); + if (id->dma_1word & 0x400) strcat(dmodes,"*"); + if (id->dma_1word & 4) strcat(dmodes,"sdma2 "); + if (id->dma_1word & 0xf800) strcat(dmodes,"*"); + if (id->dma_1word & 0xf8) strcat(dmodes,"sdma? "); + if (id->dma_mword & 0x100) strcat(dmodes,"*"); + if (id->dma_mword & 1) strcat(dmodes,"mdma0 "); + if (id->dma_mword & 0x200) strcat(dmodes,"*"); + if (id->dma_mword & 2) strcat(dmodes,"mdma1 "); + if (id->dma_mword & 0x400) strcat(dmodes,"*"); + if (id->dma_mword & 4) strcat(dmodes,"mdma2 "); + if (id->dma_mword & 0xf800) strcat(dmodes,"*"); + if (id->dma_mword & 0xf8) strcat(dmodes,"mdma? "); + } + } + printf("\n IORDY="); + if (id->capability&8) + printf((id->capability&4) ? "on/off" : "yes"); + else + printf("no"); + if ((id->capability&8) || (id->field_valid&2)) { + if (id->field_valid&2) { + printf(", tPIO={min:%u,w/IORDY:%u}", id->eide_pio, id->eide_pio_iordy); + if (id->eide_pio_modes & 1) strcat(pmodes, "pio3 "); + if (id->eide_pio_modes & 2) strcat(pmodes, "pio4 "); + if (id->eide_pio_modes &~3) strcat(pmodes, "pio? "); + } + if (id->field_valid&4) { + if (id->dma_ultra & 0x100) strcat(umodes,"*"); + if (id->dma_ultra & 0x001) strcat(umodes,"udma0 "); + if (id->dma_ultra & 0x200) strcat(umodes,"*"); + if (id->dma_ultra & 0x002) strcat(umodes,"udma1 "); + if (id->dma_ultra & 0x400) strcat(umodes,"*"); + if (id->dma_ultra & 0x004) strcat(umodes,"udma2 "); +#ifdef __NEW_HD_DRIVE_ID + if (id->hw_config & 0x2000) { +#else /* !__NEW_HD_DRIVE_ID */ + if (id->word93 & 0x2000) { +#endif /* __NEW_HD_DRIVE_ID */ + if (id->dma_ultra & 0x0800) strcat(umodes,"*"); + if (id->dma_ultra & 0x0008) strcat(umodes,"udma3 "); + if (id->dma_ultra & 0x1000) strcat(umodes,"*"); + if (id->dma_ultra & 0x0010) strcat(umodes,"udma4 "); + if (id->dma_ultra & 0x2000) strcat(umodes,"*"); + if (id->dma_ultra & 0x0020) strcat(umodes,"udma5 "); + if (id->dma_ultra & 0x4000) strcat(umodes,"*"); + if (id->dma_ultra & 0x0040) strcat(umodes,"udma6 "); + if (id->dma_ultra & 0x8000) strcat(umodes,"*"); + if (id->dma_ultra & 0x0080) strcat(umodes,"udma7 "); + } + } + } + if ((id->capability&1) && (id->field_valid&2)) + printf(", tDMA={min:%u,rec:%u}", id->eide_dma_min, id->eide_dma_time); + printf("\n PIO modes: %s", pmodes); + if (*dmodes) + printf("\n DMA modes: %s", dmodes); + if (*umodes) + printf("\n UDMA modes: %s", umodes); + + printf("\n AdvancedPM=%s",YN(id_regs[83]&8)); + if (id_regs[83] & 8) { + if (!(id_regs[86]&8)) + printf(": disabled (255)"); + else if ((id_regs[91]&0xFF00)!=0x4000) + printf(": unknown setting"); + else + printf(": mode=0x%02X (%u)",id_regs[91]&0xFF,id_regs[91]&0xFF); + } + if (id_regs[82]&0x20) + printf(" WriteCache=%s",(id_regs[85]&0x20) ? "enabled" : "disabled"); +#ifdef __NEW_HD_DRIVE_ID + if ((id->minor_rev_num && id->minor_rev_num <= 31) || (id->major_rev_num && id->minor_rev_num <= 31)) { + printf("\n Drive conforms to: "); + if (id->minor_rev_num <= 31) + printf("%s: ", minor_str[id->minor_rev_num]); + else + printf("unknown: "); + if (id->major_rev_num < 31) { + for (i=0; i <= 15; i++) { + if (id->major_rev_num & (1<<i)) + printf(" %u", i); + } + } + } +#endif /* __NEW_HD_DRIVE_ID */ + printf("\n"); + printf("\n * signifies the current active mode\n"); + printf("\n"); +} +#endif + +static void flush_buffer_cache (int fd) +{ + fsync (fd); /* flush buffers */ + if (ioctl(fd, BLKFLSBUF, NULL)) /* do it again, big time */ + bb_perror_msg("BLKFLSBUF failed"); +#ifdef HDIO_DRIVE_CMD + if (is_scsi_hd || is_xt_hd) { + sleep(1); + } else { + if (ioctl(fd, HDIO_DRIVE_CMD, NULL) && errno != EINVAL) /* await completion */ + bb_perror_msg("HDIO_DRIVE_CMD(null) (wait for flush complete) failed"); + } +#endif +} + +static int seek_to_zero (int fd) +{ + if (lseek(fd, (off_t) 0, SEEK_SET)) { + bb_perror_msg("lseek() failed"); + return 1; + } + return 0; +} + +static int read_big_block (int fd, char *buf) +{ + int i, rc; + if ((rc = read(fd, buf, TIMING_BUF_BYTES)) != TIMING_BUF_BYTES) { + if (rc) { + if (rc == -1) + bb_perror_msg("read() failed"); + else + bb_error_msg("read(%u) returned %u bytes", TIMING_BUF_BYTES, rc); + } else { + fputs ("read() hit EOF - device too small\n", stderr); + } + return 1; + } + /* access all sectors of buf to ensure the read fully completed */ + for (i = 0; i < TIMING_BUF_BYTES; i += 512) + buf[i] &= 1; + return 0; +} + +static void time_cache (int fd) +{ + char *buf; + struct itimerval e1, e2; + int shmid; + double elapsed, elapsed2; + unsigned int iterations, total_MB; + + if ((shmid = shmget(IPC_PRIVATE, TIMING_BUF_BYTES, 0600)) == -1) { + bb_perror_msg ("could not allocate sharedmem buf"); + return; + } + if (shmctl(shmid, SHM_LOCK, NULL) == -1) { + bb_perror_msg ("could not lock sharedmem buf"); + (void) shmctl(shmid, IPC_RMID, NULL); + return; + } + if ((buf = shmat(shmid, (char *) 0, 0)) == (char *) -1) { + bb_perror_msg ("could not attach sharedmem buf"); + (void) shmctl(shmid, IPC_RMID, NULL); + return; + } + if (shmctl(shmid, IPC_RMID, NULL) == -1) + bb_perror_msg ("shmctl(,IPC_RMID,) failed"); + + /* Clear out the device request queues & give them time to complete */ + sync(); + sleep(3); + + /* + * getitimer() is used rather than gettimeofday() because + * it is much more consistent (on my machine, at least). + */ + setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL); + if (seek_to_zero (fd)) return; + if (read_big_block (fd, buf)) return; + printf(" Timing buffer-cache reads: "); + fflush(stdout); + + /* Clear out the device request queues & give them time to complete */ + sync(); + sleep(1); + + /* Now do the timing */ + iterations = 0; + getitimer(ITIMER_REAL, &e1); + do { + ++iterations; + if (seek_to_zero (fd) || read_big_block (fd, buf)) + goto quit; + getitimer(ITIMER_REAL, &e2); + elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + } while (elapsed < 2.0); + total_MB = iterations * TIMING_BUF_MB; + + elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + + /* Now remove the lseek() and getitimer() overheads from the elapsed time */ + getitimer(ITIMER_REAL, &e1); + do { + if (seek_to_zero (fd)) + goto quit; + getitimer(ITIMER_REAL, &e2); + elapsed2 = (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + } while (--iterations); + + elapsed -= elapsed2; + + if ((BUFCACHE_FACTOR * total_MB) >= elapsed) /* more than 1MB/s */ + printf("%3u MB in %5.2f seconds = %6.2f MB/sec\n", + (BUFCACHE_FACTOR * total_MB), elapsed, + (BUFCACHE_FACTOR * total_MB) / elapsed); + else + printf("%3u MB in %5.2f seconds = %6.2f kB/sec\n", + (BUFCACHE_FACTOR * total_MB), elapsed, + (BUFCACHE_FACTOR * total_MB) / elapsed * 1024); + + flush_buffer_cache(fd); + sleep(1); +quit: + if (-1 == shmdt(buf)) + bb_perror_msg ("could not detach sharedmem buf"); +} + +static void time_device (int fd) +{ + char *buf; + double elapsed; + struct itimerval e1, e2; + int shmid; + unsigned int max_iterations = 1024, total_MB, iterations; + static long parm; + + // + // get device size + // + if (do_ctimings || do_timings) { + if (ioctl(fd, BLKGETSIZE, &parm)) + bb_perror_msg(" BLKGETSIZE failed"); + else + max_iterations = parm / (2 * 1024) / TIMING_BUF_MB; + } + + if ((shmid = shmget(IPC_PRIVATE, TIMING_BUF_BYTES, 0600)) == -1) { + bb_perror_msg ("could not allocate sharedmem buf"); + return; + } + if (shmctl(shmid, SHM_LOCK, NULL) == -1) { + bb_perror_msg ("could not lock sharedmem buf"); + (void) shmctl(shmid, IPC_RMID, NULL); + return; + } + if ((buf = shmat(shmid, (char *) 0, 0)) == (char *) -1) { + bb_perror_msg ("could not attach sharedmem buf"); + (void) shmctl(shmid, IPC_RMID, NULL); + return; + } + if (shmctl(shmid, IPC_RMID, NULL) == -1) + bb_perror_msg ("shmctl(,IPC_RMID,) failed"); + + /* Clear out the device request queues & give them time to complete */ + sync(); + sleep(3); + + printf(" Timing buffered disk reads: "); + fflush(stdout); + + /* + * getitimer() is used rather than gettimeofday() because + * it is much more consistent (on my machine, at least). + */ + setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL); + + /* Now do the timings for real */ + iterations = 0; + getitimer(ITIMER_REAL, &e1); + do { + ++iterations; + if (read_big_block (fd, buf)) + goto quit; + getitimer(ITIMER_REAL, &e2); + elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + } while (elapsed < 3.0 && iterations < max_iterations); + + total_MB = iterations * TIMING_BUF_MB; + if ((total_MB / elapsed) > 1.0) /* more than 1MB/s */ + printf("%3u MB in %5.2f seconds = %6.2f MB/sec\n", + total_MB, elapsed, total_MB / elapsed); + else + printf("%3u MB in %5.2f seconds = %6.2f kB/sec\n", + total_MB, elapsed, total_MB / elapsed * 1024); +quit: + if (-1 == shmdt(buf)) + bb_perror_msg ("could not detach sharedmem buf"); +} + +static void no_scsi (void) +{ + if (is_scsi_hd) { + bb_error_msg_and_die(" operation not supported on SCSI disks\n"); + } +} + +static void no_xt (void) +{ + if (is_xt_hd) { + bb_error_msg_and_die (" operation not supported on XT disks\n"); + } +} + +static void on_off (unsigned int value) +{ + printf(value ? " (on)\n" : " (off)\n"); +} + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static void bus_state_value (unsigned int value) +{ + const char *string; + + switch (value) { + case BUSSTATE_ON: + string = " (on)\n"; + break; + case BUSSTATE_OFF: + string = " (off)\n"; + break; + case BUSSTATE_TRISTATE: + string = " (tristate)\n"; + break; + default: + string = " (unknown: %d)\n"; + break; + } + printf(string, value); +} +#endif + +#ifdef HDIO_DRIVE_CMD +static void interpret_standby (unsigned int standby) +{ + printf(" ("); + switch(standby) { + case 0: printf("off"); + break; + case 252: printf("21 minutes"); + break; + case 253: printf("vendor-specific"); + break; + case 254: printf("?reserved"); + break; + case 255: printf("21 minutes + 15 seconds"); + break; + default: + if (standby <= 240) { + unsigned int secs = standby * 5; + unsigned int mins = secs / 60; + secs %= 60; + if (mins) printf("%u minutes", mins); + if (mins && secs) printf(" + "); + if (secs) printf("%u seconds", secs); + } else if (standby <= 251) { + unsigned int mins = (standby - 240) * 30; + unsigned int hrs = mins / 60; + mins %= 60; + if (hrs) printf("%u hours", hrs); + if (hrs && mins) printf(" + "); + if (mins) printf("%u minutes", mins); + } else + printf("illegal value"); + break; + } + printf(")\n"); +} + +struct xfermode_entry { + int val; + const char *name; +}; + +static const struct xfermode_entry xfermode_table[] = { + { 8, "pio0" }, + { 9, "pio1" }, + { 10, "pio2" }, + { 11, "pio3" }, + { 12, "pio4" }, + { 13, "pio5" }, + { 14, "pio6" }, + { 15, "pio7" }, + { 16, "sdma0" }, + { 17, "sdma1" }, + { 18, "sdma2" }, + { 19, "sdma3" }, + { 20, "sdma4" }, + { 21, "sdma5" }, + { 22, "sdma6" }, + { 23, "sdma7" }, + { 32, "mdma0" }, + { 33, "mdma1" }, + { 34, "mdma2" }, + { 35, "mdma3" }, + { 36, "mdma4" }, + { 37, "mdma5" }, + { 38, "mdma6" }, + { 39, "mdma7" }, + { 64, "udma0" }, + { 65, "udma1" }, + { 66, "udma2" }, + { 67, "udma3" }, + { 68, "udma4" }, + { 69, "udma5" }, + { 70, "udma6" }, + { 71, "udma7" }, + { 0, NULL } +}; + +static int translate_xfermode(char * name) +{ + const struct xfermode_entry *tmp; + char *endptr; + int val = -1; + + + for (tmp = xfermode_table; tmp->name != NULL; ++tmp) { + if (!strcmp(name, tmp->name)) + return tmp->val; + } + + val = strtol(name, &endptr, 10); + if (*endptr == '\0') + return val; + + return -1; +} + +static void interpret_xfermode (unsigned int xfermode) +{ + printf(" ("); + switch(xfermode) { + case 0: printf("default PIO mode"); + break; + case 1: printf("default PIO mode, disable IORDY"); + break; + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: printf("PIO flow control mode%u", xfermode-8); + break; + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: printf("singleword DMA mode%u", xfermode-16); + break; + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + case 38: + case 39: printf("multiword DMA mode%u", xfermode-32); + break; + case 64: + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: printf("UltraDMA mode%u", xfermode-64); + break; + default: + printf("unknown, probably not valid"); + break; + } + printf(")\n"); +} +#endif /* HDIO_DRIVE_CMD */ + +#ifndef VXVM_MAJOR +#define VXVM_MAJOR 199 +#endif + +#ifndef CCISS_MAJOR +#define CCISS_MAJOR 104 +#endif + +static void process_dev (char *devname) +{ + int fd; + static long parm, multcount; + struct stat stat_buf; +#ifndef HDIO_DRIVE_CMD + int force_operation = 0; +#endif + if (stat(devname,&stat_buf)) + bb_perror_msg_and_die(devname); + + switch(major(stat_buf.st_rdev)) { +#ifdef SCSI_DISK0_MAJOR + case (SCSI_DISK0_MAJOR): + case (SCSI_DISK1_MAJOR): + case (SCSI_DISK2_MAJOR): + case (SCSI_DISK3_MAJOR): + case (SCSI_DISK4_MAJOR): + case (SCSI_DISK5_MAJOR): + case (SCSI_DISK6_MAJOR): + case (SCSI_DISK7_MAJOR): +#else + case (SCSI_DISK_MAJOR): +#endif +#ifdef MD_MAJOR + case (MD_MAJOR): +#endif + case (VXVM_MAJOR): +#ifdef LVM_BLK_MAJOR + case (LVM_BLK_MAJOR): +#endif + case (CCISS_MAJOR): + is_scsi_hd = 1; + break; +#ifdef XT_DISK_MAJOR + case (XT_DISK_MAJOR): + is_xt_hd = 1; + break; +#endif + case IDE0_MAJOR: + case IDE1_MAJOR: +#ifdef IDE2_MAJOR + case IDE2_MAJOR: +#endif +#ifdef IDE3_MAJOR + case IDE3_MAJOR: +#endif +#ifdef IDE4_MAJOR + case IDE4_MAJOR: +#endif +#ifdef IDE5_MAJOR + case IDE5_MAJOR: +#endif +#ifdef IDE6_MAJOR + case IDE6_MAJOR: +#endif +#ifdef IDE7_MAJOR + case IDE7_MAJOR: +#endif +#ifdef IDE8_MAJOR + case IDE8_MAJOR: +#endif +#ifdef IDE9_MAJOR + case IDE9_MAJOR: +#endif + break; /* do nothing */ + default: + bb_error_msg_and_die("%s not supported by hdparm",devname); + } + + fd = open (devname, O_RDONLY|O_NONBLOCK); + if (fd < 0) + bb_perror_msg_and_die(devname); + if (!quiet) + printf("\n%s:\n", devname); + + if (set_readahead) { + if (get_readahead) + printf(" setting fs readahead to %ld\n", readahead); + if (ioctl(fd, BLKRASET, readahead)) + bb_perror_msg(" BLKRASET failed"); + } +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + if (unregister_hwif) { + no_scsi(); + printf(" attempting to unregister hwif#%u\n", hwif); + if (ioctl(fd, HDIO_UNREGISTER_HWIF, hwif)) + bb_perror_msg(" HDIO_UNREGISTER_HWIF failed"); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + if (scan_hwif) { + int args[3]; + no_scsi(); + printf(" attempting to scan hwif (0x%x, 0x%x, %u)\n", hwif_data, hwif_ctrl, hwif_irq); + args[0] = hwif_data; + args[1] = hwif_ctrl; + args[2] = hwif_irq; + if (ioctl(fd, HDIO_SCAN_HWIF, args)) + bb_perror_msg(" HDIO_SCAN_HWIF failed"); + } +#endif + if (set_piomode) { + no_scsi(); + no_xt(); + if (noisy_piomode) { + if (piomode == 255) + printf(" attempting to auto-tune PIO mode\n"); + else if (piomode < 100) + printf(" attempting to set PIO mode to %d\n", piomode); + else if (piomode < 200) + printf(" attempting to set MDMA mode to %d\n", (piomode-100)); + else + printf(" attempting to set UDMA mode to %d\n", (piomode-200)); + } + if (ioctl(fd, HDIO_SET_PIO_MODE, piomode)) + bb_perror_msg(" HDIO_SET_PIO_MODE failed"); + } + if (set_io32bit) { + no_scsi(); + no_xt(); + if (get_io32bit) + printf(" setting 32-bit IO_support flag to %ld\n", io32bit); + if (ioctl(fd, HDIO_SET_32BIT, io32bit)) + bb_perror_msg(" HDIO_SET_32BIT failed"); + } + if (set_mult) { + no_scsi(); + no_xt(); + if (get_mult) + printf(" setting multcount to %ld\n", mult); + if (ioctl(fd, HDIO_SET_MULTCOUNT, mult)) + bb_perror_msg(" HDIO_SET_MULTCOUNT failed"); +#ifndef HDIO_DRIVE_CMD + else force_operation = 1; +#endif + } + if (set_readonly) { + if (get_readonly) { + printf(" setting readonly to %ld", readonly); + on_off(readonly); + } + if (ioctl(fd, BLKROSET, &readonly)) + bb_perror_msg(" BLKROSET failed"); + } + if (set_unmask) { + no_scsi(); + no_xt(); + if (get_unmask) { + printf(" setting unmaskirq to %ld", unmask); + on_off(unmask); + } + if (ioctl(fd, HDIO_SET_UNMASKINTR, unmask)) + bb_perror_msg(" HDIO_SET_UNMASKINTR failed"); + } + if (set_dma) { + no_scsi(); + if (get_dma) { + printf(" setting using_dma to %ld", dma); + on_off(dma); + } + if (ioctl(fd, HDIO_SET_DMA, dma)) + bb_perror_msg(" HDIO_SET_DMA failed"); + } + if (set_dma_q) { + no_scsi(); + if (get_dma_q) { + printf(" setting DMA queue_depth to %ld", dma_q); + on_off(dma_q); + } + if (ioctl(fd, HDIO_SET_QDMA, dma_q)) + bb_perror_msg(" HDIO_SET_QDMA failed"); + } + if (set_nowerr) { + no_scsi(); + no_xt(); + if (get_nowerr) { + printf(" setting nowerr to %ld", nowerr); + on_off(nowerr); + } + if (ioctl(fd, HDIO_SET_NOWERR, nowerr)) + bb_perror_msg(" HDIO_SET_NOWERR failed"); + } + if (set_keep) { + no_scsi(); + no_xt(); + if (get_keep) { + printf(" setting keep_settings to %ld", keep); + on_off(keep); + } + if (ioctl(fd, HDIO_SET_KEEPSETTINGS, keep)) + bb_perror_msg(" HDIO_SET_KEEPSETTINGS failed"); + } +#ifdef HDIO_DRIVE_CMD + if (set_doorlock) { + unsigned char args[4] = {0,0,0,0}; + no_scsi(); + no_xt(); + args[0] = doorlock ? WIN_DOORLOCK : WIN_DOORUNLOCK; + if (get_doorlock) { + printf(" setting drive doorlock to %ld", doorlock); + on_off(doorlock); + } + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(doorlock) failed"); + } + if (set_dkeep) { + /* lock/unlock the drive's "feature" settings */ + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + if (get_dkeep) { + printf(" setting drive keep features to %ld", dkeep); + on_off(dkeep); + } + args[2] = dkeep ? 0x66 : 0xcc; + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(keepsettings) failed"); + } + if (set_defects) { + unsigned char args[4] = {WIN_SETFEATURES,0,0x04,0}; + no_scsi(); + args[2] = defects ? 0x04 : 0x84; + if (get_defects) + printf(" setting drive defect-mgmt to %ld\n", defects); + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(defectmgmt) failed"); + } + if (set_prefetch) { + unsigned char args[4] = {WIN_SETFEATURES,0,0xab,0}; + no_scsi(); + no_xt(); + args[1] = prefetch; + if (get_prefetch) + printf(" setting drive prefetch to %ld\n", prefetch); + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(setprefetch) failed"); + } + if (set_xfermode) { + unsigned char args[4] = {WIN_SETFEATURES,0,3,0}; + no_scsi(); + no_xt(); + args[1] = xfermode_requested; + if (get_xfermode) { + printf(" setting xfermode to %d", xfermode_requested); + interpret_xfermode(xfermode_requested); + } + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(setxfermode) failed"); + } + if (set_lookahead) { + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + args[2] = lookahead ? 0xaa : 0x55; + if (get_lookahead) { + printf(" setting drive read-lookahead to %ld", lookahead); + on_off(lookahead); + } + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(setreadahead) failed"); + } + if (set_apmmode) { + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + if (apmmode<1) apmmode=1; + if (apmmode>255) apmmode=255; + if (get_apmmode) + printf(" setting Advanced Power Management level to"); + if (apmmode==255) { + /* disable Advanced Power Management */ + args[2] = 0x85; /* feature register */ + if (get_apmmode) printf(" disabled\n"); + } else { + /* set Advanced Power Management mode */ + args[2] = 0x05; /* feature register */ + args[1] = apmmode; /* sector count register */ + if (get_apmmode) printf(" 0x%02lX (%ld)\n",apmmode,apmmode); + } + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD failed"); + } + if (set_wcache) { +#ifdef DO_FLUSHCACHE +#ifndef WIN_FLUSHCACHE +#define WIN_FLUSHCACHE 0xe7 +#endif + unsigned char flushcache[4] = {WIN_FLUSHCACHE,0,0,0}; +#endif /* DO_FLUSHCACHE */ + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + args[2] = wcache ? 0x02 : 0x82; + if (get_wcache) { + printf(" setting drive write-caching to %ld", wcache); + on_off(wcache); + } +#ifdef DO_FLUSHCACHE + if (!wcache && ioctl(fd, HDIO_DRIVE_CMD, &flushcache)) + bb_perror_msg (" HDIO_DRIVE_CMD(flushcache) failed"); +#endif /* DO_FLUSHCACHE */ + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(setcache) failed"); +#ifdef DO_FLUSHCACHE + if (!wcache && ioctl(fd, HDIO_DRIVE_CMD, &flushcache)) + bb_perror_msg (" HDIO_DRIVE_CMD(flushcache) failed"); +#endif /* DO_FLUSHCACHE */ + } + if (set_standbynow) { +#ifndef WIN_STANDBYNOW1 +#define WIN_STANDBYNOW1 0xE0 +#endif +#ifndef WIN_STANDBYNOW2 +#define WIN_STANDBYNOW2 0x94 +#endif + unsigned char args1[4] = {WIN_STANDBYNOW1,0,0,0}; + unsigned char args2[4] = {WIN_STANDBYNOW2,0,0,0}; + no_scsi(); + if (get_standbynow) + printf(" issuing standby command\n"); + if (ioctl(fd, HDIO_DRIVE_CMD, &args1) + && ioctl(fd, HDIO_DRIVE_CMD, &args2)) + bb_perror_msg(" HDIO_DRIVE_CMD(standby) failed"); + } + if (set_sleepnow) { +#ifndef WIN_SLEEPNOW1 +#define WIN_SLEEPNOW1 0xE6 +#endif +#ifndef WIN_SLEEPNOW2 +#define WIN_SLEEPNOW2 0x99 +#endif + unsigned char args1[4] = {WIN_SLEEPNOW1,0,0,0}; + unsigned char args2[4] = {WIN_SLEEPNOW2,0,0,0}; + no_scsi(); + if (get_sleepnow) + printf(" issuing sleep command\n"); + if (ioctl(fd, HDIO_DRIVE_CMD, &args1) + && ioctl(fd, HDIO_DRIVE_CMD, &args2)) + bb_perror_msg(" HDIO_DRIVE_CMD(sleep) failed"); + } + if (set_seagate) { + unsigned char args[4] = {0xfb,0,0,0}; + no_scsi(); + no_xt(); + if (get_seagate) + printf(" disabling Seagate auto powersaving mode\n"); + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(seagatepwrsave) failed"); + } + if (set_standby) { + unsigned char args[4] = {WIN_SETIDLE1,standby_requested,0,0}; + no_scsi(); + no_xt(); + if (get_standby) { + printf(" setting standby to %lu", standby_requested); + interpret_standby(standby_requested); + } + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + bb_perror_msg(" HDIO_DRIVE_CMD(setidle1) failed"); + } +#else /* HDIO_DRIVE_CMD */ + if (force_operation) { + char buf[512]; + flush_buffer_cache(fd); + if (-1 == read(fd, buf, sizeof(buf))) + bb_perror_msg(" access failed"); + } +#endif /* HDIO_DRIVE_CMD */ + + if (!flagcount) + verbose = 1; + + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_mult || get_identity) { + no_scsi(); + multcount = -1; + if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount)) { + if ((verbose && !is_xt_hd) || get_mult) + bb_perror_msg(" HDIO_GET_MULTCOUNT failed"); + } else if (verbose | get_mult) { + printf(" multcount = %2ld", multcount); + on_off(multcount); + } + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_io32bit) { + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_GET_32BIT, &parm)) + bb_perror_msg(" HDIO_GET_32BIT failed"); + else { + printf(" IO_support =%3ld (", parm); + switch (parm) { + case 0: printf("default "); + case 2: printf("16-bit)\n"); + break; + case 1: printf("32-bit)\n"); + break; + case 3: printf("32-bit w/sync)\n"); + break; + case 8: printf("Request-Queue-Bypass)\n"); + break; + default:printf("\?\?\?)\n"); + } + } + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_unmask) { + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_GET_UNMASKINTR, &parm)) + bb_perror_msg(" HDIO_GET_UNMASKINTR failed"); + else { + printf(" unmaskirq = %2ld", parm); + on_off(parm); + } + } + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GET_DMA + if ((verbose && !is_scsi_hd) || get_dma) { + no_scsi(); + if (ioctl(fd, HDIO_GET_DMA, &parm)) + bb_perror_msg(" HDIO_GET_DMA failed"); + else { + printf(" using_dma = %2ld", parm); + if (parm == 8) + printf(" (DMA-Assisted-PIO)\n"); + else + on_off(parm); + } + } +#endif + if (get_dma_q) { + no_scsi(); + if(ioctl(fd, HDIO_GET_QDMA, &parm)) { + bb_perror_msg(" HDIO_GET_QDMA failed"); + } else { + printf(" queue_depth = %2ld", parm); + on_off(parm); + } + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_keep) { + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_GET_KEEPSETTINGS, &parm)) + bb_perror_msg(" HDIO_GET_KEEPSETTINGS failed"); + else { + printf(" keepsettings = %2ld", parm); + on_off(parm); + } + } + + if (get_nowerr) { + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_GET_NOWERR, &parm)) + bb_perror_msg(" HDIO_GET_NOWERR failed"); + else { + printf(" nowerr = %2ld", parm); + on_off(parm); + } + } + if (verbose || get_readonly) { + if (ioctl(fd, BLKROGET, &parm)) + bb_perror_msg(" BLKROGET failed"); + else { + printf(" readonly = %2ld", parm); + on_off(parm); + } + } + if ((verbose && !is_scsi_hd) || get_readahead) { + if (ioctl(fd, BLKRAGET, &parm)) + bb_perror_msg(" BLKRAGET failed"); + else { + printf(" readahead = %2ld", parm); + on_off(parm); + } + } + if (verbose || get_geom) { + static const char msg[] = " geometry = %u/%u/%u, sectors = %ld, start = %ld\n"; + static struct hd_geometry g; +#ifdef HDIO_GETGEO_BIG + static struct hd_big_geometry bg; +#endif + + if (ioctl(fd, BLKGETSIZE, &parm)) + bb_perror_msg(" BLKGETSIZE failed"); +#ifdef HDIO_GETGEO_BIG + else if (!ioctl(fd, HDIO_GETGEO_BIG, &bg)) + printf(msg, bg.cylinders, bg.heads, bg.sectors, parm, bg.start); +#endif + else if (ioctl(fd, HDIO_GETGEO, &g)) + bb_perror_msg(" HDIO_GETGEO failed"); + else printf(msg, g.cylinders, g.heads, g.sectors, parm, g.start); + } +#ifdef HDIO_DRIVE_CMD + if (get_powermode) { +#ifndef WIN_CHECKPOWERMODE1 +#define WIN_CHECKPOWERMODE1 0xE5 +#endif +#ifndef WIN_CHECKPOWERMODE2 +#define WIN_CHECKPOWERMODE2 0x98 +#endif + unsigned char args[4] = {WIN_CHECKPOWERMODE1,0,0,0}; + const char *state; + no_scsi(); + if (ioctl(fd, HDIO_DRIVE_CMD, &args) + && (args[0] = WIN_CHECKPOWERMODE2) /* try again with 0x98 */ + && ioctl(fd, HDIO_DRIVE_CMD, &args)) { + if (errno != EIO || args[0] != 0 || args[1] != 0) + state = "unknown"; + else + state = "sleeping"; + } else { + state = (args[2] == 255) ? "active/idle" : "standby"; + } + printf(" drive state is: %s\n", state); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + if (perform_reset) { + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_DRIVE_RESET, NULL)) + bb_perror_msg(" HDIO_DRIVE_RESET failed"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (perform_tristate) { + unsigned char args[4] = {0,tristate,0,0}; + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_TRISTATE_HWIF, &args)) + bb_perror_msg(" HDIO_TRISTATE_HWIF failed"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + if (get_identity) { + static struct hd_driveid id; + + no_scsi(); + no_xt(); + + if (!ioctl(fd, HDIO_GET_IDENTITY, &id)) { + if (multcount != -1) { + id.multsect = multcount; + id.multsect_valid |= 1; + } else + id.multsect_valid &= ~1; + dump_identity(&id); + } else if (errno == -ENOMSG) + printf(" no identification info available\n"); + else + bb_perror_msg(" HDIO_GET_IDENTITY failed"); + } + if (get_IDentity) { + unsigned char args[4+512] = {WIN_IDENTIFY,0,0,1,}; + unsigned i; + no_scsi(); + no_xt(); + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { + args[0] = WIN_PIDENTIFY; + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { + bb_perror_msg(" HDIO_DRIVE_CMD(identify) failed"); + goto identify_abort; + } + } + for(i=0; i<(sizeof args)/2; i+=2) { + __le16_to_cpus((uint16_t *)(&args[i])); + } + identify((void *)&args[4], NULL); +identify_abort: ; + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (set_busstate) { + no_scsi(); + if (get_busstate) { + printf(" setting bus state to %d", busstate); + bus_state_value(busstate); + } + if (ioctl(fd, HDIO_SET_BUSSTATE, busstate)) + bb_perror_msg(" HDIO_SET_BUSSTATE failed"); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (get_busstate) { + no_scsi(); + if (ioctl(fd, HDIO_GET_BUSSTATE, &parm)) + bb_perror_msg(" HDIO_GET_BUSSTATE failed"); + else { + printf(" busstate = %2ld", parm); + bus_state_value(parm); + } + } +#endif + if (reread_partn) { + if (ioctl(fd, BLKRRPART, NULL)) { + bb_perror_msg(" BLKRRPART failed"); + } + } + + if (do_ctimings) + time_cache (fd); + if (do_timings) + time_device (fd); + if (do_flush) + flush_buffer_cache (fd); + close (fd); +} + +#define GET_NUMBER(flag,num) num = 0; \ + if (!*p && argc && isdigit(**argv)) \ + p = *argv++, --argc; \ + while (isdigit(*p)) { \ + flag = 1; \ + num = (num * 10) + (*p++ - '0'); \ + } + +#define GET_STRING(flag, num) tmpstr = name; \ + tmpstr[0] = '\0'; \ + if (!*p && argc && isalnum(**argv)) \ + p = *argv++, --argc; \ + while (isalnum(*p) && (tmpstr - name) < 31) { \ + tmpstr[0] = *p++; \ + tmpstr[1] = '\0'; \ + ++tmpstr; \ + } \ + num = translate_xfermode(name); \ + if (num == -1) \ + flag = 0; \ + else \ + flag = 1; + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static int fromhex (unsigned char c) +{ + if (c >= 'a' && c <= 'f') + return 10 + (c - 'a'); + if (c >= '0' && c <= '9') + return (c - '0'); + bb_error_msg_and_die("bad char: '%c' 0x%02x", c, c); +} + +static int identify_from_stdin (void) +{ + unsigned short sbuf[800]; + unsigned char buf[1600], *b = (unsigned char *)buf; + int i, count = read(0, buf, 1280); + + if (count != 1280) + bb_error_msg_and_die("read(1280 bytes) failed (rc=%d)", count); + for (i = 0; count >= 4; ++i) { + sbuf[i] = (fromhex(b[0]) << 12) | (fromhex(b[1]) << 8) | (fromhex(b[2]) << 4) | fromhex(b[3]); + __le16_to_cpus((uint16_t *)(&sbuf[i])); + b += 5; + count -= 5; + } + identify(sbuf, NULL); + return 0; +} +#endif + +/* our main() routine: */ +int hdparm_main(int argc, char **argv) +{ + char c, *p; + char *tmpstr; + char name[32]; + int neg; + + ++argv; + if (!--argc) + bb_show_usage(); + while (argc--) { +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + if (!strcmp("-Istdin", *argv)) { + exit(identify_from_stdin()); + } +#endif + p = *argv++; + if (*p == '-') { + if (!*++p) + bb_show_usage(); + while ((c = *p++)) { + ++flagcount; + switch (c) { + case 'V': + bb_error_msg_and_die("%s", VERSION); + case 'v': + verbose = 1; + break; +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + case 'I': + get_IDentity = 1; + break; + case 'i': + get_identity = 1; + break; +#endif + case 'g': + get_geom = 1; + break; + case 'f': + do_flush = 1; + break; + case 'q': + quiet = 1; + noisy = 0; + break; + case 'u': + get_unmask = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_unmask = 1; + unmask = *p++ - '0'; + } + break; + case 'd': + get_dma = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p >= '0' && *p <= '9') { + set_dma = 1; + dma = *p++ - '0'; + } + break; + case 'n': + get_nowerr = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_nowerr = 1; + nowerr = *p++ - '0'; + } + break; + case 'p': + noisy_piomode = noisy; + noisy = 1; + GET_STRING(set_piomode,piomode); + break; + case 'r': + get_readonly = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_readonly = 1; + readonly = *p++ - '0'; + } + break; + case 'm': + get_mult = noisy; + noisy = 1; + GET_NUMBER(set_mult,mult); + break; + case 'c': + get_io32bit = noisy; + noisy = 1; + GET_NUMBER(set_io32bit,io32bit); + break; +#ifdef HDIO_DRIVE_CMD + case 'S': + get_standby = noisy; + noisy = 1; + GET_NUMBER(set_standby,standby_requested); + if (!set_standby) + bb_error_msg("-S: missing value"); + break; + + case 'D': + get_defects = noisy; + noisy = 1; + GET_NUMBER(set_defects,defects); + if (!set_defects) + bb_error_msg("-D: missing value"); + break; + case 'P': + get_prefetch = noisy; + noisy = 1; + GET_NUMBER(set_prefetch,prefetch); + if (!set_prefetch) + bb_error_msg("-P: missing value"); + break; + + case 'X': + get_xfermode = noisy; + noisy = 1; + GET_STRING(set_xfermode,xfermode_requested); + if (!set_xfermode) + bb_error_msg("-X: missing value"); + break; + + case 'K': + get_dkeep = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_dkeep = 1; + dkeep = *p++ - '0'; + } else + bb_error_msg("-K: missing value (0/1)"); + break; + + case 'A': + get_lookahead = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_lookahead = 1; + lookahead = *p++ - '0'; + } else + bb_error_msg("-A: missing value (0/1)"); + break; + + case 'L': + get_doorlock = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_doorlock = 1; + doorlock = *p++ - '0'; + } else + bb_error_msg("-L: missing value (0/1)"); + break; + + case 'W': + get_wcache = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_wcache = 1; + wcache = *p++ - '0'; + } else + bb_error_msg("-W: missing value (0/1)"); + break; + + case 'C': + get_powermode = noisy; + noisy = 1; + break; + + case 'y': + get_standbynow = noisy; + noisy = 1; + set_standbynow = 1; + break; + + case 'Y': + get_sleepnow = noisy; + noisy = 1; + set_sleepnow = 1; + break; + + case 'z': + reread_partn = 1; + break; + + case 'Z': + get_seagate = noisy; + noisy = 1; + set_seagate = 1; + break; +#endif /* HDIO_DRIVE_CMD */ + case 'k': + get_keep = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + set_keep = 1; + keep = *p++ - '0'; + } + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + case 'U': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + + if(! p) { + bb_error_msg_and_die("expected hwif_nr"); + } + + sscanf(p++, "%i", &hwif); + + unregister_hwif = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + case 'R': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + + if(! p) { + bb_error_msg_and_die("expected hwif_data"); + } + + sscanf(p++, "%i", &hwif_data); + + if (argc && isdigit(**argv)) + p = *argv++, --argc; + else { + bb_error_msg_and_die("expected hwif_ctrl"); + } + + sscanf(p, "%i", &hwif_ctrl); + + if (argc && isdigit(**argv)) + p = *argv++, --argc; + else { + bb_error_msg_and_die("expected hwif_irq"); + } + + sscanf(p, "%i", &hwif_irq); + + *p = '\0'; + + scan_hwif = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF */ + case 'Q': + get_dma_q = noisy; + noisy = 1; + neg = 0; + GET_NUMBER(set_dma_q, dma_q); + if (neg) + dma_q = -dma_q; + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + case 'w': + perform_reset = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + case 'x': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if (*p == '0' || *p == '1') { + perform_tristate = 1; + tristate = *p++ - '0'; + } else + bb_error_msg("-x: missing value (0/1)"); + break; + +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ + case 'a': + get_readahead = noisy; + noisy = 1; + GET_NUMBER(set_readahead,readahead); + break; + case 'B': + get_apmmode = noisy; + noisy = 1; + GET_NUMBER(set_apmmode,apmmode); + if (!set_apmmode) + printf("-B: missing value (1-255)"); + break; + case 't': + do_timings = 1; + do_flush = 1; + break; + case 'T': + do_ctimings = 1; + do_flush = 1; + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + case 'b': + get_busstate = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + switch (*p) { + case '0': + case '1': + case '2': + set_busstate = 1; + busstate = *p++ - '0'; + break; + default: + break; + } + break; +#endif + case 'h': + default: + bb_show_usage(); + } + } + if (!argc) + bb_show_usage(); + } else { + process_dev (p); + } + } + return 0 ; +} diff --git a/release/src/router/busybox/miscutils/makedevs.c b/release/src/router/busybox/miscutils/makedevs.c new file mode 100644 index 00000000..308d651a --- /dev/null +++ b/release/src/router/busybox/miscutils/makedevs.c @@ -0,0 +1,92 @@ +/* vi: set sw=4 ts=4: */ +/* + * public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com> + * + * makedevs + * Make ranges of device files quickly. + * known bugs: can't deal with alpha ranges + */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/types.h> +#include "busybox.h" + +int makedevs_main(int argc, char **argv) +{ + mode_t mode; + char *basedev, *type, *nodname, buf[255]; + int major, Sminor, S, E; + + if (argc < 7 || *argv[1]=='-') + bb_show_usage(); + + basedev = argv[1]; + type = argv[2]; + major = atoi(argv[3]) << 8; /* correcting param to mknod() */ + Sminor = atoi(argv[4]); + S = atoi(argv[5]); + E = atoi(argv[6]); + nodname = argc == 8 ? basedev : buf; + + mode = 0660; + + switch (type[0]) { + case 'c': + mode |= S_IFCHR; + break; + case 'b': + mode |= S_IFBLK; + break; + case 'f': + mode |= S_IFIFO; + break; + default: + bb_show_usage(); + } + + while (S <= E) { + int sz; + + sz = snprintf(buf, sizeof(buf), "%s%d", basedev, S); + if(sz<0 || sz>=sizeof(buf)) /* libc different */ + bb_error_msg_and_die("%s too large", basedev); + + /* if mode != S_IFCHR and != S_IFBLK third param in mknod() ignored */ + + if (mknod(nodname, mode, major | Sminor)) + bb_error_msg("Failed to create: %s", nodname); + + if (nodname == basedev) /* ex. /dev/hda - to /dev/hda1 ... */ + nodname = buf; + S++; + Sminor++; + } + + return 0; +} + +/* +And this is what this program replaces. The shell is too slow! + +makedev () { +local basedev=$1; local S=$2; local E=$3 +local major=$4; local Sminor=$5; local type=$6 +local sbase=$7 + + if [ ! "$sbase" = "" ]; then + mknod "$basedev" $type $major $Sminor + S=`expr $S + 1` + Sminor=`expr $Sminor + 1` + fi + + while [ $S -le $E ]; do + mknod "$basedev$S" $type $major $Sminor + S=`expr $S + 1` + Sminor=`expr $Sminor + 1` + done +} +*/ diff --git a/release/src/router/busybox/miscutils/mt.c b/release/src/router/busybox/miscutils/mt.c new file mode 100644 index 00000000..e7995455 --- /dev/null +++ b/release/src/router/busybox/miscutils/mt.c @@ -0,0 +1,121 @@ +/* vi: set sw=4 ts=4: */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mtio.h> +#include <sys/fcntl.h> +#include "busybox.h" + +struct mt_opcodes { + char *name; + short value; +}; + +/* missing: eod/seod, stoptions, stwrthreshold, densities */ +static const struct mt_opcodes opcodes[] = { + {"bsf", MTBSF}, + {"bsfm", MTBSFM}, + {"bsr", MTBSR}, + {"bss", MTBSS}, + {"datacompression", MTCOMPRESSION}, + {"eom", MTEOM}, + {"erase", MTERASE}, + {"fsf", MTFSF}, + {"fsfm", MTFSFM}, + {"fsr", MTFSR}, + {"fss", MTFSS}, + {"load", MTLOAD}, + {"lock", MTLOCK}, + {"mkpart", MTMKPART}, + {"nop", MTNOP}, + {"offline", MTOFFL}, + {"rewoffline", MTOFFL}, + {"ras1", MTRAS1}, + {"ras2", MTRAS2}, + {"ras3", MTRAS3}, + {"reset", MTRESET}, + {"retension", MTRETEN}, + {"rewind", MTREW}, + {"seek", MTSEEK}, + {"setblk", MTSETBLK}, + {"setdensity", MTSETDENSITY}, + {"drvbuffer", MTSETDRVBUFFER}, + {"setpart", MTSETPART}, + {"tell", MTTELL}, + {"wset", MTWSM}, + {"unload", MTUNLOAD}, + {"unlock", MTUNLOCK}, + {"eof", MTWEOF}, + {"weof", MTWEOF}, + {0, 0} +}; + +extern int mt_main(int argc, char **argv) +{ + const char *file = "/dev/tape"; + const struct mt_opcodes *code = opcodes; + struct mtop op; + struct mtpos position; + int fd, mode; + + if (argc < 2) { + bb_show_usage(); + } + + if (strcmp(argv[1], "-f") == 0) { + if (argc < 4) { + bb_show_usage(); + } + file = argv[2]; + argv += 2; + argc -= 2; + } + + while (code->name != 0) { + if (strcmp(code->name, argv[1]) == 0) + break; + code++; + } + + if (code->name == 0) { + bb_error_msg("unrecognized opcode %s.", argv[1]); + return EXIT_FAILURE; + } + + op.mt_op = code->value; + if (argc >= 3) + op.mt_count = atoi(argv[2]); + else + op.mt_count = 1; /* One, not zero, right? */ + + switch (code->value) { + case MTWEOF: + case MTERASE: + case MTWSM: + case MTSETDRVBUFFER: + mode = O_WRONLY; + break; + + default: + mode = O_RDONLY; + break; + } + + if ((fd = open(file, mode, 0)) < 0) + bb_perror_msg_and_die("%s", file); + + switch (code->value) { + case MTTELL: + if (ioctl(fd, MTIOCPOS, &position) < 0) + bb_perror_msg_and_die("%s", file); + printf ("At block %d.\n", (int) position.mt_blkno); + break; + + default: + if (ioctl(fd, MTIOCTOP, &op) != 0) + bb_perror_msg_and_die("%s", file); + break; + } + + return EXIT_SUCCESS; +} diff --git a/release/src/router/busybox/miscutils/strings.c b/release/src/router/busybox/miscutils/strings.c new file mode 100644 index 00000000..c914338d --- /dev/null +++ b/release/src/router/busybox/miscutils/strings.c @@ -0,0 +1,160 @@ +/* vi: set sw=4 ts=4: */ +/* + * strings implementation for busybox + * + * Copyright (c) 1980, 1987 + * The Regents of the University of California. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Original copyright notice is retained at the end of this file. + * + * Modified for BusyBox by Erik Andersen <andersen@codepoet.org> + * Badly hacked by Tito Ragusa <farmatito@tiscali.it> + */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <getopt.h> +#include <unistd.h> +#include <ctype.h> +#include "busybox.h" + +#define ISSTR(ch) (isprint(ch) || ch == '\t') + +int strings_main(int argc, char **argv) +{ + int n=4, c, i, opt=0, a=0, status=EXIT_SUCCESS; + long t=0, count; + FILE *file; + char *string=NULL; + + while ((i = getopt(argc, argv, "afon:")) > 0) + switch(i) + { + case 'a': + break; + case 'f': + opt+=1; + break; + case 'o': + opt+=2; + break; + case 'n': + n = bb_xgetlarg(optarg, 10, 1, INT_MAX); + break; + default: + bb_show_usage(); + } + + argc -= optind; + argv += optind; + + i=0; + + string=xmalloc(n+1); + string[n]='\0'; + n-=1; + + if(!argc ) + { + file = stdin; + goto pipe; + } + + for(a=0;a<argc;a++) + { + if((file=fopen(argv[a],"r"))) + { +pipe: + + count=0; + do + { + c=fgetc(file); + if(ISSTR(c)) + { + if(i==0) + t=count; + if(i<=n) + string[i]=c; + if(i==n) + { + if(opt == 1 || opt == 3 ) + printf("%s: ", (!argv[a])? "{stdin}" : argv[a]); + if(opt >= 2 ) + printf("%7lo ", t); + printf("%s", string); + } + if(i>n) + putchar(c); + i++; + } + else + { + if(i>n) + puts(""); + i=0; + } + count++; + } + while(c!=EOF); + + if(file!=stdin) + fclose(file); + } + else + { + bb_perror_msg("%s",argv[a]); + status=EXIT_FAILURE; + } + } + free(string); + exit(status); +} + +/* + * Copyright (c) 1980, 1987 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change + * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change> + * + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ diff --git a/release/src/router/busybox/miscutils/time.c b/release/src/router/busybox/miscutils/time.c new file mode 100644 index 00000000..c30ef431 --- /dev/null +++ b/release/src/router/busybox/miscutils/time.c @@ -0,0 +1,502 @@ +/* `time' utility to display resource usage of processes. + Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. */ + +/* Originally written by David Keppel <pardo@cs.washington.edu>. + Heavily modified by David MacKenzie <djm@gnu.ai.mit.edu>. + Heavily modified for busybox by Erik Andersen <andersen@codepoet.org> + */ + +#include <stdlib.h> +#include <stdio.h> +#include <signal.h> +#include <errno.h> +#include <getopt.h> +#include <string.h> +#include <limits.h> +#include <unistd.h> +#include <sys/time.h> +#include <sys/types.h> /* For pid_t. */ +#include <sys/wait.h> +#include <sys/param.h> /* For getpagesize, maybe. */ + +#define TV_MSEC tv_usec / 1000 +#include <sys/resource.h> +#include "busybox.h" + +/* Information on the resources used by a child process. */ +typedef struct +{ + int waitstatus; + struct rusage ru; + struct timeval start, elapsed; /* Wallclock time of process. */ +} resource_t; + +/* msec = milliseconds = 1/1,000 (1*10e-3) second. + usec = microseconds = 1/1,000,000 (1*10e-6) second. */ + +#ifndef TICKS_PER_SEC +#define TICKS_PER_SEC 100 +#endif + +/* The number of milliseconds in one `tick' used by the `rusage' structure. */ +#define MSEC_PER_TICK (1000 / TICKS_PER_SEC) + +/* Return the number of clock ticks that occur in M milliseconds. */ +#define MSEC_TO_TICKS(m) ((m) / MSEC_PER_TICK) + +#define UL unsigned long + +static const char *const default_format = "real\t%E\nuser\t%u\nsys\t%T"; + +/* The output format for the -p option .*/ +static const char *const posix_format = "real %e\nuser %U\nsys %S"; + + +/* Format string for printing all statistics verbosely. + Keep this output to 24 lines so users on terminals can see it all.*/ +static const char *const long_format = + "\tCommand being timed: \"%C\"\n" + "\tUser time (seconds): %U\n" + "\tSystem time (seconds): %S\n" + "\tPercent of CPU this job got: %P\n" + "\tElapsed (wall clock) time (h:mm:ss or m:ss): %E\n" + "\tAverage shared text size (kbytes): %X\n" + "\tAverage unshared data size (kbytes): %D\n" + "\tAverage stack size (kbytes): %p\n" + "\tAverage total size (kbytes): %K\n" + "\tMaximum resident set size (kbytes): %M\n" + "\tAverage resident set size (kbytes): %t\n" + "\tMajor (requiring I/O) page faults: %F\n" + "\tMinor (reclaiming a frame) page faults: %R\n" + "\tVoluntary context switches: %w\n" + "\tInvoluntary context switches: %c\n" + "\tSwaps: %W\n" + "\tFile system inputs: %I\n" + "\tFile system outputs: %O\n" + "\tSocket messages sent: %s\n" + "\tSocket messages received: %r\n" + "\tSignals delivered: %k\n" + "\tPage size (bytes): %Z\n" + "\tExit status: %x"; + + + /* Wait for and fill in data on child process PID. + Return 0 on error, 1 if ok. */ + +/* pid_t is short on BSDI, so don't try to promote it. */ +static int resuse_end (pid_t pid, resource_t *resp) +{ + int status; + + pid_t caught; + + /* Ignore signals, but don't ignore the children. When wait3 + returns the child process, set the time the command finished. */ + while ((caught = wait3 (&status, 0, &resp->ru)) != pid) + { + if (caught == -1) + return 0; + } + + gettimeofday (&resp->elapsed, (struct timezone *) 0); + resp->elapsed.tv_sec -= resp->start.tv_sec; + if (resp->elapsed.tv_usec < resp->start.tv_usec) + { + /* Manually carry a one from the seconds field. */ + resp->elapsed.tv_usec += 1000000; + --resp->elapsed.tv_sec; + } + resp->elapsed.tv_usec -= resp->start.tv_usec; + + resp->waitstatus = status; + + return 1; +} + +/* Print ARGV to FP, with each entry in ARGV separated by FILLER. */ +static void fprintargv (FILE *fp, char *const *argv, const char *filler) +{ + char *const *av; + + av = argv; + fputs (*av, fp); + while (*++av) + { + fputs (filler, fp); + fputs (*av, fp); + } + if (ferror (fp)) + bb_error_msg_and_die("write error"); +} + +/* Return the number of kilobytes corresponding to a number of pages PAGES. + (Actually, we use it to convert pages*ticks into kilobytes*ticks.) + + Try to do arithmetic so that the risk of overflow errors is minimized. + This is funky since the pagesize could be less than 1K. + Note: Some machines express getrusage statistics in terms of K, + others in terms of pages. */ + +static unsigned long ptok (unsigned long pages) +{ + static unsigned long ps = 0; + unsigned long tmp; + static long size = LONG_MAX; + + /* Initialization. */ + if (ps == 0) + ps = (long) getpagesize (); + + /* Conversion. */ + if (pages > (LONG_MAX / ps)) + { /* Could overflow. */ + tmp = pages / 1024; /* Smaller first, */ + size = tmp * ps; /* then larger. */ + } + else + { /* Could underflow. */ + tmp = pages * ps; /* Larger first, */ + size = tmp / 1024; /* then smaller. */ + } + return size; +} + +/* summarize: Report on the system use of a command. + + Copy the FMT argument to FP except that `%' sequences + have special meaning, and `\n' and `\t' are translated into + newline and tab, respectively, and `\\' is translated into `\'. + + The character following a `%' can be: + (* means the tcsh time builtin also recognizes it) + % == a literal `%' + C == command name and arguments +* D == average unshared data size in K (ru_idrss+ru_isrss) +* E == elapsed real (wall clock) time in [hour:]min:sec +* F == major page faults (required physical I/O) (ru_majflt) +* I == file system inputs (ru_inblock) +* K == average total mem usage (ru_idrss+ru_isrss+ru_ixrss) +* M == maximum resident set size in K (ru_maxrss) +* O == file system outputs (ru_oublock) +* P == percent of CPU this job got (total cpu time / elapsed time) +* R == minor page faults (reclaims; no physical I/O involved) (ru_minflt) +* S == system (kernel) time (seconds) (ru_stime) +* T == system time in [hour:]min:sec +* U == user time (seconds) (ru_utime) +* u == user time in [hour:]min:sec +* W == times swapped out (ru_nswap) +* X == average amount of shared text in K (ru_ixrss) + Z == page size +* c == involuntary context switches (ru_nivcsw) + e == elapsed real time in seconds +* k == signals delivered (ru_nsignals) + p == average unshared stack size in K (ru_isrss) +* r == socket messages received (ru_msgrcv) +* s == socket messages sent (ru_msgsnd) + t == average resident set size in K (ru_idrss) +* w == voluntary context switches (ru_nvcsw) + x == exit status of command + + Various memory usages are found by converting from page-seconds + to kbytes by multiplying by the page size, dividing by 1024, + and dividing by elapsed real time. + + FP is the stream to print to. + FMT is the format string, interpreted as described above. + COMMAND is the command and args that are being summarized. + RESP is resource information on the command. */ + +static void summarize (FILE *fp, const char *fmt, char **command, resource_t *resp) +{ + unsigned long r; /* Elapsed real milliseconds. */ + unsigned long v; /* Elapsed virtual (CPU) milliseconds. */ + + if (WIFSTOPPED (resp->waitstatus)) + fprintf (fp, "Command stopped by signal %d\n", WSTOPSIG (resp->waitstatus)); + else if (WIFSIGNALED (resp->waitstatus)) + fprintf (fp, "Command terminated by signal %d\n", WTERMSIG (resp->waitstatus)); + else if (WIFEXITED (resp->waitstatus) && WEXITSTATUS (resp->waitstatus)) + fprintf (fp, "Command exited with non-zero status %d\n", WEXITSTATUS (resp->waitstatus)); + + /* Convert all times to milliseconds. Occasionally, one of these values + comes out as zero. Dividing by zero causes problems, so we first + check the time value. If it is zero, then we take `evasive action' + instead of calculating a value. */ + + r = resp->elapsed.tv_sec * 1000 + resp->elapsed.tv_usec / 1000; + + v = resp->ru.ru_utime.tv_sec * 1000 + resp->ru.ru_utime.TV_MSEC + + resp->ru.ru_stime.tv_sec * 1000 + resp->ru.ru_stime.TV_MSEC; + + while (*fmt) + { + switch (*fmt) + { + case '%': + switch (*++fmt) + { + case '%': /* Literal '%'. */ + putc ('%', fp); + break; + case 'C': /* The command that got timed. */ + fprintargv (fp, command, " "); + break; + case 'D': /* Average unshared data size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v)); + break; + case 'E': /* Elapsed real (wall clock) time. */ + if (resp->elapsed.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->elapsed.tv_sec / 3600, + (resp->elapsed.tv_sec % 3600) / 60, + resp->elapsed.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->elapsed.tv_sec / 60, + resp->elapsed.tv_sec % 60, + resp->elapsed.tv_usec / 10000); + break; + case 'F': /* Major page faults. */ + fprintf (fp, "%ld", resp->ru.ru_majflt); + break; + case 'I': /* Inputs. */ + fprintf (fp, "%ld", resp->ru.ru_inblock); + break; + case 'K': /* Average mem usage == data+stack+text. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v)); + break; + case 'M': /* Maximum resident set size. */ + fprintf (fp, "%lu", ptok ((UL) resp->ru.ru_maxrss)); + break; + case 'O': /* Outputs. */ + fprintf (fp, "%ld", resp->ru.ru_oublock); + break; + case 'P': /* Percent of CPU this job got. */ + /* % cpu is (total cpu time)/(elapsed time). */ + if (r > 0) + fprintf (fp, "%lu%%", (v * 100 / r)); + else + fprintf (fp, "?%%"); + break; + case 'R': /* Minor page faults (reclaims). */ + fprintf (fp, "%ld", resp->ru.ru_minflt); + break; + case 'S': /* System time. */ + fprintf (fp, "%ld.%02ld", + resp->ru.ru_stime.tv_sec, + resp->ru.ru_stime.TV_MSEC / 10); + break; + case 'T': /* System time. */ + if (resp->ru.ru_stime.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->ru.ru_stime.tv_sec / 3600, + (resp->ru.ru_stime.tv_sec % 3600) / 60, + resp->ru.ru_stime.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->ru.ru_stime.tv_sec / 60, + resp->ru.ru_stime.tv_sec % 60, + resp->ru.ru_stime.tv_usec / 10000); + break; + case 'U': /* User time. */ + fprintf (fp, "%ld.%02ld", + resp->ru.ru_utime.tv_sec, + resp->ru.ru_utime.TV_MSEC / 10); + break; + case 'u': /* User time. */ + if (resp->ru.ru_utime.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->ru.ru_utime.tv_sec / 3600, + (resp->ru.ru_utime.tv_sec % 3600) / 60, + resp->ru.ru_utime.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->ru.ru_utime.tv_sec / 60, + resp->ru.ru_utime.tv_sec % 60, + resp->ru.ru_utime.tv_usec / 10000); + break; + case 'W': /* Times swapped out. */ + fprintf (fp, "%ld", resp->ru.ru_nswap); + break; + case 'X': /* Average shared text size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v)); + break; + case 'Z': /* Page size. */ + fprintf (fp, "%d", getpagesize ()); + break; + case 'c': /* Involuntary context switches. */ + fprintf (fp, "%ld", resp->ru.ru_nivcsw); + break; + case 'e': /* Elapsed real time in seconds. */ + fprintf (fp, "%ld.%02ld", + resp->elapsed.tv_sec, + resp->elapsed.tv_usec / 10000); + break; + case 'k': /* Signals delivered. */ + fprintf (fp, "%ld", resp->ru.ru_nsignals); + break; + case 'p': /* Average stack segment. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v)); + break; + case 'r': /* Incoming socket messages received. */ + fprintf (fp, "%ld", resp->ru.ru_msgrcv); + break; + case 's': /* Outgoing socket messages sent. */ + fprintf (fp, "%ld", resp->ru.ru_msgsnd); + break; + case 't': /* Average resident set size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v)); + break; + case 'w': /* Voluntary context switches. */ + fprintf (fp, "%ld", resp->ru.ru_nvcsw); + break; + case 'x': /* Exit status. */ + fprintf (fp, "%d", WEXITSTATUS (resp->waitstatus)); + break; + case '\0': + putc ('?', fp); + return; + default: + putc ('?', fp); + putc (*fmt, fp); + } + ++fmt; + break; + + case '\\': /* Format escape. */ + switch (*++fmt) + { + case 't': + putc ('\t', fp); + break; + case 'n': + putc ('\n', fp); + break; + case '\\': + putc ('\\', fp); + break; + default: + putc ('?', fp); + putc ('\\', fp); + putc (*fmt, fp); + } + ++fmt; + break; + + default: + putc (*fmt++, fp); + } + + if (ferror (fp)) + bb_error_msg_and_die("write error"); + } + putc ('\n', fp); + + if (ferror (fp)) + bb_error_msg_and_die("write error"); +} + +/* Run command CMD and return statistics on it. + Put the statistics in *RESP. */ +static void run_command (char *const *cmd, resource_t *resp) +{ + pid_t pid; /* Pid of child. */ + __sighandler_t interrupt_signal, quit_signal; + + gettimeofday (&resp->start, (struct timezone *) 0); + pid = fork (); /* Run CMD as child process. */ + if (pid < 0) + bb_error_msg_and_die("cannot fork"); + else if (pid == 0) + { /* If child. */ + /* Don't cast execvp arguments; that causes errors on some systems, + versus merely warnings if the cast is left off. */ + execvp (cmd[0], cmd); + bb_error_msg("cannot run %s", cmd[0]); + _exit (errno == ENOENT ? 127 : 126); + } + + /* Have signals kill the child but not self (if possible). */ + interrupt_signal = signal (SIGINT, SIG_IGN); + quit_signal = signal (SIGQUIT, SIG_IGN); + + if (resuse_end (pid, resp) == 0) + bb_error_msg("error waiting for child process"); + + /* Re-enable signals. */ + signal (SIGINT, interrupt_signal); + signal (SIGQUIT, quit_signal); +} + +extern int time_main (int argc, char **argv) +{ + int gotone; + resource_t res; + const char *output_format = default_format; + + argc--; + argv++; + /* Parse any options -- don't use getopt() here so we don't + * consume the args of our client application... */ + while (argc > 0 && **argv == '-') { + gotone = 0; + while (gotone==0 && *++(*argv)) { + switch (**argv) { + case 'v': + output_format = long_format; + break; + case 'p': + output_format = posix_format; + break; + default: + bb_show_usage(); + } + argc--; + argv++; + gotone = 1; + } + } + + if (argv == NULL || *argv == NULL) + bb_show_usage(); + + run_command (argv, &res); + summarize (stdout, output_format, argv, &res); + fflush (stdout); + + if (WIFSTOPPED (res.waitstatus)) + exit (WSTOPSIG (res.waitstatus)); + else if (WIFSIGNALED (res.waitstatus)) + exit (WTERMSIG (res.waitstatus)); + else if (WIFEXITED (res.waitstatus)) + exit (WEXITSTATUS (res.waitstatus)); + return 0; +} diff --git a/release/src/router/busybox/miscutils/watchdog.c b/release/src/router/busybox/miscutils/watchdog.c new file mode 100644 index 00000000..b1167dc9 --- /dev/null +++ b/release/src/router/busybox/miscutils/watchdog.c @@ -0,0 +1,81 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini watchdog implementation for busybox + * + * Copyright (C) 2003 Paul Mundt <lethal@linux-sh.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include <stdio.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdlib.h> +#include <signal.h> +#include "busybox.h" + +/* Userspace timer duration, in seconds */ +static unsigned int timer_duration = 30; + +/* Watchdog file descriptor */ +static int fd; + +static void watchdog_shutdown(int unused) +{ + write(fd, "V", 1); /* Magic */ + close(fd); + exit(0); +} + +extern int watchdog_main(int argc, char **argv) +{ + int opt; + + while ((opt = getopt(argc, argv, "t:")) > 0) { + switch (opt) { + case 't': + timer_duration = bb_xgetlarg(optarg, 10, 0, INT_MAX); + break; + default: + bb_show_usage(); + } + } + + /* We're only interested in the watchdog device .. */ + if (optind < argc - 1 || argc == 1) + bb_show_usage(); + + if (daemon(0, 1) < 0) + bb_perror_msg_and_die("Failed forking watchdog daemon"); + + signal(SIGHUP, watchdog_shutdown); + signal(SIGINT, watchdog_shutdown); + + fd = bb_xopen(argv[argc - 1], O_WRONLY); + + while (1) { + /* + * Make sure we clear the counter before sleeping, as the counter value + * is undefined at this point -- PFM + */ + write(fd, "\0", 1); + sleep(timer_duration); + } + + watchdog_shutdown(0); + + return EXIT_SUCCESS; +} |