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