• Home
  • History
  • Annotate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/ap/gpl/hdparm-9.43/

Lines Matching defs:*

2  * hdparm.c - Command line interface to get/set hard disk parameters.
3 * - by Mark Lord (C) 1994-2012 -- freely distributable.
5 #define _LARGEFILE64_SOURCE /*for lseek64*/
6 #define _BSD_SOURCE /* for strtoll() */
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #define __USE_GNU /* for O_DIRECT */
11 #include <string.h>
12 #include <fcntl.h>
13 #include <errno.h>
14 #include <ctype.h>
15 #include <endian.h>
16 #include <sys/ioctl.h>
17 #include <sys/stat.h>
18 #include <sys/sysmacros.h>
19 #include <sys/time.h>
20 #include <sys/times.h>
21 #include <sys/types.h>
22 #include <sys/mount.h>
23 #include <sys/mman.h>
24 #include <sys/user.h>
25 #include <linux/types.h>
26 #include <linux/fs.h>
27 #include <linux/major.h>
28 #include <endian.h>
29 #include <asm/byteorder.h>
31 #include "hdparm.h"
32 #include "sgio.h"
34 static int argc;
35 static char **argv;
36 static char *argp;
37 static int num_flags_processed = 0;
39 extern const char *minor_str[];
41 #define VERSION "v9.43"
43 #ifndef O_DIRECT
44 #define O_DIRECT 040000 /* direct disk access, not easily obtained from headers */
45 #endif
47 #ifndef CDROM_SELECT_SPEED /* already defined in 2.3.xx kernels and above */
48 #define CDROM_SELECT_SPEED 0x5322
49 #endif
51 #define TIMING_BUF_MB 2
52 #define TIMING_BUF_BYTES (TIMING_BUF_MB * 1024 * 1024)
54 char *progname;
55 int verbose = 0;
56 int prefer_ata12 = 0;
57 static int do_defaults = 0, do_flush = 0, do_ctimings, do_timings = 0;
58 static int do_identity = 0, get_geom = 0, noisy = 1, quiet = 0;
59 static int do_flush_wcache = 0;
61 static int set_wdidle3 = 0, get_wdidle3 = 0, wdidle3 = 0;
62 static int set_timings_offset = 0;
63 static __u64 timings_offset = 0;
64 static int set_fsreadahead= 0, get_fsreadahead= 0, fsreadahead= 0;
65 static int set_readonly = 0, get_readonly = 0, readonly = 0;
66 static int set_unmask = 0, get_unmask = 0, unmask = 0;
67 static int set_mult = 0, get_mult = 0, mult = 0;
68 static int set_dma = 0, get_dma = 0, dma = 0;
69 static int set_dma_q = 0, get_dma_q = 0, dma_q = 0;
70 static int set_nowerr = 0, get_nowerr = 0, nowerr = 0;
71 static int set_keep = 0, get_keep = 0, keep = 0;
72 static int set_io32bit = 0, get_io32bit = 0, io32bit = 0;
73 static int set_piomode = 0, get_piomode= 0, piomode = 0;
74 static int set_dkeep = 0, get_dkeep = 0, dkeep = 0;
75 static int set_standby = 0, get_standby = 0, standby= 0;
76 static int set_xfermode = 0, get_xfermode = 0;
77 static int xfermode_requested= 0;
78 static int set_lookahead= 0, get_lookahead= 0, lookahead= 0;
79 static int set_prefetch = 0, get_prefetch = 0, prefetch = 0;
80 static int set_defects = 0, get_defects = 0, defects = 0;
81 static int set_wcache = 0, get_wcache = 0, wcache = 0;
82 static int set_doorlock = 0, get_doorlock = 0, doorlock = 0;
83 static int set_seagate = 0, get_seagate = 0;
84 static int get_idleimmediate = 0, set_idleimmediate = 0;
85 static int get_idleunload = 0, set_idleunload = 0;
86 static int set_standbynow = 0, get_standbynow = 0;
87 static int set_sleepnow = 0, get_sleepnow = 0;
88 static int set_powerup_in_standby = 0, get_powerup_in_standby = 0, powerup_in_standby = 0;
89 static int get_hitachi_temp = 0, set_hitachi_temp = 0;
90 static int security_freeze = 0;
91 static int security_master = 0, security_mode = 0;
92 static int enhanced_erase = 0;
93 static int set_security = 0;
94 static int do_dco_freeze = 0, do_dco_restore = 0, do_dco_identify = 0;
95 static unsigned int security_command = ATA_OP_SECURITY_UNLOCK;
97 static char security_password[33], *fwpath;
99 static int get_powermode = 0, set_powermode = 0;
100 static int set_apmmode = 0, get_apmmode= 0, apmmode = 0;
101 static int get_cdromspeed = 0, set_cdromspeed = 0, cdromspeed = 0;
102 static int do_IDentity = 0, drq_hsm_error = 0;
103 static int do_fwdownload = 0, xfer_mode = 0;
104 static int set_busstate = 0, get_busstate = 0, busstate = 0;
105 static int set_reread_partn = 0, get_reread_partn;
106 static int set_acoustic = 0, get_acoustic = 0, acoustic = 0;
107 static int write_read_verify = 0, get_write_read_verify = 0, set_write_read_verify = 0;
109 static int make_bad_sector = 0, make_bad_sector_flagged;
110 static __u64 make_bad_sector_addr = ~0ULL;
112 #ifdef FORMAT_AND_ERASE
113 static int format_track = 0;
114 static __u64 format_track_addr = ~0ULL;
116 static int erase_sectors = 0;
117 static __u64 erase_sectors_addr = ~0ULL;
118 #endif
120 static struct sector_range_s *trim_sector_ranges = NULL;
121 static int trim_sector_ranges_count = 0;
122 static int trim_from_stdin = 0;
124 static int write_sector = 0;
125 static __u64 write_sector_addr = ~0ULL;
127 static int read_sector = 0;
128 static __u64 read_sector_addr = ~0ULL;
130 static int set_max_sectors = 0, set_max_permanent, get_native_max_sectors = 0;
131 static __u64 set_max_addr = 0;
133 static int get_doreset = 0, set_doreset = 0;
134 static int i_know_what_i_am_doing = 0;
135 static int please_destroy_my_drive = 0;
137 const int timeout_15secs = 15;
138 const int timeout_60secs = 60;
139 const int timeout_5mins = (5 * 60);
140 const int timeout_2hrs = (2 * 60 * 60);
142 static int open_flags = O_RDONLY|O_NONBLOCK;
144 // Historically, if there was no HDIO_OBSOLETE_IDENTITY, then
145 // then the HDIO_GET_IDENTITY only returned 142 bytes.
146 // Otherwise, HDIO_OBSOLETE_IDENTITY returns 142 bytes,
147 // and HDIO_GET_IDENTITY returns 512 bytes. But the latest
148 // 2.5.xx kernels no longer define HDIO_OBSOLETE_IDENTITY
149 // (which they should, but they should just return -EINVAL).
151 // So.. we must now assume that HDIO_GET_IDENTITY returns 512 bytes.
152 // On a really old system, it will not, and we will be confused.
153 // Too bad, really.
155 const char *cfg_str[] =
156 { "", " HardSect", " SoftSect", " NotMFM",
157 " HdSw>15uSec", " SpinMotCtl", " Fixed", " Removeable",
158 " DTR<=5Mbs", " DTR>5Mbs", " DTR>10Mbs", " RotSpdTol>.5%",
159 " dStbOff", " TrkOff", " FmtGapReq", " nonMagnetic"
162 const char *SlowMedFast[] = {"slow", "medium", "fast", "eide", "ata"};
163 const char *BuffType[4] = {"unknown", "1Sect", "DualPort", "DualPortCache"};
165 #define YN(b) (((b)==0)?"no":"yes")
167 static void on_off (unsigned int value)
169 printf(value ? " (on)\n" : " (off)\n");
172 #ifndef ENOIOCTLCMD
173 #define ENOIOCTLCMD ENOTTY
174 #endif
176 static void flush_buffer_cache (int fd)
178 sync();
179 fsync(fd); /* flush buffers */
180 fdatasync(fd); /* flush buffers */
181 sync();
182 if (ioctl(fd, BLKFLSBUF, NULL)) /* do it again, big time */
183 perror("BLKFLSBUF failed");
184 else
185 do_drive_cmd(fd, NULL, 0); /* IDE: await completion */
186 sync();
189 static int seek_to_zero (int fd)
191 if (lseek(fd, (off_t) 0, SEEK_SET)) {
192 perror("lseek() failed");
193 return 1;
195 return 0;
198 static int read_big_block (int fd, char *buf)
200 int i, rc;
201 if ((rc = read(fd, buf, TIMING_BUF_BYTES)) != TIMING_BUF_BYTES) {
202 if (rc) {
203 if (rc == -1)
204 perror("read() failed");
205 else
206 fprintf(stderr, "read(%u) returned %u bytes\n", TIMING_BUF_BYTES, rc);
207 } else {
208 fputs ("read() hit EOF - device too small\n", stderr);
210 return 1;
212 /* access all sectors of buf to ensure the read fully completed */
213 for (i = 0; i < TIMING_BUF_BYTES; i += 512)
214 buf[i] &= 1;
215 return 0;
218 static void *prepare_timing_buf (unsigned int len)
220 unsigned int i;
221 __u8 *buf;
223 buf = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
224 if (buf == MAP_FAILED) {
225 perror("could not allocate timing buf");
226 return NULL;
228 for (i = 0; i < len; i += 4096)
229 buf[i] = 0; /* guarantee memory is present/assigned */
230 if (-1 == mlock(buf, len)) {
231 perror("mlock() failed on timing buf");
232 munmap(buf, len);
233 return NULL;
235 mlockall(MCL_CURRENT|MCL_FUTURE); // don't care if this fails on low-memory machines
236 sync();
238 /* give time for I/O to settle */
239 sleep(3);
240 return buf;
243 static void time_cache (int fd)
245 char *buf;
246 struct itimerval e1, e2;
247 double elapsed, elapsed2;
248 unsigned int iterations, total_MB;
250 buf = prepare_timing_buf(TIMING_BUF_BYTES);
251 if (!buf)
252 return;
255 * getitimer() is used rather than gettimeofday() because
256 * it is much more consistent (on my machine, at least).
258 setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL);
259 if (seek_to_zero (fd)) return;
260 if (read_big_block (fd, buf)) return;
261 printf(" Timing %scached reads: ", (open_flags & O_DIRECT) ? "O_DIRECT " : "");
262 fflush(stdout);
264 /* Clear out the device request queues & give them time to complete */
265 flush_buffer_cache(fd);
266 sleep(1);
268 /* Now do the timing */
269 iterations = 0;
270 getitimer(ITIMER_REAL, &e1);
271 do {
272 ++iterations;
273 if (seek_to_zero (fd) || read_big_block (fd, buf))
274 goto quit;
275 getitimer(ITIMER_REAL, &e2);
276 elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec)
277 + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
278 } while (elapsed < 2.0);
279 total_MB = iterations * TIMING_BUF_MB;
281 elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec)
282 + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
284 /* Now remove the lseek() and getitimer() overheads from the elapsed time */
285 getitimer(ITIMER_REAL, &e1);
286 do {
287 if (seek_to_zero (fd))
288 goto quit;
289 getitimer(ITIMER_REAL, &e2);
290 elapsed2 = (e1.it_value.tv_sec - e2.it_value.tv_sec)
291 + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
292 } while (--iterations);
294 elapsed -= elapsed2;
296 if (total_MB >= elapsed) /* more than 1MB/s */
297 printf("%3u MB in %5.2f seconds = %6.2f MB/sec\n",
298 total_MB, elapsed,
299 total_MB / elapsed);
300 else
301 printf("%3u MB in %5.2f seconds = %6.2f kB/sec\n",
302 total_MB, elapsed,
303 total_MB / elapsed * 1024);
305 flush_buffer_cache(fd);
306 sleep(1);
307 quit:
308 munlockall();
309 munmap(buf, TIMING_BUF_BYTES);
312 static int time_device (int fd)
314 char *buf;
315 double elapsed;
316 struct itimerval e1, e2;
317 int err = 0;
318 unsigned int max_iterations = 1024, total_MB, iterations;
321 * get device size
323 if (do_ctimings || do_timings) {
324 __u64 nsectors;
325 do_flush = 1;
326 err = get_dev_geometry(fd, NULL, NULL, NULL, NULL, &nsectors);
327 if (!err)
328 max_iterations = nsectors / (2 * 1024) / TIMING_BUF_MB;
330 buf = prepare_timing_buf(TIMING_BUF_BYTES);
331 if (!buf)
332 err = ENOMEM;
333 if (err)
334 goto quit;
336 printf(" Timing %s disk reads", (open_flags & O_DIRECT) ? "O_DIRECT" : "buffered");
337 if (set_timings_offset)
338 printf(" (offset %llu GB)", timings_offset / 0x40000000ULL);
339 printf(": ");
340 fflush(stdout);
342 if (set_timings_offset && lseek64(fd, timings_offset, SEEK_SET) == (off64_t)-1) {
343 err = errno;
344 perror("lseek() failed");
345 goto quit;
349 * getitimer() is used rather than gettimeofday() because
350 * it is much more consistent (on my machine, at least).
352 setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL);
354 /* Now do the timings for real */
355 iterations = 0;
356 getitimer(ITIMER_REAL, &e1);
357 do {
358 ++iterations;
359 if (read_big_block (fd, buf))
360 goto quit;
361 getitimer(ITIMER_REAL, &e2);
362 elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec)
363 + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0);
364 } while (elapsed < 3.0 && iterations < max_iterations);
366 total_MB = iterations * TIMING_BUF_MB;
367 if ((total_MB / elapsed) > 1.0) /* more than 1MB/s */
368 printf("%3u MB in %5.2f seconds = %6.2f MB/sec\n",
369 total_MB, elapsed, total_MB / elapsed);
370 else
371 printf("%3u MB in %5.2f seconds = %6.2f kB/sec\n",
372 total_MB, elapsed, total_MB / elapsed * 1024);
373 quit:
374 munlockall();
375 if (buf)
376 munmap(buf, TIMING_BUF_BYTES);
377 return err;
380 static void dmpstr (const char *prefix, unsigned int i, const char *s[], unsigned int maxi)
382 if (i > maxi)
383 printf("%s%u", prefix, i);
384 else
385 printf("%s%s", prefix, s[i]);
388 static __u16 *id;
389 static void get_identify_data (int fd);
391 static __u64 get_lba_capacity (__u16 *idw)
393 __u64 nsects = ((__u32)idw[58] << 16) | idw[57];
395 if (idw[49] & 0x200) {
396 nsects = ((__u32)idw[61] << 16) | idw[60];
397 if ((idw[83] & 0xc000) == 0x4000 && (idw[86] & 0x0400)) {
398 nsects = (__u64)idw[103] << 48 | (__u64)idw[102] << 32 |
399 (__u64)idw[101] << 16 | idw[100];
402 return nsects;
405 static char *strip (char *s)
407 char *e;
409 while (*s == ' ') ++s;
410 if (*s)
411 for (e = s + strlen(s); *--e == ' '; *e = '\0');
412 return s;
415 static void dump_identity (__u16 *idw)
417 int i;
418 char pmodes[64] = {0,}, dmodes[128]={0,}, umodes[128]={0,};
419 char *model = strip(strndup((char *)&idw[27], 40));
420 char *fwrev = strip(strndup((char *)&idw[23], 8));
421 char *serno = strip(strndup((char *)&idw[10], 20));
422 __u8 tPIO;
424 printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s", model, fwrev, serno);
425 printf("\n Config={");
426 for (i = 0; i <= 15; i++) {
427 if (idw[0] & (1<<i))
428 printf("%s", cfg_str[i]);
430 printf(" }\n");
431 printf(" RawCHS=%u/%u/%u, TrkSize=%u, SectSize=%u, ECCbytes=%u\n",
432 idw[1], idw[3], idw[6], idw[4], idw[5], idw[22]);
433 dmpstr(" BuffType=", idw[20], BuffType, 3);
434 if (idw[21] && idw[21] != 0xffff)
435 printf(", BuffSize=%ukB", idw[21] / 2);
436 else
437 printf(", BuffSize=unknown");
438 printf(", MaxMultSect=%u", idw[47] & 0xff);
439 if ((idw[47] & 0xff)) {
440 printf(", MultSect=");
441 if (!(idw[59] & 0x100))
442 printf("?%u?", idw[59] & 0xff);
443 else if (idw[59] & 0xff)
444 printf("%u", idw[59] & 0xff);
445 else
446 printf("off");
448 putchar('\n');
449 tPIO = idw[51] >> 8;
450 if (tPIO <= 5) {
451 strcat(pmodes, "pio0 ");
452 if (tPIO >= 1) strcat(pmodes, "pio1 ");
453 if (tPIO >= 2) strcat(pmodes, "pio2 ");
455 if (!(idw[53] & 1))
456 printf(" (maybe):");
457 printf(" CurCHS=%u/%u/%u, CurSects=%u", idw[54], idw[55], idw[56], idw[57] | (idw[58] << 16));
458 printf(", LBA=%s", YN(idw[49] & 0x200));
459 if (idw[49] & 0x200)
460 printf(", LBAsects=%llu", get_lba_capacity(idw));
462 if (idw[49] & 0x100) {
463 if (idw[62] | idw[63]) {
464 if (idw[62] & 0x100) strcat(dmodes,"*");
465 if (idw[62] & 1) strcat(dmodes,"sdma0 ");
466 if (idw[62] & 0x200) strcat(dmodes,"*");
467 if (idw[62] & 2) strcat(dmodes,"sdma1 ");
468 if (idw[62] & 0x400) strcat(dmodes,"*");
469 if (idw[62] & 4) strcat(dmodes,"sdma2 ");
470 if (idw[62] & 0xf800) strcat(dmodes,"*");
471 if (idw[62] & 0xf8) strcat(dmodes,"sdma? ");
472 if (idw[63] & 0x100) strcat(dmodes,"*");
473 if (idw[63] & 1) strcat(dmodes,"mdma0 ");
474 if (idw[63] & 0x200) strcat(dmodes,"*");
475 if (idw[63] & 2) strcat(dmodes,"mdma1 ");
476 if (idw[63] & 0x400) strcat(dmodes,"*");
477 if (idw[63] & 4) strcat(dmodes,"mdma2 ");
478 if (idw[63] & 0xf800) strcat(dmodes,"*");
479 if (idw[63] & 0xf8) strcat(dmodes,"mdma? ");
482 printf("\n IORDY=");
483 if (idw[49] & 0x800)
484 printf((idw[49] & 0x400) ? "on/off" : "yes");
485 else
486 printf("no");
487 if ((idw[49] & 0x800) || (idw[53] & 2)) {
488 if ((idw[53] & 2)) {
489 printf(", tPIO={min:%u,w/IORDY:%u}", idw[67], idw[68]);
490 if (idw[64] & 1) strcat(pmodes, "pio3 ");
491 if (idw[64] & 2) strcat(pmodes, "pio4 ");
492 if (idw[64] &~3) strcat(pmodes, "pio? ");
494 if (idw[53] & 4) {
495 if (idw[88] & 0x100) strcat(umodes,"*");
496 if (idw[88] & 0x001) strcat(umodes,"udma0 ");
497 if (idw[88] & 0x200) strcat(umodes,"*");
498 if (idw[88] & 0x002) strcat(umodes,"udma1 ");
499 if (idw[88] & 0x400) strcat(umodes,"*");
500 if (idw[88] & 0x004) strcat(umodes,"udma2 ");
501 if (idw[88] & 0x800) strcat(umodes,"*");
502 if (idw[88] & 0x008) strcat(umodes,"udma3 ");
503 if (idw[88] & 0x1000) strcat(umodes,"*");
504 if (idw[88] & 0x010) strcat(umodes,"udma4 ");
505 if (idw[88] & 0x2000) strcat(umodes,"*");
506 if (idw[88] & 0x020) strcat(umodes,"udma5 ");
507 if (idw[88] & 0x4000) strcat(umodes,"*");
508 if (idw[88] & 0x040) strcat(umodes,"udma6 ");
511 if ((idw[49] & 0x100) && (idw[53] & 2))
512 printf(", tDMA={min:%u,rec:%u}", idw[65], idw[66]);
513 printf("\n PIO modes: %s", pmodes);
514 if (*dmodes)
515 printf("\n DMA modes: %s", dmodes);
516 if (*umodes)
517 printf("\n UDMA modes: %s", umodes);
519 printf("\n AdvancedPM=%s",YN(idw[83]&8));
520 if (idw[83] & 8) {
521 if (!(idw[86]&8))
522 printf(": disabled (255)");
523 else if ((idw[91]&0xFF00)!=0x4000)
524 printf(": unknown setting");
525 else
526 printf(": mode=0x%02X (%u)",idw[91]&0xFF,idw[91]&0xFF);
528 if (idw[82]&0x20)
529 printf(" WriteCache=%s",(idw[85]&0x20) ? "enabled" : "disabled");
530 if (idw[81] || idw[80]) {
531 printf("\n Drive conforms to: ");
532 if (idw[81] <= 31)
533 printf("%s: ", minor_str[idw[81]]);
534 else
535 printf("unknown: ");
536 if (idw[80] != 0x0000 && /* NOVAL_0 */
537 idw[80] != 0xFFFF) { /* NOVAL_1 */
538 int count = 0;
539 for (i=0; i <= 7; i++) {
540 if (idw[80] & (1<<i))
541 printf("%s%u", count++ ? "," : " ATA/ATAPI-", i);
545 printf("\n");
546 printf("\n * signifies the current active mode\n");
547 printf("\n");
550 static const char *busstate_str (unsigned int value)
552 static const char *states[4] = {"off", "on", "tristate", "unknown"};
554 if (value > 3)
555 value = 3;
556 return states[value];
559 static void interpret_standby (void)
561 printf(" (");
562 switch(standby) {
563 case 0: printf("off");
564 break;
565 case 252: printf("21 minutes");
566 break;
567 case 253: printf("vendor-specific");
568 break;
569 case 254: printf("?reserved");
570 break;
571 case 255: printf("21 minutes + 15 seconds");
572 break;
573 default:
574 if (standby <= 240) {
575 unsigned int secs = standby * 5;
576 unsigned int mins = secs / 60;
577 secs %= 60;
578 if (mins) printf("%u minutes", mins);
579 if (mins && secs) printf(" + ");
580 if (secs) printf("%u seconds", secs);
581 } else if (standby <= 251) {
582 unsigned int mins = (standby - 240) * 30;
583 unsigned int hrs = mins / 60;
584 mins %= 60;
585 if (hrs) printf("%u hours", hrs);
586 if (hrs && mins) printf(" + ");
587 if (mins) printf("%u minutes", mins);
588 } else {
589 printf("illegal value");
591 break;
593 printf(")\n");
596 struct xfermode_entry {
597 int val;
598 const char *name;
601 static const struct xfermode_entry xfermode_table[] = {
602 { 8, "pio0" },
603 { 9, "pio1" },
604 { 10, "pio2" },
605 { 11, "pio3" },
606 { 12, "pio4" },
607 { 13, "pio5" },
608 { 14, "pio6" },
609 { 15, "pio7" },
610 { 16, "sdma0" },
611 { 17, "sdma1" },
612 { 18, "sdma2" },
613 { 19, "sdma3" },
614 { 20, "sdma4" },
615 { 21, "sdma5" },
616 { 22, "sdma6" },
617 { 23, "sdma7" },
618 { 32, "mdma0" },
619 { 33, "mdma1" },
620 { 34, "mdma2" },
621 { 35, "mdma3" },
622 { 36, "mdma4" },
623 { 37, "mdma5" },
624 { 38, "mdma6" },
625 { 39, "mdma7" },
626 { 64, "udma0" },
627 { 65, "udma1" },
628 { 66, "udma2" },
629 { 67, "udma3" },
630 { 68, "udma4" },
631 { 69, "udma5" },
632 { 70, "udma6" },
633 { 71, "udma7" },
634 { 0, NULL }
637 static int translate_xfermode(char * name)
639 const struct xfermode_entry *tmp;
640 char *endptr;
641 int val = -1;
643 for (tmp = xfermode_table; tmp->name != NULL; ++tmp) {
644 if (!strcmp(name, tmp->name))
645 return tmp->val;
647 val = strtol(name, &endptr, 10);
648 if (*endptr == '\0')
649 return val;
650 return -1;
653 static void interpret_xfermode (unsigned int xfermode)
655 printf(" (");
656 switch(xfermode) {
657 case 0: printf("default PIO mode");
658 break;
659 case 1: printf("default PIO mode, disable IORDY");
660 break;
661 case 8:
662 case 9:
663 case 10:
664 case 11:
665 case 12:
666 case 13:
667 case 14:
668 case 15: printf("PIO flow control mode%u", xfermode-8);
669 break;
670 case 16:
671 case 17:
672 case 18:
673 case 19:
674 case 20:
675 case 21:
676 case 22:
677 case 23: printf("singleword DMA mode%u", xfermode-16);
678 break;
679 case 32:
680 case 33:
681 case 34:
682 case 35:
683 case 36:
684 case 37:
685 case 38:
686 case 39: printf("multiword DMA mode%u", xfermode-32);
687 break;
688 case 64:
689 case 65:
690 case 66:
691 case 67:
692 case 68:
693 case 69:
694 case 70:
695 case 71: printf("UltraDMA mode%u", xfermode-64);
696 break;
697 default:
698 printf("unknown, probably not valid");
699 break;
701 printf(")\n");
704 static unsigned int get_erase_timeout_secs (int fd, int enhanced)
706 unsigned int timeout = 0;
707 unsigned int idx = 89 + enhanced;
709 get_identify_data(fd);
710 if (id) {
711 timeout = id[idx];
712 if (timeout && timeout <= 0xff) {
714 * 0xff means "more than 254 2-minute intervals (508+ minutes),
715 * but we really want a better idea than that.
716 * Norman Diamond suggests allowing 1sec per 30MB of capacity.
718 if (timeout == 0xff) {
719 __u64 lba_limit = get_lba_capacity(id);
720 __u64 estimate = (lba_limit / 2048ULL) / 30ULL / 60;
721 timeout = 508 + 60; /* spec says > 508 minutes */
722 if (timeout < estimate)
723 timeout = estimate;
724 } else {
725 timeout = (timeout * 2) + 30; /* Add on a 30min margin */
729 if (!timeout)
730 timeout = 2 * 60; /* default: two hours */
731 timeout *= 60; /* convert minutes to seconds */
732 return timeout;
735 static void
736 do_set_security (int fd)
738 int err = 0;
739 const char *description;
740 struct hdio_taskfile *r;
741 __u8 *data;
743 r = malloc(sizeof(struct hdio_taskfile) + 512);
744 if (!r) {
745 err = errno;
746 perror("malloc()");
747 exit(err);
750 memset(r, 0, sizeof(struct hdio_taskfile) + 512);
751 r->cmd_req = TASKFILE_CMD_REQ_OUT;
752 r->dphase = TASKFILE_DPHASE_PIO_OUT;
753 r->obytes = 512;
754 r->lob.command = security_command;
755 r->oflags.lob.nsect = 1;
756 r->lob.nsect = 1;
757 data = (__u8*)r->data;
758 data[0] = security_master & 0x01;
759 memcpy(data+2, security_password, 32);
761 r->oflags.lob.command = 1;
762 r->oflags.lob.feat = 1;
764 switch (security_command) {
765 case ATA_OP_SECURITY_ERASE_UNIT:
766 description = "SECURITY_ERASE";
767 data[0] |= enhanced_erase ? 0x02 : 0;
768 break;
769 case ATA_OP_SECURITY_DISABLE:
770 description = "SECURITY_DISABLE";
771 break;
772 case ATA_OP_SECURITY_UNLOCK:
773 description = "SECURITY_UNLOCK";
774 break;
775 case ATA_OP_SECURITY_SET_PASS:
776 description = "SECURITY_SET_PASS";
777 data[1] = (security_mode & 0x01);
778 if (security_master) {
779 /* increment master-password revision-code */
780 __u16 revcode;
781 get_identify_data(fd);
782 if (!id)
783 exit(EIO);
784 revcode = id[92];
785 if (revcode == 0xfffe)
786 revcode = 0;
787 revcode += 1;
788 data[34] = revcode;
789 data[35] = revcode >> 8;
791 break;
792 default:
793 fprintf(stderr, "BUG in do_set_security(), command1=0x%x\n", security_command);
794 exit(EINVAL);
796 printf(" Issuing %s command, password=\"%s\", user=%s",
797 description, security_password, (data[0] & 1) ? "master" : "user");
798 if (security_command == ATA_OP_SECURITY_SET_PASS)
799 printf(", mode=%s", data[1] ? "max" : "high");
800 printf("\n");
803 * The Linux kernel IDE driver (until at least 2.6.12) segfaults on the first
804 * command when issued on a locked drive, and the actual erase is never issued.
805 * One could patch the code to issue separate commands for erase prepare and
806 * erase to erase a locked drive.
808 * We would like to issue these commands consecutively, but since the Linux
809 * kernel until at least 2.6.12 segfaults on each command issued the second will
810 * never be executed.
812 * One is at least able to issue the commands consecutively in two hdparm invocations,
813 * assuming the segfault isn't followed by an oops.
815 if (security_command == ATA_OP_SECURITY_ERASE_UNIT) {
816 unsigned int timeout = get_erase_timeout_secs(fd, enhanced_erase);
817 __u8 args[4] = {ATA_OP_SECURITY_ERASE_PREPARE,0,0,0};
818 if (do_drive_cmd(fd, args, 0)) {
819 err = errno;
820 perror("ERASE_PREPARE");
821 } else {
822 if ((do_taskfile_cmd(fd, r, timeout))) {
823 err = errno;
824 perror("SECURITY_ERASE");
827 } else if (security_command == ATA_OP_SECURITY_DISABLE) {
828 /* First attempt an unlock */
829 r->lob.command = ATA_OP_SECURITY_UNLOCK;
830 if ((do_taskfile_cmd(fd, r, timeout_15secs))) {
831 err = errno;
832 perror("SECURITY_UNLOCK");
833 } else {
834 /* Then the security disable */
835 r->lob.command = security_command;
836 if ((do_taskfile_cmd(fd, r, timeout_15secs))) {
837 err = errno;
838 perror("SECURITY_DISABLE");
841 } else if (security_command == ATA_OP_SECURITY_UNLOCK) {
842 if ((do_taskfile_cmd(fd, r, timeout_15secs))) {
843 err = errno;
844 perror("SECURITY_UNLOCK");
846 } else if (security_command == ATA_OP_SECURITY_SET_PASS) {
847 if ((do_taskfile_cmd(fd, r, timeout_15secs))) {
848 err = errno;
849 perror("SECURITY_SET_PASS");
851 } else {
852 fprintf(stderr, "BUG in do_set_security(), command2=0x%x\n", security_command);
853 err = EINVAL;
855 free(r);
856 if (err)
857 exit(err);
860 static __u8 last_identify_op = 0;
862 static void get_identify_data (int fd)
864 static __u8 args[4+512];
865 int i;
867 if (id)
868 return;
869 memset(args, 0, sizeof(args));
870 last_identify_op = ATA_OP_IDENTIFY;
871 args[0] = last_identify_op;
872 args[3] = 1; /* sector count */
873 if (do_drive_cmd(fd, args, 0)) {
874 prefer_ata12 = 0;
875 memset(args, 0, sizeof(args));
876 last_identify_op = ATA_OP_PIDENTIFY;
877 args[0] = last_identify_op;
878 args[3] = 1; /* sector count */
879 if (do_drive_cmd(fd, args, 0)) {
880 perror(" HDIO_DRIVE_CMD(identify) failed");
881 return;
884 /* byte-swap the little-endian IDENTIFY data to match byte-order on host CPU */
885 id = (void *)(args + 4);
886 for (i = 0; i < 0x100; ++i)
887 __le16_to_cpus(&id[i]);
890 static void confirm_i_know_what_i_am_doing (const char *opt, const char *explanation)
892 if (!i_know_what_i_am_doing) {
893 fprintf(stderr, "Use of %s is VERY DANGEROUS.\n%s\n"
894 "Please supply the --yes-i-know-what-i-am-doing flag if you really want this.\n"
895 "Program aborted.\n", opt, explanation);
896 exit(EPERM);
900 static void confirm_please_destroy_my_drive (const char *opt, const char *explanation)
902 if (!please_destroy_my_drive) {
903 fprintf(stderr, "Use of %s is EXTREMELY DANGEROUS.\n%s\n"
904 "Please also supply the --please-destroy-my-drive flag if you really want this.\n"
905 "Program aborted.\n", opt, explanation);
906 exit(EPERM);
910 static int flush_wcache (int fd)
912 __u8 args[4] = {ATA_OP_FLUSHCACHE,0,0,0};
913 int err = 0;
915 get_identify_data(fd);
916 if (id && (id[83] & 0xe000) == 0x6000)
917 args[0] = ATA_OP_FLUSHCACHE_EXT;
918 if (do_drive_cmd(fd, args, timeout_60secs)) {
919 err = errno;
920 perror (" HDIO_DRIVE_CMD(flushcache) failed");
922 return err;
925 static void dump_sectors (__u16 *w, unsigned int count)
927 unsigned int i;
929 for (i = 0; i < (count*256/8); ++i) {
930 #if 0
931 printf("%04x %04x %04x %04x %04x %04x %04x %04x\n",
932 w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]);
933 w += 8;
934 #else
935 int word;
936 for (word = 0; word < 8; ++word) {
937 printf("%04x", le16toh(w[0]));
938 ++w;
939 putchar(word == 7 ? '\n' : ' ');
941 #endif
945 static int abort_if_not_full_device (int fd, __u64 lba, const char *devname, const char *msg)
947 __u64 start_lba;
948 int i, err, shortened = 0;
949 char *fdevname = strdup(devname);
951 err = get_dev_geometry(fd, NULL, NULL, NULL, &start_lba, NULL);
952 if (err)
953 exit(err);
954 for (i = strlen(fdevname); --i > 2 && (fdevname[i] >= '0' && fdevname[i] <= '9');) {
955 fdevname[i] = '\0';
956 shortened = 1;
959 if (!shortened)
960 fdevname = strdup("the full disk");
962 if (start_lba == 0ULL)
963 return 0;
964 if (start_lba == START_LBA_UNKNOWN || fd_is_raid(fd)) {
965 fprintf(stderr, "%s is a RAID device: please specify an absolute LBA of a raw member device instead (raid1 only)\n", devname);
966 } else if (msg) {
967 fprintf(stderr, "%s\n", msg);
968 } else {
969 fprintf(stderr, "Device %s has non-zero LBA starting offset of %llu.\n", devname, start_lba);
970 fprintf(stderr, "Please use an absolute LBA with the /dev/ entry for the raw device, rather than a partition or raid name.\n");
971 fprintf(stderr, "%s is probably a partition of %s (?)\n", devname, fdevname);
972 fprintf(stderr, "The absolute LBA of sector %llu from %s should be %llu\n", lba, devname, start_lba + lba);
974 fprintf(stderr, "Aborting.\n");
975 exit(EINVAL);
978 static __u16 *get_dco_identify_data (int fd, int quietly)
980 static __u8 args[4+512];
981 __u16 *dco = (void *)(args + 4);
982 int i;
984 memset(args, 0, sizeof(args));
985 args[0] = ATA_OP_DCO;
986 args[2] = 0xc2;
987 args[3] = 1;
988 if (do_drive_cmd(fd, args, 0)) {
989 if (!quietly)
990 perror(" HDIO_DRIVE_CMD(dco_identify) failed");
991 return NULL;
992 } else {
993 /* byte-swap the little-endian DCO data to match byte-order on host CPU */
994 for (i = 0; i < 0x100; ++i)
995 __le16_to_cpus(&dco[i]);
996 //dump_sectors(dco, 1);
997 return dco;
1001 static __u64 do_get_native_max_sectors (int fd)
1003 int err = 0;
1004 __u64 max = 0;
1005 struct hdio_taskfile r;
1007 get_identify_data(fd);
1008 if (!id)
1009 exit(EIO);
1010 memset(&r, 0, sizeof(r));
1011 r.cmd_req = TASKFILE_CMD_REQ_NODATA;
1012 r.dphase = TASKFILE_DPHASE_NONE;
1013 r.oflags.lob.dev = 1;
1014 r.oflags.lob.command = 1;
1015 r.iflags.lob.command = 1;
1016 r.iflags.lob.lbal = 1;
1017 r.iflags.lob.lbam = 1;
1018 r.iflags.lob.lbah = 1;
1019 r.lob.dev = 0x40;
1021 if (((id[83] & 0xc400) == 0x4400) && (id[86] & 0x0400)) {
1022 r.iflags.hob.lbal = 1;
1023 r.iflags.hob.lbam = 1;
1024 r.iflags.hob.lbah = 1;
1025 r.lob.command = ATA_OP_READ_NATIVE_MAX_EXT;
1026 if (do_taskfile_cmd(fd, &r, 10)) {
1027 err = errno;
1028 perror (" READ_NATIVE_MAX_ADDRESS_EXT failed");
1029 } else {
1030 if (verbose)
1031 printf("READ_NATIVE_MAX_ADDRESS_EXT response: hob={%02x %02x %02x} lob={%02x %02x %02x}\n",
1032 r.hob.lbah, r.hob.lbam, r.hob.lbal, r.lob.lbah, r.lob.lbam, r.lob.lbal);
1033 max = (((__u64)((r.hob.lbah << 16) | (r.hob.lbam << 8) | r.hob.lbal) << 24)
1034 | ((r.lob.lbah << 16) | (r.lob.lbam << 8) | r.lob.lbal)) + 1;
1036 } else {
1037 r.iflags.lob.dev = 1;
1038 r.lob.command = ATA_OP_READ_NATIVE_MAX;
1039 if (do_taskfile_cmd(fd, &r, 0)) {
1040 err = errno;
1041 perror (" READ_NATIVE_MAX_ADDRESS failed");
1042 } else {
1043 max = (((r.lob.dev & 0x0f) << 24) | (r.lob.lbah << 16) | (r.lob.lbam << 8) | r.lob.lbal) + 1;
1046 errno = err;
1047 return max;
1050 static int do_make_bad_sector (int fd, __u64 lba, const char *devname)
1052 int err = 0, has_write_unc = 0;
1053 struct hdio_taskfile *r;
1054 const char *flagged;
1056 abort_if_not_full_device(fd, lba, devname, NULL);
1057 r = malloc(sizeof(struct hdio_taskfile) + 520);
1058 if (!r) {
1059 err = errno;
1060 perror("malloc()");
1061 return err;
1064 get_identify_data(fd);
1065 if (id)
1066 has_write_unc = (id[ 83] & 0xc000) == 0x4000 && (id[ 86] & 0x8000) == 0x8000
1067 && (id[119] & 0xc004) == 0x4004 && (id[120] & 0xc000) == 0x4000;
1069 if (has_write_unc || make_bad_sector_flagged || lba >= lba28_limit) {
1070 if (!has_write_unc) {
1071 printf("Device does not claim to implement the required WRITE_UNC_EXT command\n"
1072 "This operation will probably fail (continuing regardless).\n");
1074 init_hdio_taskfile(r, ATA_OP_WRITE_UNC_EXT, RW_READ, LBA48_FORCE, lba, 1, 0);
1075 r->oflags.lob.feat = 1;
1076 r->lob.feat = make_bad_sector_flagged ? 0xaa : 0x55;
1077 flagged = make_bad_sector_flagged ? "flagged" : "pseudo";
1078 printf("Corrupting sector %llu (WRITE_UNC_EXT as %s): ", lba, flagged);
1079 } else {
1080 init_hdio_taskfile(r, ATA_OP_WRITE_LONG_ONCE, RW_WRITE, LBA28_OK, lba, 1, 520);
1081 memset(r->data, 0xa5, 520);
1082 printf("Corrupting sector %llu (WRITE_LONG): ", lba);
1084 fflush(stdout);
1086 /* Try and ensure that the system doesn't have our sector in cache */
1087 flush_buffer_cache(fd);
1089 if (do_taskfile_cmd(fd, r, timeout_60secs)) {
1090 err = errno;
1091 perror("FAILED");
1092 } else {
1093 printf("succeeded\n");
1095 free(r);
1096 return err;
1099 #ifdef FORMAT_AND_ERASE
1100 static int do_format_track (int fd, __u64 lba, const char *devname)
1102 int err = 0;
1103 struct hdio_taskfile *r;
1105 abort_if_not_full_device(fd, lba, devname, NULL);
1106 r = malloc(sizeof(struct hdio_taskfile) + 512);
1107 if (!r) {
1108 err = errno;
1109 perror("malloc()");
1110 return err;
1112 init_hdio_taskfile(r, ATA_OP_FORMAT_TRACK, RW_WRITE, LBA28_OK, lba, 1, 512);
1113 r->lob.nsect = 0;
1115 printf("re-formatting lba %llu: ", lba);
1116 fflush(stdout);
1118 if (do_taskfile_cmd(fd, r, timeout_60secs)) {
1119 err = errno;
1120 perror("FAILED");
1121 } else {
1122 printf("succeeded\n");
1125 // Try and ensure that the system doesn't have our sector in cache:
1126 flush_buffer_cache(fd);
1128 free(r);
1129 return err;
1132 static int do_erase_sectors (int fd, __u64 lba, const char *devname)
1134 int err = 0;
1135 struct hdio_taskfile *r;
1137 abort_if_not_full_device(fd, lba, devname, NULL);
1138 r = malloc(sizeof(struct hdio_taskfile) + 0);
1139 if (!r) {
1140 err = errno;
1141 perror("malloc()");
1142 return err;
1144 init_hdio_taskfile(r, ATA_OP_ERASE_SECTORS, RW_READ, LBA28_OK, lba, 256, 0);
1146 printf("erasing sectors %llu-%llu: ", lba, lba + 255);
1147 fflush(stdout);
1149 if (do_taskfile_cmd(fd, r, timeout_60secs)) {
1150 err = errno;
1151 perror("FAILED");
1152 } else {
1153 printf("succeeded\n");
1155 free(r);
1156 return err;
1158 #endif /* FORMAT_AND_ERASE */
1160 struct sector_range_s {
1161 __u64 lba;
1162 __u64 nsectors;
1165 static int trim_sectors (int fd, const char *devname, int nranges, void *data, __u64 nsectors)
1167 struct ata_tf tf;
1168 int err = 0;
1169 unsigned int data_bytes = nranges * sizeof(__u64);
1170 unsigned int data_sects = (data_bytes + 511) / 512;
1172 data_bytes = data_sects * 512;
1174 abort_if_not_full_device(fd, 0, devname, NULL);
1175 printf("trimming %llu sectors from %d ranges\n", nsectors, nranges);
1176 fflush(stdout);
1178 // Try and ensure that the system doesn't have the to-be-trimmed sectors in cache:
1179 flush_buffer_cache(fd);
1181 tf_init(&tf, ATA_OP_DSM, 0, data_sects);
1182 tf.lob.feat = 0x01; /* DSM/TRIM */
1184 if (sg16(fd, SG_WRITE, SG_DMA, &tf, data, data_bytes, 300 /* seconds */)) {
1185 err = errno;
1186 perror("FAILED");
1187 } else {
1188 printf("succeeded\n");
1190 return err;
1193 static void do_trim_sector_ranges (int fd, const char *devname, int nranges, struct sector_range_s *sr)
1195 __u64 range, *data, nsectors = 0;
1196 unsigned int data_sects, data_bytes;
1197 int i, err = 0;
1199 abort_if_not_full_device(fd, 0, devname, NULL);
1201 data_sects = ((nranges * sizeof(range)) + 511) / 512;
1202 data_bytes = data_sects * 512;
1204 data = mmap(NULL, data_bytes, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
1205 if (data == MAP_FAILED) {
1206 err = errno;
1207 perror("mmap(MAP_ANONYMOUS)");
1208 exit(err);
1210 // FIXME: handle counts > 65535 here!
1211 for (i = 0; i < nranges; ++i) {
1212 nsectors += sr->nsectors;
1213 range = sr->nsectors;
1214 range = (range << 48) | sr->lba;
1215 data[i] = __cpu_to_le64(range);
1216 ++sr;
1219 err = trim_sectors(fd, devname, nranges, data, nsectors);
1220 munmap(data, data_bytes);
1221 exit(err);
1224 static void
1225 extract_id_string (__u16 *idw, int words, char *dst)
1227 char *e;
1228 int i, max = words * 2;
1230 for (i = 0; i < words; ++i) {
1231 __u16 w = idw[i];
1232 w = __be16_to_cpu(w);
1233 dst[i*2 ] = w >> 8;
1234 dst[i*2+1] = w;
1236 dst[max] = '\0';
1237 for (e = dst + max; --e != dst;) {
1238 if (*e && *e != ' ')
1239 break;
1240 *e = '\0';
1244 static int
1245 get_trim_dev_limit (void)
1247 char model[41];
1249 if (id[105] && id[105] != 0xffff)
1250 return id[105];
1251 extract_id_string(id + 27, 20, model);
1252 if (0 == strcmp(model, "OCZ VERTEX-LE"))
1253 return 8;
1254 if (0 == strcmp(model, "OCZ-VERTEX"))
1255 return 64;
1256 return 1; /* all other drives, including Intel SSDs */
1259 static int
1260 do_trim_from_stdin (int fd, const char *devname)
1262 __u64 *data, range, nsectors = 0, lba_limit;
1263 unsigned int max_kb, data_sects, data_bytes;
1264 unsigned int total_ranges = 0, nranges = 0, max_ranges, dev_limit;
1265 int err = 0;
1267 get_identify_data(fd);
1268 if (!id)
1269 exit(EIO);
1270 lba_limit = get_lba_capacity(id);
1271 dev_limit = get_trim_dev_limit();
1273 err = sysfs_get_attr(fd, "queue/max_sectors_kb", "%u", &max_kb, NULL, 0);
1274 if (err || max_kb == 0)
1275 data_sects = 128; /* "safe" default for most controllers */
1276 else
1277 data_sects = max_kb * 2;
1278 if (data_sects > dev_limit)
1279 data_sects = dev_limit;
1280 data_bytes = data_sects * 512;
1282 data = mmap(NULL, data_bytes, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
1283 if (data == MAP_FAILED) {
1284 err = errno;
1285 perror("mmap(MAP_ANONYMOUS)");
1286 exit(err);
1288 memset(data, 0, data_bytes);
1289 max_ranges = data_bytes / sizeof(range);
1291 do {
1292 __u64 lba, nsect;
1293 int args;
1295 if (nranges == 0)
1296 memset(data, 0, data_bytes);
1297 errno = EINVAL;
1298 args = scanf("%llu:%llu", &lba, &nsect);
1299 if (args == EOF)
1300 break;
1301 if (args != 2 || nsect > 0xffff || lba >= lba_limit) {
1302 if (args == 2)
1303 errno = ERANGE;
1304 err = errno;
1305 fprintf(stderr, "stdin: error at lba:count pair #%d: %s\n", (total_ranges + 1), strerror(err));
1306 } else {
1307 range = (nsect << 48) | lba;
1308 nsectors += nsect;
1309 data[nranges++] = __cpu_to_le64(range);
1310 if (nranges == max_ranges) {
1311 err = trim_sectors(fd, devname, nranges, data, nsectors);
1312 memset(data, 0, data_bytes);
1313 nranges = 0;
1314 nsectors = 0;
1316 ++total_ranges;
1318 } while (!err);
1319 if (!err && nranges)
1320 err = trim_sectors(fd, devname, nranges, data, nsectors);
1321 munmap(data, data_bytes);
1322 return err;
1325 static int do_write_sector (int fd, __u64 lba, const char *devname)
1327 int err = 0;
1328 __u8 ata_op;
1329 struct hdio_taskfile *r;
1331 abort_if_not_full_device(fd, lba, devname, NULL);
1332 r = malloc(sizeof(struct hdio_taskfile) + 512);
1333 if (!r) {
1334 err = errno;
1335 perror("malloc()");
1336 return err;
1338 ata_op = (lba >= lba28_limit) ? ATA_OP_WRITE_PIO_EXT : ATA_OP_WRITE_PIO;
1339 init_hdio_taskfile(r, ata_op, RW_WRITE, LBA28_OK, lba, 1, 512);
1341 printf("re-writing sector %llu: ", lba);
1342 fflush(stdout);
1344 // Try and ensure that the system doesn't have our sector in cache:
1345 flush_buffer_cache(fd);
1347 if (do_taskfile_cmd(fd, r, timeout_60secs)) {
1348 err = errno;
1349 perror("FAILED");
1350 } else {
1351 printf("succeeded\n");
1354 free(r);
1355 return err;
1358 static int do_read_sector (int fd, __u64 lba, const char *devname)
1360 int err = 0;
1361 __u8 ata_op;
1362 struct hdio_taskfile *r;
1364 abort_if_not_full_device(fd, lba, devname, NULL);
1365 r = malloc(sizeof(struct hdio_taskfile) + 512);
1366 if (!r) {
1367 err = errno;
1368 perror("malloc()");
1369 return err;
1371 ata_op = (lba >= lba28_limit) ? ATA_OP_READ_PIO_EXT : ATA_OP_READ_PIO;
1372 init_hdio_taskfile(r, ata_op, RW_READ, LBA28_OK, lba, 1, 512);
1374 printf("reading sector %llu: ", lba);
1375 fflush(stdout);
1377 if (do_taskfile_cmd(fd, r, timeout_60secs)) {
1378 err = errno;
1379 perror("FAILED");
1380 } else {
1381 printf("succeeded\n");
1382 dump_sectors(r->data, 1);
1384 free(r);
1385 return err;
1388 static int do_idleunload (int fd, const char *devname)
1390 int err = 0;
1391 struct hdio_taskfile r;
1393 abort_if_not_full_device(fd, 0, devname, NULL);
1394 init_hdio_taskfile(&r, ATA_OP_IDLEIMMEDIATE, RW_READ, LBA28_OK, 0x0554e4c, 0, 0);
1395 r.oflags.lob.feat = 1;
1396 r.lob.feat = 0x44;
1398 if (do_taskfile_cmd(fd, &r, 0)) {
1399 err = errno;
1400 perror("TASKFILE(idle_immediate_unload) failed");
1402 return err;
1405 static int do_set_max_sectors (int fd, __u64 max_lba, int permanent)
1407 int err = 0;
1408 struct hdio_taskfile r;
1409 __u8 nsect = permanent ? 1 : 0;
1411 get_identify_data(fd);
1412 if (!id)
1413 exit(EIO);
1414 if ((max_lba >= lba28_limit) || (id && ((id[83] & 0xc400) == 0x4400) && (id[86] & 0x0400))) {
1415 init_hdio_taskfile(&r, ATA_OP_SET_MAX_EXT, RW_READ, LBA48_FORCE, max_lba, nsect, 0);
1416 } else {
1417 init_hdio_taskfile(&r, ATA_OP_SET_MAX, RW_READ, LBA28_OK, max_lba, nsect, 0);
1418 r.oflags.lob.feat = 1; /* this ATA op requires feat==0 */
1421 /* spec requires that we do this immediately in front.. racey */
1422 if (!do_get_native_max_sectors(fd))
1423 return errno;
1425 /* now set the new value */
1426 if (do_taskfile_cmd(fd, &r, 0)) {
1427 err = errno;
1428 perror(" SET_MAX_ADDRESS failed");
1430 return err;
1433 static void usage_help (int clue, int rc)
1435 FILE *desc = rc ? stderr : stdout;
1437 fprintf(desc,"\n%s - get/set hard disk parameters - version " VERSION ", by Mark Lord.\n\n", progname);
1438 if (0) if (rc) fprintf(desc, "clue=%d\n", clue);
1439 fprintf(desc,"Usage: %s [options] [device ...]\n\n", progname);
1440 fprintf(desc,"Options:\n"
1441 " -a Get/set fs readahead\n"
1442 " -A Get/set the drive look-ahead flag (0/1)\n"
1443 " -b Get/set bus state (0 == off, 1 == on, 2 == tristate)\n"
1444 " -B Set Advanced Power Management setting (1-255)\n"
1445 " -c Get/set IDE 32-bit IO setting\n"
1446 " -C Check drive power mode status\n"
1447 " -d Get/set using_dma flag\n"
1448 " -D Enable/disable drive defect management\n"
1449 " -E Set cd/dvd drive speed\n"
1450 " -f Flush buffer cache for device on exit\n"
1451 " -F Flush drive write cache\n"
1452 " -g Display drive geometry\n"
1453 " -h Display terse usage information\n"
1454 " -H Read temperature from drive (Hitachi only)\n"
1455 " -i Display drive identification\n"
1456 " -I Detailed/current information directly from drive\n"
1457 " -J Get/set Western DIgital \"Idle3\" timeout for a WDC \"Green\" drive (DANGEROUS)\n"
1458 " -k Get/set keep_settings_over_reset flag (0/1)\n"
1459 " -K Set drive keep_features_over_reset flag (0/1)\n"
1460 " -L Set drive doorlock (0/1) (removable harddisks only)\n"
1461 " -m Get/set multiple sector count\n"
1462 " -M Get/set acoustic management (0-254, 128: quiet, 254: fast)\n"
1463 " -n Get/set ignore-write-errors flag (0/1)\n"
1464 " -N Get/set max visible number of sectors (HPA) (VERY DANGEROUS)\n"
1465 " -p Set PIO mode on IDE interface chipset (0,1,2,3,4,...)\n"
1466 " -P Set drive prefetch count\n"
1467 " -q Change next setting quietly\n"
1468 " -Q Get/set DMA queue_depth (if supported)\n"
1469 " -r Get/set device readonly flag (DANGEROUS to set)\n"
1470 " -R Get/set device write-read-verify flag\n"
1471 " -s Set power-up in standby flag (0/1) (DANGEROUS)\n"
1472 " -S Set standby (spindown) timeout\n"
1473 " -t Perform device read timings\n"
1474 " -T Perform cache read timings\n"
1475 " -u Get/set unmaskirq flag (0/1)\n"
1476 " -U Obsolete\n"
1477 " -v Use defaults; same as -acdgkmur for IDE drives\n"
1478 " -V Display program version and exit immediately\n"
1479 " -w Perform device reset (DANGEROUS)\n"
1480 " -W Get/set drive write-caching flag (0/1)\n"
1481 " -x Obsolete\n"
1482 " -X Set IDE xfer mode (DANGEROUS)\n"
1483 " -y Put drive in standby mode\n"
1484 " -Y Put drive to sleep\n"
1485 " -z Re-read partition table\n"
1486 " -Z Disable Seagate auto-powersaving mode\n"
1487 " --dco-freeze Freeze/lock current device configuration until next power cycle\n"
1488 " --dco-identify Read/dump device configuration identify data\n"
1489 " --dco-restore Reset device configuration back to factory defaults\n"
1490 " --direct Use O_DIRECT to bypass page cache for timings\n"
1491 " --drq-hsm-error Crash system with a \"stuck DRQ\" error (VERY DANGEROUS)\n"
1492 " --fallocate Create a file without writing data to disk\n"
1493 " --fibmap Show device extents (and fragmentation) for a file\n"
1494 " --fwdownload Download firmware file to drive (EXTREMELY DANGEROUS)\n"
1495 " --fwdownload-mode3 Download firmware using min-size segments (EXTREMELY DANGEROUS)\n"
1496 " --fwdownload-mode3-max Download firmware using max-size segments (EXTREMELY DANGEROUS)\n"
1497 " --fwdownload-mode7 Download firmware using a single segment (EXTREMELY DANGEROUS)\n"
1498 " --idle-immediate Idle drive immediately\n"
1499 " --idle-unload Idle immediately and unload heads\n"
1500 " --Istdin Read identify data from stdin as ASCII hex\n"
1501 " --Istdout Write identify data to stdout as ASCII hex\n"
1502 " --make-bad-sector Deliberately corrupt a sector directly on the media (VERY DANGEROUS)\n"
1503 " --offset use with -t, to begin timings at given offset (in GiB) from start of drive\n"
1504 " --prefer-ata12 Use 12-byte (instead of 16-byte) SAT commands when possible\n"
1505 " --read-sector Read and dump (in hex) a sector directly from the media\n"
1506 " --security-help Display help for ATA security commands\n"
1507 " --trim-sector-ranges Tell SSD firmware to discard unneeded data sectors: lba:count ..\n"
1508 " --trim-sector-ranges-stdin Same as above, but reads lba:count pairs from stdin\n"
1509 " --verbose Display extra diagnostics from some commands\n"
1510 " --write-sector Repair/overwrite a (possibly bad) sector directly on the media (VERY DANGEROUS)\n"
1511 "\n");
1512 exit(rc);
1515 static void security_help (int rc)
1517 FILE *desc = rc ? stderr : stdout;
1519 fprintf(desc, "\n"
1520 "ATA Security Commands:\n"
1521 " Most of these are VERY DANGEROUS and can destroy all of your data!\n"
1522 " Due to bugs in older Linux kernels, use of these commands may even\n"
1523 " trigger kernel segfaults or worse. EXPERIMENT AT YOUR OWN RISK!\n"
1524 "\n"
1525 " --security-freeze Freeze security settings until reset.\n"
1526 "\n"
1527 " --security-set-pass PASSWD Lock drive, using password PASSWD:\n"
1528 " Use 'NULL' to set empty password.\n"
1529 " Drive gets locked if user-passwd is selected.\n"
1530 " --security-unlock PASSWD Unlock drive.\n"
1531 " --security-disable PASSWD Disable drive locking.\n"
1532 " --security-erase PASSWD Erase a (locked) drive.\n"
1533 " --security-erase-enhanced PASSWD Enhanced-erase a (locked) drive.\n"
1534 "\n"
1535 " The above four commands may optionally be preceded by these options:\n"
1536 " --security-mode LEVEL Use LEVEL to select security level:\n"
1537 " h high security (default).\n"
1538 " m maximum security.\n"
1539 " --user-master WHICH Use WHICH to choose password type:\n"
1540 " u user-password (default).\n"
1541 " m master-password\n"
1543 exit(rc);
1546 void process_dev (char *devname)
1548 int fd;
1549 int err = 0;
1550 static long parm, multcount;
1552 id = NULL;
1553 fd = open(devname, open_flags);
1554 if (fd < 0) {
1555 err = errno;
1556 perror(devname);
1557 exit(err);
1559 if (!quiet)
1560 printf("\n%s:\n", devname);
1562 if (trim_from_stdin) {
1563 if (num_flags_processed > 1 || argc)
1564 usage_help(12,EINVAL);
1565 confirm_please_destroy_my_drive("--trim-sector-ranges-stdin", "This might destroy the drive and/or all data on it.");
1566 exit(do_trim_from_stdin(fd, devname));
1569 if (set_wdidle3) {
1570 unsigned char timeout = wdidle3_msecs_to_timeout(wdidle3);
1571 confirm_please_destroy_my_drive("-J", "This implementation is not as thorough as the official WDIDLE3.EXE. Use at your own risk!");
1572 if (get_wdidle3) {
1573 printf(" setting wdidle3 to ");
1574 wdidle3_print_timeout(timeout);
1575 putchar('\n');
1577 err = wdidle3_set_timeout(fd, timeout);
1579 if (set_fsreadahead) {
1580 if (get_fsreadahead)
1581 printf(" setting fs readahead to %d\n", fsreadahead);
1582 if (ioctl(fd, BLKRASET, fsreadahead)) {
1583 err = errno;
1584 perror(" BLKRASET failed");
1587 if (set_piomode) {
1588 if (get_piomode) {
1589 if (piomode == 255)
1590 printf(" attempting to auto-tune PIO mode\n");
1591 else if (piomode < 100)
1592 printf(" attempting to set PIO mode to %d\n", piomode);
1593 else if (piomode < 200)
1594 printf(" attempting to set MDMA mode to %d\n", (piomode-100));
1595 else
1596 printf(" attempting to set UDMA mode to %d\n", (piomode-200));
1598 if (ioctl(fd, HDIO_SET_PIO_MODE, piomode)) {
1599 err = errno;
1600 perror(" HDIO_SET_PIO_MODE failed");
1603 if (set_io32bit) {
1604 if (get_io32bit)
1605 printf(" setting 32-bit IO_support flag to %d\n", io32bit);
1606 if (ioctl(fd, HDIO_SET_32BIT, io32bit)) {
1607 err = errno;
1608 perror(" HDIO_SET_32BIT failed");
1611 if (set_mult) {
1612 if (get_mult)
1613 printf(" setting multcount to %d\n", mult);
1614 if (ioctl(fd, HDIO_SET_MULTCOUNT, mult))
1615 #if 0
1616 perror(" HDIO_SET_MULTCOUNT failed");
1617 #else /* for libata */
1619 if (errno != ENOTTY) {
1620 perror(" HDIO_SET_MULTCOUNT failed");
1621 } else {
1622 __u8 args[4] = {ATA_OP_SET_MULTIPLE,mult,0,0};
1623 confirm_i_know_what_i_am_doing("-m", "Only the old IDE drivers work correctly with -m with kernels up to at least 2.6.29.\nlibata drives may fail and get hung if you set this flag.");
1624 if (do_drive_cmd(fd, args, 0)) {
1625 err = errno;
1626 perror(" HDIO_DRIVE_CMD(set_multi_count) failed");
1630 #endif
1632 if (set_readonly) {
1633 if (get_readonly) {
1634 printf(" setting readonly to %d", readonly);
1635 on_off(readonly);
1637 if (ioctl(fd, BLKROSET, &readonly)) {
1638 err = errno;
1639 perror(" BLKROSET failed");
1642 if (set_unmask) {
1643 if (get_unmask) {
1644 printf(" setting unmaskirq to %d", unmask);
1645 on_off(unmask);
1647 if (ioctl(fd, HDIO_SET_UNMASKINTR, unmask)) {
1648 err = errno;
1649 perror(" HDIO_SET_UNMASKINTR failed");
1652 if (set_dma) {
1653 if (get_dma) {
1654 printf(" setting using_dma to %d", dma);
1655 on_off(dma);
1657 if (ioctl(fd, HDIO_SET_DMA, dma)) {
1658 err = errno;
1659 perror(" HDIO_SET_DMA failed");
1662 if (set_dma_q) {
1663 if (get_dma_q)
1664 printf(" setting queue_depth to %d\n", dma_q);
1665 err = sysfs_set_attr(fd, "device/queue_depth", "%u", &dma_q, 1);
1667 if (set_nowerr) {
1668 if (get_nowerr) {
1669 printf(" setting nowerr to %d", nowerr);
1670 on_off(nowerr);
1672 if (ioctl(fd, HDIO_SET_NOWERR, nowerr)) {
1673 err = errno;
1674 perror(" HDIO_SET_NOWERR failed");
1677 if (set_keep) {
1678 if (get_keep) {
1679 printf(" setting keep_settings to %d", keep);
1680 on_off(keep);
1682 if (ioctl(fd, HDIO_SET_KEEPSETTINGS, keep)) {
1683 err = errno;
1684 perror(" HDIO_SET_KEEPSETTINGS failed");
1687 if (set_doorlock) {
1688 __u8 args[4] = {0,0,0,0};
1689 args[0] = doorlock ? ATA_OP_DOORLOCK : ATA_OP_DOORUNLOCK;
1690 if (get_doorlock) {
1691 printf(" setting drive doorlock to %d", doorlock);
1692 on_off(doorlock);
1694 if (do_drive_cmd(fd, args, timeout_15secs)) {
1695 err = errno;
1696 perror(" HDIO_DRIVE_CMD(doorlock) failed");
1699 if (set_dkeep) {
1700 /* lock/unlock the drive's "feature" settings */
1701 __u8 args[4] = {ATA_OP_SETFEATURES,0,0,0};
1702 if (get_dkeep) {
1703 printf(" setting drive keep features to %d", dkeep);
1704 on_off(dkeep);
1706 args[2] = dkeep ? 0x66 : 0xcc;
1707 if (do_drive_cmd(fd, args, 0)) {
1708 err = errno;
1709 perror(" HDIO_DRIVE_CMD(keepsettings) failed");
1712 if (set_defects) {
1713 __u8 args[4] = {ATA_OP_SETFEATURES,0,0,0};
1714 args[2] = defects ? 0x04 : 0x84;
1715 if (get_defects)
1716 printf(" setting drive defect management to %d\n", defects);
1717 if (do_drive_cmd(fd, args, 0)) {
1718 err = errno;
1719 perror(" HDIO_DRIVE_CMD(defectmgmt) failed");
1722 if (set_prefetch) {
1723 __u8 args[4] = {ATA_OP_SETFEATURES,0,0xab,0};
1724 args[1] = prefetch;
1725 if (get_prefetch)
1726 printf(" setting drive prefetch to %d\n", prefetch);
1727 if (do_drive_cmd(fd, args, 0)) {
1728 err = errno;
1729 perror(" HDIO_DRIVE_CMD(setprefetch) failed");
1732 if (set_xfermode) {
1733 __u8 args[4] = {ATA_OP_SETFEATURES,0,3,0};
1734 args[1] = xfermode_requested;
1735 if (get_xfermode) {
1736 printf(" setting xfermode to %d", xfermode_requested);
1737 interpret_xfermode(xfermode_requested);
1739 if (do_drive_cmd(fd, args, 0)) {
1740 err = errno;
1741 perror(" HDIO_DRIVE_CMD(setxfermode) failed");
1744 if (set_lookahead) {
1745 __u8 args[4] = {ATA_OP_SETFEATURES,0,0,0};
1746 args[2] = lookahead ? 0xaa : 0x55;
1747 if (get_lookahead) {
1748 printf(" setting drive read-lookahead to %d", lookahead);
1749 on_off(lookahead);
1751 if (do_drive_cmd(fd, args, 0)) {
1752 err = errno;
1753 perror(" HDIO_DRIVE_CMD(setreadahead) failed");
1756 if (set_powerup_in_standby) {
1757 __u8 args[4] = {ATA_OP_SETFEATURES,0,0,0};
1758 if (powerup_in_standby == 0) {
1759 __u8 args1[4] = {ATA_OP_SETFEATURES,0,0x07,0}; /* spinup from standby */
1760 printf(" spin-up:");
1761 fflush(stdout);
1762 (void) do_drive_cmd(fd, args1, 0);
1763 } else {
1764 confirm_i_know_what_i_am_doing("-s1",
1765 "This requires BIOS and kernel support to recognize/boot the drive.");
1767 if (get_powerup_in_standby) {
1768 printf(" setting power-up in standby to %d", powerup_in_standby);
1769 fflush(stdout);
1770 on_off(powerup_in_standby);
1772 args[0] = ATA_OP_SETFEATURES;
1773 args[2] = powerup_in_standby ? 0x06 : 0x86;
1774 if (do_drive_cmd(fd, args, 0)) {
1775 err = errno;
1776 perror(" HDIO_DRIVE_CMD(powerup_in_standby) failed");
1779 if (set_apmmode) {
1780 __u8 args[4] = {ATA_OP_SETFEATURES,0,0,0};
1781 if (get_apmmode)
1782 printf(" setting Advanced Power Management level to");
1783 if (apmmode==255) {
1784 /* disable Advanced Power Management */
1785 args[2] = 0x85; /* feature register */
1786 if (get_apmmode) printf(" disabled\n");
1787 } else {
1788 /* set Advanced Power Management mode */
1789 args[2] = 0x05; /* feature register */
1790 args[1] = apmmode; /* sector count register */
1791 if (get_apmmode)
1792 printf(" 0x%02x (%d)\n",apmmode,apmmode);
1794 if (do_drive_cmd(fd, args, 0)) {
1795 err = errno;
1796 perror(" HDIO_DRIVE_CMD failed");
1799 if (set_cdromspeed) {
1800 int err1, err2;
1801 /* The CDROM_SELECT_SPEED ioctl
1802 * actually issues GPCMD_SET_SPEED to the drive.
1803 * But many newer DVD drives want GPCMD_SET_STREAMING instead,
1804 * which we now do afterwards.
1806 if (get_cdromspeed)
1807 printf ("setting cd/dvd speed to %d\n", cdromspeed);
1808 err1 = set_dvdspeed(fd, cdromspeed);
1809 err2 = ioctl(fd, CDROM_SELECT_SPEED, cdromspeed);
1810 if (err1 && err2) {
1811 err = errno;
1812 perror(" SET_STREAMING/CDROM_SELECT_SPEED both failed");
1815 if (set_acoustic) {
1816 __u8 args[4];
1817 if (get_acoustic)
1818 printf(" setting acoustic management to %d\n", acoustic);
1819 args[0] = ATA_OP_SETFEATURES;
1820 args[1] = acoustic;
1821 args[2] = acoustic ? 0x42 : 0xc2;
1822 args[3] = 0;
1823 if (do_drive_cmd(fd, args, 0)) {
1824 err = errno;
1825 perror(" HDIO_DRIVE_CMD:ACOUSTIC failed");
1828 if (set_write_read_verify) {
1829 __u8 args[4];
1830 if (get_write_read_verify)
1831 printf(" setting write-read-verify to %d\n", write_read_verify);
1832 args[0] = ATA_OP_SETFEATURES;
1833 args[1] = write_read_verify;
1834 args[2] = write_read_verify ? 0x0b : 0x8b;
1835 args[3] = 0;
1836 if (do_drive_cmd(fd, args, 0)) {
1837 err = errno;
1838 perror(" HDIO_DRIVE_CMD:WRV failed");
1841 if (set_wcache) {
1842 if (get_wcache) {
1843 printf(" setting drive write-caching to %d", wcache);
1844 on_off(wcache);
1846 if (!wcache)
1847 err = flush_wcache(fd);
1848 if (ioctl(fd, HDIO_SET_WCACHE, wcache)) {
1849 __u8 setcache[4] = {ATA_OP_SETFEATURES,0,0,0};
1850 setcache[2] = wcache ? 0x02 : 0x82;
1851 if (do_drive_cmd(fd, setcache, 0)) {
1852 err = errno;
1853 perror(" HDIO_DRIVE_CMD(setcache) failed");
1856 if (!wcache)
1857 err = flush_wcache(fd);
1859 if (set_standby) {
1860 __u8 args[4] = {ATA_OP_SETIDLE,standby,0,0};
1861 if (get_standby) {
1862 printf(" setting standby to %u", standby);
1863 interpret_standby();
1865 if (do_drive_cmd(fd, args, 0)) {
1866 err = errno;
1867 perror(" HDIO_DRIVE_CMD(setidle) failed");
1870 if (set_security) {
1871 do_set_security(fd);
1873 if (do_dco_identify) {
1874 __u16 *dco = get_dco_identify_data(fd, 0);
1875 if (dco)
1876 dco_identify_print(dco);
1878 if (do_dco_restore) {
1879 __u8 args[4] = {ATA_OP_DCO,0,0xc0,0};
1880 confirm_i_know_what_i_am_doing("--dco-restore", "You are trying to deliberately reset your drive configuration back to the factory defaults.\nThis may change the apparent capacity and feature set of the drive, making all data on it inaccessible.\nYou could lose *everything*.");
1881 printf(" issuing DCO restore command\n");
1882 if (do_drive_cmd(fd, args, 0)) {
1883 err = errno;
1884 perror(" HDIO_DRIVE_CMD(dco_restore) failed");
1887 if (do_dco_freeze) {
1888 __u8 args[4] = {ATA_OP_DCO,0,0xc1,0};
1889 printf(" issuing DCO freeze command\n");
1890 if (do_drive_cmd(fd, args, 0)) {
1891 err = errno;
1892 perror(" HDIO_DRIVE_CMD(dco_freeze) failed");
1895 if (security_freeze) {
1896 __u8 args[4] = {ATA_OP_SECURITY_FREEZE_LOCK,0,0,0};
1897 printf(" issuing security freeze command\n");
1898 if (do_drive_cmd(fd, args, 0)) {
1899 err = errno;
1900 perror(" HDIO_DRIVE_CMD(security_freeze) failed");
1903 if (set_seagate) {
1904 __u8 args[4] = {0xfb,0,0,0};
1905 if (get_seagate)
1906 printf(" disabling Seagate auto powersaving mode\n");
1907 if (do_drive_cmd(fd, args, 0)) {
1908 err = errno;
1909 perror(" HDIO_DRIVE_CMD(seagatepwrsave) failed");
1912 if (set_busstate) {
1913 if (get_busstate)
1914 printf(" setting bus state to %d (%s)\n", busstate, busstate_str(busstate));
1915 if (ioctl(fd, HDIO_SET_BUSSTATE, busstate)) {
1916 err = errno;
1917 perror(" HDIO_SET_BUSSTATE failed");
1920 if (set_max_sectors) {
1921 if (get_native_max_sectors)
1922 printf(" setting max visible sectors to %llu (%s)\n", set_max_addr, set_max_permanent ? "permanent" : "temporary");
1923 get_identify_data(fd);
1924 if (id) {
1925 if (set_max_addr < get_lba_capacity(id))
1926 confirm_i_know_what_i_am_doing("-Nnnnnn", "You have requested reducing the apparent size of the drive.\nThis is a BAD idea, and can easily destroy all of the drive's contents.");
1927 err = do_set_max_sectors(fd, set_max_addr - 1, set_max_permanent);
1928 id = NULL; /* invalidate existing identify data */
1931 if (make_bad_sector) {
1932 get_identify_data(fd);
1933 if (id) {
1934 confirm_i_know_what_i_am_doing("--make-bad-sector", "You are trying to deliberately corrupt a low-level sector on the media.\nThis is a BAD idea, and can easily result in total data loss.");
1935 err = do_make_bad_sector(fd, make_bad_sector_addr, devname);
1938 #ifdef FORMAT_AND_ERASE
1939 if (format_track) {
1940 confirm_i_know_what_i_am_doing("--format-track", "This flag is still under development and probably does not work correctly yet.\nYou are trying to deliberately destroy your device.\nThis is a BAD idea, and can easily result in total data loss.");
1941 confirm_please_destroy_my_drive("--format-track", "This might destroy the drive and/or all data on it.");
1942 err = do_format_track(fd, format_track_addr, devname);
1944 if (erase_sectors) {
1945 confirm_i_know_what_i_am_doing("--erase-sectors", "This flag is still under development and probably does not work correctly yet.\nYou are trying to deliberately destroy your device.\nThis is a BAD idea, and can easily result in total data loss.");
1946 confirm_please_destroy_my_drive("--erase-sectors", "This might destroy the drive and/or all data on it.");
1947 err = do_erase_sectors(fd, erase_sectors_addr, devname);
1949 #endif /* FORMAT_AND_ERASE */
1950 if (trim_sector_ranges_count) {
1951 if (num_flags_processed > 1 || argc)
1952 usage_help(13,EINVAL);
1953 confirm_please_destroy_my_drive("--trim-sector-ranges", "This might destroy the drive and/or all data on it.");
1954 do_trim_sector_ranges(fd, devname, trim_sector_ranges_count, trim_sector_ranges);
1956 if (write_sector) {
1957 if (num_flags_processed > 1 || argc)
1958 usage_help(14,EINVAL);
1959 confirm_i_know_what_i_am_doing("--write-sector", "You are trying to deliberately overwrite a low-level sector on the media.\nThis is a BAD idea, and can easily result in total data loss.");
1960 err = do_write_sector(fd, write_sector_addr, devname);
1962 if (do_fwdownload) {
1963 if (num_flags_processed > 1 || argc)
1964 usage_help(15,EINVAL);
1965 abort_if_not_full_device (fd, 0, devname, "--fwdownload requires the raw device, not a partition.");
1966 confirm_i_know_what_i_am_doing("--fwdownload", "This flag has not been tested with many drives to date.\nYou are trying to deliberately overwrite the drive firmware with the contents of the specified file.\nIf this fails, your drive could be toast.");
1967 confirm_please_destroy_my_drive("--fwdownload", "This might destroy the drive and well as all of the data on it.");
1968 get_identify_data(fd);
1969 if (id) {
1970 err = fwdownload(fd, id, fwpath, xfer_mode);
1971 if (err)
1972 exit(err);
1975 if (read_sector)
1976 err = do_read_sector(fd, read_sector_addr, devname);
1977 if (drq_hsm_error) {
1978 get_identify_data(fd);
1979 if (id) {
1980 __u8 args[4] = {0,0,0,0};
1981 args[0] = last_identify_op;
1982 printf(" triggering \"stuck DRQ\" host state machine error\n");
1983 flush_buffer_cache(fd);
1984 sleep(1);
1985 do_drive_cmd(fd, args, timeout_60secs);
1986 err = errno;
1987 perror("drq_hsm_error");
1988 fprintf(stderr, "ata status=0x%02x ata error=0x%02x\n", args[0], args[1]);
1991 id = NULL; /* force re-IDENTIFY in case something above modified settings */
1992 if (get_hitachi_temp) {
1993 __u8 args[4] = {0xf0,0,0x01,0}; /* "Sense Condition", vendor-specific */
1994 if (do_drive_cmd(fd, args, 0)) {
1995 err = errno;
1996 perror(" HDIO_DRIVE_CMD(hitachisensecondition) failed");
1997 } else {
1998 printf(" drive temperature (celsius) is: ");
1999 if (args[2]==0)
2000 printf("under -20");
2001 else if (args[2]==0xFF)
2002 printf("over 107");
2003 else
2004 printf("%d", args[2]/2-20);
2005 printf("\n drive temperature in range: %s\n", YN(!(args[1]&0x10)) );
2008 if (do_defaults || get_mult || do_identity) {
2009 multcount = -1;
2010 err = 0;
2011 if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount)) {
2012 err = errno;
2013 get_identify_data(fd);
2014 if (id) {
2015 err = 0;
2016 if ((id[59] & 0xff00) == 0x100)
2017 multcount = id[59] & 0xff;
2018 else
2019 multcount = 0;
2021 if (err && get_mult) {
2022 errno = err;
2023 perror(" HDIO_GET_MULTCOUNT failed");
2026 if (!err && (do_defaults || get_mult)) {
2027 printf(" multcount = %2ld", multcount);
2028 on_off(multcount);
2031 if (do_defaults || get_io32bit) {
2032 if (0 == ioctl(fd, HDIO_GET_32BIT, &parm)) {
2033 printf(" IO_support =%3ld (", parm);
2034 switch (parm) {
2035 case 0: printf("default) \n");
2036 break;
2037 case 2: printf("16-bit)\n");
2038 break;
2039 case 1: printf("32-bit)\n");
2040 break;
2041 case 3: printf("32-bit w/sync)\n");
2042 break;
2043 case 8: printf("Request-Queue-Bypass)\n");
2044 break;
2045 default:printf("\?\?\?)\n");
2047 } else if (get_io32bit) {
2048 err = errno;
2049 perror(" HDIO_GET_32BIT failed");
2052 if (do_defaults || get_unmask) {
2053 if (0 == ioctl(fd, HDIO_GET_UNMASKINTR, &parm)) {
2054 printf(" unmaskirq = %2ld", parm);
2055 on_off(parm);
2056 } else if (get_unmask) {
2057 err = errno;
2058 perror(" HDIO_GET_UNMASKINTR failed");
2062 if (do_defaults || get_dma) {
2063 if (0 == ioctl(fd, HDIO_GET_DMA, &parm)) {
2064 printf(" using_dma = %2ld", parm);
2065 if (parm == 8)
2066 printf(" (DMA-Assisted-PIO)\n");
2067 else
2068 on_off(parm);
2069 } else if (get_dma) {
2070 err = errno;
2071 perror(" HDIO_GET_DMA failed");
2074 if (get_dma_q) {
2075 err = sysfs_get_attr(fd, "device/queue_depth", "%u", &dma_q, NULL, 1);
2076 if (!err)
2077 printf(" queue_depth = %2u\n", dma_q);
2079 if (do_defaults || get_keep) {
2080 if (0 == ioctl(fd, HDIO_GET_KEEPSETTINGS, &parm)) {
2081 printf(" keepsettings = %2ld", parm);
2082 on_off(parm);
2083 } else if (get_keep) {
2084 err = errno;
2085 perror(" HDIO_GET_KEEPSETTINGS failed");
2088 if (get_nowerr) {
2089 if (ioctl(fd, HDIO_GET_NOWERR, &parm)) {
2090 err = errno;
2091 perror(" HDIO_GET_NOWERR failed");
2092 } else {
2093 printf(" nowerr = %2ld", parm);
2094 on_off(parm);
2097 if (do_defaults || get_readonly) {
2098 if (ioctl(fd, BLKROGET, &parm)) {
2099 err = errno;
2100 perror(" BLKROGET failed");
2101 } else {
2102 printf(" readonly = %2ld", parm);
2103 on_off(parm);
2106 if (do_defaults || get_fsreadahead) {
2107 if (ioctl(fd, BLKRAGET, &parm)) {
2108 err = errno;
2109 perror(" BLKRAGET failed");
2110 } else {
2111 printf(" readahead = %2ld", parm);
2112 on_off(parm);
2115 if (do_defaults || get_geom) {
2116 __u32 cyls = 0, heads = 0, sects = 0;
2117 __u64 start_lba = 0, nsectors = 0;
2118 err = get_dev_geometry (fd, &cyls, &heads, &sects, &start_lba, &nsectors);
2119 if (!err) {
2120 printf(" geometry = %u/%u/%u, sectors = %lld, start = ", cyls, heads, sects, nsectors);
2121 if (start_lba == START_LBA_UNKNOWN)
2122 printf("unknown\n");
2123 else
2124 printf("%lld\n", start_lba);
2127 if (get_wdidle3) {
2128 unsigned char timeout = 0;
2129 err = wdidle3_get_timeout(fd, &timeout);
2130 if (!err) {
2131 printf(" wdidle3 = ");
2132 wdidle3_print_timeout(timeout);
2133 putchar('\n');
2136 if (get_powermode) {
2137 __u8 args[4] = {ATA_OP_CHECKPOWERMODE1,0,0,0};
2138 const char *state = "unknown";
2139 if (do_drive_cmd(fd, args, 0)
2140 && (args[0] = ATA_OP_CHECKPOWERMODE2) /* (single =) try again with 0x98 */
2141 && do_drive_cmd(fd, args, 0)) {
2142 err = errno;
2143 } else {
2144 switch (args[2]) {
2145 case 0x00: state = "standby"; break;
2146 case 0x40: state = "NVcache_spindown"; break;
2147 case 0x41: state = "NVcache_spinup"; break;
2148 case 0x80: state = "idle"; break;
2149 case 0xff: state = "active/idle"; break;
2152 printf(" drive state is: %s\n", state);
2154 if (do_identity) {
2155 __u16 id2[256];
2157 if (!ioctl(fd, HDIO_GET_IDENTITY, id2)) {
2158 if (multcount != -1) {
2159 id2[59] = multcount | 0x100;
2160 } else {
2161 id2[59] &= ~0x100;
2163 dump_identity(id2);
2164 } else if (errno == -ENOMSG) {
2165 printf(" no identification info available\n");
2166 } else {
2167 err = errno;
2168 perror(" HDIO_GET_IDENTITY failed");
2171 if (do_IDentity) {
2172 get_identify_data(fd);
2173 if (id) {
2174 if (do_IDentity == 2)
2175 dump_sectors(id, 1);
2176 else
2177 identify((void *)id);
2180 if (get_lookahead) {
2181 get_identify_data(fd);
2182 if (id) {
2183 int supported = id[82] & 0x0040;
2184 if (supported) {
2185 lookahead = !!(id[85] & 0x0040);
2186 printf(" look-ahead = %2d", lookahead);
2187 on_off(lookahead);
2188 } else {
2189 printf(" look-ahead = not supported\n");
2193 if (get_wcache) {
2194 get_identify_data(fd);
2195 if (id) {
2196 int supported = id[82] & 0x0020;
2197 if (supported) {
2198 wcache = !!(id[85] & 0x0020);
2199 printf(" write-caching = %2d", wcache);
2200 on_off(wcache);
2201 } else {
2202 printf(" write-caching = not supported\n");
2206 if (get_apmmode) {
2207 get_identify_data(fd);
2208 if (id) {
2209 printf(" APM_level = ");
2210 if ((id[83] & 0xc008) == 0x4008) {
2211 if (id[86] & 0x0008)
2212 printf("%u\n", id[91] & 0xff);
2213 else
2214 printf("off\n");
2215 } else
2216 printf("not supported\n");
2219 if (get_acoustic) {
2220 get_identify_data(fd);
2221 if (id) {
2222 int supported = id[83] & 0x200;
2223 if (supported)
2224 printf(" acoustic = %2u (128=quiet ... 254=fast)\n", id[94] & 0xff);
2225 else
2226 printf(" acoustic = not supported\n");
2229 if (get_write_read_verify) {
2230 get_identify_data(fd);
2231 if (id) {
2232 int supported = id[119] & 0x2;
2233 if (supported)
2234 printf(" write-read-verify = %2u\n", id[120] & 0x2);
2235 else
2236 printf(" write-read-verify = not supported\n");
2239 if (get_busstate) {
2240 if (ioctl(fd, HDIO_GET_BUSSTATE, &parm)) {
2241 err = errno;
2242 perror(" HDIO_GET_BUSSTATE failed");
2243 } else {
2244 printf(" busstate = %2ld (%s)\n", parm, busstate_str(parm));
2247 if (get_native_max_sectors) {
2248 __u64 visible, native;
2249 get_identify_data(fd);
2250 if (id) {
2251 visible = get_lba_capacity(id);
2252 native = do_get_native_max_sectors(fd);
2253 if (!native) {
2254 err = errno;
2255 } else {
2256 printf(" max sectors = %llu/%llu", visible, native);
2257 if (visible < native)
2258 printf(", HPA is enabled\n");
2259 else if (visible == native)
2260 printf(", HPA is disabled\n");
2261 else {
2262 __u16 *dco = get_dco_identify_data(fd, 1);
2263 if (dco) {
2264 __u64 dco_max = dco[5];
2265 dco_max = ((((__u64)dco[5]) << 32) | (dco[4] << 16) | dco[3]) + 1;
2266 printf("(%llu?)", dco_max);
2268 printf(", HPA setting seems invalid");
2269 if ((native & 0xffffff000000ull) == 0)
2270 printf(" (buggy kernel device driver?)");
2271 putchar('\n');
2277 if (do_ctimings)
2278 time_cache(fd);
2279 if (do_flush_wcache)
2280 err = flush_wcache(fd);
2281 if (do_timings)
2282 err = time_device(fd);
2283 if (do_flush)
2284 flush_buffer_cache(fd);
2285 if (set_reread_partn) {
2286 if (get_reread_partn)
2287 printf(" re-reading partition table\n");
2288 if (ioctl(fd, BLKRRPART, NULL)) {
2289 err = errno;
2290 perror(" BLKRRPART failed");
2293 if (set_idleimmediate) {
2294 __u8 args[4] = {ATA_OP_IDLEIMMEDIATE,0,0,0};
2295 if (get_idleimmediate)
2296 printf(" issuing idle_immediate command\n");
2297 if (do_drive_cmd(fd, args, 0)) {
2298 err = errno;
2299 perror(" HDIO_DRIVE_CMD(idle_immediate) failed");
2302 if (set_standbynow) {
2303 __u8 args1[4] = {ATA_OP_STANDBYNOW1,0,0,0};
2304 __u8 args2[4] = {ATA_OP_STANDBYNOW2,0,0,0};
2305 if (get_standbynow)
2306 printf(" issuing standby command\n");
2307 if (do_drive_cmd(fd, args1, 0) && do_drive_cmd(fd, args2, 0)) {
2308 err = errno;
2309 perror(" HDIO_DRIVE_CMD(standby) failed");
2312 if (set_idleunload) {
2313 if (get_idleunload)
2314 printf(" issuing idle_immediate_unload command\n");
2315 err = do_idleunload(fd, devname);
2317 if (set_sleepnow) {
2318 __u8 args1[4] = {ATA_OP_SLEEPNOW1,0,0,0};
2319 __u8 args2[4] = {ATA_OP_SLEEPNOW2,0,0,0};
2320 if (get_sleepnow)
2321 printf(" issuing sleep command\n");
2322 if (do_drive_cmd(fd, args1, 0) && do_drive_cmd(fd, args2, 0)) {
2323 err = errno;
2324 perror(" HDIO_DRIVE_CMD(sleep) failed");
2327 if (set_doreset) {
2328 if (get_doreset)
2329 printf(" resetting drive\n");
2330 if (ioctl(fd, HDIO_DRIVE_RESET, NULL)) {
2331 err = errno;
2332 perror(" HDIO_DRIVE_RESET failed");
2335 close (fd);
2336 if (err)
2337 exit (err);
2340 #define GET_XFERMODE(flag, num) \
2341 do { \
2342 char *tmpstr = name; \
2343 tmpstr[0] = '\0'; \
2344 if (!*argp && argc && isalnum(**argv)) \
2345 argp = *argv++, --argc; \
2346 while (isalnum(*argp) && (tmpstr - name) < 31) {\
2347 tmpstr[0] = *argp++; \
2348 tmpstr[1] = '\0'; \
2349 ++tmpstr; \
2351 num = translate_xfermode(name); \
2352 if (num == -1) \
2353 flag = 0; \
2354 else \
2355 flag = 1; \
2356 } while (0)
2358 static int fromhex (__u8 c)
2360 if (c >= '0' && c <= '9')
2361 return (c - '0');
2362 if (c >= 'a' && c <= 'f')
2363 return 10 + (c - 'a');
2364 if (c >= 'A' && c <= 'F')
2365 return 10 + (c - 'A');
2366 fprintf(stderr, "bad char: '%c' 0x%02x\n", c, c);
2367 exit(EINVAL);
2370 static int ishex (char c)
2372 return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
2375 static void
2376 identify_from_stdin (void)
2378 __u16 sbuf[512];
2379 int err, wc = 0;
2381 do {
2382 int digit;
2383 int d[4];
2385 if (ishex(d[digit=0] = getchar())
2386 && ishex(d[++digit] = getchar())
2387 && ishex(d[++digit] = getchar())
2388 && ishex(d[++digit] = getchar())) {
2389 sbuf[wc] = (fromhex(d[0]) << 12) | (fromhex(d[1]) << 8) | (fromhex(d[2]) << 4) | fromhex(d[3]);
2390 ++wc;
2391 } else if (d[digit] == EOF) {
2392 goto eof;
2393 } else if (wc == 0) {
2394 /* skip over leading lines of cruft */
2395 while (d[digit] != '\n') {
2396 if (d[digit] == EOF)
2397 goto eof;
2398 d[digit=0] = getchar();
2401 } while (wc < 256);
2402 putchar('\n');
2403 identify(sbuf);
2404 return;
2405 eof:
2406 err = errno;
2407 fprintf(stderr, "read only %u/256 IDENTIFY words from stdin: %s\n", wc, strerror(err));
2408 exit(err);
2411 static void
2412 numeric_parm (char c, const char *name, int *val, int *setparm, int *getparm, int min, int max, int set_only)
2414 int got_digit = 0;
2416 *val = 0;
2417 *getparm = noisy;
2418 noisy = 1;
2419 if (!*argp && argc && isdigit(**argv))
2420 argp = *argv++, --argc;
2421 while (isdigit(*argp)) {
2422 *setparm = 1;
2423 *val = (*val * 10) + (*argp++ - '0');
2424 got_digit = 1;
2426 if ((set_only && !got_digit) || *val < min || *val > max) {
2427 fprintf(stderr, " -%c: bad/missing %s value (%d..%d)\n", c, name, min, max);
2428 exit(EINVAL);
2432 #define NUMERIC_PARM(CH,NAME,VAR,MIN,MAX,GETSET) numeric_parm(CH,NAME,&VAR,&set_##VAR,&get_##VAR,MIN,MAX,GETSET)
2433 #define GET_SET_PARM(CH,NAME,VAR,MIN,MAX) CH:NUMERIC_PARM(CH,NAME,VAR,MIN,MAX,0);break
2434 #define SET_PARM(CH,NAME,VAR,MIN,MAX) CH:NUMERIC_PARM(CH,NAME,VAR,MIN,MAX,1);break
2435 #define SET_FLAG1(VAR) get_##VAR=noisy;noisy=1;set_##VAR=1
2436 #define SET_FLAG(CH,VAR) CH:SET_FLAG1(VAR);break
2437 #define DO_FLAG(CH,VAR) CH:VAR=1;noisy=1;break
2438 #define INCR_FLAG(CH,VAR) CH:VAR++;noisy=1;break
2440 static void get_security_password (int handle_NULL)
2442 unsigned int maxlen = sizeof(security_password) - 1;
2444 if (argc < 2) {
2445 fprintf(stderr, "missing PASSWD\n");
2446 exit(EINVAL);
2448 argp = *argv++, --argc;
2449 if (!argp) {
2450 fprintf(stderr, "missing PASSWD\n");
2451 exit(EINVAL);
2453 if (strlen(argp) > maxlen) {
2454 fprintf(stderr, "PASSWD too long (must be %d chars max)\n", maxlen);
2455 exit(EINVAL);
2457 memset(security_password, 0, maxlen + 1);
2458 if (!handle_NULL || strcmp(argp, "NULL"))
2459 strcpy(security_password, argp);
2460 printf("security_password=\"%s\"\n", security_password);
2461 while (*argp)
2462 ++argp;
2465 static const char *lba_emsg = "bad/missing sector value";
2466 static const char *count_emsg = "bad/missing sector count";
2467 static const __u64 lba_limit = (1ULL << 48) - 1;
2469 static int
2470 get_u64_parm (int optional, const char flag_c, int *flag_p, __u64 *value_p,
2471 unsigned int min_value, __u64 limit, const char *eprefix, const char *emsg)
2473 int got_value = 0;
2474 __u64 value = *value_p;
2475 char *endp = NULL;
2477 if (!*argp && argc && (isdigit(**argv) || (flag_p && flag_c == **argv)))
2478 argp = *argv++, --argc;
2480 if (flag_p) {
2481 *flag_p = 0;
2482 if (*argp == flag_c) {
2483 *flag_p = 1;
2484 argp++;
2488 errno = 0;
2489 value = strtoll(argp, &endp, 0);
2490 if (errno != 0 || (endp != argp && ((__s64)value < (__s64)min_value || value > limit))) {
2491 fprintf(stderr, " %s: %s\n", eprefix, emsg);
2492 exit(EINVAL);
2494 if (endp != argp) {
2495 got_value = 1;
2496 *value_p = value;
2497 argp = endp;
2499 if (!optional && !got_value) {
2500 fprintf(stderr, " %s: %s\n", eprefix, emsg);
2501 exit(EINVAL);
2503 return got_value;
2506 static void
2507 get_set_max_sectors_parms (void)
2509 get_native_max_sectors = noisy;
2510 noisy = 1;
2511 set_max_sectors = get_u64_parm(1, 'p', &set_max_permanent, &set_max_addr, 1, lba_limit, "-N", lba_emsg);
2514 static void
2515 handle_standalone_longarg (char *name)
2517 if (num_flags_processed) {
2518 if (verbose)
2519 fprintf(stderr, "handle_standalone_longarg: num_flags_processed == %d\n", num_flags_processed);
2520 usage_help(1,EINVAL);
2522 /* --Istdin is special: no filename arg(s) wanted here */
2523 if (0 == strcasecmp(name, "Istdin")) {
2524 if (argc > 0) {
2525 if (verbose)
2526 fprintf(stderr, "handle_standalone_longarg: argc(%d) > 0\n", argc);
2527 usage_help(2,EINVAL);
2529 identify_from_stdin();
2530 exit(0);
2532 if (0 == strcasecmp(name, "dco-restore")) {
2533 do_dco_restore = 1;
2534 } else if (0 == strcasecmp(name, "security-help")) {
2535 security_help(0);
2536 exit(0);
2537 } else if (0 == strcasecmp(name, "security-unlock")) {
2538 set_security = 1;
2539 security_command = ATA_OP_SECURITY_UNLOCK;
2540 get_security_password(0);
2541 } else if (0 == strcasecmp(name, "security-set-pass")) {
2542 set_security = 1;
2543 security_command = ATA_OP_SECURITY_SET_PASS;
2544 get_security_password(1);
2545 } else if (0 == strcasecmp(name, "security-disable")) {
2546 set_security = 1;
2547 security_command = ATA_OP_SECURITY_DISABLE;
2548 get_security_password(1);
2549 } else if (0 == strcasecmp(name, "security-erase")) {
2550 set_security = 1;
2551 security_command = ATA_OP_SECURITY_ERASE_UNIT;
2552 get_security_password(1);
2553 } else if (0 == strcasecmp(name, "security-erase-enhanced")) {
2554 set_security = 1;
2555 enhanced_erase = 1;
2556 security_command = ATA_OP_SECURITY_ERASE_UNIT;
2557 get_security_password(1);
2558 } else {
2559 usage_help(3,EINVAL);
2563 static void
2564 get_filename_parm (char **result, const char *emsg)
2566 if (!*argp && argc)
2567 argp = *argv++, --argc;
2568 if (!argp || !*argp) {
2569 fprintf(stderr, " %s: bad/missing filename parameter\n", emsg);
2570 exit(EINVAL);
2572 *result = argp;
2573 argp += strlen(argp);
2574 // if (argc) argp = *argv++, --argc;
2577 static void
2578 do_fallocate (const char *name)
2580 char *path;
2581 __u64 blkcount;
2583 get_u64_parm(0, 0, NULL, &blkcount, 0, (1ULL << 53), name, "bad/missing block-count");
2584 get_filename_parm(&path, name);
2585 if (num_flags_processed || argc)
2586 usage_help(4,EINVAL);
2587 exit(do_fallocate_syscall(path, blkcount * 1024));
2590 static void
2591 do_fibmap_file (const char *name)
2593 int err;
2594 char *path;
2596 get_filename_parm(&path, name);
2597 if (num_flags_processed || argc)
2598 usage_help(5,EINVAL);
2599 err = do_filemap(path);
2600 exit(err);
2603 static int
2604 get_longarg (void)
2606 char *name = argp;
2608 while (*argp)
2609 ++argp;
2610 if (0 == strcasecmp(name, "verbose")) {
2611 verbose = 1;
2612 --num_flags_processed; /* doesn't count as an action flag */
2613 } else if (0 == strcasecmp(name, "prefer-ata12")) {
2614 prefer_ata12 = 1;
2615 --num_flags_processed; /* doesn't count as an action flag */
2616 } else if (0 == strcasecmp(name, "offset")) {
2617 set_timings_offset = 1;
2618 get_u64_parm(0, 0, NULL, &timings_offset, 0, ~0, name, "GB offset for -t flag");
2619 timings_offset *= 0x40000000ULL;
2620 } else if (0 == strcasecmp(name, "yes-i-know-what-i-am-doing")) {
2621 i_know_what_i_am_doing = 1;
2622 --num_flags_processed; /* doesn't count as an action flag */
2623 } else if (0 == strcasecmp(name, "please-destroy-my-drive")) {
2624 please_destroy_my_drive = 1;
2625 --num_flags_processed; /* doesn't count as an action flag */
2626 } else if (0 == strcasecmp(name, "direct")) {
2627 open_flags |= O_DIRECT;
2628 --num_flags_processed; /* doesn't count as an action flag */
2629 } else if (0 == strcasecmp(name, "drq-hsm-error")) {
2630 drq_hsm_error = 1;
2631 } else if (0 == strcasecmp(name, "dco-freeze")) {
2632 do_dco_freeze = 1;
2633 } else if (0 == strcasecmp(name, "dco-identify")) {
2634 do_dco_identify = 1;
2635 } else if (0 == strcasecmp(name, "fallocate")) {
2636 do_fallocate(name);
2637 } else if (0 == strcasecmp(name, "fibmap")) {
2638 do_fibmap_file(name);
2639 } else if (0 == strcasecmp(name, "fwdownload-mode3")) {
2640 get_filename_parm(&fwpath, name);
2641 do_fwdownload = 1;
2642 xfer_mode = 3;
2643 } else if (0 == strcasecmp(name, "fwdownload-mode3-max")) {
2644 get_filename_parm(&fwpath, name);
2645 do_fwdownload = 1;
2646 xfer_mode = 30;
2647 } else if (0 == strcasecmp(name, "fwdownload-mode7")) {
2648 get_filename_parm(&fwpath, name);
2649 do_fwdownload = 1;
2650 xfer_mode = 7;
2651 } else if (0 == strcasecmp(name, "fwdownload")) {
2652 get_filename_parm(&fwpath, name);
2653 do_fwdownload = 1;
2654 xfer_mode = 0;
2655 } else if (0 == strcasecmp(name, "idle-immediate")) {
2656 SET_FLAG1(idleimmediate);
2657 } else if (0 == strcasecmp(name, "idle-unload")) {
2658 SET_FLAG1(idleunload);
2659 } else if (0 == strcasecmp(name, "make-bad-sector")) {
2660 make_bad_sector = 1;
2661 get_u64_parm(0, 'f', &make_bad_sector_flagged, &make_bad_sector_addr, 0, lba_limit, name, lba_emsg);
2662 #ifdef FORMAT_AND_ERASE
2663 } else if (0 == strcasecmp(name, "format-track")) {
2664 format_track = 1;
2665 get_u64_parm(0, 0, NULL, &format_track_addr, 0, lba_limit, name, lba_emsg);
2666 } else if (0 == strcasecmp(name, "erase-sectors")) {
2667 erase_sectors = 1;
2668 get_u64_parm(0, 0, NULL, &erase_sectors_addr, 0, lba_limit, name, lba_emsg);
2669 #endif
2670 } else if (0 == strcasecmp(name, "trim-sector-ranges-stdin")) {
2671 trim_from_stdin = 1;
2672 } else if (0 == strcasecmp(name, "trim-sector-ranges")) {
2673 int i, optional = 0, max_ranges = argc;
2674 trim_sector_ranges = malloc(sizeof(struct sector_range_s) * max_ranges);
2675 if (!trim_sector_ranges) {
2676 int err = errno;
2677 perror("malloc()");
2678 exit(err);
2680 open_flags |= O_RDWR;
2681 for (i = 0; i < max_ranges; ++i) {
2682 char err_prefix[64];
2683 struct sector_range_s *p = &trim_sector_ranges[i];
2684 sprintf(err_prefix, "%s[%u]", name, i);
2685 if (!get_u64_parm(optional, 0, NULL, &(p->lba), 0, lba_limit, err_prefix, lba_emsg))
2686 break;
2687 if (*argp++ != ':' || !isdigit(*argp)) {
2688 fprintf(stderr, "%s: %s\n", err_prefix, count_emsg);
2689 exit(EINVAL);
2691 get_u64_parm(0, 0, NULL, &(p->nsectors), 1, 0xffff, err_prefix, count_emsg);
2692 optional = 1;
2693 trim_sector_ranges_count = i + 1;
2695 } else if (0 == strcasecmp(name, "write-sector") || 0 == strcasecmp(name, "repair-sector")) {
2696 write_sector = 1;
2697 get_u64_parm(0, 0, NULL, &write_sector_addr, 0, lba_limit, name, lba_emsg);
2698 } else if (0 == strcasecmp(name, "read-sector")) {
2699 read_sector = 1;
2700 get_u64_parm(0, 0, NULL, &read_sector_addr, 0, lba_limit, name, lba_emsg);
2701 } else if (0 == strcasecmp(name, "Istdout")) {
2702 do_IDentity = 2;
2703 } else if (0 == strcasecmp(name, "security-mode")) {
2704 if (argc && isalpha(**argv)) {
2705 argp = *argv++, --argc;
2706 if (*argp == 'm') /* max */
2707 security_mode = 1;
2708 else if (*argp == 'h') /* high */
2709 security_mode = 0;
2710 else
2711 security_help(EINVAL);
2712 while (*argp) ++argp;
2714 --num_flags_processed; /* doesn't count as an action flag */
2715 } else if (0 == strcasecmp(name, "user-master")) {
2716 if (argc && isalpha(**argv)) {
2717 argp = *argv++, --argc;
2718 if (*argp == 'u') /* user */
2719 security_master = 0;
2720 else if (*argp == 'm') /* master */
2721 security_master = 1;
2722 else
2723 security_help(EINVAL);
2724 while (*argp) ++argp;
2726 --num_flags_processed; /* doesn't count as an action flag */
2727 } else if (0 == strcasecmp(name, "security-freeze")) {
2728 security_freeze = 1;
2729 } else {
2730 handle_standalone_longarg(name);
2731 return 1; /* 1 == no more flags allowed */
2733 return 0; /* additional flags allowed */
2736 int main (int _argc, char **_argv)
2738 int no_more_flags = 0, disallow_flags = 0;
2739 char c;
2740 char name[32];
2742 argc = _argc;
2743 argv = _argv;
2744 argp = NULL;
2746 if ((progname = (char *) strrchr(*argv, '/')) == NULL)
2747 progname = *argv;
2748 else
2749 progname++;
2750 ++argv;
2752 if (!--argc)
2753 usage_help(6,EINVAL);
2754 while (argc--) {
2755 argp = *argv++;
2756 if (no_more_flags || argp[0] != '-') {
2757 if (!num_flags_processed)
2758 do_defaults = 1;
2759 process_dev(argp);
2760 continue;
2762 if (0 == strcmp(argp, "--")) {
2763 no_more_flags = 1;
2764 continue;
2766 if (disallow_flags)
2767 usage_help(7,EINVAL);
2768 if (!*++argp)
2769 usage_help(8,EINVAL);
2770 while (argp && (c = *argp++)) {
2771 switch (c) {
2772 case GET_SET_PARM('a',"filesystem-read-ahead",fsreadahead,0,2048);
2773 case GET_SET_PARM('A',"look-ahead",lookahead,0,1);
2774 case GET_SET_PARM('b',"bus-state",busstate,0,2);
2775 case GET_SET_PARM('B',"power-management-mode",apmmode,0,255);
2776 case GET_SET_PARM('c',"32-bit-IO",io32bit,0,3);
2777 case SET_FLAG('C',powermode);
2778 case GET_SET_PARM('d',"dma-enable",dma,0,1);
2779 case SET_PARM('D',"defects-management",defects,0,1);
2780 case SET_PARM('E',"CDROM/DVD-speed",cdromspeed,0,255);
2781 case DO_FLAG('f',do_flush);
2782 case DO_FLAG('F',do_flush_wcache);
2783 case DO_FLAG('g',get_geom);
2784 case 'h': usage_help(9,0); break;
2785 case SET_FLAG('H',hitachi_temp);
2786 case DO_FLAG('i',do_identity);
2787 case DO_FLAG('I',do_IDentity);
2788 case GET_SET_PARM('J',"WDC-idle3-timeout",wdidle3,0,300);
2789 case GET_SET_PARM('k',"kernel-keep-settings",keep,0,1);
2790 case SET_PARM('K',"drive-keep-settings",dkeep,0,1);
2791 case SET_PARM('L',"door-lock",doorlock,0,1);
2792 case GET_SET_PARM('m',"multmode-count",mult,0,64);
2793 case GET_SET_PARM('M',"acoustic-management",acoustic,0,255);
2794 case GET_SET_PARM('n',"ignore-write-errors",nowerr,0,1);
2795 case 'N': get_set_max_sectors_parms(); break;
2796 case SET_PARM('P',"prefetch",prefetch,0,255);
2797 case 'q': quiet = 1; noisy = 0; break;
2798 case GET_SET_PARM('Q',"queue-depth",dma_q,0,1024);
2799 case SET_PARM('s',"powerup-in-standby",powerup_in_standby,0,1);
2800 case SET_PARM('S',"standby-interval",standby,0,255);
2801 case GET_SET_PARM('r',"read-only",readonly,0,1);
2802 case GET_SET_PARM('R',"write-read-verify",write_read_verify,0,3);
2803 case DO_FLAG('t',do_timings);
2804 case DO_FLAG('T',do_ctimings);
2805 case GET_SET_PARM('u',"unmask-irq",unmask,0,1);
2806 case DO_FLAG('v',do_defaults);
2807 case 'V': fprintf(stdout, "%s %s\n", progname, VERSION); exit(0);
2808 case SET_FLAG('w',doreset);
2809 case GET_SET_PARM('W',"write-cache",wcache,0,1);
2810 case SET_FLAG('y',standbynow);
2811 case SET_FLAG('Y',sleepnow);
2812 case SET_FLAG('z',reread_partn);
2813 case SET_FLAG('Z',seagate);
2815 case '-':
2816 if (get_longarg())
2817 disallow_flags = 1;
2818 break;
2820 case 'p':
2821 get_piomode = noisy;
2822 noisy = 1;
2823 GET_XFERMODE(set_piomode,piomode);
2824 break;
2826 case 'X':
2827 get_xfermode = noisy;
2828 noisy = 1;
2829 GET_XFERMODE(set_xfermode,xfermode_requested);
2830 if (!set_xfermode)
2831 fprintf(stderr, "-X: missing value\n");
2832 break;
2835 default:
2836 usage_help(10,EINVAL);
2838 num_flags_processed++;
2840 if (!argc)
2841 usage_help(11,EINVAL);
2843 return 0;