libdm - fix two warnings
[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
427         log_error("dangerous zone...\n");
428
429         mode |= S_IFCHR;
430
431         name = devname(dev,mode);
432
433         r = snprintf(buf, (size_t) bufsize, "/dev/%s",name);
434
435         if (r < 0 || r > bufsize - 1 || name == NULL)
436                 return 0;
437
438         return 1;
439 }
440
441 /* Fill info from dm_ioctl structure. Look at DM_EXISTS_FLAG*/
442 int dm_task_get_info(struct dm_task *dmt, struct dm_info *info)
443 {
444         if (!dmt->dmi.v4)
445                 return 0;
446
447         memset(info, 0, sizeof(*info));
448
449         info->exists = dmt->dmi.v4->flags & DM_EXISTS_FLAG ? 1 : 0;
450         if (!info->exists)
451                 return 1;
452
453         info->suspended = dmt->dmi.v4->flags & DM_SUSPEND_FLAG ? 1 : 0;
454         info->read_only = dmt->dmi.v4->flags & DM_READONLY_FLAG ? 1 : 0;
455         info->live_table = dmt->dmi.v4->flags & DM_ACTIVE_PRESENT_FLAG ? 1 : 0;
456         info->inactive_table = dmt->dmi.v4->flags & DM_INACTIVE_PRESENT_FLAG ?
457             1 : 0;
458         info->target_count = dmt->dmi.v4->target_count;
459         info->open_count = dmt->dmi.v4->open_count;
460         info->event_nr = dmt->dmi.v4->event_nr;
461         
462         nbsd_get_dm_major(&info->major, DM_BLOCK_MAJOR); /* get netbsd dm device major number */
463         info->minor = MINOR(dmt->dmi.v4->dev);
464         
465         return 1;
466 }
467
468 /* Unsupported on NetBSD */
469 uint32_t dm_task_get_read_ahead(const struct dm_task *dmt, uint32_t *read_ahead)
470 {
471         *read_ahead = DM_READ_AHEAD_NONE;
472         return 1;
473 }
474
475 const char *dm_task_get_name(const struct dm_task *dmt)
476 {
477
478         return (dmt->dmi.v4->name);
479 }
480
481 const char *dm_task_get_uuid(const struct dm_task *dmt)
482 {
483
484         return (dmt->dmi.v4->uuid);
485 }
486
487 struct dm_deps *dm_task_get_deps(struct dm_task *dmt)
488 {
489         return (struct dm_deps *) (((void *) dmt->dmi.v4) +
490                                    dmt->dmi.v4->data_start);
491 }
492
493 struct dm_names *dm_task_get_names(struct dm_task *dmt)
494 {
495         return (struct dm_names *) (((void *) dmt->dmi.v4) +
496                                     dmt->dmi.v4->data_start);
497 }
498
499 struct dm_versions *dm_task_get_versions(struct dm_task *dmt)
500 {
501         return (struct dm_versions *) (((void *) dmt->dmi.v4) +
502                                        dmt->dmi.v4->data_start);
503 }
504
505 int dm_task_set_ro(struct dm_task *dmt)
506 {
507         dmt->read_only = 1;
508         return 1;
509 }
510
511 /* Unsupported on NetBSD */
512 int dm_task_set_read_ahead(struct dm_task *dmt, uint32_t read_ahead,
513                            uint32_t read_ahead_flags)
514 {
515         return 1;
516 }
517
518 int dm_task_suppress_identical_reload(struct dm_task *dmt)
519 {
520         dmt->suppress_identical_reload = 1;
521         return 1;
522 }
523
524 int dm_task_set_newname(struct dm_task *dmt, const char *newname)
525 {
526         if (!(dmt->newname = dm_strdup(newname))) {
527                 log_error("dm_task_set_newname: strdup(%s) failed", newname);
528                 return 0;
529         }
530
531         return 1;
532 }
533
534 int dm_task_set_message(struct dm_task *dmt, const char *message)
535 {
536         if (!(dmt->message = dm_strdup(message))) {
537                 log_error("dm_task_set_message: strdup(%s) failed", message);
538                 return 0;
539         }
540
541         return 1;
542 }
543
544 int dm_task_set_sector(struct dm_task *dmt, uint64_t sector)
545 {
546         dmt->sector = sector;
547
548         return 1;
549 }
550
551 /* Unsupported in NetBSD */
552 int dm_task_set_geometry(struct dm_task *dmt, const char *cylinders,
553     const char *heads, const char *sectors, const char *start)
554 {
555         return 0;
556 }
557
558 int dm_task_no_flush(struct dm_task *dmt)
559 {
560         dmt->no_flush = 1;
561
562         return 1;
563 }
564
565 int dm_task_no_open_count(struct dm_task *dmt)
566 {
567         dmt->no_open_count = 1;
568
569         return 1;
570 }
571
572 int dm_task_skip_lockfs(struct dm_task *dmt)
573 {
574         dmt->skip_lockfs = 1;
575
576         return 1;
577 }
578
579 int dm_task_query_inactive_table(struct dm_task *dmt)
580 {
581         dmt->query_inactive_table = 1;
582
583         return 1;
584 }
585
586 int dm_task_set_event_nr(struct dm_task *dmt, uint32_t event_nr)
587 {
588         dmt->event_nr = event_nr;
589
590         return 1;
591 }
592
593 /* Allocate one target(table description) entry. */
594 struct target *create_target(uint64_t start, uint64_t len, const char *type,
595                              const char *params)
596 {
597         struct target *t = dm_malloc(sizeof(*t));
598         log_error("params is at create_target: %s", params);
599         if (!t) {
600                 log_error("create_target: malloc(%" PRIsize_t ") failed",
601                           sizeof(*t));
602                 return NULL;
603         }
604
605         memset(t, 0, sizeof(*t));
606
607         if (!(t->params = dm_strdup(params))) {
608                 log_error("create_target: strdup(params) failed");
609                 goto bad;
610         }
611
612         if (!(t->type = dm_strdup(type))) {
613                 log_error("create_target: strdup(type) failed");
614                 goto bad;
615         }
616
617         t->start = start;
618         t->length = len;
619         return t;
620
621       bad:
622         dm_free(t->params);
623         dm_free(t->type);
624         dm_free(t);
625         return NULL;
626 }
627
628 /* Parse given dm task structure to proplib dictionary.  */
629 static int _flatten(struct dm_task *dmt, prop_dictionary_t dm_dict)
630 {
631         prop_array_t cmd_array;
632         prop_dictionary_t target_spec;
633         
634         struct target *t;
635         
636         size_t len;
637         char type[DM_MAX_TYPE_NAME];
638         
639         uint32_t major, flags;
640         int count = 0;
641         char *str = NULL;
642         const int (*version)[3];
643         
644         flags = 0;
645         version = &_cmd_data_v4[dmt->type].version;
646
647         cmd_array = prop_array_create();
648
649         for (t = dmt->head; t; t = t->next) {
650                 target_spec = prop_dictionary_create();
651
652                 prop_dictionary_set_uint64(target_spec,DM_TABLE_START,t->start);
653                 prop_dictionary_set_uint64(target_spec,DM_TABLE_LENGTH,t->length);
654
655                 strlcpy(type,t->type,DM_MAX_TYPE_NAME);
656
657                 prop_dictionary_set_cstring(target_spec,DM_TABLE_TYPE,type);
658                 log_error("t->params: %s\n", t->params);
659                 prop_dictionary_set_cstring(target_spec,DM_TABLE_PARAMS,t->params);
660
661                 prop_dictionary_get_cstring(target_spec,
662                     DM_TABLE_PARAMS, (char **) &str);
663                 log_error("t->params from dict: %s\n", str);
664
665                 prop_array_set(cmd_array,count,target_spec);
666
667                 prop_object_release(target_spec);
668                 
669                 count++;
670         }
671
672         
673         if (count && (dmt->sector || dmt->message)) {
674                 log_error("targets and message are incompatible");
675                 return -1;
676         }
677
678         if (count && dmt->newname) {
679                 log_error("targets and newname are incompatible");
680                 return -1;
681         }
682
683         if (count && dmt->geometry) {
684                 log_error("targets and geometry are incompatible");
685                 return -1;
686         }
687
688         if (dmt->newname && (dmt->sector || dmt->message)) {
689                 log_error("message and newname are incompatible");
690                 return -1;
691         }
692
693         if (dmt->newname && dmt->geometry) {
694                 log_error("geometry and newname are incompatible");
695                 return -1;
696         }
697
698         if (dmt->geometry && (dmt->sector || dmt->message)) {
699                 log_error("geometry and message are incompatible");
700                 return -1;
701         }
702
703         if (dmt->sector && !dmt->message) {
704                 log_error("message is required with sector");
705                 return -1;
706         }
707
708         if (dmt->newname)
709                 len += strlen(dmt->newname) + 1;
710
711         if (dmt->message)
712                 len += sizeof(struct dm_target_msg) + strlen(dmt->message) + 1;
713
714         if (dmt->geometry)
715                 len += strlen(dmt->geometry) + 1;
716
717         nbsd_dmi_add_version((*version), dm_dict);
718             
719         nbsd_get_dm_major(&major, DM_BLOCK_MAJOR);
720         /* 
721          * Only devices with major which is equal to netbsd dm major 
722          * dm devices in NetBSD can't have more majors then one assigned to dm.
723          */
724         if (dmt->major != major && dmt->major != -1)
725                 return -1;
726                 
727         if (dmt->minor >= 0) {
728                 flags |= DM_PERSISTENT_DEV_FLAG;
729                 
730                 prop_dictionary_set_uint32(dm_dict, DM_IOCTL_MINOR, dmt->minor);
731         }
732
733         /* Set values to dictionary. */
734         if (dmt->dev_name)
735                 prop_dictionary_set_cstring(dm_dict, DM_IOCTL_NAME, dmt->dev_name);
736
737         if (dmt->uuid)
738                 prop_dictionary_set_cstring(dm_dict, DM_IOCTL_UUID, dmt->uuid);
739         
740         if (dmt->type == DM_DEVICE_SUSPEND)
741                 flags |= DM_SUSPEND_FLAG;
742         if (dmt->no_flush)
743                 flags |= DM_NOFLUSH_FLAG;
744         if (dmt->read_only)
745                 flags |= DM_READONLY_FLAG;
746         if (dmt->skip_lockfs)
747                 flags |= DM_SKIP_LOCKFS_FLAG;
748
749         if (dmt->query_inactive_table) {
750                 if (_dm_version_minor < 16)
751                         log_warn("WARNING: Inactive table query unsupported "
752                                  "by kernel.  It will use live table.");
753                 flags |= DM_QUERY_INACTIVE_TABLE_FLAG;
754         }
755         
756         prop_dictionary_set_uint32(dm_dict, DM_IOCTL_FLAGS, flags);
757
758         prop_dictionary_set_uint32(dm_dict, DM_IOCTL_EVENT, dmt->event_nr);
759
760         if (dmt->newname)
761                 prop_array_set_cstring(cmd_array, 0, dmt->newname);
762         
763         /* Add array for all COMMAND specific data. */
764         prop_dictionary_set(dm_dict, DM_IOCTL_CMD_DATA, cmd_array);
765         prop_object_release(cmd_array);
766         
767         return 0;
768 }
769
770 static int _process_mapper_dir(struct dm_task *dmt)
771 {
772         struct dirent *dirent;
773         DIR *d;
774         const char *dir;
775         int r = 1;
776
777         dir = dm_dir();
778         if (!(d = opendir(dir))) {
779                 log_sys_error("opendir", dir);
780                 return 0;
781         }
782
783         while ((dirent = readdir(d))) {
784                 if (!strcmp(dirent->d_name, ".") ||
785                     !strcmp(dirent->d_name, "..") ||
786                     !strcmp(dirent->d_name, "control"))
787                         continue;
788                 dm_task_set_name(dmt, dirent->d_name);
789                 dm_task_run(dmt);
790         }
791
792         if (closedir(d))
793                 log_sys_error("closedir", dir);
794
795         return r;
796 }
797
798 /* Get list of all devices. */
799 static int _process_all_v4(struct dm_task *dmt)
800 {
801         struct dm_task *task;
802         struct dm_names *names;
803         unsigned next = 0;
804         int r = 1;
805
806         if (!(task = dm_task_create(DM_DEVICE_LIST)))
807                 return 0;
808
809         if (!dm_task_run(task)) {
810                 r = 0;
811                 goto out;
812         }
813
814         if (!(names = dm_task_get_names(task))) {
815                 r = 0;
816                 goto out;
817         }
818
819         if (!names->dev)
820                 goto out;
821
822         do {
823                 names = (void *) names + next;
824                 if (!dm_task_set_name(dmt, names->name)) {
825                         r = 0;
826                         goto out;
827                 }
828                 if (!dm_task_run(dmt))
829                         r = 0;
830                 next = names->next;
831         } while (next);
832
833       out:
834         dm_task_destroy(task);
835         return r;
836 }
837
838 static int _mknodes_v4(struct dm_task *dmt)
839 {
840         (void) _process_mapper_dir(dmt);
841
842         return _process_all_v4(dmt);
843 }
844
845 /* Create new device and load table to it. */
846 static int _create_and_load_v4(struct dm_task *dmt)
847 {
848         struct dm_task *task;
849         int r;
850
851         printf("create and load called \n");
852         
853         /* Use new task struct to create the device */
854         if (!(task = dm_task_create(DM_DEVICE_CREATE))) {
855                 log_error("Failed to create device-mapper task struct");
856                 return 0;
857         }
858
859         /* Copy across relevant fields */
860         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
861                 dm_task_destroy(task);
862                 return 0;
863         }
864
865         if (dmt->uuid && !dm_task_set_uuid(task, dmt->uuid)) {
866                 dm_task_destroy(task);
867                 return 0;
868         }
869
870         task->major = dmt->major;
871         task->minor = dmt->minor;
872         task->uid = dmt->uid;
873         task->gid = dmt->gid;
874         task->mode = dmt->mode;
875
876         r = dm_task_run(task);
877         dm_task_destroy(task);
878         if (!r)
879                 return r;
880
881         /* Next load the table */
882         if (!(task = dm_task_create(DM_DEVICE_RELOAD))) {
883                 log_error("Failed to create device-mapper task struct");
884                 return 0;
885         }
886
887         /* Copy across relevant fields */
888         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
889                 dm_task_destroy(task);
890                 return 0;
891         }
892
893         task->read_only = dmt->read_only;
894         task->head = dmt->head;
895         task->tail = dmt->tail;
896
897         r = dm_task_run(task);
898
899         task->head = NULL;
900         task->tail = NULL;
901         dm_task_destroy(task);
902         if (!r)
903                 goto revert;
904
905         /* Use the original structure last so the info will be correct */
906         dmt->type = DM_DEVICE_RESUME;
907         dm_free(dmt->uuid);
908         dmt->uuid = NULL;
909
910         r = dm_task_run(dmt);
911
912         if (r)
913                 return r;
914
915       revert:
916         dmt->type = DM_DEVICE_REMOVE;
917         dm_free(dmt->uuid);
918         dmt->uuid = NULL;
919
920         if (!dm_task_run(dmt))
921                 log_error("Failed to revert device creation.");
922
923         return r;
924 }
925
926 uint64_t dm_task_get_existing_table_size(struct dm_task *dmt)
927 {
928         return dmt->existing_table_size;
929 }
930
931 static int _reload_with_suppression_v4(struct dm_task *dmt)
932 {
933         struct dm_task *task;
934         struct target *t1, *t2;
935         int r;
936         
937         /* New task to get existing table information */
938         if (!(task = dm_task_create(DM_DEVICE_TABLE))) {
939                 log_error("Failed to create device-mapper task struct");
940                 return 0;
941         }
942
943         /* Copy across relevant fields */
944         if (dmt->dev_name && !dm_task_set_name(task, dmt->dev_name)) {
945                 dm_task_destroy(task);
946                 return 0;
947         }
948
949         if (dmt->uuid && !dm_task_set_uuid(task, dmt->uuid)) {
950                 dm_task_destroy(task);
951                 return 0;
952         }
953
954         task->major = dmt->major;
955         task->minor = dmt->minor;
956
957         r = dm_task_run(task);
958
959         if (!r) {
960                 dm_task_destroy(task);
961                 return r;
962         }
963
964         /* Store existing table size */
965         t2 = task->head;
966         while (t2 && t2->next)
967                 t2 = t2->next;
968         dmt->existing_table_size = t2 ? t2->start + t2->length : 0;
969         
970         if ((task->dmi.v4->flags & DM_READONLY_FLAG) ? 1 : 0 != dmt->read_only)
971                 goto no_match;
972
973         t1 = dmt->head;
974         t2 = task->head;
975
976         while (t1 && t2) {
977                 while (t2->params[strlen(t2->params) - 1] == ' ')
978                         t2->params[strlen(t2->params) - 1] = '\0';
979                 if ((t1->start != t2->start) ||
980                     (t1->length != t2->length) ||
981                     (strcmp(t1->type, t2->type)) ||
982                     (strcmp(t1->params, t2->params)))
983                         goto no_match;
984                 t1 = t1->next;
985                 t2 = t2->next;
986         }
987         
988         if (!t1 && !t2) {
989                 dmt->dmi.v4 = task->dmi.v4;
990                 task->dmi.v4 = NULL;
991                 dm_task_destroy(task);
992                 return 1;
993         }
994
995 no_match:
996         dm_task_destroy(task);
997
998         /* Now do the original reload */
999         dmt->suppress_identical_reload = 0;
1000         r = dm_task_run(dmt);
1001
1002         return r;
1003 }
1004
1005 /*
1006  * This function is heart of NetBSD libdevmapper-> device-mapper kernel protocol
1007  * It creates proplib_dictionary from dm task structure and sends it to NetBSD
1008  * kernel driver. After succesfull ioctl it create dmi structure from returned
1009  * proplib dictionary. This way I keep number of changes in NetBSD version of
1010  * libdevmapper as small as posible.
1011  */
1012 static struct dm_ioctl *_do_dm_ioctl(struct dm_task *dmt, unsigned command)
1013 {
1014         struct dm_ioctl *dmi;
1015         prop_dictionary_t dm_dict_in, dm_dict_out;
1016         
1017         uint32_t flags;
1018
1019         dm_dict_in = NULL;
1020         
1021         dm_dict_in = prop_dictionary_create(); /* Dictionary send to kernel */
1022         dm_dict_out = prop_dictionary_create(); /* Dictionary received from kernel */
1023
1024         /* Set command name to dictionary */
1025         prop_dictionary_set_cstring(dm_dict_in, DM_IOCTL_COMMAND,
1026             _cmd_data_v4[dmt->type].name);
1027
1028         /* Parse dmi from libdevmapper to dictionary */
1029         if (_flatten(dmt, dm_dict_in) < 0)
1030                 goto bad;
1031
1032         prop_dictionary_get_uint32(dm_dict_in, DM_IOCTL_FLAGS, &flags);
1033                 
1034         if (dmt->type == DM_DEVICE_TABLE)
1035                 flags |= DM_STATUS_TABLE_FLAG;
1036
1037         if (dmt->no_open_count)
1038                 flags |= DM_SKIP_BDGET_FLAG;
1039
1040         flags |= DM_EXISTS_FLAG;
1041         
1042         /* Set flags to dictionary. */
1043         prop_dictionary_set_uint32(dm_dict_in,DM_IOCTL_FLAGS,flags);
1044         
1045         prop_dictionary_externalize_to_file(dm_dict_in,"/tmp/test_in");
1046         
1047         log_very_verbose("Ioctl type  %s --- flags %d",_cmd_data_v4[dmt->type].name,flags);
1048         //printf("name %s, major %d minor %d\n uuid %s\n", 
1049         //dm_task_get_name(dmt), dmt->minor, dmt->major, dm_task_get_uuid(dmt));
1050         /* Send dictionary to kernel and wait for reply. */
1051
1052         if (prop_dictionary_sendrecv_ioctl(dm_dict_in,_control_fd,
1053                 NETBSD_DM_IOCTL,&dm_dict_out) != 0) {
1054
1055                 if (errno == ENOENT &&
1056                     ((dmt->type == DM_DEVICE_INFO) ||
1057                         (dmt->type == DM_DEVICE_MKNODES) ||
1058                         (dmt->type == DM_DEVICE_STATUS))) {
1059
1060                         /*
1061                          * Linux version doesn't fail when ENOENT is returned
1062                          * for nonexisting device after info, deps, mknodes call.
1063                          * It returns dmi sent to kernel with DM_EXISTS_FLAG = 0;
1064                          */
1065                         
1066                         dmi = nbsd_dm_dict_to_dmi(dm_dict_in,_cmd_data_v4[dmt->type].cmd);
1067
1068                         dmi->flags &= ~DM_EXISTS_FLAG; 
1069
1070                         prop_object_release(dm_dict_in);
1071                         prop_object_release(dm_dict_out);
1072
1073                         goto out;
1074                 } else {
1075                         log_error("ioctl %s call failed with errno %d\n", 
1076                                           _cmd_data_v4[dmt->type].name, errno);
1077
1078                         prop_object_release(dm_dict_in);
1079                         prop_object_release(dm_dict_out);
1080
1081                         goto bad;
1082                 }
1083         }
1084
1085 #ifdef RUMP_ACTION
1086         dm_dict_out = prop_dictionary_internalize(prefp.pref_plist);
1087 #endif  
1088         prop_dictionary_externalize_to_file(dm_dict_out,"/tmp/test_out");
1089
1090         /* Parse kernel dictionary to dmi structure and return it to libdevmapper. */
1091         dmi = nbsd_dm_dict_to_dmi(dm_dict_out,_cmd_data_v4[dmt->type].cmd);
1092
1093         prop_object_release(dm_dict_in);
1094         prop_object_release(dm_dict_out);
1095 out:    
1096         return dmi;
1097 bad:
1098         return NULL;
1099 }
1100
1101 /* Create new edvice nodes in mapper/ dir. */
1102 void dm_task_update_nodes(void)
1103 {
1104         update_devs();
1105 }
1106
1107 static void _dm_rename_kern(struct dm_task *dmt)
1108 {
1109         prop_dictionary_t dm_dict_in, dm_dict_out;
1110
1111         dm_dict_in = prop_dictionary_create(); /* Dictionary send to kernel */
1112
1113         /* Set command name to dictionary */
1114         prop_dictionary_set_cstring(dm_dict_in, DM_IOCTL_COMMAND,
1115             "nrename");
1116         prop_dictionary_set_cstring(dm_dict_in, "dev_name", dmt->dev_name);
1117         prop_dictionary_set_cstring(dm_dict_in, "new_name", dmt->newname);
1118
1119         /* Set flags to dictionary. */
1120         prop_dictionary_set_uint32(dm_dict_in,DM_IOCTL_FLAGS,0);
1121
1122         if (prop_dictionary_sendrecv_ioctl(dm_dict_in,_control_fd,
1123                 NETBSD_DM_IOCTL,&dm_dict_out) != 0) {
1124                 log_error("rename failed");
1125         }
1126 }
1127
1128 /* Run dm command which is descirbed in dm_task structure. */
1129 int dm_task_run(struct dm_task *dmt)
1130 {
1131         struct dm_ioctl *dmi;
1132         unsigned command;
1133
1134         if ((unsigned) dmt->type >=
1135             (sizeof(_cmd_data_v4) / sizeof(*_cmd_data_v4))) {
1136                 log_error("Internal error: unknown device-mapper task %d",
1137                           dmt->type);
1138                 return 0;
1139         }
1140
1141         command = _cmd_data_v4[dmt->type].cmd;
1142
1143         /* Old-style creation had a table supplied */
1144         if (dmt->type == DM_DEVICE_CREATE && dmt->head)
1145                 return _create_and_load_v4(dmt);
1146
1147         if (dmt->type == DM_DEVICE_MKNODES && !dmt->dev_name &&
1148             !dmt->uuid && dmt->major <= 0)
1149                 return _mknodes_v4(dmt);
1150
1151         if ((dmt->type == DM_DEVICE_RELOAD) && dmt->suppress_identical_reload)
1152                 return _reload_with_suppression_v4(dmt);
1153         
1154         if (!_open_control())
1155                 return 0;
1156
1157         if (!(dmi = _do_dm_ioctl(dmt, command)))
1158                 return 0;
1159
1160         switch (dmt->type) {
1161         case DM_DEVICE_CREATE:
1162                 printf("create dmt->dev_name = %s\n", dmt->dev_name);
1163                 /* XXX: ideally kernel takes care of this */
1164 #if 0
1165                 add_dev_node(dmt->dev_name, MAJOR(dmi->dev), MINOR(dmi->dev),
1166                     dmt->uid, dmt->gid, dmt->mode, 0);
1167 #endif
1168                 break;
1169
1170         case DM_DEVICE_REMOVE:
1171                 printf("remove dmt->dev_name = %s\n", dmt->dev_name);
1172                 /* XXX: ideally kernel takes care of this */
1173 #if 0
1174                 /* FIXME Kernel needs to fill in dmi->name */
1175                 if (dmt->dev_name)
1176                         rm_dev_node(dmt->dev_name, 0);
1177 #endif
1178                 break;
1179
1180         case DM_DEVICE_RENAME:
1181                 /* FIXME Kernel needs to fill in dmi->name */
1182                 printf("rename dmt->dev_name = %s\n", dmt->dev_name);
1183                  _dm_rename_kern(dmt);
1184 #if 0
1185                 if (dmt->dev_name)
1186                         rename_dev_node(dmt->dev_name, dmt->newname, 0);
1187 #endif
1188                 break;
1189
1190         case DM_DEVICE_RESUME:
1191                 /* FIXME Kernel needs to fill in dmi->name */
1192                 set_dev_node_read_ahead(dmt->dev_name, dmt->read_ahead,
1193                                         dmt->read_ahead_flags);
1194                 break;
1195         
1196         case DM_DEVICE_MKNODES:
1197                 printf("mknodes dmt->dev_name = %s\n", dmt->dev_name);
1198 #if 0
1199                 if (dmi->flags & DM_EXISTS_FLAG)
1200                         add_dev_node(dmi->name, MAJOR(dmi->dev),
1201                                      MINOR(dmi->dev),
1202                             dmt->uid, dmt->gid, dmt->mode, 0);
1203                 else if (dmt->dev_name)
1204                         rm_dev_node(dmt->dev_name, 0);
1205 #endif
1206                 break;
1207
1208         case DM_DEVICE_STATUS:
1209         case DM_DEVICE_TABLE:
1210         case DM_DEVICE_WAITEVENT:
1211                 if (!_unmarshal_status(dmt, dmi))
1212                         goto bad;
1213                 break;
1214         }
1215
1216         /* Was structure reused? */
1217         if (dmt->dmi.v4)
1218                 dm_free(dmt->dmi.v4);
1219
1220         dmt->dmi.v4 = dmi;
1221         return 1;
1222
1223       bad:
1224         dm_free(dmi);
1225         return 0;
1226 }
1227
1228 void dm_lib_release(void)
1229 {
1230         if (_control_fd != -1) {
1231                 close(_control_fd);
1232                 _control_fd = -1;
1233         }
1234         update_devs();
1235 }
1236
1237 void dm_lib_exit(void)
1238 {
1239         dm_lib_release();
1240         dm_dump_memory();
1241         _version_ok = 1;
1242         _version_checked = 0;
1243 }