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