chiark / gitweb /
ata_id: export more advanced ATA features
[elogind.git] / extras / ata_id / ata_id.c
1 /*
2  * ata_id - reads product/serial number from ATA drives
3  *
4  * Copyright (C) 2005-2008 Kay Sievers <kay.sievers@vrfy.org>
5  * Copyright (C) 2009 Lennart Poettering <lennart@poettering.net>
6  * Copyright (C) 2009 David Zeuthen <zeuthen@gmail.com>
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdint.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 #include <assert.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <getopt.h>
32 #include <scsi/scsi.h>
33 #include <scsi/sg.h>
34 #include <scsi/scsi_ioctl.h>
35 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <linux/types.h>
39 #include <linux/hdreg.h>
40 #include <linux/fs.h>
41 #include <arpa/inet.h>
42
43 #include "libudev.h"
44 #include "libudev-private.h"
45
46 #define COMMAND_TIMEOUT 2000
47
48 /* Sends a SCSI command block */
49 static int sg_io(int fd, int direction,
50                  const void *cdb, size_t cdb_len,
51                  void *data, size_t data_len,
52                  void *sense, size_t sense_len)
53 {
54
55         struct sg_io_hdr io_hdr;
56
57         memset(&io_hdr, 0, sizeof(struct sg_io_hdr));
58         io_hdr.interface_id = 'S';
59         io_hdr.cmdp = (unsigned char*) cdb;
60         io_hdr.cmd_len = cdb_len;
61         io_hdr.dxferp = data;
62         io_hdr.dxfer_len = data_len;
63         io_hdr.sbp = sense;
64         io_hdr.mx_sb_len = sense_len;
65         io_hdr.dxfer_direction = direction;
66         io_hdr.timeout = COMMAND_TIMEOUT;
67         return ioctl(fd, SG_IO, &io_hdr);
68 }
69
70 static int disk_command(int fd, int command, int direction, void *cmd_data,
71                         void *data, size_t *len)
72 {
73         uint8_t *bytes = cmd_data;
74         uint8_t cdb[12];
75         uint8_t sense[32];
76         uint8_t *desc = sense+8;
77         int ret;
78
79         /*
80          * ATA Pass-Through 12 byte command, as described in "T10 04-262r8
81          * ATA Command Pass-Through":
82          * http://www.t10.org/ftp/t10/document.04/04-262r8.pdf
83          */
84         memset(cdb, 0, sizeof(cdb));
85         cdb[0] = 0xa1; /* OPERATION CODE: 12 byte pass through */
86         if (direction == SG_DXFER_NONE) {
87                 cdb[1] = 3 << 1;        /* PROTOCOL: Non-Data */
88                 cdb[2] = 0x20;          /* OFF_LINE=0, CK_COND=1, T_DIR=0, BYT_BLOK=0, T_LENGTH=0 */
89         } else if (direction == SG_DXFER_FROM_DEV) {
90                 cdb[1] = 4 << 1;        /* PROTOCOL: PIO Data-in */
91                 cdb[2] = 0x2e;          /* OFF_LINE=0, CK_COND=1, T_DIR=1, BYT_BLOK=1, T_LENGTH=2 */
92         } else if (direction == SG_DXFER_TO_DEV) {
93                 cdb[1] = 5 << 1;        /* PROTOCOL: PIO Data-Out */
94                 cdb[2] = 0x26;          /* OFF_LINE=0, CK_COND=1, T_DIR=0, BYT_BLOK=1, T_LENGTH=2 */
95         }
96         cdb[3] = bytes[1];              /* FEATURES */
97         cdb[4] = bytes[3];              /* SECTORS */
98         cdb[5] = bytes[9];              /* LBA LOW */
99         cdb[6] = bytes[8];              /* LBA MID */
100         cdb[7] = bytes[7];              /* LBA HIGH */
101         cdb[8] = bytes[10] & 0x4F;      /* SELECT */
102         cdb[9] = (uint8_t) command;
103         memset(sense, 0, sizeof(sense));
104         if ((ret = sg_io(fd, direction, cdb, sizeof(cdb), data, len ? *len : 0, sense, sizeof(sense))) < 0)
105                 return ret;
106         if (sense[0] != 0x72 || desc[0] != 0x9 || desc[1] != 0x0c) {
107                 errno = EIO;
108                 return -1;
109         }
110
111         memset(bytes, 0, 12);
112         bytes[1] = desc[3]; /* FEATURES */
113         bytes[2] = desc[4]; /* STATUS */
114         bytes[3] = desc[5]; /* SECTORS */
115         bytes[9] = desc[7]; /* LBA LOW */
116         bytes[8] = desc[9]; /* LBA MID */
117         bytes[7] = desc[11]; /* LBA HIGH */
118         bytes[10] = desc[12]; /* SELECT */
119         bytes[11] = desc[13]; /* ERROR */
120         return ret;
121 }
122
123 /**
124  * disk_identify_get_string:
125  * @identify: A block of IDENTIFY data
126  * @offset_words: Offset of the string to get, in words.
127  * @dest: Destination buffer for the string.
128  * @dest_len: Length of destination buffer, in bytes.
129  *
130  * Copies the ATA string from @identify located at @offset_words into @dest.
131  */
132 static void disk_identify_get_string (uint8_t identify[512],
133                                       unsigned int offset_words,
134                                       char *dest,
135                                       size_t dest_len)
136 {
137         unsigned int c1;
138         unsigned int c2;
139
140         assert (identify != NULL);
141         assert (dest != NULL);
142         assert ((dest_len & 1) == 0);
143
144         while (dest_len > 0) {
145                 c1 = ((uint16_t *) identify)[offset_words] >> 8;
146                 c2 = ((uint16_t *) identify)[offset_words] & 0xff;
147                 *dest = c1;
148                 dest++;
149                 *dest = c2;
150                 dest++;
151                 offset_words++;
152                 dest_len -= 2;
153         }
154 }
155
156 static void disk_identify_fixup_string (uint8_t identify[512],
157                                         unsigned int offset_words,
158                                         size_t len)
159 {
160         disk_identify_get_string(identify, offset_words,
161                                  (char *) identify + offset_words * 2, len);
162 }
163
164 static void disk_identify_fixup_uint16 (uint8_t identify[512], unsigned int offset_words)
165 {
166         uint16_t *p;
167
168         p = (uint16_t *) identify;
169         p[offset_words] = le16toh (p[offset_words]);
170 }
171
172 /**
173  * disk_identify:
174  * @udev: The libudev context.
175  * @fd: File descriptor for the block device.
176  * @out_identify: Return location for IDENTIFY data.
177  *
178  * Sends the IDENTIFY DEVICE command to the device represented by
179  * @fd. If successful, then the result will be copied into
180  * @out_identify.
181  *
182  * This routine is based on code from libatasmart, Copyright 2008
183  * Lennart Poettering, LGPL v2.1.
184  *
185  * Returns: 0 if the IDENTIFY data was successfully obtained,
186  * otherwise non-zero with errno set.
187  */
188 static int disk_identify (struct udev *udev,
189                           int fd,
190                           uint8_t out_identify[512])
191 {
192         int ret;
193         uint64_t size;
194         struct stat st;
195         uint16_t cmd[6];
196         size_t len = 512;
197         const uint8_t *p;
198
199         assert (out_identify != NULL);
200
201         /* init results */
202         ret = -1;
203         memset (out_identify, '\0', 512);
204
205         if ((ret = fstat(fd, &st)) < 0)
206                 goto fail;
207
208         if (!S_ISBLK(st.st_mode)) {
209                 errno = ENODEV;
210                 goto fail;
211         }
212
213         /* So, it's a block device. Let's make sure the ioctls work */
214         if ((ret = ioctl(fd, BLKGETSIZE64, &size)) < 0)
215                 goto fail;
216
217         if (size <= 0 || size == (uint64_t) -1) {
218                 errno = EIO;
219                 goto fail;
220         }
221
222         memset(cmd, 0, sizeof(cmd));
223         cmd[1] = htons(1);
224         ret = disk_command(fd,
225                            0xEC, /* IDENTIFY DEVICE command */
226                            SG_DXFER_FROM_DEV, cmd,
227                            out_identify, &len);
228         if (ret != 0)
229                 goto fail;
230
231         if (len != 512) {
232                 errno = EIO;
233                 goto fail;
234         }
235
236          /* Check if IDENTIFY data is all NULs */
237         for (p = out_identify; p < (const uint8_t*) out_identify + len; p++) {
238                 if (*p) {
239                         p = NULL;
240                         break;
241                 }
242         }
243
244         if (p) {
245                 errno = EIO;
246                 goto fail;
247         }
248
249         ret = 0;
250 fail:
251         return ret;
252 }
253
254 static void log_fn(struct udev *udev, int priority,
255                    const char *file, int line, const char *fn,
256                    const char *format, va_list args)
257 {
258         vsyslog(priority, format, args);
259 }
260
261 int main(int argc, char *argv[])
262 {
263         struct udev *udev;
264         struct hd_driveid id;
265          uint8_t identify[512];
266         char model[41];
267         char model_enc[256];
268         char serial[21];
269         char revision[9];
270         const char *node = NULL;
271         int export = 0;
272         int fd;
273          uint16_t word;
274         int rc = 0;
275         static const struct option options[] = {
276                 { "export", no_argument, NULL, 'x' },
277                 { "help", no_argument, NULL, 'h' },
278                 {}
279         };
280
281         udev = udev_new();
282         if (udev == NULL)
283                 goto exit;
284
285         udev_log_init("ata_id");
286         udev_set_log_fn(udev, log_fn);
287
288         while (1) {
289                 int option;
290
291                 option = getopt_long(argc, argv, "xh", options, NULL);
292                 if (option == -1)
293                         break;
294
295                 switch (option) {
296                 case 'x':
297                         export = 1;
298                         break;
299                 case 'h':
300                         printf("Usage: ata_id [--export] [--help] <device>\n"
301                                "  --export    print values as environment keys\n"
302                                "  --help      print this help text\n\n");
303                 default:
304                         rc = 1;
305                         goto exit;
306                 }
307         }
308
309         node = argv[optind];
310         if (node == NULL) {
311                 err(udev, "no node specified\n");
312                 rc = 1;
313                 goto exit;
314         }
315
316         fd = open(node, O_RDONLY|O_NONBLOCK);
317         if (fd < 0) {
318                 err(udev, "unable to open '%s'\n", node);
319                 rc = 1;
320                 goto exit;
321         }
322
323         if (disk_identify(udev, fd, identify) == 0) {
324                 /*
325                  * fix up only the fields from the IDENTIFY data that we are going to
326                  * use and copy it into the hd_driveid struct for convenience
327                  */
328                 disk_identify_fixup_string (identify,  10, 20); /* serial */
329                 disk_identify_fixup_string (identify,  23,  6); /* fwrev */
330                 disk_identify_fixup_string (identify,  27, 40); /* model */
331                 disk_identify_fixup_uint16 (identify,   0);     /* configuration */
332                 disk_identify_fixup_uint16 (identify,  75);     /* queue depth */
333                 disk_identify_fixup_uint16 (identify,  75);     /* SATA capabilities */
334                 disk_identify_fixup_uint16 (identify,  82);     /* command set supported */
335                 disk_identify_fixup_uint16 (identify,  83);     /* command set supported */
336                 disk_identify_fixup_uint16 (identify,  84);     /* command set supported */
337                 disk_identify_fixup_uint16 (identify,  85);     /* command set supported */
338                 disk_identify_fixup_uint16 (identify,  86);     /* command set supported */
339                 disk_identify_fixup_uint16 (identify,  87);     /* command set supported */
340                 disk_identify_fixup_uint16 (identify,  89);     /* time required for SECURITY ERASE UNIT */
341                 disk_identify_fixup_uint16 (identify,  90);     /* time required for enhanced SECURITY ERASE UNIT */
342                 disk_identify_fixup_uint16 (identify,  91);     /* current APM values */
343                 disk_identify_fixup_uint16 (identify,  94);     /* current AAM value */
344                 disk_identify_fixup_uint16 (identify, 128);     /* device lock function */
345                 disk_identify_fixup_uint16 (identify, 217);     /* nominal media rotation rate */
346                 memcpy(&id, identify, sizeof id);
347         } else {
348                 /* If this fails, then try HDIO_GET_IDENTITY */
349                 if (ioctl(fd, HDIO_GET_IDENTITY, &id) != 0) {
350                         if (errno == ENOTTY) {
351                                 info(udev, "HDIO_GET_IDENTITY unsupported for '%s'\n", node);
352                                 rc = 2;
353                         } else {
354                                 err(udev, "HDIO_GET_IDENTITY failed for '%s'\n", node);
355                                 rc = 3;
356                         }
357                         goto close;
358                 }
359         }
360
361         memcpy (model, id.model, 40);
362         model[40] = '\0';
363         udev_util_encode_string(model, model_enc, sizeof(model_enc));
364         udev_util_replace_whitespace((char *) id.model, model, 40);
365         udev_util_replace_chars(model, NULL);
366         udev_util_replace_whitespace((char *) id.serial_no, serial, 20);
367         udev_util_replace_chars(serial, NULL);
368         udev_util_replace_whitespace((char *) id.fw_rev, revision, 8);
369         udev_util_replace_chars(revision, NULL);
370
371         if (export) {
372                   /* Set this to convey the disk speaks the ATA protocol */
373                   printf("ID_ATA=1\n");
374
375                 if ((id.config >> 8) & 0x80) {
376                         /* This is an ATAPI device */
377                         switch ((id.config >> 8) & 0x1f) {
378                         case 0:
379                                 printf("ID_TYPE=cd\n");
380                                 break;
381                         case 1:
382                                 printf("ID_TYPE=tape\n");
383                                 break;
384                         case 5:
385                                 printf("ID_TYPE=cd\n");
386                                 break;
387                         case 7:
388                                 printf("ID_TYPE=optical\n");
389                                 break;
390                         default:
391                                 printf("ID_TYPE=generic\n");
392                                 break;
393                         }
394                 } else {
395                         printf("ID_TYPE=disk\n");
396                 }
397                 printf("ID_BUS=ata\n");
398                 printf("ID_MODEL=%s\n", model);
399                 printf("ID_MODEL_ENC=%s\n", model_enc);
400                 printf("ID_REVISION=%s\n", revision);
401                 printf("ID_SERIAL=%s_%s\n", model, serial);
402                 printf("ID_SERIAL_SHORT=%s\n", serial);
403
404                 if (id.command_set_1 & (1<<5)) {
405                         printf ("ID_ATA_WRITE_CACHE=1\n");
406                         printf ("ID_ATA_WRITE_CACHE_ENABLED=%d\n", (id.cfs_enable_1 & (1<<5)) ? 1 : 0);
407                 }
408                 if (id.command_set_1 & (1<<10)) {
409                         printf("ID_ATA_FEATURE_SET_HPA=1\n");
410                         printf("ID_ATA_FEATURE_SET_HPA_ENABLED=%d\n", (id.cfs_enable_1 & (1<<10)) ? 1 : 0);
411
412                         /*
413                          * TODO: use the READ NATIVE MAX ADDRESS command to get the native max address
414                          * so it is easy to check whether the protected area is in use.
415                          */
416                 }
417                 if (id.command_set_1 & (1<<3)) {
418                         printf("ID_ATA_FEATURE_SET_PM=1\n");
419                         printf("ID_ATA_FEATURE_SET_PM_ENABLED=%d\n", (id.cfs_enable_1 & (1<<3)) ? 1 : 0);
420                 }
421                 if (id.command_set_1 & (1<<1)) {
422                         printf("ID_ATA_FEATURE_SET_SECURITY=1\n");
423                         printf("ID_ATA_FEATURE_SET_SECURITY_ENABLED=%d\n", (id.cfs_enable_1 & (1<<1)) ? 1 : 0);
424                         printf("ID_ATA_FEATURE_SET_SECURITY_ERASE_UNIT_MIN=%d\n", id.trseuc * 2);
425                         if ((id.cfs_enable_1 & (1<<1))) /* enabled */ {
426                                 if (id.dlf & (1<<8))
427                                         printf("ID_ATA_FEATURE_SET_SECURITY_LEVEL=maximum\n");
428                                 else
429                                         printf("ID_ATA_FEATURE_SET_SECURITY_LEVEL=high\n");
430                         }
431                         if (id.dlf & (1<<5))
432                                 printf("ID_ATA_FEATURE_SET_SECURITY_ENHANCED_ERASE_UNIT_MIN=%d\n", id.trsEuc * 2);
433                         if (id.dlf & (1<<4))
434                                 printf("ID_ATA_FEATURE_SET_SECURITY_EXPIRE=1\n");
435                         if (id.dlf & (1<<3))
436                                 printf("ID_ATA_FEATURE_SET_SECURITY_FROZEN=1\n");
437                         if (id.dlf & (1<<2))
438                                 printf("ID_ATA_FEATURE_SET_SECURITY_LOCKED=1\n");
439                 }
440                 if (id.command_set_1 & (1<<0)) {
441                         printf("ID_ATA_FEATURE_SET_SMART=1\n");
442                         printf("ID_ATA_FEATURE_SET_SMART_ENABLED=%d\n", (id.cfs_enable_1 & (1<<0)) ? 1 : 0);
443                 }
444                 if (id.command_set_2 & (1<<9)) {
445                         printf("ID_ATA_FEATURE_SET_AAM=1\n");
446                         printf("ID_ATA_FEATURE_SET_AAM_ENABLED=%d\n", (id.cfs_enable_2 & (1<<9)) ? 1 : 0);
447                         printf("ID_ATA_FEATURE_SET_AAM_VENDOR_RECOMMENDED_VALUE=%d\n", id.acoustic >> 8);
448                         printf("ID_ATA_FEATURE_SET_AAM_CURRENT_VALUE=%d\n", id.acoustic & 0xff);
449                 }
450                 if (id.command_set_2 & (1<<5)) {
451                         printf("ID_ATA_FEATURE_SET_PUIS=1\n");
452                         printf("ID_ATA_FEATURE_SET_PUIS_ENABLED=%d\n", (id.cfs_enable_2 & (1<<5)) ? 1 : 0);
453                 }
454                 if (id.command_set_2 & (1<<3)) {
455                         printf("ID_ATA_FEATURE_SET_APM=1\n");
456                         printf("ID_ATA_FEATURE_SET_APM_ENABLED=%d\n", (id.cfs_enable_2 & (1<<3)) ? 1 : 0);
457                         if ((id.cfs_enable_2 & (1<<3)))
458                                 printf("ID_ATA_FEATURE_SET_APM_CURRENT_VALUE=%d\n", id.CurAPMvalues & 0xff);
459                 }
460                 if (id.command_set_2 & (1<<0))
461                         printf("ID_ATA_DOWNLOAD_MICROCODE=1\n");
462
463                 /*
464                  * Word 76 indicates the capabilities of a SATA device. A PATA device shall set
465                  * word 76 to 0000h or FFFFh. If word 76 is set to 0000h or FFFFh, then
466                  * the device does not claim compliance with the Serial ATA specification and words
467                  * 76 through 79 are not valid and shall be ignored.
468                  */
469                 word = *((uint16_t *) identify + 76);
470                 if (word != 0x0000 && word != 0xffff) {
471                         printf("ID_ATA_SATA=1\n");
472                         /*
473                          * If bit 2 of word 76 is set to one, then the device supports the Gen2
474                          * signaling rate of 3.0 Gb/s (see SATA 2.6).
475                          *
476                          * If bit 1 of word 76 is set to one, then the device supports the Gen1
477                          * signaling rate of 1.5 Gb/s (see SATA 2.6).
478                          */
479                         if (word & (1<<2))
480                                 printf("ID_ATA_SATA_SIGNAL_RATE_GEN2=1\n");
481                         if (word & (1<<1))
482                                 printf("ID_ATA_SATA_SIGNAL_RATE_GEN1=1\n");
483                 }
484
485                 /* Word 217 indicates the nominal media rotation rate of the device */
486                 word = *((uint16_t *) identify + 217);
487                 if (word != 0x0000) {
488                         if (word == 0x0001) {
489                                 printf ("ID_ATA_ROTATION_RATE_RPM=0\n"); /* non-rotating e.g. SSD */
490                         } else if (word >= 0x0401 && word <= 0xfffe) {
491                                 printf ("ID_ATA_ROTATION_RATE_RPM=%d\n", word);
492                         }
493                 }
494
495                 /*
496                  * Words 108-111 contain a mandatory World Wide Name (WWN) in the NAA IEEE Registered identifier
497                  * format. Word 108 bits (15:12) shall contain 5h, indicating that the naming authority is IEEE.
498                  * All other values are reserved.
499                  */
500                 word = *((uint16_t *) identify + 108);
501                 if ((word & 0xf000) == 0x5000) {
502                         uint64_t wwwn;
503
504                         wwwn   = *((uint16_t *) identify + 108);
505                         wwwn <<= 16;
506                         wwwn  |= *((uint16_t *) identify + 109);
507                         wwwn <<= 16;
508                         wwwn  |= *((uint16_t *) identify + 110);
509                         wwwn <<= 16;
510                         wwwn  |= *((uint16_t *) identify + 111);
511                         printf("ID_WWN=0x%llx\n", (unsigned long long int) wwwn);
512                 }
513         } else {
514                 if (serial[0] != '\0')
515                         printf("%s_%s\n", model, serial);
516                 else
517                         printf("%s\n", model);
518         }
519 close:
520         close(fd);
521 exit:
522         udev_unref(udev);
523         udev_log_close();
524         return rc;
525 }