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