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