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