Tizen 2.1 base
[external/device-mapper.git] / libdm / libdm-common.c
1 /*
2  * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3  * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
4  *
5  * This file is part of the device-mapper userspace tools.
6  *
7  * This copyrighted material is made available to anyone wishing to use,
8  * modify, copy, or redistribute it subject to the terms and conditions
9  * of the GNU Lesser General Public License v.2.1.
10  *
11  * You should have received a copy of the GNU Lesser General Public License
12  * along with this program; if not, write to the Free Software Foundation,
13  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14  */
15
16 #include "dmlib.h"
17 #include "libdm-targets.h"
18 #include "libdm-common.h"
19 #include "kdev_t.h"
20 #include "dm-ioctl.h"
21
22 #include <stdarg.h>
23 #include <sys/param.h>
24 #include <sys/ioctl.h>
25 #include <fcntl.h>
26 #include <dirent.h>
27
28 #ifdef UDEV_SYNC_SUPPORT
29 #  include <sys/types.h>
30 #  include <sys/ipc.h>
31 #  include <sys/sem.h>
32 #  define LIBUDEV_I_KNOW_THE_API_IS_SUBJECT_TO_CHANGE
33 #  include <libudev.h>
34 #endif
35
36 #ifdef linux
37 #  include <linux/fs.h>
38 #endif
39
40 #ifdef HAVE_SELINUX
41 #  include <selinux/selinux.h>
42 #endif
43 #ifdef HAVE_SELINUX_LABEL_H
44 #  include <selinux/label.h>
45 #endif
46
47 #define DEV_DIR "/dev/"
48
49 #ifdef UDEV_SYNC_SUPPORT
50 #ifdef _SEM_SEMUN_UNDEFINED
51 union semun
52 {
53         int val;                        /* value for SETVAL */
54         struct semid_ds *buf;           /* buffer for IPC_STAT & IPC_SET */
55         unsigned short int *array;      /* array for GETALL & SETALL */
56         struct seminfo *__buf;          /* buffer for IPC_INFO */
57 };
58 #endif
59 #endif
60
61 static char _dm_dir[PATH_MAX] = DEV_DIR DM_DIR;
62
63 static int _verbose = 0;
64
65 #ifdef HAVE_SELINUX_LABEL_H
66 static struct selabel_handle *_selabel_handle = NULL;
67 #endif
68
69 #ifdef UDEV_SYNC_SUPPORT
70 static int _semaphore_supported = -1;
71 static int _udev_running = -1;
72 static int _sync_with_udev = 1;
73 static int _udev_checking = 1;
74 #endif
75
76 /*
77  * Library users can provide their own logging
78  * function.
79  */
80
81 static void _default_log_line(int level,
82             const char *file __attribute__((unused)),
83             int line __attribute__((unused)), int dm_errno, 
84             const char *f, va_list ap)
85 {
86         int use_stderr = level & _LOG_STDERR;
87
88         level &= ~_LOG_STDERR;
89
90         if (level > _LOG_WARN && !_verbose)
91                 return;
92
93         if (level < _LOG_WARN)
94                 vfprintf(stderr, f, ap);
95         else
96                 vfprintf(use_stderr ? stderr : stdout, f, ap);
97
98         if (level < _LOG_WARN)
99                 fprintf(stderr, "\n");
100         else
101                 fprintf(use_stderr ? stderr : stdout, "\n");
102 }
103
104 static void _default_log_with_errno(int level,
105             const char *file __attribute__((unused)),
106             int line __attribute__((unused)), int dm_errno, 
107             const char *f, ...)
108 {
109         va_list ap;
110
111         va_start(ap, f);
112         _default_log_line(level, file, line, dm_errno, f, ap);
113         va_end(ap);
114 }
115
116 static void _default_log(int level, const char *file,
117                          int line, const char *f, ...)
118 {
119         va_list ap;
120
121         va_start(ap, f);
122         _default_log_line(level, file, line, 0, f, ap);
123         va_end(ap);
124 }
125
126 dm_log_fn dm_log = _default_log;
127 dm_log_with_errno_fn dm_log_with_errno = _default_log_with_errno;
128
129 void dm_log_init(dm_log_fn fn)
130 {
131         if (fn)
132                 dm_log = fn;
133         else
134                 dm_log = _default_log;
135
136         dm_log_with_errno = _default_log_with_errno;
137 }
138
139 int dm_log_is_non_default(void)
140 {
141         return (dm_log == _default_log) ? 0 : 1;
142 }
143
144 void dm_log_with_errno_init(dm_log_with_errno_fn fn)
145 {
146         if (fn)
147                 dm_log_with_errno = fn;
148         else
149                 dm_log_with_errno = _default_log_with_errno;
150
151         dm_log = _default_log;
152 }
153
154 void dm_log_init_verbose(int level)
155 {
156         _verbose = level;
157 }
158
159 static void _build_dev_path(char *buffer, size_t len, const char *dev_name)
160 {
161         /* If there's a /, assume caller knows what they're doing */
162         if (strchr(dev_name, '/'))
163                 snprintf(buffer, len, "%s", dev_name);
164         else
165                 snprintf(buffer, len, "%s/%s", _dm_dir, dev_name);
166 }
167
168 int dm_get_library_version(char *version, size_t size)
169 {
170         strncpy(version, DM_LIB_VERSION, size);
171         return 1;
172 }
173
174 struct dm_task *dm_task_create(int type)
175 {
176         struct dm_task *dmt = dm_zalloc(sizeof(*dmt));
177
178         if (!dmt) {
179                 log_error("dm_task_create: malloc(%" PRIsize_t ") failed",
180                           sizeof(*dmt));
181                 return NULL;
182         }
183
184         if (!dm_check_version()) {
185                 dm_free(dmt);
186                 return NULL;
187         }
188
189         dmt->type = type;
190         dmt->minor = -1;
191         dmt->major = -1;
192         dmt->allow_default_major_fallback = 1;
193         dmt->uid = DM_DEVICE_UID;
194         dmt->gid = DM_DEVICE_GID;
195         dmt->mode = DM_DEVICE_MODE;
196         dmt->no_open_count = 0;
197         dmt->read_ahead = DM_READ_AHEAD_AUTO;
198         dmt->read_ahead_flags = 0;
199         dmt->event_nr = 0;
200         dmt->cookie_set = 0;
201         dmt->query_inactive_table = 0;
202         dmt->new_uuid = 0;
203
204         return dmt;
205 }
206
207 /*
208  * Find the name associated with a given device number by scanning _dm_dir.
209  */
210 static char *_find_dm_name_of_device(dev_t st_rdev)
211 {
212         const char *name;
213         char path[PATH_MAX];
214         struct dirent *dirent;
215         DIR *d;
216         struct stat buf;
217         char *new_name = NULL;
218
219         if (!(d = opendir(_dm_dir))) {
220                 log_sys_error("opendir", _dm_dir);
221                 return NULL;
222         }
223
224         while ((dirent = readdir(d))) {
225                 name = dirent->d_name;
226
227                 if (!strcmp(name, ".") || !strcmp(name, ".."))
228                         continue;
229
230                 if (dm_snprintf(path, sizeof(path), "%s/%s", _dm_dir,
231                                 name) == -1) {
232                         log_error("Couldn't create path for %s", name);
233                         continue;
234                 }
235
236                 if (stat(path, &buf))
237                         continue;
238
239                 if (buf.st_rdev == st_rdev) {
240                         if (!(new_name = dm_strdup(name)))
241                                 log_error("dm_task_set_name: strdup(%s) failed",
242                                           name);
243                         break;
244                 }
245         }
246
247         if (closedir(d))
248                 log_sys_error("closedir", _dm_dir);
249
250         return new_name;
251 }
252
253 int dm_task_set_name(struct dm_task *dmt, const char *name)
254 {
255         char *pos;
256         char *new_name = NULL;
257         char path[PATH_MAX];
258         struct stat st1, st2;
259
260         dm_free(dmt->dev_name);
261         dmt->dev_name = NULL;
262
263         /*
264          * Path supplied for existing device?
265          */
266         if ((pos = strrchr(name, '/'))) {
267                 if (dmt->type == DM_DEVICE_CREATE) {
268                         log_error("Name \"%s\" invalid. It contains \"/\".", name);
269                         return 0;
270                 }
271
272                 if (stat(name, &st1)) {
273                         log_error("Device %s not found", name);
274                         return 0;
275                 }
276
277                 /*
278                  * If supplied path points to same device as last component
279                  * under /dev/mapper, use that name directly.  Otherwise call
280                  * _find_dm_name_of_device() to scan _dm_dir for a match.
281                  */
282                 if (dm_snprintf(path, sizeof(path), "%s/%s", _dm_dir,
283                                 pos + 1) == -1) {
284                         log_error("Couldn't create path for %s", pos + 1);
285                         return 0;
286                 }
287
288                 if (!stat(path, &st2) && (st1.st_rdev == st2.st_rdev))
289                         name = pos + 1;
290                 else if ((new_name = _find_dm_name_of_device(st1.st_rdev)))
291                         name = new_name;
292                 else {
293                         log_error("Device %s not found", name);
294                         return 0;
295                 }
296         }
297
298         if (strlen(name) >= DM_NAME_LEN) {
299                 log_error("Name \"%s\" too long", name);
300                 dm_free(new_name);
301                 return 0;
302         }
303
304         if (new_name)
305                 dmt->dev_name = new_name;
306         else if (!(dmt->dev_name = dm_strdup(name))) {
307                 log_error("dm_task_set_name: strdup(%s) failed", name);
308                 return 0;
309         }
310
311         return 1;
312 }
313
314 int dm_task_set_uuid(struct dm_task *dmt, const char *uuid)
315 {
316         dm_free(dmt->uuid);
317
318         if (!(dmt->uuid = dm_strdup(uuid))) {
319                 log_error("dm_task_set_uuid: strdup(%s) failed", uuid);
320                 return 0;
321         }
322
323         return 1;
324 }
325
326 int dm_task_set_major(struct dm_task *dmt, int major)
327 {
328         dmt->major = major;
329         dmt->allow_default_major_fallback = 0;
330
331         return 1;
332 }
333
334 int dm_task_set_minor(struct dm_task *dmt, int minor)
335 {
336         dmt->minor = minor;
337
338         return 1;
339 }
340
341 int dm_task_set_major_minor(struct dm_task *dmt, int major, int minor,
342                             int allow_default_major_fallback)
343 {
344         dmt->major = major;
345         dmt->minor = minor;
346         dmt->allow_default_major_fallback = allow_default_major_fallback;
347
348         return 1;
349 }
350
351 int dm_task_set_uid(struct dm_task *dmt, uid_t uid)
352 {
353         dmt->uid = uid;
354
355         return 1;
356 }
357
358 int dm_task_set_gid(struct dm_task *dmt, gid_t gid)
359 {
360         dmt->gid = gid;
361
362         return 1;
363 }
364
365 int dm_task_set_mode(struct dm_task *dmt, mode_t mode)
366 {
367         dmt->mode = mode;
368
369         return 1;
370 }
371
372 int dm_task_add_target(struct dm_task *dmt, uint64_t start, uint64_t size,
373                        const char *ttype, const char *params)
374 {
375         struct target *t = create_target(start, size, ttype, params);
376
377         if (!t)
378                 return 0;
379
380         if (!dmt->head)
381                 dmt->head = dmt->tail = t;
382         else {
383                 dmt->tail->next = t;
384                 dmt->tail = t;
385         }
386
387         return 1;
388 }
389
390 #ifdef HAVE_SELINUX
391 static int _selabel_lookup(const char *path, mode_t mode,
392                            security_context_t *scontext)
393 {
394 #ifdef HAVE_SELINUX_LABEL_H
395         if (!_selabel_handle &&
396             !(_selabel_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0))) {
397                 log_error("selabel_open failed: %s", strerror(errno));
398                 return 0;
399         }
400
401         if (selabel_lookup(_selabel_handle, scontext, path, mode)) {
402                 log_error("selabel_lookup failed: %s", strerror(errno));
403                 return 0;
404         }
405 #else
406         if (matchpathcon(path, mode, scontext)) {
407                 log_error("matchpathcon failed: %s", strerror(errno));
408                 return 0;
409         }
410 #endif
411         return 1;
412 }
413 #endif
414
415 int dm_prepare_selinux_context(const char *path, mode_t mode)
416 {
417 #ifdef HAVE_SELINUX
418         security_context_t scontext = NULL;
419
420         if (is_selinux_enabled() <= 0)
421                 return 1;
422
423         if (path) {
424                 if (!_selabel_lookup(path, mode, &scontext))
425                         return_0;
426
427                 log_debug("Preparing SELinux context for %s to %s.", path, scontext);
428         }
429         else
430                 log_debug("Resetting SELinux context to default value.");
431
432         if (setfscreatecon(scontext) < 0) {
433                 log_sys_error("setfscreatecon", path);
434                 freecon(scontext);
435                 return 0;
436         }
437
438         freecon(scontext);
439 #endif
440         return 1;
441 }
442
443 int dm_set_selinux_context(const char *path, mode_t mode)
444 {
445 #ifdef HAVE_SELINUX
446         security_context_t scontext;
447
448         if (is_selinux_enabled() <= 0)
449                 return 1;
450
451         if (!_selabel_lookup(path, mode, &scontext))
452                 return_0;
453
454         log_debug("Setting SELinux context for %s to %s.", path, scontext);
455
456         if ((lsetfilecon(path, scontext) < 0) && (errno != ENOTSUP)) {
457                 log_sys_error("lsetfilecon", path);
458                 freecon(scontext);
459                 return 0;
460         }
461
462         freecon(scontext);
463 #endif
464         return 1;
465 }
466
467 void selinux_release(void)
468 {
469 #ifdef HAVE_SELINUX_LABEL_H
470         if (_selabel_handle)
471                 selabel_close(_selabel_handle);
472         _selabel_handle = NULL;
473 #endif
474 }
475
476 static int _add_dev_node(const char *dev_name, uint32_t major, uint32_t minor,
477                          uid_t uid, gid_t gid, mode_t mode, int check_udev)
478 {
479         char path[PATH_MAX];
480         struct stat info;
481         dev_t dev = MKDEV(major, minor);
482         mode_t old_mask;
483
484         _build_dev_path(path, sizeof(path), dev_name);
485
486         if (stat(path, &info) >= 0) {
487                 if (!S_ISBLK(info.st_mode)) {
488                         log_error("A non-block device file at '%s' "
489                                   "is already present", path);
490                         return 0;
491                 }
492
493                 /* If right inode already exists we don't touch uid etc. */
494                 if (info.st_rdev == dev)
495                         return 1;
496
497                 if (unlink(path) < 0) {
498                         log_error("Unable to unlink device node for '%s'",
499                                   dev_name);
500                         return 0;
501                 }
502         } else if (dm_udev_get_sync_support() && dm_udev_get_checking() &&
503                    check_udev)
504                 log_warn("%s not set up by udev: Falling back to direct "
505                          "node creation.", path);
506
507         (void) dm_prepare_selinux_context(path, S_IFBLK);
508         old_mask = umask(0);
509         if (mknod(path, S_IFBLK | mode, dev) < 0) {
510                 log_error("Unable to make device node for '%s'", dev_name);
511                 umask(old_mask);
512                 (void) dm_prepare_selinux_context(NULL, 0);
513                 return 0;
514         }
515         umask(old_mask);
516         (void) dm_prepare_selinux_context(NULL, 0);
517
518         if (chown(path, uid, gid) < 0) {
519                 log_sys_error("chown", path);
520                 return 0;
521         }
522
523         log_debug("Created %s", path);
524
525         return 1;
526 }
527
528 static int _rm_dev_node(const char *dev_name, int check_udev)
529 {
530         char path[PATH_MAX];
531         struct stat info;
532
533         _build_dev_path(path, sizeof(path), dev_name);
534
535         if (stat(path, &info) < 0)
536                 return 1;
537         else if (dm_udev_get_sync_support() && dm_udev_get_checking() &&
538                  check_udev)
539                 log_warn("Node %s was not removed by udev. "
540                          "Falling back to direct node removal.", path);
541
542         if (unlink(path) < 0) {
543                 log_error("Unable to unlink device node for '%s'", dev_name);
544                 return 0;
545         }
546
547         log_debug("Removed %s", path);
548
549         return 1;
550 }
551
552 static int _rename_dev_node(const char *old_name, const char *new_name,
553                             int check_udev)
554 {
555         char oldpath[PATH_MAX];
556         char newpath[PATH_MAX];
557         struct stat info;
558
559         _build_dev_path(oldpath, sizeof(oldpath), old_name);
560         _build_dev_path(newpath, sizeof(newpath), new_name);
561
562         if (stat(newpath, &info) == 0) {
563                 if (!S_ISBLK(info.st_mode)) {
564                         log_error("A non-block device file at '%s' "
565                                   "is already present", newpath);
566                         return 0;
567                 }
568                 else if (dm_udev_get_sync_support() && dm_udev_get_checking() &&
569                          check_udev) {
570                         if (stat(oldpath, &info) < 0 &&
571                                  errno == ENOENT)
572                                 /* assume udev already deleted this */
573                                 return 1;
574                         else {
575                                 log_warn("The node %s should have been renamed to %s "
576                                          "by udev but old node is still present. "
577                                          "Falling back to direct old node removal.",
578                                          oldpath, newpath);
579                                 return _rm_dev_node(old_name, 0);
580                         }
581                 }
582
583                 if (unlink(newpath) < 0) {
584                         if (errno == EPERM) {
585                                 /* devfs, entry has already been renamed */
586                                 return 1;
587                         }
588                         log_error("Unable to unlink device node for '%s'",
589                                   new_name);
590                         return 0;
591                 }
592         }
593         else if (dm_udev_get_sync_support() && dm_udev_get_checking() &&
594                  check_udev)
595                 log_warn("The node %s should have been renamed to %s "
596                          "by udev but new node is not present. "
597                          "Falling back to direct node rename.",
598                          oldpath, newpath);
599
600         if (rename(oldpath, newpath) < 0) {
601                 log_error("Unable to rename device node from '%s' to '%s'",
602                           old_name, new_name);
603                 return 0;
604         }
605
606         log_debug("Renamed %s to %s", oldpath, newpath);
607
608         return 1;
609 }
610
611 #ifdef linux
612 static int _open_dev_node(const char *dev_name)
613 {
614         int fd = -1;
615         char path[PATH_MAX];
616
617         _build_dev_path(path, sizeof(path), dev_name);
618
619         if ((fd = open(path, O_RDONLY, 0)) < 0)
620                 log_sys_error("open", path);
621
622         return fd;
623 }
624
625 int get_dev_node_read_ahead(const char *dev_name, uint32_t *read_ahead)
626 {
627         int r = 1;
628         int fd;
629         long read_ahead_long;
630
631         if (!*dev_name) {
632                 log_error("Empty device name passed to BLKRAGET");
633                 return 0;
634         }
635
636         if ((fd = _open_dev_node(dev_name)) < 0)
637                 return_0;
638
639         if (ioctl(fd, BLKRAGET, &read_ahead_long)) {
640                 log_sys_error("BLKRAGET", dev_name);
641                 *read_ahead = 0;
642                 r = 0;
643         }  else {
644                 *read_ahead = (uint32_t) read_ahead_long;
645                 log_debug("%s: read ahead is %" PRIu32, dev_name, *read_ahead);
646         }
647
648         if (close(fd))
649                 stack;
650
651         return r;
652 }
653
654 static int _set_read_ahead(const char *dev_name, uint32_t read_ahead)
655 {
656         int r = 1;
657         int fd;
658         long read_ahead_long = (long) read_ahead;
659
660         if (!*dev_name) {
661                 log_error("Empty device name passed to BLKRAGET");
662                 return 0;
663         }
664
665         if ((fd = _open_dev_node(dev_name)) < 0)
666                 return_0;
667
668         log_debug("%s: Setting read ahead to %" PRIu32, dev_name, read_ahead);
669
670         if (ioctl(fd, BLKRASET, read_ahead_long)) {
671                 log_sys_error("BLKRASET", dev_name);
672                 r = 0;
673         }
674
675         if (close(fd))
676                 stack;
677
678         return r;
679 }
680
681 static int _set_dev_node_read_ahead(const char *dev_name, uint32_t read_ahead,
682                                     uint32_t read_ahead_flags)
683 {
684         uint32_t current_read_ahead;
685
686         if (read_ahead == DM_READ_AHEAD_AUTO)
687                 return 1;
688
689         if (read_ahead == DM_READ_AHEAD_NONE)
690                 read_ahead = 0;
691
692         if (read_ahead_flags & DM_READ_AHEAD_MINIMUM_FLAG) {
693                 if (!get_dev_node_read_ahead(dev_name, &current_read_ahead))
694                         return_0;
695
696                 if (current_read_ahead > read_ahead) {
697                         log_debug("%s: retaining kernel read ahead of %" PRIu32
698                                   " (requested %" PRIu32 ")",           
699                                   dev_name, current_read_ahead, read_ahead);
700                         return 1;
701                 }
702         }
703
704         return _set_read_ahead(dev_name, read_ahead);
705 }
706
707 #else
708
709 int get_dev_node_read_ahead(const char *dev_name, uint32_t *read_ahead)
710 {
711         *read_ahead = 0;
712
713         return 1;
714 }
715
716 static int _set_dev_node_read_ahead(const char *dev_name, uint32_t read_ahead,
717                                     uint32_t read_ahead_flags)
718 {
719         return 1;
720 }
721 #endif
722
723 typedef enum {
724         NODE_ADD,
725         NODE_DEL,
726         NODE_RENAME,
727         NODE_READ_AHEAD
728 } node_op_t;
729
730 static int _do_node_op(node_op_t type, const char *dev_name, uint32_t major,
731                        uint32_t minor, uid_t uid, gid_t gid, mode_t mode,
732                        const char *old_name, uint32_t read_ahead,
733                        uint32_t read_ahead_flags, int check_udev)
734 {
735         switch (type) {
736         case NODE_ADD:
737                 return _add_dev_node(dev_name, major, minor, uid, gid,
738                                      mode, check_udev);
739         case NODE_DEL:
740                 return _rm_dev_node(dev_name, check_udev);
741         case NODE_RENAME:
742                 return _rename_dev_node(old_name, dev_name, check_udev);
743         case NODE_READ_AHEAD:
744                 return _set_dev_node_read_ahead(dev_name, read_ahead,
745                                                 read_ahead_flags);
746         }
747
748         return 1;
749 }
750
751 static DM_LIST_INIT(_node_ops);
752
753 struct node_op_parms {
754         struct dm_list list;
755         node_op_t type;
756         char *dev_name;
757         uint32_t major;
758         uint32_t minor;
759         uid_t uid;
760         gid_t gid;
761         mode_t mode;
762         uint32_t read_ahead;
763         uint32_t read_ahead_flags;
764         char *old_name;
765         int check_udev;
766         char names[0];
767 };
768
769 static void _store_str(char **pos, char **ptr, const char *str)
770 {
771         strcpy(*pos, str);
772         *ptr = *pos;
773         *pos += strlen(*ptr) + 1;
774 }
775
776 static int _stack_node_op(node_op_t type, const char *dev_name, uint32_t major,
777                           uint32_t minor, uid_t uid, gid_t gid, mode_t mode,
778                           const char *old_name, uint32_t read_ahead,
779                           uint32_t read_ahead_flags, int check_udev)
780 {
781         struct node_op_parms *nop;
782         struct dm_list *noph, *nopht;
783         size_t len = strlen(dev_name) + strlen(old_name) + 2;
784         char *pos;
785
786         /*
787          * Ignore any outstanding operations on the node if deleting it
788          */
789         if (type == NODE_DEL) {
790                 dm_list_iterate_safe(noph, nopht, &_node_ops) {
791                         nop = dm_list_item(noph, struct node_op_parms);
792                         if (!strcmp(dev_name, nop->dev_name)) {
793                                 dm_list_del(&nop->list);
794                                 dm_free(nop);
795                         }
796                 }
797         }
798
799         if (!(nop = dm_malloc(sizeof(*nop) + len))) {
800                 log_error("Insufficient memory to stack mknod operation");
801                 return 0;
802         }
803
804         pos = nop->names;
805         nop->type = type;
806         nop->major = major;
807         nop->minor = minor;
808         nop->uid = uid;
809         nop->gid = gid;
810         nop->mode = mode;
811         nop->read_ahead = read_ahead;
812         nop->read_ahead_flags = read_ahead_flags;
813         nop->check_udev = check_udev;
814
815         _store_str(&pos, &nop->dev_name, dev_name);
816         _store_str(&pos, &nop->old_name, old_name);
817
818         dm_list_add(&_node_ops, &nop->list);
819
820         return 1;
821 }
822
823 static void _pop_node_ops(void)
824 {
825         struct dm_list *noph, *nopht;
826         struct node_op_parms *nop;
827
828         dm_list_iterate_safe(noph, nopht, &_node_ops) {
829                 nop = dm_list_item(noph, struct node_op_parms);
830                 _do_node_op(nop->type, nop->dev_name, nop->major, nop->minor,
831                             nop->uid, nop->gid, nop->mode, nop->old_name,
832                             nop->read_ahead, nop->read_ahead_flags,
833                             nop->check_udev);
834                 dm_list_del(&nop->list);
835                 dm_free(nop);
836         }
837 }
838
839 int add_dev_node(const char *dev_name, uint32_t major, uint32_t minor,
840                  uid_t uid, gid_t gid, mode_t mode, int check_udev)
841 {
842         log_debug("%s: Stacking NODE_ADD (%" PRIu32 ",%" PRIu32 ") %u:%u 0%o",
843                   dev_name, major, minor, uid, gid, mode);
844
845         return _stack_node_op(NODE_ADD, dev_name, major, minor, uid,
846                               gid, mode, "", 0, 0, check_udev);
847 }
848
849 int rename_dev_node(const char *old_name, const char *new_name, int check_udev)
850 {
851         log_debug("%s: Stacking NODE_RENAME to %s", old_name, new_name);
852
853         return _stack_node_op(NODE_RENAME, new_name, 0, 0, 0,
854                               0, 0, old_name, 0, 0, check_udev);
855 }
856
857 int rm_dev_node(const char *dev_name, int check_udev)
858 {
859         log_debug("%s: Stacking NODE_DEL (replaces other stacked ops)", dev_name);
860
861         return _stack_node_op(NODE_DEL, dev_name, 0, 0, 0,
862                               0, 0, "", 0, 0, check_udev);
863 }
864
865 int set_dev_node_read_ahead(const char *dev_name, uint32_t read_ahead,
866                             uint32_t read_ahead_flags)
867 {
868         if (read_ahead == DM_READ_AHEAD_AUTO)
869                 return 1;
870
871         log_debug("%s: Stacking NODE_READ_AHEAD %" PRIu32 " (flags=%" PRIu32
872                   ")", dev_name, read_ahead, read_ahead_flags);
873
874         return _stack_node_op(NODE_READ_AHEAD, dev_name, 0, 0, 0, 0,
875                               0, "", read_ahead, read_ahead_flags, 0);
876 }
877
878 void update_devs(void)
879 {
880         _pop_node_ops();
881 }
882
883 int dm_set_dev_dir(const char *dev_dir)
884 {
885         size_t len;
886         const char *slash;
887         if (*dev_dir != '/') {
888                 log_debug("Invalid dev_dir value, %s: "
889                           "not an absolute name.", dev_dir);
890                 return 0;
891         }
892
893         len = strlen(dev_dir);
894         slash = dev_dir[len-1] == '/' ? "" : "/";
895
896         if (snprintf(_dm_dir, sizeof _dm_dir, "%s%s%s", dev_dir, slash, DM_DIR)
897             >= sizeof _dm_dir) {
898                 log_debug("Invalid dev_dir value, %s: name too long.", dev_dir);
899                 return 0;
900         }
901
902         return 1;
903 }
904
905 const char *dm_dir(void)
906 {
907         return _dm_dir;
908 }
909
910 int dm_mknodes(const char *name)
911 {
912         struct dm_task *dmt;
913         int r = 0;
914
915         if (!(dmt = dm_task_create(DM_DEVICE_MKNODES)))
916                 return 0;
917
918         if (name && !dm_task_set_name(dmt, name))
919                 goto out;
920
921         if (!dm_task_no_open_count(dmt))
922                 goto out;
923
924         r = dm_task_run(dmt);
925
926 out:
927         dm_task_destroy(dmt);
928         return r;
929 }
930
931 int dm_driver_version(char *version, size_t size)
932 {
933         struct dm_task *dmt;
934         int r = 0;
935
936         if (!(dmt = dm_task_create(DM_DEVICE_VERSION)))
937                 return 0;
938
939         if (!dm_task_run(dmt))
940                 log_error("Failed to get driver version");
941
942         if (!dm_task_get_driver_version(dmt, version, size))
943                 goto out;
944
945         r = 1;
946
947 out:
948         dm_task_destroy(dmt);
949         return r;
950 }
951
952 #ifndef UDEV_SYNC_SUPPORT
953 void dm_udev_set_sync_support(int sync_with_udev)
954 {
955 }
956
957 int dm_udev_get_sync_support(void)
958 {
959         return 0;
960 }
961
962 void dm_udev_set_checking(int checking)
963 {
964 }
965
966 int dm_udev_get_checking(void)
967 {
968         return 0;
969 }
970
971 int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags)
972 {
973         if (dm_cookie_supported())
974                 dmt->event_nr = flags << DM_UDEV_FLAGS_SHIFT;
975         *cookie = 0;
976
977         return 1;
978 }
979
980 int dm_udev_complete(uint32_t cookie)
981 {
982         return 1;
983 }
984
985 int dm_udev_wait(uint32_t cookie)
986 {
987         return 1;
988 }
989
990 #else           /* UDEV_SYNC_SUPPORT */
991
992 static int _check_semaphore_is_supported(void)
993 {
994         int maxid;
995         union semun arg;
996         struct seminfo seminfo;
997
998         arg.__buf = &seminfo;
999         maxid = semctl(0, 0, SEM_INFO, arg);
1000
1001         if (maxid < 0) {
1002                 log_warn("Kernel not configured for semaphores (System V IPC). "
1003                          "Not using udev synchronisation code.");
1004                 return 0;
1005         }
1006
1007         return 1;
1008 }
1009
1010 static int _check_udev_is_running(void)
1011 {
1012         struct udev *udev;
1013         struct udev_queue *udev_queue;
1014         int r;
1015
1016         if (!(udev = udev_new()))
1017                 goto_bad;
1018
1019         if (!(udev_queue = udev_queue_new(udev))) {
1020                 udev_unref(udev);
1021                 goto_bad;
1022         }
1023
1024         if (!(r = udev_queue_get_udev_is_active(udev_queue)))
1025                 log_debug("Udev is not running. "
1026                           "Not using udev synchronisation code.");
1027
1028         udev_queue_unref(udev_queue);
1029         udev_unref(udev);
1030
1031         return r;
1032
1033 bad:
1034         log_error("Could not get udev state. Assuming udev is not running.");
1035         return 0;
1036 }
1037
1038 static void _check_udev_sync_requirements_once(void)
1039 {
1040         if (_semaphore_supported < 0)
1041                 _semaphore_supported = _check_semaphore_is_supported();
1042
1043         if (_udev_running < 0)
1044                 _udev_running = _check_udev_is_running();
1045 }
1046
1047 void dm_udev_set_sync_support(int sync_with_udev)
1048 {
1049         _check_udev_sync_requirements_once();
1050         _sync_with_udev = sync_with_udev;
1051 }
1052
1053 int dm_udev_get_sync_support(void)
1054 {
1055         _check_udev_sync_requirements_once();
1056
1057         return _semaphore_supported && dm_cookie_supported() &&
1058                 _udev_running && _sync_with_udev;
1059 }
1060
1061 void dm_udev_set_checking(int checking)
1062 {
1063         if ((_udev_checking = checking))
1064                 log_debug("DM udev checking enabled");
1065         else
1066                 log_debug("DM udev checking disabled");
1067 }
1068
1069 int dm_udev_get_checking(void)
1070 {
1071         return _udev_checking;
1072 }
1073
1074 static int _get_cookie_sem(uint32_t cookie, int *semid)
1075 {
1076         if (cookie >> 16 != DM_COOKIE_MAGIC) {
1077                 log_error("Could not continue to access notification "
1078                           "semaphore identified by cookie value %"
1079                           PRIu32 " (0x%x). Incorrect cookie prefix.",
1080                           cookie, cookie);
1081                 return 0;
1082         }
1083
1084         if ((*semid = semget((key_t) cookie, 1, 0)) >= 0)
1085                 return 1;
1086
1087         switch (errno) {
1088                 case ENOENT:
1089                         log_error("Could not find notification "
1090                                   "semaphore identified by cookie "
1091                                   "value %" PRIu32 " (0x%x)",
1092                                   cookie, cookie);
1093                         break;
1094                 case EACCES:
1095                         log_error("No permission to access "
1096                                   "notificaton semaphore identified "
1097                                   "by cookie value %" PRIu32 " (0x%x)",
1098                                   cookie, cookie);
1099                         break;
1100                 default:
1101                         log_error("Failed to access notification "
1102                                    "semaphore identified by cookie "
1103                                    "value %" PRIu32 " (0x%x): %s",
1104                                   cookie, cookie, strerror(errno));
1105                         break;
1106         }
1107
1108         return 0;
1109 }
1110
1111 static int _udev_notify_sem_inc(uint32_t cookie, int semid)
1112 {
1113         struct sembuf sb = {0, 1, 0};
1114
1115         if (semop(semid, &sb, 1) < 0) {
1116                 log_error("semid %d: semop failed for cookie 0x%" PRIx32 ": %s",
1117                           semid, cookie, strerror(errno));
1118                 return 0;
1119         }
1120
1121         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) incremented",
1122                   cookie, semid);
1123
1124         return 1;
1125 }
1126
1127 static int _udev_notify_sem_dec(uint32_t cookie, int semid)
1128 {
1129         struct sembuf sb = {0, -1, IPC_NOWAIT};
1130
1131         if (semop(semid, &sb, 1) < 0) {
1132                 switch (errno) {
1133                         case EAGAIN:
1134                                 log_error("semid %d: semop failed for cookie "
1135                                           "0x%" PRIx32 ": "
1136                                           "incorrect semaphore state",
1137                                           semid, cookie);
1138                                 break;
1139                         default:
1140                                 log_error("semid %d: semop failed for cookie "
1141                                           "0x%" PRIx32 ": %s",
1142                                           semid, cookie, strerror(errno));
1143                                 break;
1144                 }
1145                 return 0;
1146         }
1147
1148         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) decremented",
1149                   cookie, semid);
1150
1151         return 1;
1152 }
1153
1154 static int _udev_notify_sem_destroy(uint32_t cookie, int semid)
1155 {
1156         if (semctl(semid, 0, IPC_RMID, 0) < 0) {
1157                 log_error("Could not cleanup notification semaphore "
1158                           "identified by cookie value %" PRIu32 " (0x%x): %s",
1159                           cookie, cookie, strerror(errno));
1160                 return 0;
1161         }
1162
1163         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) destroyed", cookie,
1164                   semid);
1165
1166         return 1;
1167 }
1168
1169 static int _udev_notify_sem_create(uint32_t *cookie, int *semid)
1170 {
1171         int fd;
1172         int gen_semid;
1173         uint16_t base_cookie;
1174         uint32_t gen_cookie;
1175         union semun sem_arg;
1176
1177         if ((fd = open("/dev/urandom", O_RDONLY)) < 0) {
1178                 log_error("Failed to open /dev/urandom "
1179                           "to create random cookie value");
1180                 *cookie = 0;
1181                 return 0;
1182         }
1183
1184         /* Generate random cookie value. Be sure it is unique and non-zero. */
1185         do {
1186                 /* FIXME Handle non-error returns from read(). Move _io() into libdm? */
1187                 if (read(fd, &base_cookie, sizeof(base_cookie)) != sizeof(base_cookie)) {
1188                         log_error("Failed to initialize notification cookie");
1189                         goto bad;
1190                 }
1191
1192                 gen_cookie = DM_COOKIE_MAGIC << 16 | base_cookie;
1193
1194                 if (base_cookie && (gen_semid = semget((key_t) gen_cookie,
1195                                     1, 0600 | IPC_CREAT | IPC_EXCL)) < 0) {
1196                         switch (errno) {
1197                                 case EEXIST:
1198                                         /* if the semaphore key exists, we
1199                                          * simply generate another random one */
1200                                         base_cookie = 0;
1201                                         break;
1202                                 case ENOMEM:
1203                                         log_error("Not enough memory to create "
1204                                                   "notification semaphore");
1205                                         goto bad;
1206                                 case ENOSPC:
1207                                         log_error("Limit for the maximum number "
1208                                                   "of semaphores reached. You can "
1209                                                   "check and set the limits in "
1210                                                   "/proc/sys/kernel/sem.");
1211                                         goto bad;
1212                                 default:
1213                                         log_error("Failed to create notification "
1214                                                   "semaphore: %s", strerror(errno));
1215                                         goto bad;
1216                         }
1217                 }
1218         } while (!base_cookie);
1219
1220         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) created",
1221                   gen_cookie, gen_semid);
1222
1223         sem_arg.val = 1;
1224
1225         if (semctl(gen_semid, 0, SETVAL, sem_arg) < 0) {
1226                 log_error("semid %d: semctl failed: %s", gen_semid, strerror(errno));
1227                 /* We have to destroy just created semaphore
1228                  * so it won't stay in the system. */
1229                 (void) _udev_notify_sem_destroy(gen_cookie, gen_semid);
1230                 goto bad;
1231         }
1232
1233         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) incremented",
1234                   gen_cookie, gen_semid);
1235
1236         if (close(fd))
1237                 stack;
1238
1239         *semid = gen_semid;
1240         *cookie = gen_cookie;
1241
1242         return 1;
1243
1244 bad:
1245         if (close(fd))
1246                 stack;
1247
1248         *cookie = 0;
1249
1250         return 0;
1251 }
1252
1253 int dm_udev_create_cookie(uint32_t *cookie)
1254 {
1255         int semid;
1256
1257         if (!dm_udev_get_sync_support()) {
1258                 *cookie = 0;
1259                 return 1;
1260         }
1261
1262         return _udev_notify_sem_create(cookie, &semid);
1263 }
1264
1265 int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags)
1266 {
1267         int semid;
1268
1269         if (dm_cookie_supported())
1270                 dmt->event_nr = flags << DM_UDEV_FLAGS_SHIFT;
1271
1272         if (!dm_udev_get_sync_support()) {
1273                 *cookie = 0;
1274                 return 1;
1275         }
1276
1277         if (*cookie) {
1278                 if (!_get_cookie_sem(*cookie, &semid))
1279                         goto_bad;
1280         } else if (!_udev_notify_sem_create(cookie, &semid))
1281                 goto_bad;
1282
1283         if (!_udev_notify_sem_inc(*cookie, semid)) {
1284                 log_error("Could not set notification semaphore "
1285                           "identified by cookie value %" PRIu32 " (0x%x)",
1286                           *cookie, *cookie);
1287                 goto bad;
1288         }
1289
1290         dmt->event_nr |= ~DM_UDEV_FLAGS_MASK & *cookie;
1291         dmt->cookie_set = 1;
1292
1293         log_debug("Udev cookie 0x%" PRIx32 " (semid %d) assigned to dm_task "
1294                   "type %d with flags 0x%" PRIx16, *cookie, semid, dmt->type, flags);
1295
1296         return 1;
1297
1298 bad:
1299         dmt->event_nr = 0;
1300         return 0;
1301 }
1302
1303 int dm_udev_complete(uint32_t cookie)
1304 {
1305         int semid;
1306
1307         if (!cookie || !dm_udev_get_sync_support())
1308                 return 1;
1309
1310         if (!_get_cookie_sem(cookie, &semid))
1311                 return_0;
1312
1313         if (!_udev_notify_sem_dec(cookie, semid)) {
1314                 log_error("Could not signal waiting process using notification "
1315                           "semaphore identified by cookie value %" PRIu32 " (0x%x)",
1316                           cookie, cookie);
1317                 return 0;
1318         }
1319
1320         return 1;
1321 }
1322
1323 int dm_udev_wait(uint32_t cookie)
1324 {
1325         int semid;
1326         struct sembuf sb = {0, 0, 0};
1327
1328         if (!cookie || !dm_udev_get_sync_support())
1329                 return 1;
1330
1331         if (!_get_cookie_sem(cookie, &semid))
1332                 return_0;
1333
1334         if (!_udev_notify_sem_dec(cookie, semid)) {
1335                 log_error("Failed to set a proper state for notification "
1336                           "semaphore identified by cookie value %" PRIu32 " (0x%x) "
1337                           "to initialize waiting for incoming notifications.",
1338                           cookie, cookie);
1339                 (void) _udev_notify_sem_destroy(cookie, semid);
1340                 return 0;
1341         }
1342
1343         log_debug("Udev cookie 0x%" PRIx32 " (semid %d): Waiting for zero",
1344                   cookie, semid);
1345
1346 repeat_wait:
1347         if (semop(semid, &sb, 1) < 0) {
1348                 if (errno == EINTR)
1349                         goto repeat_wait;
1350                 else if (errno == EIDRM)
1351                         return 1;
1352
1353                 log_error("Could not set wait state for notification semaphore "
1354                           "identified by cookie value %" PRIu32 " (0x%x): %s",
1355                           cookie, cookie, strerror(errno));
1356                 (void) _udev_notify_sem_destroy(cookie, semid);
1357                 return 0;
1358         }
1359
1360         return _udev_notify_sem_destroy(cookie, semid);
1361 }
1362
1363 #endif          /* UDEV_SYNC_SUPPORT */