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