lvm/dm - clean up debug, fix open bug
[dragonfly.git] / contrib / lvm2 / dist / libdm / ioctl / libdm-dragonfly-iface.c
1 /*      $NetBSD: libdm-nbsd-iface.c,v 1.7 2010/03/12 16:24:40 haad Exp $        */
2
3 /*
4  * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
5  * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
6  * Copyright (C) 2008 Adam Hamsik. All rights reserved.
7  * Copyright (C) 2010 Alex Hornung. All rights reserved.
8  *
9  * This file is part of the device-mapper userspace tools.
10  *
11  * This copyrighted material is made available to anyone wishing to use,
12  * modify, copy, or redistribute it subject to the terms and conditions
13  * of the GNU Lesser General Public License v.2.1.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #undef _XOPEN_SOURCE
21 #include "dmlib.h"
22 #include "libdm-targets.h"
23 #include "libdm-common.h"
24 #include "libdm-netbsd.h"
25
26 #include <sys/param.h>
27 #include <sys/ioctl.h>
28 #include <sys/sysctl.h>
29 #include <sys/stat.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <dirent.h>
33 #include <limits.h>
34
35 #include <netbsd-dm.h>
36 #include <dm-ioctl.h>
37
38 #ifdef RUMP_ACTION
39 #include <rump/rump.h>
40 #include <rump/rump_syscalls.h>
41 #endif
42
43 /*
44  * Ensure build compatibility.  
45  * The hard-coded versions here are the highest present 
46  * in the _cmd_data arrays.
47  */
48
49 #if !((DM_VERSION_MAJOR == 1 && DM_VERSION_MINOR >= 0) || \
50       (DM_VERSION_MAJOR == 4 && DM_VERSION_MINOR >= 0))
51 #error The version of dm-ioctl.h included is incompatible.
52 #endif
53
54 /* dm major version no for running kernel */
55 static unsigned _dm_version_minor = 0;
56 static unsigned _dm_version_patchlevel = 0;
57
58 static int _control_fd = -1;
59 static int _version_checked = 0;
60 static int _version_ok = 1;
61 static unsigned _ioctl_buffer_double_factor = 0;
62
63 /* *INDENT-OFF* */
64
65 /*
66  * XXX Remove this structure and write another own one
67  * I don't understand why ioctl calls has different
68  * names then dm task type
69  */
70 static struct cmd_data _cmd_data_v4[] = {
71         {"create",      DM_DEV_CREATE,          {4, 0, 0}},
72         {"reload",      DM_TABLE_LOAD,          {4, 0, 0}}, /* DM_DEVICE_RELOAD */
73         {"remove",      DM_DEV_REMOVE,          {4, 0, 0}},
74         {"remove_all",  DM_REMOVE_ALL,          {4, 0, 0}},
75         {"suspend",     DM_DEV_SUSPEND,         {4, 0, 0}},
76         {"resume",      DM_DEV_SUSPEND,         {4, 0, 0}},
77         {"info",        DM_DEV_STATUS,          {4, 0, 0}},
78         {"deps",        DM_TABLE_DEPS,          {4, 0, 0}}, /* DM_DEVICE_DEPS */
79         {"rename",      DM_DEV_RENAME,          {4, 0, 0}},
80         {"version",     DM_VERSION,             {4, 0, 0}},
81         {"status",      DM_TABLE_STATUS,        {4, 0, 0}},
82         {"table",       DM_TABLE_STATUS,        {4, 0, 0}}, /* DM_DEVICE_TABLE */
83         {"waitevent",   DM_DEV_WAIT,            {4, 0, 0}},
84         {"names",       DM_LIST_DEVICES,        {4, 0, 0}},
85         {"clear",       DM_TABLE_CLEAR,         {4, 0, 0}},
86         {"mknodes",     DM_DEV_STATUS,          {4, 0, 0}},
87 #ifdef DM_LIST_VERSIONS
88         {"targets",     DM_LIST_VERSIONS,       {4, 1, 0}},
89 #endif
90 #ifdef DM_TARGET_MSG
91         {"message",     DM_TARGET_MSG,          {4, 2, 0}},
92 #endif
93 #ifdef DM_DEV_SET_GEOMETRY
94         {"setgeometry", DM_DEV_SET_GEOMETRY,    {4, 6, 0}},
95 #endif
96 };
97 /* *INDENT-ON* */
98
99 /*
100  * In NetBSD we use sysctl to get kernel drivers info. control device
101  * has predefined minor number 0 and major number = char major number
102  * of dm driver. First slot is therefore ocupied with control device
103  * and minor device starts from 1;
104  */
105
106 static int _control_device_number(uint32_t *major, uint32_t *minor)
107 {
108
109         nbsd_get_dm_major(major, DM_CHAR_MAJOR);
110         
111         *minor = 0;
112         
113         return 1;
114 }
115
116 /*
117  * Returns 1 if exists; 0 if it doesn't; -1 if it's wrong
118  */
119 static int _control_exists(const char *control, uint32_t major, uint32_t minor)
120 {
121         struct stat buf;
122
123         if (stat(control, &buf) < 0) {
124                 if (errno != ENOENT)
125                         log_sys_error("stat", control);
126                 return 0;
127         }
128
129         if (!S_ISCHR(buf.st_mode)) {
130                 log_verbose("%s: Wrong inode type", control);
131                 if (!unlink(control))
132                         return 0;
133                 log_sys_error("unlink", control);
134                 return -1;
135         }
136
137         if (major && buf.st_rdev != MKDEV(major, minor)) {
138                 log_verbose("%s: Wrong device number: (%u, %u) instead of "
139                             "(%u, %u)", control,
140                             MAJOR(buf.st_mode), MINOR(buf.st_mode),
141                             major, minor);
142                 if (!unlink(control))
143                         return 0;
144                 log_sys_error("unlink", control);
145                 return -1;
146         }
147
148         return 1;
149 }
150
151 static int _create_control(const char *control, uint32_t major, uint32_t minor)
152 {
153         int ret;
154         mode_t old_umask;
155
156         if (!major)
157                 return 0;
158
159         old_umask = umask(0022);
160         ret = dm_create_dir(dm_dir());
161         umask(old_umask);
162
163         if (!ret)
164                 return 0;
165
166         log_verbose("Creating device %s (%u, %u)", control, major, minor);
167
168         if (mknod(control, S_IFCHR | S_IRUSR | S_IWUSR,
169                   MKDEV(major, minor)) < 0)  {
170                 log_sys_error("mknod", control);
171                 return 0;
172         }
173
174
175         return 1;
176 }
177
178 /* Check if major is device-mapper block device major number */
179 int dm_is_dm_major(uint32_t major)
180 {
181         uint32_t dm_major;
182
183         nbsd_get_dm_major(&dm_major, DM_BLOCK_MAJOR);
184         
185         if (major == dm_major)
186                 return 1;
187
188         return 0;
189 }
190
191 /* Open control device if doesn't exist create it. */
192 static int _open_control(void)
193 {
194         char control[PATH_MAX];
195         uint32_t major = 0, minor = 0;
196
197         if (_control_fd != -1)
198                 return 1;
199
200 #ifdef RUMP_ACTION      
201         rump_init();
202 #endif
203         snprintf(control, sizeof(control), "%s/control", dm_dir());
204
205         if (!_control_device_number(&major, &minor))
206                 log_error("Is device-mapper driver missing from kernel?");
207
208 #if 0
209         if (!_control_exists(control, major, minor) &&
210             !_create_control(control, major, minor)) {
211                 log_error("create_control or control_exists");
212                 goto error;
213         }
214 #endif
215
216         if ((_control_fd = open(control, O_RDWR)) < 0) {
217                 log_sys_error("open", control);
218                 goto error;
219         }
220
221         return 1;
222
223 error:
224         log_error("Failure to communicate with kernel device-mapper driver.");
225         return 0;
226 }
227
228 /*
229  * Destroy dm task structure there are some dynamically alocated values there.
230  * name, uuid, head, tail list.
231  */
232 void dm_task_destroy(struct dm_task *dmt)
233 {
234         struct target *t, *n;
235
236         for (t = dmt->head; t; t = n) {
237                 n = t->next;
238                 dm_free(t->params);
239                 dm_free(t->type);
240                 dm_free(t);
241         }
242
243         if (dmt->dev_name)
244                 dm_free(dmt->dev_name);
245
246         if (dmt->newname)
247                 dm_free(dmt->newname);
248
249         if (dmt->message)
250                 dm_free(dmt->message);
251
252         if (dmt->dmi.v4)
253                 dm_free(dmt->dmi.v4);
254
255         if (dmt->uuid)
256                 dm_free(dmt->uuid);
257
258         dm_free(dmt);
259
260 }
261
262 /* Get kernel driver version from dm_ioctl structure. */
263 int dm_task_get_driver_version(struct dm_task *dmt, char *version, size_t size)
264 {
265         unsigned *v;
266
267         if (!dmt->dmi.v4) {
268                 version[0] = '\0';
269                 return 0;
270         }
271
272         v = dmt->dmi.v4->version;
273         snprintf(version, size, "%u.%u.%u", v[0], v[1], v[2]);
274         _dm_version_minor = v[1];
275         _dm_version_patchlevel = v[2];
276
277         return 1;
278 }
279
280 /* Get kernel driver protocol version and comapre it with library version. */
281 static int _check_version(char *version, size_t size)
282 {
283         struct dm_task *task;
284         int r;
285
286         if (!(task = dm_task_create(DM_DEVICE_VERSION))) {
287                 log_error("Failed to get device-mapper version");
288                 version[0] = '\0';
289                 return 0;
290         }
291
292         r = dm_task_run(task);
293         dm_task_get_driver_version(task, version, size);
294         dm_task_destroy(task);
295
296         return r;
297 }
298
299 /*
300  * Find out device-mapper's major version number the first time 
301  * this is called and whether or not we support it.
302  */
303 int dm_check_version(void)
304 {
305         char dmversion[64];
306
307         if (_version_checked)
308                 return _version_ok;
309
310         _version_checked = 1;
311
312         if (_check_version(dmversion, sizeof(dmversion)))
313                 return 1;
314
315
316         return 0;
317 }
318
319 int dm_cookie_supported(void)
320 {
321         return (0);
322 }
323
324 /* Get next target(table description) from list pointed by dmt->head. */
325 void *dm_get_next_target(struct dm_task *dmt, void *next,
326                          uint64_t *start, uint64_t *length,
327                          char **target_type, char **params)
328 {
329         struct target *t = (struct target *) next;
330
331         if (!t)
332                 t = dmt->head;
333
334         if (!t)
335                 return NULL;
336
337         *start = t->start;
338         *length = t->length;
339         *target_type = t->type;
340         *params = t->params;
341
342         return t->next;
343 }
344
345 /* Unmarshall the target info returned from a status call */
346 static int _unmarshal_status(struct dm_task *dmt, struct dm_ioctl *dmi)
347 {
348         char *outbuf = (char *) dmi + dmi->data_start;
349         char *outptr = outbuf;
350         uint32_t i;
351         struct dm_target_spec *spec;
352
353         for (i = 0; i < dmi->target_count; i++) {
354                 spec = (struct dm_target_spec *) outptr;
355                 if (!dm_task_add_target(dmt, spec->sector_start,
356                                         spec->length,
357                                         spec->target_type,
358                                         outptr + sizeof(*spec))) {
359                         return 0;
360                 }
361
362                 outptr = outbuf + spec->next;
363         }
364
365         return 1;
366 }
367
368 static char *
369 get_dev_name(char *d_name, uint32_t d_major, uint32_t d_minor)
370 {
371         static char d_buf[MAXPATHLEN];
372         struct dirent *dire;
373         struct stat st;
374         DIR *dev_dir;
375
376         int err;
377         char *name;
378
379         dev_dir = opendir("/dev");
380
381         while ((dire = readdir(dev_dir)) != NULL) {
382
383                 if (strstr(dire->d_name, d_name) == NULL)
384                         continue;
385
386                 snprintf(d_buf, MAXPATHLEN, "/dev/%s", dire->d_name);
387
388                 if ((err = stat(d_buf, &st)) < 0)
389                         printf("stat failed with %d", err);
390
391                 if (st.st_mode & S_IFBLK){
392                         if ((major(st.st_rdev) == d_major) && (minor(st.st_rdev) == d_minor)) {
393                                 strncpy(d_buf, dire->d_name, strlen(dire->d_name) + 1);
394                                 name = d_buf;
395                                 break;
396                         }
397                 }
398
399                 memset(d_buf, '0', sizeof(d_buf));
400         }
401
402         (void)closedir(dev_dir);
403
404         return name;
405 }
406
407 /*
408  * @dev_major is major number of char device
409  *
410  * I have to find it's block device number and lookup dev in
411  * device database to find device path.
412  *
413  */
414
415 int dm_format_dev(char *buf, int bufsize, uint32_t dev_major,
416                   uint32_t dev_minor)
417 {
418         int r;
419         uint32_t major, dm_major;
420         char *name;
421         mode_t mode = 0;
422         dev_t dev;
423         size_t val_len,i;
424
425         dev = MKDEV(dev_major,dev_minor);
426         mode |= S_IFCHR;
427
428         name = devname(dev,mode);
429
430         r = snprintf(buf, (size_t) bufsize, "/dev/%s",name);
431
432         if (r < 0 || r > bufsize - 1 || name == NULL)
433                 return 0;
434
435         return 1;
436 }
437
438 /* Fill info from dm_ioctl structure. Look at DM_EXISTS_FLAG*/
439 int dm_task_get_info(struct dm_task *dmt, struct dm_info *info)
440 {
441         if (!dmt->dmi.v4)
442                 return 0;
443
444         memset(info, 0, sizeof(*info));
445
446         info->exists = dmt->dmi.v4->flags & DM_EXISTS_FLAG ? 1 : 0;
447         if (!info->exists)
448                 return 1;
449
450         info->suspended = dmt->dmi.v4->flags & DM_SUSPEND_FLAG ? 1 : 0;
451         info->read_only = dmt->dmi.v4->flags & DM_READONLY_FLAG ? 1 : 0;
452         info->live_table = dmt->dmi.v4->flags & DM_ACTIVE_PRESENT_FLAG ? 1 : 0;
453         info->inactive_table = dmt->dmi.v4->flags & DM_INACTIVE_PRESENT_FLAG ?
454             1 : 0;
455         info->target_count = dmt->dmi.v4->target_count;
456         info->open_count = dmt->dmi.v4->open_count;
457         info->event_nr = dmt->dmi.v4->event_nr;
458         
459         nbsd_get_dm_major(&info->major, DM_BLOCK_MAJOR); /* get netbsd dm device major number */
460         info->minor = MINOR(dmt->dmi.v4->dev);
461         
462         return 1;
463 }
464
465 /* Unsupported on NetBSD */
466 uint32_t dm_task_get_read_ahead(const struct dm_task *dmt, uint32_t *read_ahead)
467 {
468         *read_ahead = DM_READ_AHEAD_NONE;
469         return 1;
470 }
471
472 const char *dm_task_get_name(const struct dm_task *dmt)
473 {
474
475         return (dmt->dmi.v4->name);
476 }
477
478 const char *dm_task_get_uuid(const struct dm_task *dmt)
479 {
480
481         return (dmt->dmi.v4->uuid);
482 }
483
484 struct dm_deps *dm_task_get_deps(struct dm_task *dmt)
485 {
486         return (struct dm_deps *) (((void *) dmt->dmi.v4) +
487                                    dmt->dmi.v4->data_start);
488 }
489
490 struct dm_names *dm_task_get_names(struct dm_task *dmt)
491 {
492         return (struct dm_names *) (((void *) dmt->dmi.v4) +
493                                     dmt->dmi.v4->data_start);
494 }
495
496 struct dm_versions *dm_task_get_versions(struct dm_task *dmt)
497 {
498         return (struct dm_versions *) (((void *) dmt->dmi.v4) +
499                                        dmt->dmi.v4->data_start);
500 }
501
502 int dm_task_set_ro(struct dm_task *dmt)
503 {
504         dmt->read_only = 1;
505         return 1;
506 }
507
508 /* Unsupported on NetBSD */
509 int dm_task_set_read_ahead(struct dm_task *dmt, uint32_t read_ahead,
510                            uint32_t read_ahead_flags)
511 {
512         return 1;
513 }
514
515 int dm_task_suppress_identical_reload(struct dm_task *dmt)
516 {
517         dmt->suppress_identical_reload = 1;
518         return 1;
519 }
520
521 int dm_task_set_newname(struct dm_task *dmt, const char *newname)
522 {
523         if (!(dmt->newname = dm_strdup(newname))) {
524                 log_error("dm_task_set_newname: strdup(%s) failed", newname);
525                 return 0;
526         }
527
528         return 1;
529 }
530
531 int dm_task_set_message(struct dm_task *dmt, const char *message)
532 {
533         if (!(dmt->message = dm_strdup(message))) {
534                 log_error("dm_task_set_message: strdup(%s) failed", message);
535                 return 0;
536         }
537
538         return 1;
539 }
540
541 int dm_task_set_sector(struct dm_task *dmt, uint64_t sector)
542 {
543         dmt->sector = sector;
544
545         return 1;
546 }
547
548 /* Unsupported in NetBSD */
549 int dm_task_set_geometry(struct dm_task *dmt, const char *cylinders,
550     const char *heads, const char *sectors, const char *start)
551 {
552         return 0;
553 }
554
555 int dm_task_no_flush(struct dm_task *dmt)
556 {
557         dmt->no_flush = 1;
558
559         return 1;
560 }
561
562 int dm_task_no_open_count(struct dm_task *dmt)
563 {
564         dmt->no_open_count = 1;
565
566         return 1;
567 }
568
569 int dm_task_skip_lockfs(struct dm_task *dmt)
570 {
571         dmt->skip_lockfs = 1;
572
573         return 1;
574 }
575
576 int dm_task_query_inactive_table(struct dm_task *dmt)
577 {
578         dmt->query_inactive_table = 1;
579
580         return 1;
581 }
582
583 int dm_task_set_event_nr(struct dm_task *dmt, uint32_t event_nr)
584 {
585         dmt->event_nr = event_nr;
586
587         return 1;
588 }
589
590 /* Allocate one target(table description) entry. */
591 struct target *create_target(uint64_t start, uint64_t len, const char *type,
592                              const char *params)
593 {
594         struct target *t = dm_malloc(sizeof(*t));
595         log_verbose("params is at create_target: %s", params);
596         if (!t) {
597                 log_error("create_target: malloc(%" PRIsize_t ") failed",
598                           sizeof(*t));
599                 return NULL;
600         }
601
602         memset(t, 0, sizeof(*t));
603
604         if (!(t->params = dm_strdup(params))) {
605                 log_error("create_target: strdup(params) failed");
606                 goto bad;
607         }
608
609         if (!(t->type = dm_strdup(type))) {
610                 log_error("create_target: strdup(type) failed");
611                 goto bad;
612         }
613
614         t->start = start;
615         t->length = len;
616         return t;
617
618       bad:
619         dm_free(t->params);
620         dm_free(t->type);
621         dm_free(t);
622         return NULL;
623 }
624
625 /* Parse given dm task structure to proplib dictionary.  */
626 static int _flatten(struct dm_task *dmt, prop_dictionary_t dm_dict)
627 {
628         prop_array_t cmd_array;
629         prop_dictionary_t target_spec;
630         
631         struct target *t;
632         
633         size_t len;
634         char type[DM_MAX_TYPE_NAME];
635         
636         uint32_t major, flags;
637         int count = 0;
638         char *str = NULL;
639         const int (*version)[3];
640         
641         flags = 0;
642         version = &_cmd_data_v4[dmt->type].version;
643
644         cmd_array = prop_array_create();
645
646         for (t = dmt->head; t; t = t->next) {
647                 target_spec = prop_dictionary_create();
648
649                 prop_dictionary_set_uint64(target_spec,DM_TABLE_START,t->start);
650                 prop_dictionary_set_uint64(target_spec,DM_TABLE_LENGTH,t->length);
651
652                 strlcpy(type,t->type,DM_MAX_TYPE_NAME);
653
654                 prop_dictionary_set_cstring(target_spec,DM_TABLE_TYPE,type);
655                 prop_dictionary_set_cstring(target_spec,DM_TABLE_PARAMS,t->params);
656
657                 prop_dictionary_get_cstring(target_spec,
658                     DM_TABLE_PARAMS, (char **) &str);
659
660                 prop_array_set(cmd_array,count,target_spec);
661
662                 prop_object_release(target_spec);
663                 
664                 count++;
665         }
666
667         
668         if (count && (dmt->sector || dmt->message)) {
669                 log_error("targets and message are incompatible");
670                 return -1;
671         }
672
673         if (count && dmt->newname) {
674                 log_error("targets and newname are incompatible");
675                 return -1;
676         }
677
678         if (count && dmt->geometry) {
679                 log_error("targets and geometry are incompatible");
680                 return -1;
681         }
682
683         if (dmt->newname && (dmt->sector || dmt->message)) {
684                 log_error("message and newname are incompatible");
685                 return -1;
686         }
687
688         if (dmt->newname && dmt->geometry) {
689                 log_error("geometry and newname are incompatible");
690                 return -1;
691         }
692
693         if (dmt->geometry && (dmt->sector || dmt->message)) {
694                 log_error("geometry and message are incompatible");
695                 return -1;
696         }
697
698         if (dmt->sector && !dmt->message) {
699                 log_error("message is required with sector");
700                 return -1;
701         }
702
703         if (dmt->newname)
704                 len += strlen(dmt->newname) + 1;
705
706         if (dmt->message)
707                 len += sizeof(struct dm_target_msg) + strlen(dmt->message) + 1;
708
709         if (dmt->geometry)
710                 len += strlen(dmt->geometry) + 1;
711
712         nbsd_dmi_add_version((*version), dm_dict);
713             
714         nbsd_get_dm_major(&major, DM_BLOCK_MAJOR);
715         /* 
716          * Only devices with major which is equal to netbsd dm major 
717          * dm devices in NetBSD can't have more majors then one assigned to dm.
718          */
719         if (dmt->major != major && dmt->major != -1)
720                 return -1;
721                 
722         if (dmt->minor >= 0) {
723                 flags |= DM_PERSISTENT_DEV_FLAG;
724                 
725                 prop_dictionary_set_uint32(dm_dict, DM_IOCTL_MINOR, dmt->minor);
726         }
727
728         /* Set values to dictionary. */
729         if (dmt->dev_name)
730                 prop_dictionary_set_cstring(dm_dict, DM_IOCTL_NAME, dmt->dev_name);
731
732         if (dmt->uuid)
733                 prop_dictionary_set_cstring(dm_dict, DM_IOCTL_UUID, dmt->uuid);
734         
735         if (dmt->type == DM_DEVICE_SUSPEND)
736                 flags |= DM_SUSPEND_FLAG;
737         if (dmt->no_flush)
738                 flags |= DM_NOFLUSH_FLAG;
739         if (dmt->read_only)
740                 flags |= DM_READONLY_FLAG;
741         if (dmt->skip_lockfs)
742                 flags |= DM_SKIP_LOCKFS_FLAG;
743
744         if (dmt->query_inactive_table) {
745                 if (_dm_version_minor < 16)
746                         log_warn("WARNING: Inactive table query unsupported "
747                                  "by kernel.  It will use live table.");
748                 flags |= DM_QUERY_INACTIVE_TABLE_FLAG;
749         }
750         
751         prop_dictionary_set_uint32(dm_dict, DM_IOCTL_FLAGS, flags);
752
753         prop_dictionary_set_uint32(dm_dict, DM_IOCTL_EVENT, dmt->event_nr);
754
755         if (dmt->newname)
756                 prop_array_set_cstring(cmd_array, 0, dmt->newname);
757         
758         /* Add array for all COMMAND specific data. */
759         prop_dictionary_set(dm_dict, DM_IOCTL_CMD_DATA, cmd_array);
760         prop_object_release(cmd_array);
761         
762         return 0;
763 }
764
765 static int _process_mapper_dir(struct dm_task *dmt)
766 {
767         struct dirent *dirent;
768         DIR *d;
769         const char *dir;
770         int r = 1;
771
772         dir = dm_dir();
773         if (!(d = opendir(dir))) {
774                 log_sys_error("opendir", dir);
775                 return 0;
776         }
777
778         while ((dirent = readdir(d))) {
779                 if (!strcmp(dirent->d_name, ".") ||
780                     !strcmp(dirent->d_name, "..") ||
781                     !strcmp(dirent->d_name, "control"))
782                         continue;
783                 dm_task_set_name(dmt, dirent->d_name);
784                 dm_task_run(dmt);
785         }
786
787         if (closedir(d))
788                 log_sys_error("closedir", dir);
789
790         return r;
791 }
792
793 /* Get list of all devices. */
794 static int _process_all_v4(struct dm_task *dmt)
795 {
796         struct dm_task *task;
797         struct dm_names *names;
798         unsigned next = 0;
799         int r = 1;
800
801         if (!(task = dm_task_create(DM_DEVICE_LIST)))
802                 return 0;
803
804         if (!dm_task_run(task)) {
805                 r = 0;
806                 goto out;
807         }
808
809         if (!(names = dm_task_get_names(task))) {
810                 r = 0;
811                 goto out;
812         }
813
814         if (!names->dev)
815                 goto out;
816
817         do {
818                 names = (void *) names + next;
819                 if (!dm_task_set_name(dmt, names->name)) {
820                         r = 0;
821                         goto out;
822                 }
823                 if (!dm_task_run(dmt))
824                         r = 0;
825                 next = names->next;
826         } while (next);
827
828       out:
829         dm_task_destroy(task);
830         return r;
831 }
832
833 static int _mknodes_v4(struct dm_task *dmt)
834 {
835         (void) _process_mapper_dir(dmt);
836
837         return _process_all_v4(dmt);
838 }
839
840 /* Create new device and load table to it. */
841 static int _create_and_load_v4(struct dm_task *dmt)
842 {
843         struct dm_task *task;
844         int r;
845
846         log_verbose("create and load called");
847         
848         /* Use new task struct to create the device */
849         if (!(task = dm_task_create(DM_DEVICE_CREATE))) {
850                 log_error("Failed to create device-mapper task struct");
851                 return 0;
852         }
853
854         /* Copy across relevant fields */
855         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
856                 dm_task_destroy(task);
857                 return 0;
858         }
859
860         if (dmt->uuid && !dm_task_set_uuid(task, dmt->uuid)) {
861                 dm_task_destroy(task);
862                 return 0;
863         }
864
865         task->major = dmt->major;
866         task->minor = dmt->minor;
867         task->uid = dmt->uid;
868         task->gid = dmt->gid;
869         task->mode = dmt->mode;
870
871         r = dm_task_run(task);
872         dm_task_destroy(task);
873         if (!r)
874                 return r;
875
876         /* Next load the table */
877         if (!(task = dm_task_create(DM_DEVICE_RELOAD))) {
878                 log_error("Failed to create device-mapper task struct");
879                 return 0;
880         }
881
882         /* Copy across relevant fields */
883         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
884                 dm_task_destroy(task);
885                 return 0;
886         }
887
888         task->read_only = dmt->read_only;
889         task->head = dmt->head;
890         task->tail = dmt->tail;
891
892         r = dm_task_run(task);
893
894         task->head = NULL;
895         task->tail = NULL;
896         dm_task_destroy(task);
897         if (!r)
898                 goto revert;
899
900         /* Use the original structure last so the info will be correct */
901         dmt->type = DM_DEVICE_RESUME;
902         dm_free(dmt->uuid);
903         dmt->uuid = NULL;
904
905         r = dm_task_run(dmt);
906
907         if (r)
908                 return r;
909
910       revert:
911         dmt->type = DM_DEVICE_REMOVE;
912         dm_free(dmt->uuid);
913         dmt->uuid = NULL;
914
915         if (!dm_task_run(dmt))
916                 log_error("Failed to revert device creation.");
917
918         return r;
919 }
920
921 uint64_t dm_task_get_existing_table_size(struct dm_task *dmt)
922 {
923         return dmt->existing_table_size;
924 }
925
926 static int _reload_with_suppression_v4(struct dm_task *dmt)
927 {
928         struct dm_task *task;
929         struct target *t1, *t2;
930         int r;
931         
932         /* New task to get existing table information */
933         if (!(task = dm_task_create(DM_DEVICE_TABLE))) {
934                 log_error("Failed to create device-mapper task struct");
935                 return 0;
936         }
937
938         /* Copy across relevant fields */
939         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
940                 dm_task_destroy(task);
941                 return 0;
942         }
943
944         if (dmt->uuid && !dm_task_set_uuid(task, dmt->uuid)) {
945                 dm_task_destroy(task);
946                 return 0;
947         }
948
949         task->major = dmt->major;
950         task->minor = dmt->minor;
951
952         r = dm_task_run(task);
953
954         if (!r) {
955                 dm_task_destroy(task);
956                 return r;
957         }
958
959         /* Store existing table size */
960         t2 = task->head;
961         while (t2 && t2->next)
962                 t2 = t2->next;
963         dmt->existing_table_size = t2 ? t2->start + t2->length : 0;
964         
965         if ((task->dmi.v4->flags & DM_READONLY_FLAG) ? 1 : 0 != dmt->read_only)
966                 goto no_match;
967
968         t1 = dmt->head;
969         t2 = task->head;
970
971         while (t1 && t2) {
972                 while (t2->params[strlen(t2->params) - 1] == ' ')
973                         t2->params[strlen(t2->params) - 1] = '\0';
974                 if ((t1->start != t2->start) ||
975                     (t1->length != t2->length) ||
976                     (strcmp(t1->type, t2->type)) ||
977                     (strcmp(t1->params, t2->params)))
978                         goto no_match;
979                 t1 = t1->next;
980                 t2 = t2->next;
981         }
982         
983         if (!t1 && !t2) {
984                 dmt->dmi.v4 = task->dmi.v4;
985                 task->dmi.v4 = NULL;
986                 dm_task_destroy(task);
987                 return 1;
988         }
989
990 no_match:
991         dm_task_destroy(task);
992
993         /* Now do the original reload */
994         dmt->suppress_identical_reload = 0;
995         r = dm_task_run(dmt);
996
997         return r;
998 }
999
1000 /*
1001  * This function is heart of NetBSD libdevmapper-> device-mapper kernel protocol
1002  * It creates proplib_dictionary from dm task structure and sends it to NetBSD
1003  * kernel driver. After succesfull ioctl it create dmi structure from returned
1004  * proplib dictionary. This way I keep number of changes in NetBSD version of
1005  * libdevmapper as small as posible.
1006  */
1007 static struct dm_ioctl *_do_dm_ioctl(struct dm_task *dmt, unsigned command)
1008 {
1009         struct dm_ioctl *dmi;
1010         prop_dictionary_t dm_dict_in, dm_dict_out;
1011         
1012         uint32_t flags;
1013
1014         dm_dict_in = NULL;
1015         
1016         dm_dict_in = prop_dictionary_create(); /* Dictionary send to kernel */
1017         dm_dict_out = prop_dictionary_create(); /* Dictionary received from kernel */
1018
1019         /* Set command name to dictionary */
1020         prop_dictionary_set_cstring(dm_dict_in, DM_IOCTL_COMMAND,
1021             _cmd_data_v4[dmt->type].name);
1022
1023         /* Parse dmi from libdevmapper to dictionary */
1024         if (_flatten(dmt, dm_dict_in) < 0)
1025                 goto bad;
1026
1027         prop_dictionary_get_uint32(dm_dict_in, DM_IOCTL_FLAGS, &flags);
1028                 
1029         if (dmt->type == DM_DEVICE_TABLE)
1030                 flags |= DM_STATUS_TABLE_FLAG;
1031
1032         if (dmt->no_open_count)
1033                 flags |= DM_SKIP_BDGET_FLAG;
1034
1035         flags |= DM_EXISTS_FLAG;
1036         
1037         /* Set flags to dictionary. */
1038         prop_dictionary_set_uint32(dm_dict_in,DM_IOCTL_FLAGS,flags);
1039         
1040         prop_dictionary_externalize_to_file(dm_dict_in,"/tmp/test_in");
1041         
1042         log_very_verbose("Ioctl type  %s --- flags %d",_cmd_data_v4[dmt->type].name,flags);
1043         //printf("name %s, major %d minor %d\n uuid %s\n", 
1044         //dm_task_get_name(dmt), dmt->minor, dmt->major, dm_task_get_uuid(dmt));
1045         /* Send dictionary to kernel and wait for reply. */
1046
1047         if (prop_dictionary_sendrecv_ioctl(dm_dict_in,_control_fd,
1048                 NETBSD_DM_IOCTL,&dm_dict_out) != 0) {
1049
1050                 if (errno == ENOENT &&
1051                     ((dmt->type == DM_DEVICE_INFO) ||
1052                         (dmt->type == DM_DEVICE_MKNODES) ||
1053                         (dmt->type == DM_DEVICE_STATUS))) {
1054
1055                         /*
1056                          * Linux version doesn't fail when ENOENT is returned
1057                          * for nonexisting device after info, deps, mknodes call.
1058                          * It returns dmi sent to kernel with DM_EXISTS_FLAG = 0;
1059                          */
1060                         
1061                         dmi = nbsd_dm_dict_to_dmi(dm_dict_in,_cmd_data_v4[dmt->type].cmd);
1062
1063                         dmi->flags &= ~DM_EXISTS_FLAG; 
1064
1065                         prop_object_release(dm_dict_in);
1066                         prop_object_release(dm_dict_out);
1067
1068                         goto out;
1069                 } else {
1070                         log_error("ioctl %s call failed with errno %d\n", 
1071                                           _cmd_data_v4[dmt->type].name, errno);
1072
1073                         prop_object_release(dm_dict_in);
1074                         prop_object_release(dm_dict_out);
1075
1076                         goto bad;
1077                 }
1078         }
1079
1080 #ifdef RUMP_ACTION
1081         dm_dict_out = prop_dictionary_internalize(prefp.pref_plist);
1082 #endif  
1083         prop_dictionary_externalize_to_file(dm_dict_out,"/tmp/test_out");
1084
1085         /* Parse kernel dictionary to dmi structure and return it to libdevmapper. */
1086         dmi = nbsd_dm_dict_to_dmi(dm_dict_out,_cmd_data_v4[dmt->type].cmd);
1087
1088         prop_object_release(dm_dict_in);
1089         prop_object_release(dm_dict_out);
1090 out:    
1091         return dmi;
1092 bad:
1093         return NULL;
1094 }
1095
1096 /* Create new edvice nodes in mapper/ dir. */
1097 void dm_task_update_nodes(void)
1098 {
1099         update_devs();
1100 }
1101
1102 static void _dm_rename_kern(struct dm_task *dmt)
1103 {
1104         prop_dictionary_t dm_dict_in, dm_dict_out;
1105
1106         dm_dict_in = prop_dictionary_create(); /* Dictionary send to kernel */
1107
1108         /* Set command name to dictionary */
1109         prop_dictionary_set_cstring(dm_dict_in, DM_IOCTL_COMMAND,
1110             "nrename");
1111         prop_dictionary_set_cstring(dm_dict_in, "dev_name", dmt->dev_name);
1112         prop_dictionary_set_cstring(dm_dict_in, "new_name", dmt->newname);
1113
1114         /* Set flags to dictionary. */
1115         prop_dictionary_set_uint32(dm_dict_in,DM_IOCTL_FLAGS,0);
1116
1117         if (prop_dictionary_sendrecv_ioctl(dm_dict_in,_control_fd,
1118                 NETBSD_DM_IOCTL,&dm_dict_out) != 0) {
1119                 log_error("rename failed");
1120         }
1121 }
1122
1123 /* Run dm command which is descirbed in dm_task structure. */
1124 int dm_task_run(struct dm_task *dmt)
1125 {
1126         struct dm_ioctl *dmi;
1127         unsigned command;
1128
1129         if ((unsigned) dmt->type >=
1130             (sizeof(_cmd_data_v4) / sizeof(*_cmd_data_v4))) {
1131                 log_error("Internal error: unknown device-mapper task %d",
1132                           dmt->type);
1133                 return 0;
1134         }
1135
1136         command = _cmd_data_v4[dmt->type].cmd;
1137
1138         /* Old-style creation had a table supplied */
1139         if (dmt->type == DM_DEVICE_CREATE && dmt->head)
1140                 return _create_and_load_v4(dmt);
1141
1142         if (dmt->type == DM_DEVICE_MKNODES && !dmt->dev_name &&
1143             !dmt->uuid && dmt->major <= 0)
1144                 return _mknodes_v4(dmt);
1145
1146         if ((dmt->type == DM_DEVICE_RELOAD) && dmt->suppress_identical_reload)
1147                 return _reload_with_suppression_v4(dmt);
1148         
1149         if (!_open_control())
1150                 return 0;
1151
1152         if (!(dmi = _do_dm_ioctl(dmt, command)))
1153                 return 0;
1154
1155         switch (dmt->type) {
1156         case DM_DEVICE_CREATE:
1157                 log_verbose("create dmt->dev_name = %s", dmt->dev_name);
1158                 /* XXX: ideally kernel takes care of this */
1159 #if 0
1160                 add_dev_node(dmt->dev_name, MAJOR(dmi->dev), MINOR(dmi->dev),
1161                     dmt->uid, dmt->gid, dmt->mode, 0);
1162 #endif
1163                 break;
1164
1165         case DM_DEVICE_REMOVE:
1166                 log_verbose("remove dmt->dev_name = %s", dmt->dev_name);
1167                 /* XXX: ideally kernel takes care of this */
1168 #if 0
1169                 /* FIXME Kernel needs to fill in dmi->name */
1170                 if (dmt->dev_name)
1171                         rm_dev_node(dmt->dev_name, 0);
1172 #endif
1173                 break;
1174
1175         case DM_DEVICE_RENAME:
1176                 /* FIXME Kernel needs to fill in dmi->name */
1177                 log_verbose("rename dmt->dev_name = %s", dmt->dev_name);
1178                  _dm_rename_kern(dmt);
1179 #if 0
1180                 if (dmt->dev_name)
1181                         rename_dev_node(dmt->dev_name, dmt->newname, 0);
1182 #endif
1183                 break;
1184
1185         case DM_DEVICE_RESUME:
1186                 /* FIXME Kernel needs to fill in dmi->name */
1187                 set_dev_node_read_ahead(dmt->dev_name, dmt->read_ahead,
1188                                         dmt->read_ahead_flags);
1189                 break;
1190         
1191         case DM_DEVICE_MKNODES:
1192                 log_verbose("mknodes dmt->dev_name = %s", dmt->dev_name);
1193 #if 0
1194                 if (dmi->flags & DM_EXISTS_FLAG)
1195                         add_dev_node(dmi->name, MAJOR(dmi->dev),
1196                                      MINOR(dmi->dev),
1197                             dmt->uid, dmt->gid, dmt->mode, 0);
1198                 else if (dmt->dev_name)
1199                         rm_dev_node(dmt->dev_name, 0);
1200 #endif
1201                 break;
1202
1203         case DM_DEVICE_STATUS:
1204         case DM_DEVICE_TABLE:
1205         case DM_DEVICE_WAITEVENT:
1206                 if (!_unmarshal_status(dmt, dmi))
1207                         goto bad;
1208                 break;
1209         }
1210
1211         /* Was structure reused? */
1212         if (dmt->dmi.v4)
1213                 dm_free(dmt->dmi.v4);
1214
1215         dmt->dmi.v4 = dmi;
1216         return 1;
1217
1218       bad:
1219         dm_free(dmi);
1220         return 0;
1221 }
1222
1223 void dm_lib_release(void)
1224 {
1225         if (_control_fd != -1) {
1226                 close(_control_fd);
1227                 _control_fd = -1;
1228         }
1229         update_devs();
1230 }
1231
1232 void dm_lib_exit(void)
1233 {
1234         dm_lib_release();
1235         dm_dump_memory();
1236         _version_ok = 1;
1237         _version_checked = 0;
1238 }