Consolidate #include <sys/time.h> so libbb.h does it.
[oweals/busybox.git] / miscutils / hdparm.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * hdparm implementation for busybox
4  *
5  * Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
6  * Hacked by Tito <farmatito@tiscali.it> for size optimization.
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  *
10  * This program is based on the source code of hdparm: see below...
11  * hdparm.c - Command line interface to get/set hard disk parameters
12  *          - by Mark Lord (C) 1994-2002 -- freely distributable
13  */
14
15 #include <string.h>
16 #include <stdlib.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <ctype.h>
20 #include <endian.h>
21 #include <sys/ioctl.h>
22 #include <sys/sysmacros.h>
23 #include <sys/times.h>
24 #include <sys/mount.h>
25 #include <sys/mman.h>
26 #include <getopt.h>
27 #include <linux/types.h>
28 #include <linux/hdreg.h>
29 #include <asm/byteorder.h>
30
31 #if BB_BIG_ENDIAN && !defined(__USE_XOPEN)
32 # define __USE_XOPEN
33 #endif
34 #include <unistd.h>
35
36 #include "busybox.h"
37
38 /* device types */
39 /* ------------ */
40 #define NO_DEV                  0xffff
41 #define ATA_DEV                 0x0000
42 #define ATAPI_DEV               0x0001
43
44 /* word definitions */
45 /* ---------------- */
46 #define GEN_CONFIG              0   /* general configuration */
47 #define LCYLS                   1   /* number of logical cylinders */
48 #define CONFIG                  2   /* specific configuration */
49 #define LHEADS                  3   /* number of logical heads */
50 #define TRACK_BYTES             4   /* number of bytes/track (ATA-1) */
51 #define SECT_BYTES              5   /* number of bytes/sector (ATA-1) */
52 #define LSECTS                  6   /* number of logical sectors/track */
53 #define START_SERIAL            10  /* ASCII serial number */
54 #define LENGTH_SERIAL           10  /* 10 words (20 bytes or characters) */
55 #define BUF_TYPE                20  /* buffer type (ATA-1) */
56 #define BUFFER__SIZE            21  /* buffer size (ATA-1) */
57 #define RW_LONG                 22  /* extra bytes in R/W LONG cmd ( < ATA-4)*/
58 #define START_FW_REV            23  /* ASCII firmware revision */
59 #define LENGTH_FW_REV            4  /*  4 words (8 bytes or characters) */
60 #define START_MODEL             27  /* ASCII model number */
61 #define LENGTH_MODEL            20  /* 20 words (40 bytes or characters) */
62 #define SECTOR_XFER_MAX         47  /* r/w multiple: max sectors xfered */
63 #define DWORD_IO                48  /* can do double-word IO (ATA-1 only) */
64 #define CAPAB_0                 49  /* capabilities */
65 #define CAPAB_1                 50
66 #define PIO_MODE                51  /* max PIO mode supported (obsolete)*/
67 #define DMA_MODE                52  /* max Singleword DMA mode supported (obs)*/
68 #define WHATS_VALID             53  /* what fields are valid */
69 #define LCYLS_CUR               54  /* current logical cylinders */
70 #define LHEADS_CUR              55  /* current logical heads */
71 #define LSECTS_CUR              56  /* current logical sectors/track */
72 #define CAPACITY_LSB            57  /* current capacity in sectors */
73 #define CAPACITY_MSB            58
74 #define SECTOR_XFER_CUR         59  /* r/w multiple: current sectors xfered */
75 #define LBA_SECTS_LSB           60  /* LBA: total number of user */
76 #define LBA_SECTS_MSB           61  /*      addressable sectors */
77 #define SINGLE_DMA              62  /* singleword DMA modes */
78 #define MULTI_DMA               63  /* multiword DMA modes */
79 #define ADV_PIO_MODES           64  /* advanced PIO modes supported */
80                                     /* multiword DMA xfer cycle time: */
81 #define DMA_TIME_MIN            65  /*   - minimum */
82 #define DMA_TIME_NORM           66  /*   - manufacturer's recommended   */
83                                     /* minimum PIO xfer cycle time: */
84 #define PIO_NO_FLOW             67  /*   - without flow control */
85 #define PIO_FLOW                68  /*   - with IORDY flow control */
86 #define PKT_REL                 71  /* typical #ns from PKT cmd to bus rel */
87 #define SVC_NBSY                72  /* typical #ns from SERVICE cmd to !BSY */
88 #define CDR_MAJOR               73  /* CD ROM: major version number */
89 #define CDR_MINOR               74  /* CD ROM: minor version number */
90 #define QUEUE_DEPTH             75  /* queue depth */
91 #define MAJOR                   80  /* major version number */
92 #define MINOR                   81  /* minor version number */
93 #define CMDS_SUPP_0             82  /* command/feature set(s) supported */
94 #define CMDS_SUPP_1             83
95 #define CMDS_SUPP_2             84
96 #define CMDS_EN_0               85  /* command/feature set(s) enabled */
97 #define CMDS_EN_1               86
98 #define CMDS_EN_2               87
99 #define ULTRA_DMA               88  /* ultra DMA modes */
100                                     /* time to complete security erase */
101 #define ERASE_TIME              89  /*   - ordinary */
102 #define ENH_ERASE_TIME          90  /*   - enhanced */
103 #define ADV_PWR                 91  /* current advanced power management level
104                                        in low byte, 0x40 in high byte. */
105 #define PSWD_CODE               92  /* master password revision code    */
106 #define HWRST_RSLT              93  /* hardware reset result */
107 #define ACOUSTIC                94  /* acoustic mgmt values ( >= ATA-6) */
108 #define LBA_LSB                 100 /* LBA: maximum.  Currently only 48 */
109 #define LBA_MID                 101 /*      bits are used, but addr 103 */
110 #define LBA_48_MSB              102 /*      has been reserved for LBA in */
111 #define LBA_64_MSB              103 /*      the future. */
112 #define RM_STAT                 127 /* removable media status notification feature set support */
113 #define SECU_STATUS             128 /* security status */
114 #define CFA_PWR_MODE            160 /* CFA power mode 1 */
115 #define START_MEDIA             176 /* media serial number */
116 #define LENGTH_MEDIA            20  /* 20 words (40 bytes or characters)*/
117 #define START_MANUF             196 /* media manufacturer I.D. */
118 #define LENGTH_MANUF            10  /* 10 words (20 bytes or characters) */
119 #define INTEGRITY               255 /* integrity word */
120
121 /* bit definitions within the words */
122 /* -------------------------------- */
123
124 /* many words are considered valid if bit 15 is 0 and bit 14 is 1 */
125 #define VALID                   0xc000
126 #define VALID_VAL               0x4000
127 /* many words are considered invalid if they are either all-0 or all-1 */
128 #define NOVAL_0                 0x0000
129 #define NOVAL_1                 0xffff
130
131 /* word 0: gen_config */
132 #define NOT_ATA                 0x8000
133 #define NOT_ATAPI               0x4000  /* (check only if bit 15 == 1) */
134 #define MEDIA_REMOVABLE         0x0080
135 #define DRIVE_NOT_REMOVABLE     0x0040  /* bit obsoleted in ATA 6 */
136 #define INCOMPLETE              0x0004
137 #define CFA_SUPPORT_VAL         0x848a  /* 848a=CFA feature set support */
138 #define DRQ_RESPONSE_TIME       0x0060
139 #define DRQ_3MS_VAL             0x0000
140 #define DRQ_INTR_VAL            0x0020
141 #define DRQ_50US_VAL            0x0040
142 #define PKT_SIZE_SUPPORTED      0x0003
143 #define PKT_SIZE_12_VAL         0x0000
144 #define PKT_SIZE_16_VAL         0x0001
145 #define EQPT_TYPE               0x1f00
146 #define SHIFT_EQPT              8
147
148 #define CDROM 0x0005
149
150 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
151 static const char * const pkt_str[] = {
152         "Direct-access device",                 /* word 0, bits 12-8 = 00 */
153         "Sequential-access device",             /* word 0, bits 12-8 = 01 */
154         "Printer",                              /* word 0, bits 12-8 = 02 */
155         "Processor",                            /* word 0, bits 12-8 = 03 */
156         "Write-once device",                    /* word 0, bits 12-8 = 04 */
157         "CD-ROM",                               /* word 0, bits 12-8 = 05 */
158         "Scanner",                              /* word 0, bits 12-8 = 06 */
159         "Optical memory",                       /* word 0, bits 12-8 = 07 */
160         "Medium changer",                       /* word 0, bits 12-8 = 08 */
161         "Communications device",                /* word 0, bits 12-8 = 09 */
162         "ACS-IT8 device",                       /* word 0, bits 12-8 = 0a */
163         "ACS-IT8 device",                       /* word 0, bits 12-8 = 0b */
164         "Array controller",                     /* word 0, bits 12-8 = 0c */
165         "Enclosure services",                   /* word 0, bits 12-8 = 0d */
166         "Reduced block command device",         /* word 0, bits 12-8 = 0e */
167         "Optical card reader/writer",           /* word 0, bits 12-8 = 0f */
168         "",                                     /* word 0, bits 12-8 = 10 */
169         "",                                     /* word 0, bits 12-8 = 11 */
170         "",                                     /* word 0, bits 12-8 = 12 */
171         "",                                     /* word 0, bits 12-8 = 13 */
172         "",                                     /* word 0, bits 12-8 = 14 */
173         "",                                     /* word 0, bits 12-8 = 15 */
174         "",                                     /* word 0, bits 12-8 = 16 */
175         "",                                     /* word 0, bits 12-8 = 17 */
176         "",                                     /* word 0, bits 12-8 = 18 */
177         "",                                     /* word 0, bits 12-8 = 19 */
178         "",                                     /* word 0, bits 12-8 = 1a */
179         "",                                     /* word 0, bits 12-8 = 1b */
180         "",                                     /* word 0, bits 12-8 = 1c */
181         "",                                     /* word 0, bits 12-8 = 1d */
182         "",                                     /* word 0, bits 12-8 = 1e */
183         "Unknown",                      /* word 0, bits 12-8 = 1f */
184 };
185
186 static const char * const ata1_cfg_str[] = {                    /* word 0 in ATA-1 mode */
187         "Reserved",                             /* bit 0 */
188         "hard sectored",                        /* bit 1 */
189         "soft sectored",                        /* bit 2 */
190         "not MFM encoded ",                     /* bit 3 */
191         "head switch time > 15us",              /* bit 4 */
192         "spindle motor control option",         /* bit 5 */
193         "fixed drive",                          /* bit 6 */
194         "removable drive",                      /* bit 7 */
195         "disk xfer rate <= 5Mbs",               /* bit 8 */
196         "disk xfer rate > 5Mbs, <= 10Mbs",      /* bit 9 */
197         "disk xfer rate > 5Mbs",                /* bit 10 */
198         "rotational speed tol.",                /* bit 11 */
199         "data strobe offset option",            /* bit 12 */
200         "track offset option",                  /* bit 13 */
201         "format speed tolerance gap reqd",      /* bit 14 */
202         "ATAPI"                                 /* bit 14 */
203 };
204 #endif
205
206 /* word 1: number of logical cylinders */
207 #define LCYLS_MAX               0x3fff /* maximum allowable value */
208
209 /* word 2: specific configuration
210  * (a) require SET FEATURES to spin-up
211  * (b) require spin-up to fully reply to IDENTIFY DEVICE
212  */
213 #define STBY_NID_VAL            0x37c8  /*     (a) and     (b) */
214 #define STBY_ID_VAL             0x738c  /*     (a) and not (b) */
215 #define PWRD_NID_VAL            0x8c73  /* not (a) and     (b) */
216 #define PWRD_ID_VAL             0xc837  /* not (a) and not (b) */
217
218 /* words 47 & 59: sector_xfer_max & sector_xfer_cur */
219 #define SECTOR_XFER             0x00ff  /* sectors xfered on r/w multiple cmds*/
220 #define MULTIPLE_SETTING_VALID  0x0100  /* 1=multiple sector setting is valid */
221
222 /* word 49: capabilities 0 */
223 #define STD_STBY                0x2000  /* 1=standard values supported (ATA);
224                                            0=vendor specific values */
225 #define IORDY_SUP               0x0800  /* 1=support; 0=may be supported */
226 #define IORDY_OFF               0x0400  /* 1=may be disabled */
227 #define LBA_SUP                 0x0200  /* 1=Logical Block Address support */
228 #define DMA_SUP                 0x0100  /* 1=Direct Memory Access support */
229 #define DMA_IL_SUP              0x8000  /* 1=interleaved DMA support (ATAPI) */
230 #define CMD_Q_SUP               0x4000  /* 1=command queuing support (ATAPI) */
231 #define OVLP_SUP                0x2000  /* 1=overlap operation support (ATAPI) */
232 #define SWRST_REQ               0x1000  /* 1=ATA SW reset required (ATAPI, obsolete */
233
234 /* word 50: capabilities 1 */
235 #define MIN_STANDBY_TIMER       0x0001  /* 1=device specific standby timer value minimum */
236
237 /* words 51 & 52: PIO & DMA cycle times */
238 #define MODE                    0xff00  /* the mode is in the MSBs */
239
240 /* word 53: whats_valid */
241 #define OK_W88                  0x0004  /* the ultra_dma info is valid */
242 #define OK_W64_70               0x0002  /* see above for word descriptions */
243 #define OK_W54_58               0x0001  /* current cyl, head, sector, cap. info valid */
244
245 /*word 63,88: dma_mode, ultra_dma_mode*/
246 #define MODE_MAX                7       /* bit definitions force udma <=7 (when
247                                          * udma >=8 comes out it'll have to be
248                                          * defined in a new dma_mode word!) */
249
250 /* word 64: PIO transfer modes */
251 #define PIO_SUP                 0x00ff  /* only bits 0 & 1 are used so far,  */
252 #define PIO_MODE_MAX            8       /* but all 8 bits are defined        */
253
254 /* word 75: queue_depth */
255 #define DEPTH_BITS              0x001f  /* bits used for queue depth */
256
257 /* words 80-81: version numbers */
258 /* NOVAL_0 or  NOVAL_1 means device does not report version */
259
260 /* word 81: minor version number */
261 #define MINOR_MAX               0x22
262 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
263 static const char *minor_str[MINOR_MAX+2] = {                   /* word 81 value: */
264         "Unspecified",                                  /* 0x0000       */
265         "ATA-1 X3T9.2 781D prior to rev.4",     /* 0x0001       */
266         "ATA-1 published, ANSI X3.221-1994",            /* 0x0002       */
267         "ATA-1 X3T9.2 781D rev.4",                      /* 0x0003       */
268         "ATA-2 published, ANSI X3.279-1996",            /* 0x0004       */
269         "ATA-2 X3T10 948D prior to rev.2k",     /* 0x0005       */
270         "ATA-3 X3T10 2008D rev.1",                      /* 0x0006       */
271         "ATA-2 X3T10 948D rev.2k",                      /* 0x0007       */
272         "ATA-3 X3T10 2008D rev.0",                      /* 0x0008       */
273         "ATA-2 X3T10 948D rev.3",                       /* 0x0009       */
274         "ATA-3 published, ANSI X3.298-199x",            /* 0x000a       */
275         "ATA-3 X3T10 2008D rev.6",                      /* 0x000b       */
276         "ATA-3 X3T13 2008D rev.7 and 7a",               /* 0x000c       */
277         "ATA/ATAPI-4 X3T13 1153D rev.6",                /* 0x000d       */
278         "ATA/ATAPI-4 T13 1153D rev.13",         /* 0x000e       */
279         "ATA/ATAPI-4 X3T13 1153D rev.7",                /* 0x000f       */
280         "ATA/ATAPI-4 T13 1153D rev.18",         /* 0x0010       */
281         "ATA/ATAPI-4 T13 1153D rev.15",         /* 0x0011       */
282         "ATA/ATAPI-4 published, ANSI INCITS 317-1998",  /* 0x0012       */
283         "ATA/ATAPI-5 T13 1321D rev.3",
284         "ATA/ATAPI-4 T13 1153D rev.14",         /* 0x0014       */
285         "ATA/ATAPI-5 T13 1321D rev.1",          /* 0x0015       */
286         "ATA/ATAPI-5 published, ANSI INCITS 340-2000",  /* 0x0016       */
287         "ATA/ATAPI-4 T13 1153D rev.17",         /* 0x0017       */
288         "ATA/ATAPI-6 T13 1410D rev.0",          /* 0x0018       */
289         "ATA/ATAPI-6 T13 1410D rev.3a",         /* 0x0019       */
290         "ATA/ATAPI-7 T13 1532D rev.1",          /* 0x001a       */
291         "ATA/ATAPI-6 T13 1410D rev.2",          /* 0x001b       */
292         "ATA/ATAPI-6 T13 1410D rev.1",          /* 0x001c       */
293         "ATA/ATAPI-7 published, ANSI INCITS 397-2005",  /* 0x001d       */
294         "ATA/ATAPI-7 T13 1532D rev.0",          /* 0x001e       */
295         "Reserved"                                      /* 0x001f       */
296         "Reserved"                                      /* 0x0020       */
297         "ATA/ATAPI-7 T13 1532D rev.4a",         /* 0x0021       */
298         "ATA/ATAPI-6 published, ANSI INCITS 361-2002",  /* 0x0022       */
299         "Reserved"                                      /* 0x0023-0xfffe*/
300 };
301 #endif
302 static const char actual_ver[MINOR_MAX+2] = {
303                         /* word 81 value: */
304         0,              /* 0x0000       WARNING:        */
305         1,              /* 0x0001       WARNING:        */
306         1,              /* 0x0002       WARNING:        */
307         1,              /* 0x0003       WARNING:        */
308         2,              /* 0x0004       WARNING:   This array           */
309         2,              /* 0x0005       WARNING:   corresponds          */
310         3,              /* 0x0006       WARNING:   *exactly*            */
311         2,              /* 0x0007       WARNING:   to the ATA/          */
312         3,              /* 0x0008       WARNING:   ATAPI version        */
313         2,              /* 0x0009       WARNING:   listed in            */
314         3,              /* 0x000a       WARNING:   the                  */
315         3,              /* 0x000b       WARNING:   minor_str            */
316         3,              /* 0x000c       WARNING:   array                */
317         4,              /* 0x000d       WARNING:   above.               */
318         4,              /* 0x000e       WARNING:                        */
319         4,              /* 0x000f       WARNING:   if you change        */
320         4,              /* 0x0010       WARNING:   that one,            */
321         4,              /* 0x0011       WARNING:   change this one      */
322         4,              /* 0x0012       WARNING:   too!!!               */
323         5,              /* 0x0013       WARNING:        */
324         4,              /* 0x0014       WARNING:        */
325         5,              /* 0x0015       WARNING:        */
326         5,              /* 0x0016       WARNING:        */
327         4,              /* 0x0017       WARNING:        */
328         6,              /* 0x0018       WARNING:        */
329         6,              /* 0x0019       WARNING:        */
330         7,              /* 0x001a       WARNING:        */
331         6,              /* 0x001b       WARNING:        */
332         6,              /* 0x001c       WARNING:        */
333         7,              /* 0x001d       WARNING:        */
334         7,              /* 0x001e       WARNING:        */
335         0,              /* 0x001f       WARNING:        */
336         0,              /* 0x0020       WARNING:        */
337         7,              /* 0x0021       WARNING:        */
338         6,              /* 0x0022       WARNING:        */
339         0               /* 0x0023-0xfffe        */
340 };
341
342 /* words 82-84: cmds/feats supported */
343 #define CMDS_W82                0x77ff  /* word 82: defined command locations*/
344 #define CMDS_W83                0x3fff  /* word 83: defined command locations*/
345 #define CMDS_W84                0x002f  /* word 83: defined command locations*/
346 #define SUPPORT_48_BIT          0x0400
347 #define NUM_CMD_FEAT_STR        48
348
349 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
350 static const char * const cmd_feat_str[] = {
351         "",                                     /* word 82 bit 15: obsolete  */
352         "NOP cmd",                              /* word 82 bit 14 */
353         "READ BUFFER cmd",                      /* word 82 bit 13 */
354         "WRITE BUFFER cmd",                     /* word 82 bit 12 */
355         "",                                     /* word 82 bit 11: obsolete  */
356         "Host Protected Area feature set",      /* word 82 bit 10 */
357         "DEVICE RESET cmd",                     /* word 82 bit  9 */
358         "SERVICE interrupt",                    /* word 82 bit  8 */
359         "Release interrupt",                    /* word 82 bit  7 */
360         "Look-ahead",                           /* word 82 bit  6 */
361         "Write cache",                          /* word 82 bit  5 */
362         "PACKET command feature set",           /* word 82 bit  4 */
363         "Power Management feature set",         /* word 82 bit  3 */
364         "Removable Media feature set",          /* word 82 bit  2 */
365         "Security Mode feature set",            /* word 82 bit  1 */
366         "SMART feature set",                    /* word 82 bit  0 */
367                                                 /* --------------*/
368         "",                                     /* word 83 bit 15: !valid bit */
369         "",                                     /* word 83 bit 14:  valid bit */
370         "FLUSH CACHE EXT cmd",          /* word 83 bit 13 */
371         "Mandatory FLUSH CACHE cmd ",   /* word 83 bit 12 */
372         "Device Configuration Overlay feature set ",
373         "48-bit Address feature set ",          /* word 83 bit 10 */
374         "",
375         "SET MAX security extension",           /* word 83 bit  8 */
376         "Address Offset Reserved Area Boot",    /* word 83 bit  7 */
377         "SET FEATURES subcommand required to spinup after power up",
378         "Power-Up In Standby feature set",      /* word 83 bit  5 */
379         "Removable Media Status Notification feature set",
380         "Adv. Power Management feature set",/* word 83 bit  3 */
381         "CFA feature set",                      /* word 83 bit  2 */
382         "READ/WRITE DMA QUEUED",                /* word 83 bit  1 */
383         "DOWNLOAD MICROCODE cmd",               /* word 83 bit  0 */
384                                                 /* --------------*/
385         "",                                     /* word 84 bit 15: !valid bit */
386         "",                                     /* word 84 bit 14:  valid bit */
387         "",                                     /* word 84 bit 13:  reserved */
388         "",                                     /* word 84 bit 12:  reserved */
389         "",                                     /* word 84 bit 11:  reserved */
390         "",                                     /* word 84 bit 10:  reserved */
391         "",                                     /* word 84 bit  9:  reserved */
392         "",                                     /* word 84 bit  8:  reserved */
393         "",                                     /* word 84 bit  7:  reserved */
394         "",                                     /* word 84 bit  6:  reserved */
395         "General Purpose Logging feature set",  /* word 84 bit  5 */
396         "",                                     /* word 84 bit  4:  reserved */
397         "Media Card Pass Through Command feature set ",
398         "Media serial number ",                 /* word 84 bit  2 */
399         "SMART self-test ",                     /* word 84 bit  1 */
400         "SMART error logging "                  /* word 84 bit  0 */
401 };
402
403 static void identify(uint16_t *id_supplied) ATTRIBUTE_NORETURN;
404 static void identify_from_stdin(void) ATTRIBUTE_NORETURN;
405
406 #endif
407
408
409 /* words 85-87: cmds/feats enabled */
410 /* use cmd_feat_str[] to display what commands and features have
411  * been enabled with words 85-87
412  */
413
414 /* words 89, 90, SECU ERASE TIME */
415 #define ERASE_BITS              0x00ff
416
417 /* word 92: master password revision */
418 /* NOVAL_0 or  NOVAL_1 means no support for master password revision */
419
420 /* word 93: hw reset result */
421 #define CBLID                   0x2000  /* CBLID status */
422 #define RST0                    0x0001  /* 1=reset to device #0 */
423 #define DEV_DET                 0x0006  /* how device num determined */
424 #define JUMPER_VAL              0x0002  /* device num determined by jumper */
425 #define CSEL_VAL                0x0004  /* device num determined by CSEL_VAL */
426
427 /* word 127: removable media status notification feature set support */
428 #define RM_STAT_BITS            0x0003
429 #define RM_STAT_SUP             0x0001
430
431 /* word 128: security */
432 #define SECU_ENABLED    0x0002
433 #define SECU_LEVEL              0x0010
434 #define NUM_SECU_STR    6
435 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
436 static const char * const secu_str[] = {
437         "supported",                    /* word 128, bit 0 */
438         "enabled",                      /* word 128, bit 1 */
439         "locked",                       /* word 128, bit 2 */
440         "frozen",                       /* word 128, bit 3 */
441         "expired: security count",      /* word 128, bit 4 */
442         "supported: enhanced erase"     /* word 128, bit 5 */
443 };
444 #endif
445
446 /* word 160: CFA power mode */
447 #define VALID_W160              0x8000  /* 1=word valid */
448 #define PWR_MODE_REQ            0x2000  /* 1=CFA power mode req'd by some cmds*/
449 #define PWR_MODE_OFF            0x1000  /* 1=CFA power moded disabled */
450 #define MAX_AMPS                0x0fff  /* value = max current in ma */
451
452 /* word 255: integrity */
453 #define SIG                     0x00ff  /* signature location */
454 #define SIG_VAL                 0x00A5  /* signature value */
455
456 #define TIMING_MB               64
457 #define TIMING_BUF_MB           1
458 #define TIMING_BUF_BYTES        (TIMING_BUF_MB * 1024 * 1024)
459 #define TIMING_BUF_COUNT        (timing_MB / TIMING_BUF_MB)
460 #define BUFCACHE_FACTOR         2
461
462 #undef DO_FLUSHCACHE            /* under construction: force cache flush on -W0 */
463
464 /* Busybox messages and functions */
465 static int bb_ioctl(int fd, int request, void *argp, const char *string)
466 {
467         int e = ioctl(fd, request, argp);
468         if (e && string)
469                 bb_perror_msg(" %s", string);
470         return e;
471 }
472
473 static int bb_ioctl_alt(int fd, int cmd, unsigned char *args, int alt, const char *string)
474 {
475         if (!ioctl(fd, cmd, args))
476                 return 0;
477         args[0] = alt;
478         return bb_ioctl(fd, cmd, args, string);
479 }
480
481 static void on_off(unsigned int value);
482
483 static void print_flag_on_off(unsigned long get_arg, const char *s, unsigned long arg)
484 {
485
486         if (get_arg)
487         {
488                 printf(" setting %s to %ld", s, arg);
489                 on_off(arg);
490         }
491 }
492
493 static void bb_ioctl_on_off(int fd, int request, void *argp, const char *string,
494                                                          const char * str)
495 {
496         if (ioctl(fd, request, &argp) != 0)
497                 bb_perror_msg(" %s", string);
498         else
499         {
500                 printf(" %s\t= %2ld", str, (unsigned long) argp);
501                 on_off((unsigned long) argp);
502         }
503 }
504
505 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
506 static void print_ascii(uint16_t *p, uint8_t length);
507
508 static void xprint_ascii(uint16_t *val ,int i, char * string, int n)
509 {
510         if (val[i])
511         {
512                 printf("\t%-20s",string);
513                 print_ascii(&val[i], n);
514         }
515 }
516 #endif
517 /* end of  busybox specific stuff */
518
519 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
520 static uint8_t mode_loop(uint16_t mode_sup, uint16_t mode_sel, int cc, uint8_t *have_mode)
521 {
522         uint16_t ii;
523         uint8_t err_dma = 0;
524
525         for (ii = 0; ii <= MODE_MAX; ii++)
526         {
527                 if (mode_sel & 0x0001)
528                 {
529                         printf("*%cdma%u ",cc,ii);
530                         if (*have_mode)
531                                 err_dma = 1;
532                         *have_mode = 1;
533                 }
534                 else if (mode_sup & 0x0001)
535                         printf("%cdma%u ",cc,ii);
536
537                 mode_sup >>=1;
538                 mode_sel >>=1;
539         }
540         return err_dma;
541 }
542
543 static void print_ascii(uint16_t *p, uint8_t length) {
544         uint8_t ii;
545         char cl;
546
547         /* find first non-space & print it */
548         for (ii = 0; ii< length; ii++)
549         {
550                 if (((char) 0x00ff&((*p)>>8)) != ' ')
551                         break;
552                 if ((cl = (char) 0x00ff&(*p)) != ' ')
553                 {
554                         if (cl != '\0') printf("%c",cl);
555                         p++;
556                         ii++;
557                         break;
558                 }
559                 p++;
560         }
561         /* print the rest */
562         for (; ii< length; ii++)
563         {
564                 if (!(*p))
565                         break; /* some older devices have NULLs */
566                 printf("%c%c",(char)0x00ff&((*p)>>8),(char)(*p)&0x00ff);
567                 p++;
568         }
569         printf("\n");
570 }
571
572 /* identify() is the only extern function used across two source files.  The
573    others, though, were declared in hdparm.c with global scope; since other
574    functions in that file have static (file) scope, I assume the difference is
575    intentional. */
576 static void identify(uint16_t *id_supplied)
577 {
578         uint16_t buf[256];
579         uint16_t *val, ii, jj, kk;
580         uint16_t like_std = 1, std = 0, min_std = 0xffff;
581         uint16_t dev = NO_DEV, eqpt = NO_DEV;
582         uint8_t  have_mode = 0, err_dma = 0;
583         uint8_t  chksum = 0;
584         uint32_t ll, mm, nn, oo;
585         uint64_t bbbig; /* (:) */
586         const char *strng;
587
588         if (BB_BIG_ENDIAN) {
589                 swab(id_supplied, buf, sizeof(buf));
590                 val = buf;
591         } else val = id_supplied;
592
593         chksum &= 0xff;
594
595         /* check if we recognise the device type */
596         printf("\n");
597         if(!(val[GEN_CONFIG] & NOT_ATA))
598         {
599                 dev = ATA_DEV;
600                 printf("ATA device, with ");
601         }
602         else if(val[GEN_CONFIG]==CFA_SUPPORT_VAL)
603         {
604                 dev = ATA_DEV;
605                 like_std = 4;
606                 printf("CompactFlash ATA device, with ");
607         }
608         else if(!(val[GEN_CONFIG] & NOT_ATAPI))
609         {
610                 dev = ATAPI_DEV;
611                 eqpt = (val[GEN_CONFIG] & EQPT_TYPE) >> SHIFT_EQPT;
612                 printf("ATAPI %s, with ", pkt_str[eqpt]);
613                 like_std = 3;
614         }
615         else
616                 /*"Unknown device type:\n\tbits 15&14 of general configuration word 0 both set to 1.\n"*/
617                 bb_error_msg_and_die("Unknown device type");
618
619         printf("%sremovable media\n", !(val[GEN_CONFIG] & MEDIA_REMOVABLE) ? "non-" : "");
620         /* Info from the specific configuration word says whether or not the
621          * ID command completed correctly.  It is only defined, however in
622          * ATA/ATAPI-5 & 6; it is reserved (value theoretically 0) in prior
623          * standards.  Since the values allowed for this word are extremely
624          * specific, it should be safe to check it now, even though we don't
625          * know yet what standard this device is using.
626          */
627         if ((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL) ||
628            (val[CONFIG]==PWRD_NID_VAL) || (val[CONFIG]==PWRD_ID_VAL) )
629         {
630                 like_std = 5;
631                 if((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL))
632                         printf("powers-up in standby; SET FEATURES subcmd spins-up.\n");
633                 if(((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==PWRD_NID_VAL)) && (val[GEN_CONFIG] & INCOMPLETE))
634                         printf("\n\tWARNING: ID response incomplete.\n\tFollowing data may be incorrect.\n\n");
635         }
636
637         /* output the model and serial numbers and the fw revision */
638         xprint_ascii(val, START_MODEL,  "Model Number:",        LENGTH_MODEL);
639         xprint_ascii(val, START_SERIAL, "Serial Number:",       LENGTH_SERIAL);
640         xprint_ascii(val, START_FW_REV, "Firmware Revision:",   LENGTH_FW_REV);
641         xprint_ascii(val, START_MEDIA,  "Media Serial Num:",    LENGTH_MEDIA);
642         xprint_ascii(val, START_MANUF,  "Media Manufacturer:",  LENGTH_MANUF);
643
644         /* major & minor standards version number (Note: these words were not
645          * defined until ATA-3 & the CDROM std uses different words.) */
646         printf("Standards:");
647         if (eqpt != CDROM)
648         {
649                 if (val[MINOR] && (val[MINOR] <= MINOR_MAX))
650                 {
651                         if(like_std < 3) like_std = 3;
652                         std = actual_ver[val[MINOR]];
653                         if(std) printf("\n\tUsed: %s ",minor_str[val[MINOR]]);
654
655                 }
656                 /* looks like when they up-issue the std, they obsolete one;
657                  * thus, only the newest 4 issues need be supported. (That's
658                  * what "kk" and "min_std" are all about.) */
659                 if (val[MAJOR] && (val[MAJOR] !=NOVAL_1))
660                 {
661                         printf("\n\tSupported: ");
662                         jj = val[MAJOR] << 1;
663                         kk = like_std >4 ? like_std-4: 0;
664                         for (ii = 14; (ii >0)&&(ii>kk); ii--)
665                         {
666                                 if (jj & 0x8000)
667                                 {
668                                         printf("%u ", ii);
669                                         if (like_std < ii)
670                                         {
671                                                 like_std = ii;
672                                                 kk = like_std >4 ? like_std-4: 0;
673                                         }
674                                         if(min_std > ii) min_std = ii;
675                                 }
676                                 jj <<= 1;
677                         }
678                         if(like_std < 3) like_std = 3;
679                 }
680                 /* Figure out what standard the device is using if it hasn't told
681                  * us.  If we know the std, check if the device is using any of
682                  * the words from the next level up.  It happens.
683                  */
684                 if(like_std < std) like_std = std;
685
686                 if (((std == 5) || (!std && (like_std < 6))) &&
687                         ((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
688                         ((      val[CMDS_SUPP_1] & CMDS_W83) > 0x00ff)) ||
689                         (((     val[CMDS_SUPP_2] & VALID) == VALID_VAL) &&
690                         (       val[CMDS_SUPP_2] & CMDS_W84) ) ) )
691                 {
692                         like_std = 6;
693                 }
694                 else if (((std == 4) || (!std && (like_std < 5))) &&
695                         ((((val[INTEGRITY]      & SIG) == SIG_VAL) && !chksum) ||
696                         ((      val[HWRST_RSLT] & VALID) == VALID_VAL) ||
697                         (((     val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
698                         ((      val[CMDS_SUPP_1] & CMDS_W83) > 0x001f)) ) )
699                 {
700                         like_std = 5;
701                 }
702                 else if (((std == 3) || (!std && (like_std < 4))) &&
703                                 ((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
704                                 (((     val[CMDS_SUPP_1] & CMDS_W83) > 0x0000) ||
705                                 ((      val[CMDS_SUPP_0] & CMDS_W82) > 0x000f))) ||
706                                 ((      val[CAPAB_1] & VALID) == VALID_VAL) ||
707                                 ((      val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) ||
708                                 ((      val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) ) )
709                 {
710                         like_std = 4;
711                 }
712                 else if (((std == 2) || (!std && (like_std < 3))) &&
713                            ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) )
714                 {
715                         like_std = 3;
716                 }
717                 else if (((std == 1) || (!std && (like_std < 2))) &&
718                                 ((val[CAPAB_0] & (IORDY_SUP | IORDY_OFF)) ||
719                                 (val[WHATS_VALID] & OK_W64_70)) )
720                 {
721                         like_std = 2;
722                 }
723                 if (!std)
724                         printf("\n\tLikely used: %u\n",like_std);
725                 else if (like_std > std)
726                         printf("& some of %u\n",like_std);
727                 else
728                         printf("\n");
729         }
730         else
731         {
732                 /* TBD: do CDROM stuff more thoroughly.  For now... */
733                 kk = 0;
734                 if (val[CDR_MINOR] == 9)
735                 {
736                         kk = 1;
737                         printf("\n\tUsed: ATAPI for CD-ROMs, SFF-8020i, r2.5");
738                 }
739                 if (val[CDR_MAJOR] && (val[CDR_MAJOR] !=NOVAL_1))
740                 {
741                         kk = 1;
742                         printf("\n\tSupported: CD-ROM ATAPI");
743                         jj = val[CDR_MAJOR] >> 1;
744                         for (ii = 1; ii <15; ii++)
745                         {
746                                 if(jj & 0x0001) printf("-%u ", ii);
747                                 jj >>= 1;
748                         }
749                 }
750                 printf("%s\n", (!kk) ? "\n\tLikely used CD-ROM ATAPI-1" : "" );
751                 /* the cdrom stuff is more like ATA-2 than anything else, so: */
752                 like_std = 2;
753         }
754
755         if (min_std == 0xffff)
756                 min_std = like_std > 4 ? like_std - 3 : 1;
757
758         printf("Configuration:\n");
759         /* more info from the general configuration word */
760         if ((eqpt != CDROM) && (like_std == 1))
761         {
762                 jj = val[GEN_CONFIG] >> 1;
763                 for (ii = 1; ii < 15; ii++)
764                 {
765                         if(jj & 0x0001) printf("\t%s\n",ata1_cfg_str[ii]);
766                         jj >>=1;
767                 }
768         }
769         if (dev == ATAPI_DEV)
770         {
771                 if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_3MS_VAL)
772                         strng = "3ms";
773                 else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_INTR_VAL)
774                         strng = "<=10ms with INTRQ";
775                 else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) ==  DRQ_50US_VAL)
776                         strng ="50us";
777                 else 
778                         strng = "Unknown";
779                 printf("\tDRQ response: %s\n\tPacket size: ", strng); /* Data Request (DRQ) */
780
781                 if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_12_VAL)
782                         strng = "12 bytes";
783                 else if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_16_VAL)
784                         strng = "16 bytes";
785                 else
786                         strng = "Unknown";
787                 puts(strng);
788         }
789         else
790         {
791                 /* addressing...CHS? See section 6.2 of ATA specs 4 or 5 */
792                 ll = (uint32_t)val[LBA_SECTS_MSB] << 16 | val[LBA_SECTS_LSB];
793                 mm = 0; bbbig = 0;
794                 if ( (ll > 0x00FBFC10) && (!val[LCYLS]))
795                         printf("\tCHS addressing not supported\n");
796                 else
797                 {
798                         jj = val[WHATS_VALID] & OK_W54_58;
799                         printf("\tLogical\t\tmax\tcurrent\n\tcylinders\t%u\t%u\n\theads\t\t%u\t%u\n\tsectors/track\t%u\t%u\n\t--\n",
800                                         val[LCYLS],jj?val[LCYLS_CUR]:0, val[LHEADS],jj?val[LHEADS_CUR]:0, val[LSECTS],jj?val[LSECTS_CUR]:0);
801
802                         if ((min_std == 1) && (val[TRACK_BYTES] || val[SECT_BYTES]))
803                                 printf("\tbytes/track: %u\tbytes/sector: %u\n",val[TRACK_BYTES], val[SECT_BYTES]);
804
805                         if (jj)
806                         {
807                                 mm = (uint32_t)val[CAPACITY_MSB] << 16 | val[CAPACITY_LSB];
808                                 if (like_std < 3)
809                                 {
810                                          /* check Endian of capacity bytes */
811                                         nn = val[LCYLS_CUR] * val[LHEADS_CUR] * val[LSECTS_CUR];
812                                         oo = (uint32_t)val[CAPACITY_LSB] << 16 | val[CAPACITY_MSB];
813                                         if (abs(mm - nn) > abs(oo - nn))
814                                                 mm = oo;
815                                 }
816                                 printf("\tCHS current addressable sectors:%11u\n",mm);
817                         }
818                 }
819                 /* LBA addressing */
820                 printf("\tLBA    user addressable sectors:%11u\n",ll);
821                 if ( ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) &&
822                      (val[CMDS_SUPP_1] & SUPPORT_48_BIT) )
823                 {
824                         bbbig = (uint64_t)val[LBA_64_MSB]       << 48 |
825                                 (uint64_t)val[LBA_48_MSB]       << 32 |
826                                 (uint64_t)val[LBA_MID]  << 16 |
827                                         val[LBA_LSB] ;
828                         printf("\tLBA48  user addressable sectors:%11llu\n",(long long unsigned int)bbbig);
829                 }
830
831                 if (!bbbig)
832                         bbbig = (uint64_t)(ll>mm ? ll : mm); /* # 512 byte blocks */
833                 printf("\tdevice size with M = 1024*1024: %11llu MBytes\n",(long long unsigned int)(bbbig>>11));
834                 bbbig = (bbbig<<9)/1000000;
835                 printf("\tdevice size with M = 1000*1000: %11llu MBytes ",(long long unsigned int)bbbig);
836
837                 if (bbbig > 1000)
838                         printf("(%llu GB)\n", (long long unsigned int)bbbig/1000);
839                 else 
840                         printf("\n");
841         }
842
843         /* hw support of commands (capabilities) */
844         printf("Capabilities:\n\t");
845
846         if (dev == ATAPI_DEV)
847         {
848                 if (eqpt != CDROM && (val[CAPAB_0] & CMD_Q_SUP)) printf("Cmd queuing, ");
849                 if (val[CAPAB_0] & OVLP_SUP) printf("Cmd overlap, ");
850         }
851         if (val[CAPAB_0] & LBA_SUP) printf("LBA, ");
852
853         if (like_std != 1)
854         {
855                 printf("IORDY%s(can%s be disabled)\n", 
856                                 !(val[CAPAB_0] & IORDY_SUP) ? "(may be)" : "", 
857                                 (val[CAPAB_0] & IORDY_OFF) ? "" :"not");
858         }
859         else
860                 printf("no IORDY\n");
861
862         if ((like_std == 1) && val[BUF_TYPE])
863         {
864                 printf("\tBuffer type: %04x: %s%s\n", val[BUF_TYPE],
865                                 (val[BUF_TYPE] < 2) ? "single port, single-sector" : "dual port, multi-sector", 
866                                 (val[BUF_TYPE] > 2) ? " with read caching ability" : "");
867         }
868
869         if ((min_std == 1) && (val[BUFFER__SIZE] && (val[BUFFER__SIZE] != NOVAL_1)))
870         {
871                 printf("\tBuffer size: %.1fkB\n",(float)val[BUFFER__SIZE]/2);
872         }
873         if ((min_std < 4) && (val[RW_LONG]))
874         {
875                 printf("\tbytes avail on r/w long: %u\n",val[RW_LONG]);
876         }
877         if ((eqpt != CDROM) && (like_std > 3))
878         {
879                 printf("\tQueue depth: %u\n",(val[QUEUE_DEPTH] & DEPTH_BITS)+1);
880         }
881
882         if (dev == ATA_DEV)
883         {
884                 if (like_std == 1)
885                         printf("\tCan%s perform double-word IO\n",(!val[DWORD_IO]) ?"not":"");
886                 else
887                 {
888                         printf("\tStandby timer values: spec'd by %s", (val[CAPAB_0] & STD_STBY) ? "Standard" : "Vendor");
889                         if ((like_std > 3) && ((val[CAPAB_1] & VALID) == VALID_VAL))
890                                 printf(", %s device specific minimum\n",(val[CAPAB_1] & MIN_STANDBY_TIMER)?"with":"no");
891                         else
892                           printf("\n");
893                 }
894                 printf("\tR/W multiple sector transfer: ");
895                 if ((like_std < 3) && !(val[SECTOR_XFER_MAX] & SECTOR_XFER))
896                         printf("not supported\n");
897                 else
898                 {
899                         printf("Max = %u\tCurrent = ",val[SECTOR_XFER_MAX] & SECTOR_XFER);
900                         if (val[SECTOR_XFER_CUR] & MULTIPLE_SETTING_VALID)
901                                 printf("%u\n", val[SECTOR_XFER_CUR] & SECTOR_XFER);
902                         else
903                                 printf("?\n");
904                 }
905                 if ((like_std > 3) && (val[CMDS_SUPP_1] & 0x0008))
906                 {
907                         /* We print out elsewhere whether the APM feature is enabled or
908                            not.  If it's not enabled, let's not repeat the info; just print
909                            nothing here. */
910                         printf("\tAdvancedPM level: ");
911                         if ( (val[ADV_PWR] & 0xFF00) == 0x4000 )
912                         {
913                                 uint8_t apm_level = val[ADV_PWR] & 0x00FF;
914                                 printf("%u (0x%x)\n", apm_level, apm_level);
915                         }
916                         else
917                                 printf("unknown setting (0x%04x)\n", val[ADV_PWR]);
918                 }
919                 if (like_std > 5 && val[ACOUSTIC]) {
920                         printf("\tRecommended acoustic management value: %u, current value: %u\n",
921                                                                         (val[ACOUSTIC] >> 8) & 0x00ff, val[ACOUSTIC] & 0x00ff);
922                 }
923         }
924         else
925         {
926                  /* ATAPI */
927                 if (eqpt != CDROM && (val[CAPAB_0] & SWRST_REQ))
928                         printf("\tATA sw reset required\n");
929
930                 if (val[PKT_REL] || val[SVC_NBSY])
931                 {
932                         printf("\tOverlap support:");
933                         if (val[PKT_REL]) printf(" %uus to release bus.",val[PKT_REL]);
934                         if (val[SVC_NBSY]) printf(" %uus to clear BSY after SERVICE cmd.",val[SVC_NBSY]);
935                         printf("\n");
936                 }
937         }
938
939         /* DMA stuff. Check that only one DMA mode is selected. */
940         printf("\tDMA: ");
941         if (!(val[CAPAB_0] & DMA_SUP))
942                 printf("not supported\n");
943         else
944         {
945                 if (val[DMA_MODE] && !val[SINGLE_DMA] && !val[MULTI_DMA])
946                         printf(" sdma%u\n",(val[DMA_MODE] & MODE) >> 8);
947                 if (val[SINGLE_DMA])
948                 {
949                         jj = val[SINGLE_DMA];
950                         kk = val[SINGLE_DMA] >> 8;
951                         err_dma += mode_loop(jj,kk,'s',&have_mode);
952                 }
953                 if (val[MULTI_DMA])
954                 {
955                         jj = val[MULTI_DMA];
956                         kk = val[MULTI_DMA] >> 8;
957                         err_dma += mode_loop(jj,kk,'m',&have_mode);
958                 }
959                 if ((val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA])
960                 {
961                         jj = val[ULTRA_DMA];
962                         kk = val[ULTRA_DMA] >> 8;
963                         err_dma += mode_loop(jj,kk,'u',&have_mode);
964                 }
965                 if (err_dma || !have_mode) printf("(?)");
966                 printf("\n");
967
968                 if ((dev == ATAPI_DEV) && (eqpt != CDROM) && (val[CAPAB_0] & DMA_IL_SUP))
969                         printf("\t\tInterleaved DMA support\n");
970
971                 if ((val[WHATS_VALID] & OK_W64_70) &&
972                    (val[DMA_TIME_MIN] || val[DMA_TIME_NORM]))
973                 {
974                         printf("\t\tCycle time:");
975                         if (val[DMA_TIME_MIN]) printf(" min=%uns",val[DMA_TIME_MIN]);
976                         if (val[DMA_TIME_NORM]) printf(" recommended=%uns",val[DMA_TIME_NORM]);
977                         printf("\n");
978                 }
979         }
980
981         /* Programmed IO stuff */
982         printf("\tPIO: ");
983         /* If a drive supports mode n (e.g. 3), it also supports all modes less
984          * than n (e.g. 3, 2, 1 and 0).  Print all the modes. */
985         if ((val[WHATS_VALID] & OK_W64_70) && (val[ADV_PIO_MODES] & PIO_SUP))
986         {
987                 jj = ((val[ADV_PIO_MODES] & PIO_SUP) << 3) | 0x0007;
988                 for (ii = 0; ii <= PIO_MODE_MAX ; ii++)
989                 {
990                         if (jj & 0x0001) printf("pio%d ",ii);
991                         jj >>=1;
992                 }
993                 printf("\n");
994         }
995         else if (((min_std < 5) || (eqpt == CDROM)) && (val[PIO_MODE] & MODE) )
996         {
997                 for (ii = 0; ii <= val[PIO_MODE]>>8; ii++)
998                         printf("pio%d ",ii);
999                 printf("\n");
1000         }
1001         else
1002                 printf("unknown\n");
1003
1004         if (val[WHATS_VALID] & OK_W64_70)
1005         {
1006                 if (val[PIO_NO_FLOW] || val[PIO_FLOW])
1007                 {
1008                         printf("\t\tCycle time:");
1009                         if (val[PIO_NO_FLOW]) printf(" no flow control=%uns", val[PIO_NO_FLOW]);
1010                         if (val[PIO_FLOW]) printf("  IORDY flow control=%uns", val[PIO_FLOW]);
1011                         printf("\n");
1012                 }
1013         }
1014
1015         if ((val[CMDS_SUPP_1] & VALID) == VALID_VAL)
1016         {
1017                 printf("Commands/features:\n\tEnabled\tSupported:\n");
1018                 jj = val[CMDS_SUPP_0];
1019                 kk = val[CMDS_EN_0];
1020                 for (ii = 0; ii < NUM_CMD_FEAT_STR; ii++)
1021                 {
1022                         if ((jj & 0x8000) && (*cmd_feat_str[ii] != '\0'))
1023                         {
1024                                 printf("\t%s\t%s\n", (kk & 0x8000) ? "   *" : "", cmd_feat_str[ii]);
1025                         }
1026                         jj <<=1; kk<<=1;
1027                         if (ii%16 == 15)
1028                         {
1029                                 jj = val[CMDS_SUPP_0+1+(ii/16)];
1030                                 kk = val[CMDS_EN_0+1+(ii/16)];
1031                         }
1032                         if (ii == 31)
1033                         {
1034                                 if ((val[CMDS_SUPP_2] & VALID) != VALID_VAL)
1035                                         ii +=16;
1036                         }
1037                 }
1038         }
1039         /* Removable Media Status Notification feature set */
1040         if((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP)
1041                 printf("\t%s supported\n", cmd_feat_str[27]);
1042
1043
1044         /* security */
1045         if ((eqpt != CDROM) && (like_std > 3) &&
1046            (val[SECU_STATUS] || val[ERASE_TIME] || val[ENH_ERASE_TIME]))
1047         {
1048                 printf("Security:\n");
1049                 if (val[PSWD_CODE] && (val[PSWD_CODE] != NOVAL_1))
1050                         printf("\tMaster password revision code = %u\n",val[PSWD_CODE]);
1051                 jj = val[SECU_STATUS];
1052                 if (jj)
1053                 {
1054                         for (ii = 0; ii < NUM_SECU_STR; ii++)
1055                         {
1056                                 printf("\t%s\t%s\n", (!(jj & 0x0001)) ? "not" : "",  secu_str[ii]);
1057                                 jj >>=1;
1058                         }
1059                         if (val[SECU_STATUS] & SECU_ENABLED)
1060                         {
1061                                 printf("\tSecurity level %s\n", (val[SECU_STATUS] & SECU_LEVEL) ? "maximum" : "high");
1062                         }
1063                 }
1064                 jj =  val[ERASE_TIME]     & ERASE_BITS;
1065                 kk =  val[ENH_ERASE_TIME] & ERASE_BITS;
1066                 if (jj || kk)
1067                 {
1068                         printf("\t");
1069                         if (jj) printf("%umin for %sSECURITY ERASE UNIT. ", jj==ERASE_BITS ? 508 : jj<<1, "");
1070                         if (kk) printf("%umin for %sSECURITY ERASE UNIT. ", kk==ERASE_BITS ? 508 : kk<<1, "ENHANCED ");
1071                         printf("\n");
1072                 }
1073         }
1074
1075         /* reset result */
1076         jj = val[HWRST_RSLT];
1077         if ((jj & VALID) == VALID_VAL)
1078         {
1079                 if (!(oo = (jj & RST0)))
1080                         jj >>= 8;
1081                 if ((jj & DEV_DET) == JUMPER_VAL)
1082                         strng = " determined by the jumper";
1083                 else if ((jj & DEV_DET) == CSEL_VAL)
1084                         strng = " determined by CSEL";
1085                 else 
1086                         strng = "";
1087                 printf("HW reset results:\n\tCBLID- %s Vih\n\tDevice num = %i%s\n", 
1088                                 (val[HWRST_RSLT] & CBLID) ? "above" : "below", !(oo), strng);
1089         }
1090
1091         /* more stuff from std 5 */
1092         if ((like_std > 4) && (eqpt != CDROM))
1093         {
1094                 if (val[CFA_PWR_MODE] & VALID_W160)
1095                 {
1096                         printf("CFA power mode 1:\n\t%s%s\n", (val[CFA_PWR_MODE] & PWR_MODE_OFF) ? "disabled" : "enabled",
1097                                                                                 (val[CFA_PWR_MODE] & PWR_MODE_REQ) ? " and required by some commands" : "");
1098
1099                         if (val[CFA_PWR_MODE] & MAX_AMPS) printf("\tMaximum current = %uma\n",val[CFA_PWR_MODE] & MAX_AMPS);
1100                 }
1101                 if ((val[INTEGRITY] & SIG) == SIG_VAL)
1102                 {
1103                         printf("Checksum: %scorrect\n", chksum ? "in" : "");
1104                 }
1105         }
1106
1107         exit(EXIT_SUCCESS);
1108 }
1109 #endif
1110
1111 static int get_identity, get_geom;
1112 static int do_flush;
1113 static int do_ctimings, do_timings;
1114 static unsigned long set_readahead, get_readahead, Xreadahead;
1115 static unsigned long set_readonly, get_readonly, readonly;
1116 static unsigned long set_unmask, get_unmask, unmask;
1117 static unsigned long set_mult, get_mult, mult;
1118 #ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA
1119 static unsigned long set_dma, get_dma, dma;
1120 #endif
1121 static unsigned long set_dma_q, get_dma_q, dma_q;
1122 static unsigned long set_nowerr, get_nowerr, nowerr;
1123 static unsigned long set_keep, get_keep, keep;
1124 static unsigned long set_io32bit, get_io32bit, io32bit;
1125 static unsigned long set_piomode, noisy_piomode;
1126 static int piomode;
1127 #ifdef HDIO_DRIVE_CMD
1128 static unsigned long set_dkeep, get_dkeep, dkeep;
1129 static unsigned long set_standby, get_standby, standby_requested;
1130 static unsigned long set_xfermode, get_xfermode;
1131 static int xfermode_requested;
1132 static unsigned long set_lookahead, get_lookahead, lookahead;
1133 static unsigned long set_prefetch, get_prefetch, prefetch;
1134 static unsigned long set_defects, get_defects, defects;
1135 static unsigned long set_wcache, get_wcache, wcache;
1136 static unsigned long set_doorlock, get_doorlock, doorlock;
1137 static unsigned long set_seagate, get_seagate;
1138 static unsigned long set_standbynow, get_standbynow;
1139 static unsigned long set_sleepnow, get_sleepnow;
1140 static unsigned long get_powermode;
1141 static unsigned long set_apmmode, get_apmmode, apmmode;
1142 #endif
1143 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
1144 static int get_IDentity;
1145 #endif
1146 #ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF
1147 static unsigned long    unregister_hwif;
1148 static unsigned long    hwif;
1149 #endif
1150 #ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF
1151 static unsigned long scan_hwif;
1152 static unsigned long hwif_data;
1153 static unsigned long hwif_ctrl;
1154 static unsigned long hwif_irq;
1155 #endif
1156 #ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
1157 static unsigned long    set_busstate, get_busstate, busstate;
1158 #endif
1159 static int      reread_partn;
1160
1161 #ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET
1162 static int      perform_reset;
1163 #endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */
1164 #ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
1165 static unsigned long    perform_tristate,       tristate;
1166 #endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */
1167
1168 // Historically, if there was no HDIO_OBSOLETE_IDENTITY, then
1169 // then the HDIO_GET_IDENTITY only returned 142 bytes.
1170 // Otherwise, HDIO_OBSOLETE_IDENTITY returns 142 bytes,
1171 // and HDIO_GET_IDENTITY returns 512 bytes.  But the latest
1172 // 2.5.xx kernels no longer define HDIO_OBSOLETE_IDENTITY
1173 // (which they should, but they should just return -EINVAL).
1174 //
1175 // So.. we must now assume that HDIO_GET_IDENTITY returns 512 bytes.
1176 // On a really old system, it will not, and we will be confused.
1177 // Too bad, really.
1178
1179 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
1180 static const char * const cfg_str[] =
1181 {       "",          "HardSect",   "SoftSect",   "NotMFM",
1182         "HdSw>15uSec", "SpinMotCtl", "Fixed",     "Removeable",
1183         "DTR<=5Mbs",   "DTR>5Mbs",   "DTR>10Mbs", "RotSpdTol>.5%",
1184         "dStbOff",     "TrkOff",     "FmtGapReq", "nonMagnetic"
1185 };
1186
1187 static const char * const BuffType[] = {"Unknown", "1Sect", "DualPort", "DualPortCache"};
1188
1189 static void dump_identity(const struct hd_driveid *id)
1190 {
1191         int i;
1192         const unsigned short int *id_regs= (const void*) id;
1193
1194         printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s\n Config={",
1195                                 id->model, id->fw_rev, id->serial_no);
1196         for (i=0; i<=15; i++) {
1197                 if (id->config & (1<<i))
1198                         printf(" %s", cfg_str[i]);
1199         }
1200         printf( " }\n RawCHS=%u/%u/%u, TrkSize=%u, SectSize=%u, ECCbytes=%u\n"
1201                         " BuffType=(%u) %s, BuffSize=%ukB, MaxMultSect=%u",
1202                                 id->cyls, id->heads, id->sectors, id->track_bytes,
1203                                 id->sector_bytes, id->ecc_bytes,
1204                                 id->buf_type, BuffType[(id->buf_type > 3) ? 0 :  id->buf_type],
1205                                 id->buf_size/2, id->max_multsect);
1206         if (id->max_multsect)
1207         {
1208                 printf(", MultSect=");
1209                 if (!(id->multsect_valid&1))
1210                         printf("?%u?", id->multsect);
1211                 else if (id->multsect)
1212                         printf("%u", id->multsect);
1213                 else
1214                         printf("off");
1215         }
1216         printf("\n");
1217
1218         if(!(id->field_valid&1))
1219                 printf(" (maybe):");
1220
1221         printf(" CurCHS=%u/%u/%u, CurSects=%lu, LBA=%s",id->cur_cyls, id->cur_heads,
1222                                                                                                         id->cur_sectors, 
1223                                                                                                         (BB_BIG_ENDIAN) ? 
1224                                                                                                         (long unsigned int)(id->cur_capacity0 << 16) | id->cur_capacity1 :
1225                                                                                                         (long unsigned int)(id->cur_capacity1 << 16) | id->cur_capacity0,
1226                                                                                                         ((id->capability&2) == 0) ? "no" : "yes");
1227
1228         if (id->capability&2)
1229                 printf(", LBAsects=%u", id->lba_capacity);
1230
1231         printf("\n IORDY=%s", (id->capability&8) ? (id->capability&4) ?  "on/off" : "yes" : "no");
1232
1233         if (((id->capability&8) || (id->field_valid&2)) && id->field_valid&2)
1234                 printf(", tPIO={min:%u,w/IORDY:%u}", id->eide_pio, id->eide_pio_iordy);
1235         
1236         if ((id->capability&1) && (id->field_valid&2))
1237                 printf(", tDMA={min:%u,rec:%u}", id->eide_dma_min, id->eide_dma_time);
1238
1239         printf("\n PIO modes:  ");
1240         if (id->tPIO <= 5)
1241         {
1242                 printf("pio0 ");
1243                 if (id->tPIO >= 1) printf("pio1 ");
1244                 if (id->tPIO >= 2) printf("pio2 ");
1245         }
1246         if (id->field_valid&2)
1247         {
1248                 if (id->eide_pio_modes & 1) printf("pio3 ");
1249                 if (id->eide_pio_modes & 2) printf("pio4 ");
1250                 if (id->eide_pio_modes &~3) printf("pio? ");
1251         }
1252         if (id->capability&1)
1253         {
1254                 if (id->dma_1word | id->dma_mword)
1255                 {
1256                         printf("\n DMA modes:  ");
1257                         if (id->dma_1word & 0x100) printf("*");
1258                         if (id->dma_1word & 1) printf("sdma0 ");
1259                         if (id->dma_1word & 0x200) printf("*");
1260                         if (id->dma_1word & 2) printf("sdma1 ");
1261                         if (id->dma_1word & 0x400) printf("*");
1262                         if (id->dma_1word & 4) printf("sdma2 ");
1263                         if (id->dma_1word & 0xf800) printf("*");
1264                         if (id->dma_1word & 0xf8) printf("sdma? ");
1265                         if (id->dma_mword & 0x100) printf("*");
1266                         if (id->dma_mword & 1) printf("mdma0 ");
1267                         if (id->dma_mword & 0x200) printf("*");
1268                         if (id->dma_mword & 2) printf("mdma1 ");
1269                         if (id->dma_mword & 0x400) printf("*");
1270                         if (id->dma_mword & 4) printf("mdma2 ");
1271                         if (id->dma_mword & 0xf800) printf("*");
1272                         if (id->dma_mword & 0xf8) printf("mdma? ");
1273                 }
1274         }
1275         if (((id->capability&8) || (id->field_valid&2)) && id->field_valid&4)
1276         {       
1277                 printf("\n UDMA modes: ");
1278                 if (id->dma_ultra & 0x100) printf("*");
1279                 if (id->dma_ultra & 0x001) printf("udma0 ");
1280                 if (id->dma_ultra & 0x200) printf("*");
1281                 if (id->dma_ultra & 0x002) printf("udma1 ");
1282                 if (id->dma_ultra & 0x400) printf("*");
1283                 if (id->dma_ultra & 0x004) printf("udma2 ");
1284 #ifdef __NEW_HD_DRIVE_ID
1285                 if (id->hw_config & 0x2000)
1286                 {
1287 #else /* !__NEW_HD_DRIVE_ID */
1288                 if (id->word93 & 0x2000)
1289                 {
1290 #endif /* __NEW_HD_DRIVE_ID */
1291                         if (id->dma_ultra & 0x0800) printf("*");
1292                         if (id->dma_ultra & 0x0008) printf("udma3 ");
1293                         if (id->dma_ultra & 0x1000) printf("*");
1294                         if (id->dma_ultra & 0x0010) printf("udma4 ");
1295                         if (id->dma_ultra & 0x2000) printf("*");
1296                         if (id->dma_ultra & 0x0020) printf("udma5 ");
1297                         if (id->dma_ultra & 0x4000) printf("*");
1298                         if (id->dma_ultra & 0x0040) printf("udma6 ");
1299                         if (id->dma_ultra & 0x8000) printf("*");
1300                         if (id->dma_ultra & 0x0080) printf("udma7 ");
1301                 }
1302         }
1303         printf("\n AdvancedPM=%s",((id_regs[83]&8)==0)?"no":"yes");
1304         if (id_regs[83] & 8)
1305         {
1306                 if (!(id_regs[86]&8))
1307                         printf(": disabled (255)");
1308                 else if ((id_regs[91]&0xFF00)!=0x4000)
1309                         printf(": unknown setting");
1310                 else
1311                         printf(": mode=0x%02X (%u)",id_regs[91]&0xFF,id_regs[91]&0xFF);
1312         }
1313         if (id_regs[82]&0x20)
1314                 printf(" WriteCache=%s",(id_regs[85]&0x20) ? "enabled" : "disabled");
1315 #ifdef __NEW_HD_DRIVE_ID
1316         if ((id->minor_rev_num && id->minor_rev_num <= 31) || (id->major_rev_num && id->minor_rev_num <= 31))
1317         {
1318                 printf("\n Drive conforms to: %s: ", (id->minor_rev_num <= 31) ? minor_str[id->minor_rev_num] : "Unknown");
1319                 if (id->major_rev_num != 0x0000 &&  /* NOVAL_0 */
1320                     id->major_rev_num != 0xFFFF) {  /* NOVAL_1 */
1321                         for (i=0; i <= 15; i++) {
1322                                 if (id->major_rev_num & (1<<i))
1323                                                 printf(" ATA/ATAPI-%u", i);
1324                         }
1325                 }
1326         }
1327 #endif /* __NEW_HD_DRIVE_ID */
1328         printf("\n\n * current active mode\n\n");
1329 }
1330 #endif
1331
1332 static void flush_buffer_cache(int fd)
1333 {
1334         fsync(fd);                              /* flush buffers */
1335         bb_ioctl(fd, BLKFLSBUF, NULL,"BLKFLSBUF" ) ;/* do it again, big time */
1336 #ifdef HDIO_DRIVE_CMD
1337         sleep(1);
1338         if (ioctl(fd, HDIO_DRIVE_CMD, NULL) && errno != EINVAL) /* await completion */
1339                 bb_perror_msg("HDIO_DRIVE_CMD");
1340 #endif
1341 }
1342
1343 static int seek_to_zero(int fd)
1344 {
1345         if (lseek(fd, (off_t) 0, SEEK_SET))
1346                 return 1;
1347         return 0;
1348 }
1349
1350 static int read_big_block(int fd, char *buf)
1351 {
1352         int i;
1353
1354         if ((i = read(fd, buf, TIMING_BUF_BYTES)) != TIMING_BUF_BYTES) {
1355                 bb_error_msg("read(%d bytes) failed (rc=%d)", TIMING_BUF_BYTES, i);
1356                 return 1;
1357         }
1358         /* access all sectors of buf to ensure the read fully completed */
1359         for (i = 0; i < TIMING_BUF_BYTES; i += 512)
1360                 buf[i] &= 1;
1361         return 0;
1362 }
1363
1364 static void print_timing(int t, double e)
1365 {
1366         if (t >= e)  /* more than 1MB/s */
1367                 printf("%2d MB in %5.2f seconds =%6.2f %cB/sec\n", t, e, t / e, 'M');
1368         else
1369                 printf("%2d MB in %5.2f seconds =%6.2f %cB/sec\n", t, e, t / e * 1024, 'k');
1370 }
1371
1372 static int do_blkgetsize (int fd, unsigned long long *blksize64)
1373 {
1374         int             rc;
1375         unsigned int    blksize32 = 0;
1376
1377         if (0 == ioctl(fd, BLKGETSIZE64, blksize64)) {  // returns bytes
1378                 *blksize64 /= 512;
1379                 return 0;
1380         }
1381         rc = ioctl(fd, BLKGETSIZE, &blksize32); // returns sectors
1382         if (rc)
1383                 bb_perror_msg("BLKGETSIZE");
1384         *blksize64 = blksize32;
1385         return rc;
1386 }
1387
1388 static void do_time(int flag, int fd)
1389 /*
1390         flag = 0 time_cache
1391         flag = 1 time_device
1392 */
1393 {
1394         struct itimerval e1, e2;
1395         double elapsed, elapsed2;
1396         unsigned int max_iterations = 1024, total_MB, iterations;
1397         unsigned long long blksize;
1398         RESERVE_CONFIG_BUFFER(buf, TIMING_BUF_BYTES);
1399
1400         if (mlock(buf, TIMING_BUF_BYTES)) {
1401                 bb_perror_msg("mlock");
1402                 goto quit2;
1403         }
1404
1405         if (0 == do_blkgetsize(fd, &blksize)) {
1406                 max_iterations = blksize / (2 * 1024) / TIMING_BUF_MB;
1407         }
1408
1409         /* Clear out the device request queues & give them time to complete */
1410         sync();
1411         sleep(3);
1412
1413         setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL);
1414
1415         if (flag  == 0) /* Time cache */
1416         {
1417                 if (seek_to_zero (fd)) return;
1418                 if (read_big_block (fd, buf)) return;
1419                 printf(" Timing cached reads:   ");
1420                 fflush(stdout);
1421         
1422                 /* Now do the timing */
1423                 iterations = 0;
1424                 getitimer(ITIMER_REAL, &e1);
1425                 do {
1426                         ++iterations;
1427                         if (seek_to_zero (fd) || read_big_block (fd, buf))
1428                                 goto quit;
1429                         getitimer(ITIMER_REAL, &e2);
1430                         elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec)
1431                         + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
1432                 } while (elapsed < 2.0);
1433                 total_MB = iterations * TIMING_BUF_MB;
1434
1435                 /* Now remove the lseek() and getitimer() overheads from the elapsed time */
1436                 getitimer(ITIMER_REAL, &e1);
1437                 do {
1438                         if (seek_to_zero (fd))
1439                                 goto quit;
1440                         getitimer(ITIMER_REAL, &e2);
1441                         elapsed2 = (e1.it_value.tv_sec - e2.it_value.tv_sec)
1442                         + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
1443                 } while (--iterations);
1444         
1445                 elapsed -= elapsed2;
1446                 print_timing(BUFCACHE_FACTOR * total_MB, elapsed);      
1447                 flush_buffer_cache(fd);
1448                 sleep(1);
1449         }
1450         else /* Time device */
1451         {
1452                 printf(" Timing buffered disk reads:  ");
1453                 fflush(stdout);
1454                 /*
1455                 * getitimer() is used rather than gettimeofday() because
1456                 * it is much more consistent (on my machine, at least).
1457                 */
1458                 /* Now do the timings for real */
1459                 iterations = 0;
1460                 getitimer(ITIMER_REAL, &e1);
1461                 do {
1462                         ++iterations;
1463                         if (read_big_block (fd, buf))
1464                                 goto quit;
1465                         getitimer(ITIMER_REAL, &e2);
1466                         elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec)
1467                         + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
1468                 } while (elapsed < 3.0 && iterations < max_iterations);
1469         
1470                 total_MB = iterations * TIMING_BUF_MB;
1471                 print_timing(total_MB, elapsed);
1472         }
1473 quit:
1474         munlock(buf, TIMING_BUF_BYTES);
1475 quit2:
1476         RELEASE_CONFIG_BUFFER(buf);
1477 }
1478
1479 static void on_off (unsigned int value)
1480 {
1481         printf(value ? " (on)\n" : " (off)\n");
1482 }
1483
1484 #ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
1485 static void bus_state_value(unsigned int value)
1486 {
1487         if (value == BUSSTATE_ON)
1488                 on_off(1);
1489         else if (value == BUSSTATE_OFF)
1490                 on_off(0);
1491         else if (value == BUSSTATE_TRISTATE)
1492                 printf(" (tristate)\n");
1493         else
1494                 printf(" (unknown: %d)\n", value);
1495 }
1496 #endif
1497
1498 #ifdef HDIO_DRIVE_CMD
1499 static void interpret_standby(unsigned int standby)
1500 {
1501         unsigned int t;
1502
1503
1504         if (standby == 0)
1505                 printf("off");
1506         else if (standby == 252)
1507                 printf("21 minutes");
1508         else if (standby == 253)
1509                 printf("vendor-specific");
1510         else if (standby == 254)
1511                 printf("Reserved");
1512         else if (standby == 255)
1513                 printf("21 minutes + 15 seconds");
1514         else {
1515                 if (standby <= 240) {
1516                         t = standby * 5;
1517                         printf("%u minutes + %u seconds", t / 60, t % 60);
1518                 } else if (standby <= 251) {
1519                         t = (standby - 240) * 30;
1520                         printf("%u hours + %u minutes", t / 60, t % 60);
1521                 } else
1522                         printf("illegal value");
1523         }
1524         printf(")\n");
1525 }
1526
1527 struct xfermode_entry {
1528     int val;
1529     const char *name;
1530 };
1531
1532 static const struct xfermode_entry xfermode_table[] = {
1533     { 8,    "pio0" },
1534     { 9,    "pio1" },
1535     { 10,   "pio2" },
1536     { 11,   "pio3" },
1537     { 12,   "pio4" },
1538     { 13,   "pio5" },
1539     { 14,   "pio6" },
1540     { 15,   "pio7" },
1541     { 16,   "sdma0" },
1542     { 17,   "sdma1" },
1543     { 18,   "sdma2" },
1544     { 19,   "sdma3" },
1545     { 20,   "sdma4" },
1546     { 21,   "sdma5" },
1547     { 22,   "sdma6" },
1548     { 23,   "sdma7" },
1549     { 32,   "mdma0" },
1550     { 33,   "mdma1" },
1551     { 34,   "mdma2" },
1552     { 35,   "mdma3" },
1553     { 36,   "mdma4" },
1554     { 37,   "mdma5" },
1555     { 38,   "mdma6" },
1556     { 39,   "mdma7" },
1557     { 64,   "udma0" },
1558     { 65,   "udma1" },
1559     { 66,   "udma2" },
1560     { 67,   "udma3" },
1561     { 68,   "udma4" },
1562     { 69,   "udma5" },
1563     { 70,   "udma6" },
1564     { 71,   "udma7" },
1565     { 0, NULL }
1566 };
1567
1568 static int translate_xfermode(char * name)
1569 {
1570         const struct xfermode_entry *tmp;
1571         char *endptr;
1572         int val = -1;
1573
1574
1575         for (tmp = xfermode_table; tmp->name != NULL; ++tmp)
1576         {
1577                 if (!strcmp(name, tmp->name))
1578                         return tmp->val;
1579         }
1580
1581         val = strtol(name, &endptr, 10);
1582         if (*endptr == '\0')
1583                 return val;
1584
1585         return -1;
1586 }
1587
1588 static void interpret_xfermode(unsigned int xfermode)
1589 {
1590         printf(" (");
1591         if (xfermode == 0)
1592                 printf("default PIO mode");
1593         else if (xfermode == 1)
1594                 printf("default PIO mode, disable IORDY");
1595         else if (xfermode >= 8 && xfermode <= 15)
1596                 printf("PIO flow control mode%u", xfermode-8);
1597         else if (xfermode >= 16 && xfermode <= 23)
1598                 printf("singleword DMA mode%u", xfermode-16);
1599         else if (xfermode >= 32 && xfermode <= 39)
1600                 printf("multiword DMA mode%u", xfermode-32);
1601         else if (xfermode >= 64 && xfermode <= 71)
1602                 printf("UltraDMA mode%u", xfermode-64);
1603         else
1604                 printf("Unknown");
1605         printf(")\n");
1606 }
1607 #endif /* HDIO_DRIVE_CMD */
1608
1609 static void print_flag(unsigned long flag, char *s, unsigned long value)
1610 {
1611         if(flag)
1612                 printf(" setting %s to %ld\n", s, value);
1613 }
1614
1615 static void process_dev(char *devname)
1616 {
1617         int fd;
1618         static long parm, multcount;
1619 #ifndef HDIO_DRIVE_CMD
1620         int force_operation = 0;
1621 #endif
1622         /* Please restore args[n] to these values after each ioctl
1623            except for args[2] */
1624         unsigned char args[4] = {WIN_SETFEATURES,0,0,0};
1625         const char *fmt = " %s\t= %2ld";
1626
1627         fd = bb_xopen(devname, O_RDONLY|O_NONBLOCK);
1628         printf("\n%s:\n", devname);
1629
1630         if (set_readahead)
1631         {
1632                 print_flag(get_readahead,"fs readahead", Xreadahead);
1633                 bb_ioctl(fd, BLKRASET,(int *)Xreadahead,"BLKRASET");
1634         }
1635 #ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF
1636         if (unregister_hwif)
1637         {
1638                 printf(" attempting to unregister hwif#%lu\n", hwif);
1639                 bb_ioctl(fd, HDIO_UNREGISTER_HWIF,(int *)(unsigned long)hwif,"HDIO_UNREGISTER_HWIF");
1640         }
1641 #endif
1642 #ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF
1643         if (scan_hwif)
1644         {
1645                 printf(" attempting to scan hwif (0x%lx, 0x%lx, %lu)\n", hwif_data, hwif_ctrl, hwif_irq);
1646                 args[0] = hwif_data;
1647                 args[1] = hwif_ctrl;
1648                 args[2] = hwif_irq;
1649                 bb_ioctl(fd, HDIO_SCAN_HWIF, args, "HDIO_SCAN_HWIF");
1650                 args[0] = WIN_SETFEATURES;
1651                 args[1] = 0;
1652         }
1653 #endif
1654         if (set_piomode)
1655         {
1656                 if (noisy_piomode)
1657                 {
1658                         printf(" attempting to ");
1659                         if (piomode == 255)
1660                                 printf("auto-tune PIO mode\n");
1661                         else if (piomode < 100)
1662                                 printf("set PIO mode to %d\n", piomode);
1663                         else if (piomode < 200)
1664                                 printf("set MDMA mode to %d\n", (piomode-100));
1665                         else
1666                                 printf("set UDMA mode to %d\n", (piomode-200));
1667                 }
1668                 bb_ioctl(fd, HDIO_SET_PIO_MODE, (int *)(unsigned long)piomode, "HDIO_SET_PIO_MODE");
1669         }
1670         if (set_io32bit)
1671         {
1672                 print_flag(get_io32bit,"32-bit IO_support flag", io32bit);
1673                 bb_ioctl(fd, HDIO_SET_32BIT, (int *)io32bit, "HDIO_SET_32BIT");
1674         }
1675         if (set_mult)
1676         {
1677                 print_flag(get_mult, "multcount", mult);
1678 #ifdef HDIO_DRIVE_CMD
1679                 bb_ioctl(fd, HDIO_SET_MULTCOUNT, &mult, "HDIO_SET_MULTCOUNT");
1680 #else
1681                 force_operation |= (!bb_ioctl(fd, HDIO_SET_MULTCOUNT, &mult, "HDIO_SET_MULTCOUNT"));
1682 #endif
1683         }
1684         if (set_readonly)
1685         {
1686                 print_flag_on_off(get_readonly,"readonly", readonly);
1687                 bb_ioctl(fd, BLKROSET, &readonly, "BLKROSET");
1688         }
1689         if (set_unmask)
1690         {
1691                 print_flag_on_off(get_unmask,"unmaskirq", unmask);
1692                 bb_ioctl(fd, HDIO_SET_UNMASKINTR, (int *)unmask, "HDIO_SET_UNMASKINTR");
1693         }
1694 #ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA
1695         if (set_dma)
1696         {
1697                 print_flag_on_off(get_dma, "using_dma", dma);
1698                 bb_ioctl(fd, HDIO_SET_DMA, (int *)dma, "HDIO_SET_DMA");
1699         }
1700 #endif /* CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA */
1701         if (set_dma_q)
1702         {
1703                 print_flag_on_off(get_dma_q,"DMA queue_depth", dma_q);
1704                 bb_ioctl(fd, HDIO_SET_QDMA, (int *)dma_q, "HDIO_SET_QDMA");
1705         }
1706         if (set_nowerr)
1707         {
1708                 print_flag_on_off(get_nowerr,"nowerr", nowerr);
1709                 bb_ioctl(fd, HDIO_SET_NOWERR, (int *)nowerr,"HDIO_SET_NOWERR");
1710         }
1711         if (set_keep)
1712         {
1713                 print_flag_on_off(get_keep,"keep_settings", keep);
1714                 bb_ioctl(fd, HDIO_SET_KEEPSETTINGS, (int *)keep,"HDIO_SET_KEEPSETTINGS");
1715         }
1716 #ifdef HDIO_DRIVE_CMD
1717         if (set_doorlock)
1718         {
1719                 args[0] = doorlock ? WIN_DOORLOCK : WIN_DOORUNLOCK;
1720                 args[2] = 0;
1721                 print_flag_on_off(get_doorlock,"drive doorlock", doorlock);
1722                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(doorlock)");
1723                 args[0] = WIN_SETFEATURES;
1724         }
1725         if (set_dkeep)
1726         {
1727                 /* lock/unlock the drive's "feature" settings */
1728                 print_flag_on_off(get_dkeep,"drive keep features", dkeep);
1729                 args[2] = dkeep ? 0x66 : 0xcc;
1730                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(keepsettings)");
1731         }
1732         if (set_defects)
1733         {
1734                 args[2] = defects ? 0x04 : 0x84;
1735                 print_flag(get_defects,"drive defect-mgmt", defects);
1736                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(defectmgmt)");
1737         }
1738         if (set_prefetch)
1739         {
1740                 args[1] = prefetch;
1741                 args[2] = 0xab;
1742                 print_flag(get_prefetch,"drive prefetch", prefetch);
1743                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setprefetch)");
1744                 args[1] = 0;
1745         }
1746         if (set_xfermode)
1747         {
1748                 args[1] = xfermode_requested;
1749                 args[2] = 3;
1750                 if (get_xfermode)
1751                 {
1752                         print_flag(1,"xfermode", xfermode_requested);
1753                         interpret_xfermode(xfermode_requested);
1754                 }
1755                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(setxfermode)");
1756                 args[1] = 0;
1757         }
1758         if (set_lookahead)
1759         {
1760                 args[2] = lookahead ? 0xaa : 0x55;
1761                 print_flag_on_off(get_lookahead,"drive read-lookahead", lookahead);
1762                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setreadahead)");
1763         }
1764         if (set_apmmode)
1765         {
1766                 args[2] = (apmmode == 255) ? 0x85 /* disable */ : 0x05 /* set */; /* feature register */
1767                 args[1] = apmmode; /* sector count register 1-255 */
1768                 if (get_apmmode)
1769                         printf(" setting APM level to %s 0x%02lX (%ld)\n", (apmmode == 255) ? "disabled" : "", apmmode, apmmode);
1770                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD");
1771                 args[1] = 0;
1772         }
1773         if (set_wcache)
1774         {
1775 #ifdef DO_FLUSHCACHE
1776 #ifndef WIN_FLUSHCACHE
1777 #define WIN_FLUSHCACHE 0xe7
1778 #endif
1779                 static unsigned char flushcache[4] = {WIN_FLUSHCACHE,0,0,0};
1780 #endif /* DO_FLUSHCACHE */
1781                 args[2] = wcache ? 0x02 : 0x82;
1782                 print_flag_on_off(get_wcache,"drive write-caching", wcache);
1783 #ifdef DO_FLUSHCACHE
1784                 if (!wcache)
1785                         bb_ioctl(fd, HDIO_DRIVE_CMD, &flushcache, "HDIO_DRIVE_CMD(flushcache)");
1786 #endif /* DO_FLUSHCACHE */
1787                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setcache)");
1788 #ifdef DO_FLUSHCACHE
1789                 if (!wcache)
1790                         bb_ioctl(fd, HDIO_DRIVE_CMD, &flushcache, "HDIO_DRIVE_CMD(flushcache)");
1791 #endif /* DO_FLUSHCACHE */
1792         }
1793
1794         /* In code below, we do not preserve args[0], but the rest
1795            is preserved, including args[2] */
1796         args[2] = 0;
1797
1798         if (set_standbynow)
1799         {
1800 #ifndef WIN_STANDBYNOW1
1801 #define WIN_STANDBYNOW1 0xE0
1802 #endif
1803 #ifndef WIN_STANDBYNOW2
1804 #define WIN_STANDBYNOW2 0x94
1805 #endif
1806                 if (get_standbynow) printf(" issuing standby command\n");
1807                 args[0] = WIN_STANDBYNOW1;
1808                 bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_STANDBYNOW2, "HDIO_DRIVE_CMD(standby)");
1809         }
1810         if (set_sleepnow)
1811         {
1812 #ifndef WIN_SLEEPNOW1
1813 #define WIN_SLEEPNOW1 0xE6
1814 #endif
1815 #ifndef WIN_SLEEPNOW2
1816 #define WIN_SLEEPNOW2 0x99
1817 #endif
1818                 if (get_sleepnow) printf(" issuing sleep command\n");
1819                 args[0] = WIN_SLEEPNOW1;
1820                 bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_SLEEPNOW2, "HDIO_DRIVE_CMD(sleep)");
1821         }
1822         if (set_seagate)
1823         {
1824                 args[0] = 0xfb;
1825                 if (get_seagate) printf(" disabling Seagate auto powersaving mode\n");
1826                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(seagatepwrsave)");
1827         }
1828         if (set_standby)
1829         {
1830                 args[0] = WIN_SETIDLE1;
1831                 args[1] = standby_requested;
1832                 if (get_standby)
1833                 {
1834                         print_flag(1,"standby", standby_requested);
1835                         interpret_standby(standby_requested);
1836                 }
1837                 bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setidle1)");
1838                 args[1] = 0;
1839         }
1840 #else   /* HDIO_DRIVE_CMD */
1841         if (force_operation)
1842         {
1843                 char buf[512];
1844                 flush_buffer_cache(fd);
1845                 if (-1 == read(fd, buf, sizeof(buf)))
1846                         bb_perror_msg("read(%d bytes) failed (rc=%d)", sizeof(buf), -1);
1847         }
1848 #endif  /* HDIO_DRIVE_CMD */
1849
1850         if (get_mult || get_identity)
1851         {
1852                 multcount = -1;
1853                 if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount))
1854                 {
1855                         if (get_mult)
1856                                 bb_perror_msg("HDIO_GET_MULTCOUNT");
1857                 }
1858                 else if (get_mult)
1859                 {
1860                         printf(fmt, "multcount", multcount);
1861                         on_off(multcount);
1862                 }
1863         }
1864         if (get_io32bit)
1865         {
1866                 if (!bb_ioctl(fd, HDIO_GET_32BIT, &parm, "HDIO_GET_32BIT"))
1867                 {
1868                         printf(" IO_support\t=%3ld (", parm);
1869                         if (parm == 0)
1870                                 printf("default 16-bit)\n");
1871                         else if (parm == 2)
1872                                 printf("16-bit)\n");
1873                         else if (parm == 1)
1874                                 printf("32-bit)\n");
1875                         else if (parm == 3)
1876                                 printf("32-bit w/sync)\n");
1877                         else if (parm == 8)
1878                                 printf("Request-Queue-Bypass)\n");
1879                         else
1880                                 printf("\?\?\?)\n");
1881                 }
1882         }
1883         if (get_unmask)
1884         {
1885                 bb_ioctl_on_off(fd, HDIO_GET_UNMASKINTR,(unsigned long *)parm,
1886                                                 "HDIO_GET_UNMASKINTR","unmaskirq");
1887         }
1888
1889
1890 #ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA
1891         if (get_dma) {
1892                 if (!bb_ioctl(fd, HDIO_GET_DMA, &parm, "HDIO_GET_DMA"))
1893                 {
1894                         printf(fmt, "using_dma", parm);
1895                         if (parm == 8)
1896                                 printf(" (DMA-Assisted-PIO)\n");
1897                         else
1898                                 on_off(parm);
1899                 }
1900         }
1901 #endif
1902         if (get_dma_q)
1903         {
1904                 bb_ioctl_on_off (fd, HDIO_GET_QDMA,(unsigned long *)parm,
1905                                                   "HDIO_GET_QDMA","queue_depth");
1906         }
1907         if (get_keep)
1908         {
1909                 bb_ioctl_on_off (fd, HDIO_GET_KEEPSETTINGS,(unsigned long *)parm,
1910                                                         "HDIO_GET_KEEPSETTINGS","keepsettings");
1911         }
1912
1913         if (get_nowerr)
1914         {
1915                 bb_ioctl_on_off  (fd, HDIO_GET_NOWERR,(unsigned long *)&parm,
1916                                                         "HDIO_GET_NOWERR","nowerr");
1917         }
1918         if (get_readonly)
1919         {
1920                 bb_ioctl_on_off(fd, BLKROGET,(unsigned long *)parm,
1921                                                   "BLKROGET","readonly");
1922         }
1923         if (get_readahead)
1924         {
1925                 bb_ioctl_on_off (fd, BLKRAGET, (unsigned long *) parm,
1926                                                         "BLKRAGET","readahead");
1927         }
1928         if (get_geom)
1929         {
1930                 if (!bb_ioctl(fd, BLKGETSIZE, &parm, "BLKGETSIZE"))
1931                 {
1932                         struct hd_geometry g;
1933
1934                         if (!bb_ioctl(fd, HDIO_GETGEO, &g, "HDIO_GETGEO"))
1935                                 printf(" geometry\t= %u/%u/%u, sectors = %ld, start = %ld\n",
1936                                                 g.cylinders, g.heads, g.sectors, parm, g.start);
1937                 }
1938         }
1939 #ifdef HDIO_DRIVE_CMD
1940         if (get_powermode)
1941         {
1942 #ifndef WIN_CHECKPOWERMODE1
1943 #define WIN_CHECKPOWERMODE1 0xE5
1944 #endif
1945 #ifndef WIN_CHECKPOWERMODE2
1946 #define WIN_CHECKPOWERMODE2 0x98
1947 #endif
1948                 const char *state;
1949
1950                 args[0] = WIN_CHECKPOWERMODE1;
1951                 if (bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_CHECKPOWERMODE2, 0))
1952                 {
1953                         if (errno != EIO || args[0] != 0 || args[1] != 0)
1954                                 state = "Unknown";
1955                         else
1956                                 state = "sleeping";
1957                 }
1958                 else
1959                         state = (args[2] == 255) ? "active/idle" : "standby";
1960                 args[1] = args[2] = 0;
1961
1962                 printf(" drive state is:  %s\n", state);
1963         }
1964 #endif
1965 #ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET
1966         if (perform_reset)
1967         {
1968                 bb_ioctl(fd, HDIO_DRIVE_RESET, NULL, "HDIO_DRIVE_RESET");
1969         }
1970 #endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */
1971 #ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
1972         if (perform_tristate)
1973         {
1974                 args[0] = 0;
1975                 args[1] = tristate;
1976                 bb_ioctl(fd, HDIO_TRISTATE_HWIF, &args, "HDIO_TRISTATE_HWIF");
1977         }
1978 #endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */
1979 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
1980         if (get_identity)
1981         {
1982                 static struct hd_driveid id;
1983
1984                 if (!ioctl(fd, HDIO_GET_IDENTITY, &id))
1985                 {
1986                         if (multcount != -1)
1987                         {
1988                                 id.multsect = multcount;
1989                                 id.multsect_valid |= 1;
1990                         }
1991                         else
1992                                 id.multsect_valid &= ~1;
1993                         dump_identity(&id);
1994                 }
1995                 else if (errno == -ENOMSG)
1996                         printf(" no identification info available\n");
1997                 else
1998                         bb_perror_msg("HDIO_GET_IDENTITY");
1999         }
2000
2001         if (get_IDentity)
2002         {
2003                 unsigned char args1[4+512]; /* = { ... } will eat 0.5k of rodata! */
2004                 unsigned i;
2005
2006                 memset(args1, 0, sizeof(args1));
2007                 args1[0] = WIN_IDENTIFY;
2008                 args1[3] = 1;
2009                 if (!bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args1, WIN_PIDENTIFY, "HDIO_DRIVE_CMD(identify)")) {
2010                         for (i=0; i<(sizeof args1)/2; i+=2)
2011                                 __le16_to_cpus((uint16_t *)(&args1[i]));
2012                         identify((void *)&args1[4]);
2013                 }
2014         }
2015 #endif
2016 #ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF
2017         if (set_busstate)
2018         {
2019                 if (get_busstate)
2020                 {
2021                         print_flag(1, "bus state", busstate);
2022                         bus_state_value(busstate);
2023                 }
2024                 bb_ioctl(fd, HDIO_SET_BUSSTATE, (int *)(unsigned long)busstate, "HDIO_SET_BUSSTATE");
2025         }
2026         if (get_busstate)
2027         {
2028                 if (!bb_ioctl(fd, HDIO_GET_BUSSTATE, &parm, "HDIO_GET_BUSSTATE"))
2029                 {
2030                         printf(fmt, "bus state", parm);
2031                         bus_state_value(parm);
2032                 }
2033         }
2034 #endif
2035         if (reread_partn)
2036                 bb_ioctl(fd, BLKRRPART, NULL, "BLKRRPART");
2037
2038
2039         if (do_ctimings)
2040                 do_time(0,fd);          /*time cache  */
2041         if (do_timings)
2042                 do_time(1,fd);          /*time device */
2043         if (do_flush)
2044                 flush_buffer_cache(fd);
2045         close(fd);
2046 }
2047
2048 #ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY
2049 static int fromhex(unsigned char c)
2050 {
2051         if (c >= 'a' && c <= 'f')
2052                 return 10 + (c - 'a');
2053         if (c >= '0' && c <= '9')
2054                 return (c - '0');
2055         bb_error_msg_and_die("bad char: '%c' 0x%02x", c, c);
2056 }
2057
2058 static void identify_from_stdin(void)
2059 {
2060         unsigned short sbuf[800];
2061         unsigned char  buf[1600], *b = (unsigned char *)buf;
2062         int i, count = read(0, buf, 1280);
2063
2064         if (count != 1280)
2065                 bb_error_msg_and_die("read(%d bytes) failed (rc=%d)", 1280, count);
2066
2067         for (i = 0; count >= 4; ++i)
2068         {
2069                 sbuf[i] = (fromhex(b[0]) << 12) | (fromhex(b[1]) << 8) | (fromhex(b[2]) << 4) | fromhex(b[3]);
2070                 __le16_to_cpus((uint16_t *)(&sbuf[i]));
2071                 b += 5;
2072                 count -= 5;
2073         }
2074         identify(sbuf);
2075 }
2076 #endif
2077
2078 /* busybox specific stuff */
2079 static void parse_opts(unsigned long *get, unsigned long *set, unsigned long *value, int min, int max)
2080 {
2081                 if (get) {
2082                         *get = 1;
2083                 }
2084                 if (optarg) {
2085                         *set = 1;
2086                         *value = bb_xgetlarg(optarg, 10, min, max);
2087                 }
2088 }
2089
2090 static void parse_xfermode(int flag, unsigned long *get, unsigned long *set, int *value)
2091 {
2092         if (flag) {
2093                 *get = 1;
2094                 if (optarg) {
2095                         *set = ((*value = translate_xfermode(optarg)) > -1);
2096                 }
2097         }
2098 }
2099
2100 /*-------------------------------------*/
2101 /* getopt long options */
2102 #if ENABLE_FEATURE_HDPARM_GET_IDENTITY
2103 static const struct option HDPARM_LONG_OPT[] =
2104 {
2105         {"Istdin", 0, NULL, '\256'},
2106         {NULL, 0, NULL, 0}
2107 };
2108 #else
2109 #define HDPARM_LONG_OPT                 NULL
2110 #endif
2111 /*-------------------------------------*/
2112 /* getopt short options */
2113 static const char hdparm_options[]=     "gfu::n::p:r::m::c::k::a::B:tTh"\
2114         USE_FEATURE_HDPARM_GET_IDENTITY("\256iI")
2115         USE_FEATURE_HDPARM_HDIO_GETSET_DMA("d::")
2116 #ifdef HDIO_DRIVE_CMD
2117                                                                         "S::D::P::X::K::A::L::W::CyYzZ"
2118 #endif
2119         USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF("U:")
2120 #ifdef HDIO_GET_QDMA
2121 #ifdef HDIO_SET_QDMA
2122                                                                         "Q:"
2123 #else
2124                                                                         "Q"
2125 #endif
2126 #endif
2127         USE_FEATURE_HDPARM_HDIO_DRIVE_RESET("w")
2128         USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF("x::b:")
2129         USE_FEATURE_HDPARM_HDIO_SCAN_HWIF("R:");
2130 /*-------------------------------------*/
2131
2132 /* our main() routine: */
2133 int hdparm_main(int argc, char **argv) ATTRIBUTE_NORETURN;
2134 int hdparm_main(int argc, char **argv)
2135 {
2136         int c;
2137         int flagcount = 0;
2138
2139         while ((c = getopt_long (argc, argv, hdparm_options, HDPARM_LONG_OPT , NULL)) >= 0) {
2140                 flagcount++;
2141 #if ENABLE_FEATURE_HDPARM_GET_IDENTITY
2142                 if (c == '\256') {
2143                         identify_from_stdin(); /* EXIT */
2144                 }
2145 #endif
2146                 USE_FEATURE_HDPARM_GET_IDENTITY(get_IDentity = (c == 'I'));
2147                 USE_FEATURE_HDPARM_GET_IDENTITY(get_identity = (c == 'i'));
2148                 get_geom |= (c == 'g');
2149                 do_flush |= (c == 'f');
2150                 if (c == 'u') parse_opts(&get_unmask, &set_unmask, &unmask, 0, 1);
2151                 USE_FEATURE_HDPARM_HDIO_GETSET_DMA(if (c == 'd') parse_opts(&get_dma, &set_dma, &dma, 0, 9));
2152                 if (c == 'n') parse_opts(&get_nowerr, &set_nowerr, &nowerr, 0, 1);
2153                 parse_xfermode((c == 'p'),&noisy_piomode, &set_piomode, &piomode);
2154                 if (c == 'r') parse_opts(&get_readonly, &set_readonly, &readonly, 0, 1);
2155                 if (c == 'm') parse_opts(&get_mult, &set_mult, &mult, 0, INT_MAX /*32*/);
2156                 if (c == 'c') parse_opts(&get_io32bit, &set_io32bit, &io32bit, 0, INT_MAX /*8*/);
2157                 if (c == 'k') parse_opts(&get_keep, &set_keep, &keep, 0, 1);
2158                 if (c == 'a') parse_opts(&get_readahead, &set_readahead, &Xreadahead, 0, INT_MAX);
2159                 if (c == 'B') parse_opts(&get_apmmode, &set_apmmode, &apmmode, 1, 255);
2160                 do_flush |= do_timings |= (c == 't');
2161                 do_flush |= do_ctimings |= (c == 'T');
2162 #ifdef HDIO_DRIVE_CMD
2163                 if (c == 'S') parse_opts(&get_standby, &set_standby, &standby_requested, 0, INT_MAX);   
2164                 if (c == 'D') parse_opts(&get_defects, &set_defects, &defects, 0, INT_MAX);
2165                 if (c == 'P') parse_opts(&get_prefetch, &set_prefetch, &prefetch, 0, INT_MAX);
2166                 parse_xfermode((c == 'X'), &get_xfermode, &set_xfermode, &xfermode_requested);
2167                 if (c == 'K') parse_opts(&get_dkeep, &set_dkeep, &prefetch, 0, 1);
2168                 if (c == 'A') parse_opts(&get_lookahead, &set_lookahead, &lookahead, 0, 1);
2169                 if (c == 'L') parse_opts(&get_doorlock, &set_doorlock, &doorlock, 0, 1);
2170                 if (c == 'W') parse_opts(&get_wcache, &set_wcache, &wcache, 0, 1);
2171                 get_powermode |= (c == 'C');
2172                 get_standbynow = set_standbynow |= (c == 'y');
2173                 get_sleepnow = set_sleepnow |= (c == 'Y');
2174                 reread_partn |= (c == 'z');
2175                 get_seagate = set_seagate |= (c == 'Z');
2176 #endif
2177                 USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF(if (c == 'U') parse_opts(NULL, &unregister_hwif, &hwif, 0, INT_MAX));   
2178 #ifdef HDIO_GET_QDMA
2179                 if (c == 'Q') {
2180 #ifdef HDIO_SET_QDMA
2181                         parse_opts(&get_dma_q, &set_dma_q, &dma_q, 0, INT_MAX);
2182 #else
2183                         parse_opts(&get_dma_q, NULL, NULL, 0, 0);       
2184 #endif
2185                 }
2186 #endif          
2187                 USE_FEATURE_HDPARM_HDIO_DRIVE_RESET(perform_reset = (c == 'r'));
2188                 USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'x') parse_opts(NULL, &perform_tristate, &tristate, 0, 1));      
2189                 USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'b') parse_opts(&get_busstate, &set_busstate, &busstate, 0, 2)); 
2190 #if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF
2191                 if (c == 'R') {
2192                         parse_opts(NULL, &scan_hwif, &hwif_data, 0, INT_MAX);   
2193                         hwif_ctrl =  bb_xgetlarg((argv[optind]) ? argv[optind] : "", 10, 0, INT_MAX);
2194                         hwif_irq  =  bb_xgetlarg((argv[optind+1]) ? argv[optind+1] : "", 10, 0, INT_MAX);
2195                         /* Move past the 2 additional arguments */
2196                         argv += 2;
2197                         argc -= 2;
2198                 }
2199 #endif
2200         }
2201         /* When no flags are given (flagcount = 0), -acdgkmnru is assumed. */
2202         if (!flagcount){
2203                 get_mult = get_io32bit = get_unmask = get_keep = get_readonly = get_readahead = get_geom = 1;
2204                 USE_FEATURE_HDPARM_HDIO_GETSET_DMA(get_dma = 1);
2205         }
2206         argc -= optind;
2207         argv += optind;
2208
2209         if (argc < 1) {
2210                 bb_show_usage();
2211         }
2212
2213         while (argc--) {
2214                 process_dev(*argv);
2215                 argv++;
2216         }
2217         exit(EXIT_SUCCESS);
2218 }