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