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