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