GNU Linux-libre 4.19.304-gnu1
[releases.git] / drivers / md / dm-ioctl.c
1 /*
2  * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3  * Copyright (C) 2004 - 2006 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm-core.h"
9
10 #include <linux/module.h>
11 #include <linux/vmalloc.h>
12 #include <linux/miscdevice.h>
13 #include <linux/sched/mm.h>
14 #include <linux/init.h>
15 #include <linux/wait.h>
16 #include <linux/slab.h>
17 #include <linux/dm-ioctl.h>
18 #include <linux/hdreg.h>
19 #include <linux/compat.h>
20 #include <linux/nospec.h>
21
22 #include <linux/uaccess.h>
23
24 #define DM_MSG_PREFIX "ioctl"
25 #define DM_DRIVER_EMAIL "dm-devel@redhat.com"
26
27 struct dm_file {
28         /*
29          * poll will wait until the global event number is greater than
30          * this value.
31          */
32         volatile unsigned global_event_nr;
33 };
34
35 /*-----------------------------------------------------------------
36  * The ioctl interface needs to be able to look up devices by
37  * name or uuid.
38  *---------------------------------------------------------------*/
39 struct hash_cell {
40         struct list_head name_list;
41         struct list_head uuid_list;
42
43         char *name;
44         char *uuid;
45         struct mapped_device *md;
46         struct dm_table *new_map;
47 };
48
49 struct vers_iter {
50     size_t param_size;
51     struct dm_target_versions *vers, *old_vers;
52     char *end;
53     uint32_t flags;
54 };
55
56
57 #define NUM_BUCKETS 64
58 #define MASK_BUCKETS (NUM_BUCKETS - 1)
59 static struct list_head _name_buckets[NUM_BUCKETS];
60 static struct list_head _uuid_buckets[NUM_BUCKETS];
61
62 static void dm_hash_remove_all(bool keep_open_devices, bool mark_deferred, bool only_deferred);
63
64 /*
65  * Guards access to both hash tables.
66  */
67 static DECLARE_RWSEM(_hash_lock);
68
69 /*
70  * Protects use of mdptr to obtain hash cell name and uuid from mapped device.
71  */
72 static DEFINE_MUTEX(dm_hash_cells_mutex);
73
74 static void init_buckets(struct list_head *buckets)
75 {
76         unsigned int i;
77
78         for (i = 0; i < NUM_BUCKETS; i++)
79                 INIT_LIST_HEAD(buckets + i);
80 }
81
82 static int dm_hash_init(void)
83 {
84         init_buckets(_name_buckets);
85         init_buckets(_uuid_buckets);
86         return 0;
87 }
88
89 static void dm_hash_exit(void)
90 {
91         dm_hash_remove_all(false, false, false);
92 }
93
94 /*-----------------------------------------------------------------
95  * Hash function:
96  * We're not really concerned with the str hash function being
97  * fast since it's only used by the ioctl interface.
98  *---------------------------------------------------------------*/
99 static unsigned int hash_str(const char *str)
100 {
101         const unsigned int hash_mult = 2654435387U;
102         unsigned int h = 0;
103
104         while (*str)
105                 h = (h + (unsigned int) *str++) * hash_mult;
106
107         return h & MASK_BUCKETS;
108 }
109
110 /*-----------------------------------------------------------------
111  * Code for looking up a device by name
112  *---------------------------------------------------------------*/
113 static struct hash_cell *__get_name_cell(const char *str)
114 {
115         struct hash_cell *hc;
116         unsigned int h = hash_str(str);
117
118         list_for_each_entry (hc, _name_buckets + h, name_list)
119                 if (!strcmp(hc->name, str)) {
120                         dm_get(hc->md);
121                         return hc;
122                 }
123
124         return NULL;
125 }
126
127 static struct hash_cell *__get_uuid_cell(const char *str)
128 {
129         struct hash_cell *hc;
130         unsigned int h = hash_str(str);
131
132         list_for_each_entry (hc, _uuid_buckets + h, uuid_list)
133                 if (!strcmp(hc->uuid, str)) {
134                         dm_get(hc->md);
135                         return hc;
136                 }
137
138         return NULL;
139 }
140
141 static struct hash_cell *__get_dev_cell(uint64_t dev)
142 {
143         struct mapped_device *md;
144         struct hash_cell *hc;
145
146         md = dm_get_md(huge_decode_dev(dev));
147         if (!md)
148                 return NULL;
149
150         hc = dm_get_mdptr(md);
151         if (!hc) {
152                 dm_put(md);
153                 return NULL;
154         }
155
156         return hc;
157 }
158
159 /*-----------------------------------------------------------------
160  * Inserting, removing and renaming a device.
161  *---------------------------------------------------------------*/
162 static struct hash_cell *alloc_cell(const char *name, const char *uuid,
163                                     struct mapped_device *md)
164 {
165         struct hash_cell *hc;
166
167         hc = kmalloc(sizeof(*hc), GFP_KERNEL);
168         if (!hc)
169                 return NULL;
170
171         hc->name = kstrdup(name, GFP_KERNEL);
172         if (!hc->name) {
173                 kfree(hc);
174                 return NULL;
175         }
176
177         if (!uuid)
178                 hc->uuid = NULL;
179
180         else {
181                 hc->uuid = kstrdup(uuid, GFP_KERNEL);
182                 if (!hc->uuid) {
183                         kfree(hc->name);
184                         kfree(hc);
185                         return NULL;
186                 }
187         }
188
189         INIT_LIST_HEAD(&hc->name_list);
190         INIT_LIST_HEAD(&hc->uuid_list);
191         hc->md = md;
192         hc->new_map = NULL;
193         return hc;
194 }
195
196 static void free_cell(struct hash_cell *hc)
197 {
198         if (hc) {
199                 kfree(hc->name);
200                 kfree(hc->uuid);
201                 kfree(hc);
202         }
203 }
204
205 /*
206  * The kdev_t and uuid of a device can never change once it is
207  * initially inserted.
208  */
209 static int dm_hash_insert(const char *name, const char *uuid, struct mapped_device *md)
210 {
211         struct hash_cell *cell, *hc;
212
213         /*
214          * Allocate the new cells.
215          */
216         cell = alloc_cell(name, uuid, md);
217         if (!cell)
218                 return -ENOMEM;
219
220         /*
221          * Insert the cell into both hash tables.
222          */
223         down_write(&_hash_lock);
224         hc = __get_name_cell(name);
225         if (hc) {
226                 dm_put(hc->md);
227                 goto bad;
228         }
229
230         list_add(&cell->name_list, _name_buckets + hash_str(name));
231
232         if (uuid) {
233                 hc = __get_uuid_cell(uuid);
234                 if (hc) {
235                         list_del(&cell->name_list);
236                         dm_put(hc->md);
237                         goto bad;
238                 }
239                 list_add(&cell->uuid_list, _uuid_buckets + hash_str(uuid));
240         }
241         dm_get(md);
242         mutex_lock(&dm_hash_cells_mutex);
243         dm_set_mdptr(md, cell);
244         mutex_unlock(&dm_hash_cells_mutex);
245         up_write(&_hash_lock);
246
247         return 0;
248
249  bad:
250         up_write(&_hash_lock);
251         free_cell(cell);
252         return -EBUSY;
253 }
254
255 static struct dm_table *__hash_remove(struct hash_cell *hc)
256 {
257         struct dm_table *table;
258         int srcu_idx;
259
260         /* remove from the dev hash */
261         list_del(&hc->uuid_list);
262         list_del(&hc->name_list);
263         mutex_lock(&dm_hash_cells_mutex);
264         dm_set_mdptr(hc->md, NULL);
265         mutex_unlock(&dm_hash_cells_mutex);
266
267         table = dm_get_live_table(hc->md, &srcu_idx);
268         if (table)
269                 dm_table_event(table);
270         dm_put_live_table(hc->md, srcu_idx);
271
272         table = NULL;
273         if (hc->new_map)
274                 table = hc->new_map;
275         dm_put(hc->md);
276         free_cell(hc);
277
278         return table;
279 }
280
281 static void dm_hash_remove_all(bool keep_open_devices, bool mark_deferred, bool only_deferred)
282 {
283         int i, dev_skipped;
284         struct hash_cell *hc;
285         struct mapped_device *md;
286         struct dm_table *t;
287
288 retry:
289         dev_skipped = 0;
290
291         down_write(&_hash_lock);
292
293         for (i = 0; i < NUM_BUCKETS; i++) {
294                 list_for_each_entry(hc, _name_buckets + i, name_list) {
295                         md = hc->md;
296                         dm_get(md);
297
298                         if (keep_open_devices &&
299                             dm_lock_for_deletion(md, mark_deferred, only_deferred)) {
300                                 dm_put(md);
301                                 dev_skipped++;
302                                 continue;
303                         }
304
305                         t = __hash_remove(hc);
306
307                         up_write(&_hash_lock);
308
309                         if (t) {
310                                 dm_sync_table(md);
311                                 dm_table_destroy(t);
312                         }
313                         dm_put(md);
314                         if (likely(keep_open_devices))
315                                 dm_destroy(md);
316                         else
317                                 dm_destroy_immediate(md);
318
319                         /*
320                          * Some mapped devices may be using other mapped
321                          * devices, so repeat until we make no further
322                          * progress.  If a new mapped device is created
323                          * here it will also get removed.
324                          */
325                         goto retry;
326                 }
327         }
328
329         up_write(&_hash_lock);
330
331         if (dev_skipped)
332                 DMWARN("remove_all left %d open device(s)", dev_skipped);
333 }
334
335 /*
336  * Set the uuid of a hash_cell that isn't already set.
337  */
338 static void __set_cell_uuid(struct hash_cell *hc, char *new_uuid)
339 {
340         mutex_lock(&dm_hash_cells_mutex);
341         hc->uuid = new_uuid;
342         mutex_unlock(&dm_hash_cells_mutex);
343
344         list_add(&hc->uuid_list, _uuid_buckets + hash_str(new_uuid));
345 }
346
347 /*
348  * Changes the name of a hash_cell and returns the old name for
349  * the caller to free.
350  */
351 static char *__change_cell_name(struct hash_cell *hc, char *new_name)
352 {
353         char *old_name;
354
355         /*
356          * Rename and move the name cell.
357          */
358         list_del(&hc->name_list);
359         old_name = hc->name;
360
361         mutex_lock(&dm_hash_cells_mutex);
362         hc->name = new_name;
363         mutex_unlock(&dm_hash_cells_mutex);
364
365         list_add(&hc->name_list, _name_buckets + hash_str(new_name));
366
367         return old_name;
368 }
369
370 static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
371                                             const char *new)
372 {
373         char *new_data, *old_name = NULL;
374         struct hash_cell *hc;
375         struct dm_table *table;
376         struct mapped_device *md;
377         unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0;
378         int srcu_idx;
379
380         /*
381          * duplicate new.
382          */
383         new_data = kstrdup(new, GFP_KERNEL);
384         if (!new_data)
385                 return ERR_PTR(-ENOMEM);
386
387         down_write(&_hash_lock);
388
389         /*
390          * Is new free ?
391          */
392         if (change_uuid)
393                 hc = __get_uuid_cell(new);
394         else
395                 hc = __get_name_cell(new);
396
397         if (hc) {
398                 DMWARN("Unable to change %s on mapped device %s to one that "
399                        "already exists: %s",
400                        change_uuid ? "uuid" : "name",
401                        param->name, new);
402                 dm_put(hc->md);
403                 up_write(&_hash_lock);
404                 kfree(new_data);
405                 return ERR_PTR(-EBUSY);
406         }
407
408         /*
409          * Is there such a device as 'old' ?
410          */
411         hc = __get_name_cell(param->name);
412         if (!hc) {
413                 DMWARN("Unable to rename non-existent device, %s to %s%s",
414                        param->name, change_uuid ? "uuid " : "", new);
415                 up_write(&_hash_lock);
416                 kfree(new_data);
417                 return ERR_PTR(-ENXIO);
418         }
419
420         /*
421          * Does this device already have a uuid?
422          */
423         if (change_uuid && hc->uuid) {
424                 DMWARN("Unable to change uuid of mapped device %s to %s "
425                        "because uuid is already set to %s",
426                        param->name, new, hc->uuid);
427                 dm_put(hc->md);
428                 up_write(&_hash_lock);
429                 kfree(new_data);
430                 return ERR_PTR(-EINVAL);
431         }
432
433         if (change_uuid)
434                 __set_cell_uuid(hc, new_data);
435         else
436                 old_name = __change_cell_name(hc, new_data);
437
438         /*
439          * Wake up any dm event waiters.
440          */
441         table = dm_get_live_table(hc->md, &srcu_idx);
442         if (table)
443                 dm_table_event(table);
444         dm_put_live_table(hc->md, srcu_idx);
445
446         if (!dm_kobject_uevent(hc->md, KOBJ_CHANGE, param->event_nr))
447                 param->flags |= DM_UEVENT_GENERATED_FLAG;
448
449         md = hc->md;
450         up_write(&_hash_lock);
451         kfree(old_name);
452
453         return md;
454 }
455
456 void dm_deferred_remove(void)
457 {
458         dm_hash_remove_all(true, false, true);
459 }
460
461 /*-----------------------------------------------------------------
462  * Implementation of the ioctl commands
463  *---------------------------------------------------------------*/
464 /*
465  * All the ioctl commands get dispatched to functions with this
466  * prototype.
467  */
468 typedef int (*ioctl_fn)(struct file *filp, struct dm_ioctl *param, size_t param_size);
469
470 static int remove_all(struct file *filp, struct dm_ioctl *param, size_t param_size)
471 {
472         dm_hash_remove_all(true, !!(param->flags & DM_DEFERRED_REMOVE), false);
473         param->data_size = 0;
474         return 0;
475 }
476
477 /*
478  * Round up the ptr to an 8-byte boundary.
479  */
480 #define ALIGN_MASK 7
481 static inline size_t align_val(size_t val)
482 {
483         return (val + ALIGN_MASK) & ~ALIGN_MASK;
484 }
485 static inline void *align_ptr(void *ptr)
486 {
487         return (void *)align_val((size_t)ptr);
488 }
489
490 /*
491  * Retrieves the data payload buffer from an already allocated
492  * struct dm_ioctl.
493  */
494 static void *get_result_buffer(struct dm_ioctl *param, size_t param_size,
495                                size_t *len)
496 {
497         param->data_start = align_ptr(param + 1) - (void *) param;
498
499         if (param->data_start < param_size)
500                 *len = param_size - param->data_start;
501         else
502                 *len = 0;
503
504         return ((void *) param) + param->data_start;
505 }
506
507 static int list_devices(struct file *filp, struct dm_ioctl *param, size_t param_size)
508 {
509         unsigned int i;
510         struct hash_cell *hc;
511         size_t len, needed = 0;
512         struct gendisk *disk;
513         struct dm_name_list *orig_nl, *nl, *old_nl = NULL;
514         uint32_t *event_nr;
515
516         down_write(&_hash_lock);
517
518         /*
519          * Loop through all the devices working out how much
520          * space we need.
521          */
522         for (i = 0; i < NUM_BUCKETS; i++) {
523                 list_for_each_entry (hc, _name_buckets + i, name_list) {
524                         needed += align_val(offsetof(struct dm_name_list, name) + strlen(hc->name) + 1);
525                         needed += align_val(sizeof(uint32_t));
526                 }
527         }
528
529         /*
530          * Grab our output buffer.
531          */
532         nl = orig_nl = get_result_buffer(param, param_size, &len);
533         if (len < needed || len < sizeof(nl->dev)) {
534                 param->flags |= DM_BUFFER_FULL_FLAG;
535                 goto out;
536         }
537         param->data_size = param->data_start + needed;
538
539         nl->dev = 0;    /* Flags no data */
540
541         /*
542          * Now loop through filling out the names.
543          */
544         for (i = 0; i < NUM_BUCKETS; i++) {
545                 list_for_each_entry (hc, _name_buckets + i, name_list) {
546                         if (old_nl)
547                                 old_nl->next = (uint32_t) ((void *) nl -
548                                                            (void *) old_nl);
549                         disk = dm_disk(hc->md);
550                         nl->dev = huge_encode_dev(disk_devt(disk));
551                         nl->next = 0;
552                         strcpy(nl->name, hc->name);
553
554                         old_nl = nl;
555                         event_nr = align_ptr(nl->name + strlen(hc->name) + 1);
556                         *event_nr = dm_get_event_nr(hc->md);
557                         nl = align_ptr(event_nr + 1);
558                 }
559         }
560         /*
561          * If mismatch happens, security may be compromised due to buffer
562          * overflow, so it's better to crash.
563          */
564         BUG_ON((char *)nl - (char *)orig_nl != needed);
565
566  out:
567         up_write(&_hash_lock);
568         return 0;
569 }
570
571 static void list_version_get_needed(struct target_type *tt, void *needed_param)
572 {
573     size_t *needed = needed_param;
574
575     *needed += sizeof(struct dm_target_versions);
576     *needed += strlen(tt->name) + 1;
577     *needed += ALIGN_MASK;
578 }
579
580 static void list_version_get_info(struct target_type *tt, void *param)
581 {
582     struct vers_iter *info = param;
583
584     /* Check space - it might have changed since the first iteration */
585     if ((char *)info->vers + sizeof(tt->version) + strlen(tt->name) + 1 >
586         info->end) {
587
588         info->flags = DM_BUFFER_FULL_FLAG;
589         return;
590     }
591
592     if (info->old_vers)
593         info->old_vers->next = (uint32_t) ((void *)info->vers -
594                                            (void *)info->old_vers);
595     info->vers->version[0] = tt->version[0];
596     info->vers->version[1] = tt->version[1];
597     info->vers->version[2] = tt->version[2];
598     info->vers->next = 0;
599     strcpy(info->vers->name, tt->name);
600
601     info->old_vers = info->vers;
602     info->vers = align_ptr(((void *) ++info->vers) + strlen(tt->name) + 1);
603 }
604
605 static int list_versions(struct file *filp, struct dm_ioctl *param, size_t param_size)
606 {
607         size_t len, needed = 0;
608         struct dm_target_versions *vers;
609         struct vers_iter iter_info;
610
611         /*
612          * Loop through all the devices working out how much
613          * space we need.
614          */
615         dm_target_iterate(list_version_get_needed, &needed);
616
617         /*
618          * Grab our output buffer.
619          */
620         vers = get_result_buffer(param, param_size, &len);
621         if (len < needed) {
622                 param->flags |= DM_BUFFER_FULL_FLAG;
623                 goto out;
624         }
625         param->data_size = param->data_start + needed;
626
627         iter_info.param_size = param_size;
628         iter_info.old_vers = NULL;
629         iter_info.vers = vers;
630         iter_info.flags = 0;
631         iter_info.end = (char *)vers + needed;
632
633         /*
634          * Now loop through filling out the names & versions.
635          */
636         dm_target_iterate(list_version_get_info, &iter_info);
637         param->flags |= iter_info.flags;
638
639  out:
640         return 0;
641 }
642
643 static int check_name(const char *name)
644 {
645         if (strchr(name, '/')) {
646                 DMWARN("invalid device name");
647                 return -EINVAL;
648         }
649
650         return 0;
651 }
652
653 /*
654  * On successful return, the caller must not attempt to acquire
655  * _hash_lock without first calling dm_put_live_table, because dm_table_destroy
656  * waits for this dm_put_live_table and could be called under this lock.
657  */
658 static struct dm_table *dm_get_inactive_table(struct mapped_device *md, int *srcu_idx)
659 {
660         struct hash_cell *hc;
661         struct dm_table *table = NULL;
662
663         /* increment rcu count, we don't care about the table pointer */
664         dm_get_live_table(md, srcu_idx);
665
666         down_read(&_hash_lock);
667         hc = dm_get_mdptr(md);
668         if (!hc || hc->md != md) {
669                 DMWARN("device has been removed from the dev hash table.");
670                 goto out;
671         }
672
673         table = hc->new_map;
674
675 out:
676         up_read(&_hash_lock);
677
678         return table;
679 }
680
681 static struct dm_table *dm_get_live_or_inactive_table(struct mapped_device *md,
682                                                       struct dm_ioctl *param,
683                                                       int *srcu_idx)
684 {
685         return (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) ?
686                 dm_get_inactive_table(md, srcu_idx) : dm_get_live_table(md, srcu_idx);
687 }
688
689 /*
690  * Fills in a dm_ioctl structure, ready for sending back to
691  * userland.
692  */
693 static void __dev_status(struct mapped_device *md, struct dm_ioctl *param)
694 {
695         struct gendisk *disk = dm_disk(md);
696         struct dm_table *table;
697         int srcu_idx;
698
699         param->flags &= ~(DM_SUSPEND_FLAG | DM_READONLY_FLAG |
700                           DM_ACTIVE_PRESENT_FLAG | DM_INTERNAL_SUSPEND_FLAG);
701
702         if (dm_suspended_md(md))
703                 param->flags |= DM_SUSPEND_FLAG;
704
705         if (dm_suspended_internally_md(md))
706                 param->flags |= DM_INTERNAL_SUSPEND_FLAG;
707
708         if (dm_test_deferred_remove_flag(md))
709                 param->flags |= DM_DEFERRED_REMOVE;
710
711         param->dev = huge_encode_dev(disk_devt(disk));
712
713         /*
714          * Yes, this will be out of date by the time it gets back
715          * to userland, but it is still very useful for
716          * debugging.
717          */
718         param->open_count = dm_open_count(md);
719
720         param->event_nr = dm_get_event_nr(md);
721         param->target_count = 0;
722
723         table = dm_get_live_table(md, &srcu_idx);
724         if (table) {
725                 if (!(param->flags & DM_QUERY_INACTIVE_TABLE_FLAG)) {
726                         if (get_disk_ro(disk))
727                                 param->flags |= DM_READONLY_FLAG;
728                         param->target_count = dm_table_get_num_targets(table);
729                 }
730
731                 param->flags |= DM_ACTIVE_PRESENT_FLAG;
732         }
733         dm_put_live_table(md, srcu_idx);
734
735         if (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) {
736                 int srcu_idx;
737                 table = dm_get_inactive_table(md, &srcu_idx);
738                 if (table) {
739                         if (!(dm_table_get_mode(table) & FMODE_WRITE))
740                                 param->flags |= DM_READONLY_FLAG;
741                         param->target_count = dm_table_get_num_targets(table);
742                 }
743                 dm_put_live_table(md, srcu_idx);
744         }
745 }
746
747 static int dev_create(struct file *filp, struct dm_ioctl *param, size_t param_size)
748 {
749         int r, m = DM_ANY_MINOR;
750         struct mapped_device *md;
751
752         r = check_name(param->name);
753         if (r)
754                 return r;
755
756         if (param->flags & DM_PERSISTENT_DEV_FLAG)
757                 m = MINOR(huge_decode_dev(param->dev));
758
759         r = dm_create(m, &md);
760         if (r)
761                 return r;
762
763         r = dm_hash_insert(param->name, *param->uuid ? param->uuid : NULL, md);
764         if (r) {
765                 dm_put(md);
766                 dm_destroy(md);
767                 return r;
768         }
769
770         param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
771
772         __dev_status(md, param);
773
774         dm_put(md);
775
776         return 0;
777 }
778
779 /*
780  * Always use UUID for lookups if it's present, otherwise use name or dev.
781  */
782 static struct hash_cell *__find_device_hash_cell(struct dm_ioctl *param)
783 {
784         struct hash_cell *hc = NULL;
785
786         if (*param->uuid) {
787                 if (*param->name || param->dev)
788                         return NULL;
789
790                 hc = __get_uuid_cell(param->uuid);
791                 if (!hc)
792                         return NULL;
793         } else if (*param->name) {
794                 if (param->dev)
795                         return NULL;
796
797                 hc = __get_name_cell(param->name);
798                 if (!hc)
799                         return NULL;
800         } else if (param->dev) {
801                 hc = __get_dev_cell(param->dev);
802                 if (!hc)
803                         return NULL;
804         } else
805                 return NULL;
806
807         /*
808          * Sneakily write in both the name and the uuid
809          * while we have the cell.
810          */
811         strlcpy(param->name, hc->name, sizeof(param->name));
812         if (hc->uuid)
813                 strlcpy(param->uuid, hc->uuid, sizeof(param->uuid));
814         else
815                 param->uuid[0] = '\0';
816
817         if (hc->new_map)
818                 param->flags |= DM_INACTIVE_PRESENT_FLAG;
819         else
820                 param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
821
822         return hc;
823 }
824
825 static struct mapped_device *find_device(struct dm_ioctl *param)
826 {
827         struct hash_cell *hc;
828         struct mapped_device *md = NULL;
829
830         down_read(&_hash_lock);
831         hc = __find_device_hash_cell(param);
832         if (hc)
833                 md = hc->md;
834         up_read(&_hash_lock);
835
836         return md;
837 }
838
839 static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_size)
840 {
841         struct hash_cell *hc;
842         struct mapped_device *md;
843         int r;
844         struct dm_table *t;
845
846         down_write(&_hash_lock);
847         hc = __find_device_hash_cell(param);
848
849         if (!hc) {
850                 DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
851                 up_write(&_hash_lock);
852                 return -ENXIO;
853         }
854
855         md = hc->md;
856
857         /*
858          * Ensure the device is not open and nothing further can open it.
859          */
860         r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false);
861         if (r) {
862                 if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
863                         up_write(&_hash_lock);
864                         dm_put(md);
865                         return 0;
866                 }
867                 DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
868                 up_write(&_hash_lock);
869                 dm_put(md);
870                 return r;
871         }
872
873         t = __hash_remove(hc);
874         up_write(&_hash_lock);
875
876         if (t) {
877                 dm_sync_table(md);
878                 dm_table_destroy(t);
879         }
880
881         param->flags &= ~DM_DEFERRED_REMOVE;
882
883         if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr))
884                 param->flags |= DM_UEVENT_GENERATED_FLAG;
885
886         dm_put(md);
887         dm_destroy(md);
888         return 0;
889 }
890
891 /*
892  * Check a string doesn't overrun the chunk of
893  * memory we copied from userland.
894  */
895 static int invalid_str(char *str, void *end)
896 {
897         while ((void *) str < end)
898                 if (!*str++)
899                         return 0;
900
901         return -EINVAL;
902 }
903
904 static int dev_rename(struct file *filp, struct dm_ioctl *param, size_t param_size)
905 {
906         int r;
907         char *new_data = (char *) param + param->data_start;
908         struct mapped_device *md;
909         unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0;
910
911         if (new_data < param->data ||
912             invalid_str(new_data, (void *) param + param_size) || !*new_data ||
913             strlen(new_data) > (change_uuid ? DM_UUID_LEN - 1 : DM_NAME_LEN - 1)) {
914                 DMWARN("Invalid new mapped device name or uuid string supplied.");
915                 return -EINVAL;
916         }
917
918         if (!change_uuid) {
919                 r = check_name(new_data);
920                 if (r)
921                         return r;
922         }
923
924         md = dm_hash_rename(param, new_data);
925         if (IS_ERR(md))
926                 return PTR_ERR(md);
927
928         __dev_status(md, param);
929         dm_put(md);
930
931         return 0;
932 }
933
934 static int dev_set_geometry(struct file *filp, struct dm_ioctl *param, size_t param_size)
935 {
936         int r = -EINVAL, x;
937         struct mapped_device *md;
938         struct hd_geometry geometry;
939         unsigned long indata[4];
940         char *geostr = (char *) param + param->data_start;
941         char dummy;
942
943         md = find_device(param);
944         if (!md)
945                 return -ENXIO;
946
947         if (geostr < param->data ||
948             invalid_str(geostr, (void *) param + param_size)) {
949                 DMWARN("Invalid geometry supplied.");
950                 goto out;
951         }
952
953         x = sscanf(geostr, "%lu %lu %lu %lu%c", indata,
954                    indata + 1, indata + 2, indata + 3, &dummy);
955
956         if (x != 4) {
957                 DMWARN("Unable to interpret geometry settings.");
958                 goto out;
959         }
960
961         if (indata[0] > 65535 || indata[1] > 255 ||
962             indata[2] > 255 || indata[3] > ULONG_MAX) {
963                 DMWARN("Geometry exceeds range limits.");
964                 goto out;
965         }
966
967         geometry.cylinders = indata[0];
968         geometry.heads = indata[1];
969         geometry.sectors = indata[2];
970         geometry.start = indata[3];
971
972         r = dm_set_geometry(md, &geometry);
973
974         param->data_size = 0;
975
976 out:
977         dm_put(md);
978         return r;
979 }
980
981 static int do_suspend(struct dm_ioctl *param)
982 {
983         int r = 0;
984         unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG;
985         struct mapped_device *md;
986
987         md = find_device(param);
988         if (!md)
989                 return -ENXIO;
990
991         if (param->flags & DM_SKIP_LOCKFS_FLAG)
992                 suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
993         if (param->flags & DM_NOFLUSH_FLAG)
994                 suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG;
995
996         if (!dm_suspended_md(md)) {
997                 r = dm_suspend(md, suspend_flags);
998                 if (r)
999                         goto out;
1000         }
1001
1002         __dev_status(md, param);
1003
1004 out:
1005         dm_put(md);
1006
1007         return r;
1008 }
1009
1010 static int do_resume(struct dm_ioctl *param)
1011 {
1012         int r = 0;
1013         unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG;
1014         struct hash_cell *hc;
1015         struct mapped_device *md;
1016         struct dm_table *new_map, *old_map = NULL;
1017
1018         down_write(&_hash_lock);
1019
1020         hc = __find_device_hash_cell(param);
1021         if (!hc) {
1022                 DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1023                 up_write(&_hash_lock);
1024                 return -ENXIO;
1025         }
1026
1027         md = hc->md;
1028
1029         new_map = hc->new_map;
1030         hc->new_map = NULL;
1031         param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
1032
1033         up_write(&_hash_lock);
1034
1035         /* Do we need to load a new map ? */
1036         if (new_map) {
1037                 /* Suspend if it isn't already suspended */
1038                 if (param->flags & DM_SKIP_LOCKFS_FLAG)
1039                         suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
1040                 if (param->flags & DM_NOFLUSH_FLAG)
1041                         suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG;
1042                 if (!dm_suspended_md(md))
1043                         dm_suspend(md, suspend_flags);
1044
1045                 old_map = dm_swap_table(md, new_map);
1046                 if (IS_ERR(old_map)) {
1047                         dm_sync_table(md);
1048                         dm_table_destroy(new_map);
1049                         dm_put(md);
1050                         return PTR_ERR(old_map);
1051                 }
1052
1053                 if (dm_table_get_mode(new_map) & FMODE_WRITE)
1054                         set_disk_ro(dm_disk(md), 0);
1055                 else
1056                         set_disk_ro(dm_disk(md), 1);
1057         }
1058
1059         if (dm_suspended_md(md)) {
1060                 r = dm_resume(md);
1061                 if (!r && !dm_kobject_uevent(md, KOBJ_CHANGE, param->event_nr))
1062                         param->flags |= DM_UEVENT_GENERATED_FLAG;
1063         }
1064
1065         /*
1066          * Since dm_swap_table synchronizes RCU, nobody should be in
1067          * read-side critical section already.
1068          */
1069         if (old_map)
1070                 dm_table_destroy(old_map);
1071
1072         if (!r)
1073                 __dev_status(md, param);
1074
1075         dm_put(md);
1076         return r;
1077 }
1078
1079 /*
1080  * Set or unset the suspension state of a device.
1081  * If the device already is in the requested state we just return its status.
1082  */
1083 static int dev_suspend(struct file *filp, struct dm_ioctl *param, size_t param_size)
1084 {
1085         if (param->flags & DM_SUSPEND_FLAG)
1086                 return do_suspend(param);
1087
1088         return do_resume(param);
1089 }
1090
1091 /*
1092  * Copies device info back to user space, used by
1093  * the create and info ioctls.
1094  */
1095 static int dev_status(struct file *filp, struct dm_ioctl *param, size_t param_size)
1096 {
1097         struct mapped_device *md;
1098
1099         md = find_device(param);
1100         if (!md)
1101                 return -ENXIO;
1102
1103         __dev_status(md, param);
1104         dm_put(md);
1105
1106         return 0;
1107 }
1108
1109 /*
1110  * Build up the status struct for each target
1111  */
1112 static void retrieve_status(struct dm_table *table,
1113                             struct dm_ioctl *param, size_t param_size)
1114 {
1115         unsigned int i, num_targets;
1116         struct dm_target_spec *spec;
1117         char *outbuf, *outptr;
1118         status_type_t type;
1119         size_t remaining, len, used = 0;
1120         unsigned status_flags = 0;
1121
1122         outptr = outbuf = get_result_buffer(param, param_size, &len);
1123
1124         if (param->flags & DM_STATUS_TABLE_FLAG)
1125                 type = STATUSTYPE_TABLE;
1126         else
1127                 type = STATUSTYPE_INFO;
1128
1129         /* Get all the target info */
1130         num_targets = dm_table_get_num_targets(table);
1131         for (i = 0; i < num_targets; i++) {
1132                 struct dm_target *ti = dm_table_get_target(table, i);
1133                 size_t l;
1134
1135                 remaining = len - (outptr - outbuf);
1136                 if (remaining <= sizeof(struct dm_target_spec)) {
1137                         param->flags |= DM_BUFFER_FULL_FLAG;
1138                         break;
1139                 }
1140
1141                 spec = (struct dm_target_spec *) outptr;
1142
1143                 spec->status = 0;
1144                 spec->sector_start = ti->begin;
1145                 spec->length = ti->len;
1146                 strncpy(spec->target_type, ti->type->name,
1147                         sizeof(spec->target_type));
1148
1149                 outptr += sizeof(struct dm_target_spec);
1150                 remaining = len - (outptr - outbuf);
1151                 if (remaining <= 0) {
1152                         param->flags |= DM_BUFFER_FULL_FLAG;
1153                         break;
1154                 }
1155
1156                 /* Get the status/table string from the target driver */
1157                 if (ti->type->status) {
1158                         if (param->flags & DM_NOFLUSH_FLAG)
1159                                 status_flags |= DM_STATUS_NOFLUSH_FLAG;
1160                         ti->type->status(ti, type, status_flags, outptr, remaining);
1161                 } else
1162                         outptr[0] = '\0';
1163
1164                 l = strlen(outptr) + 1;
1165                 if (l == remaining) {
1166                         param->flags |= DM_BUFFER_FULL_FLAG;
1167                         break;
1168                 }
1169
1170                 outptr += l;
1171                 used = param->data_start + (outptr - outbuf);
1172
1173                 outptr = align_ptr(outptr);
1174                 spec->next = outptr - outbuf;
1175         }
1176
1177         if (used)
1178                 param->data_size = used;
1179
1180         param->target_count = num_targets;
1181 }
1182
1183 /*
1184  * Wait for a device to report an event
1185  */
1186 static int dev_wait(struct file *filp, struct dm_ioctl *param, size_t param_size)
1187 {
1188         int r = 0;
1189         struct mapped_device *md;
1190         struct dm_table *table;
1191         int srcu_idx;
1192
1193         md = find_device(param);
1194         if (!md)
1195                 return -ENXIO;
1196
1197         /*
1198          * Wait for a notification event
1199          */
1200         if (dm_wait_event(md, param->event_nr)) {
1201                 r = -ERESTARTSYS;
1202                 goto out;
1203         }
1204
1205         /*
1206          * The userland program is going to want to know what
1207          * changed to trigger the event, so we may as well tell
1208          * him and save an ioctl.
1209          */
1210         __dev_status(md, param);
1211
1212         table = dm_get_live_or_inactive_table(md, param, &srcu_idx);
1213         if (table)
1214                 retrieve_status(table, param, param_size);
1215         dm_put_live_table(md, srcu_idx);
1216
1217 out:
1218         dm_put(md);
1219
1220         return r;
1221 }
1222
1223 /*
1224  * Remember the global event number and make it possible to poll
1225  * for further events.
1226  */
1227 static int dev_arm_poll(struct file *filp, struct dm_ioctl *param, size_t param_size)
1228 {
1229         struct dm_file *priv = filp->private_data;
1230
1231         priv->global_event_nr = atomic_read(&dm_global_event_nr);
1232
1233         return 0;
1234 }
1235
1236 static inline fmode_t get_mode(struct dm_ioctl *param)
1237 {
1238         fmode_t mode = FMODE_READ | FMODE_WRITE;
1239
1240         if (param->flags & DM_READONLY_FLAG)
1241                 mode = FMODE_READ;
1242
1243         return mode;
1244 }
1245
1246 static int next_target(struct dm_target_spec *last, uint32_t next, void *end,
1247                        struct dm_target_spec **spec, char **target_params)
1248 {
1249         *spec = (struct dm_target_spec *) ((unsigned char *) last + next);
1250         *target_params = (char *) (*spec + 1);
1251
1252         if (*spec < (last + 1))
1253                 return -EINVAL;
1254
1255         return invalid_str(*target_params, end);
1256 }
1257
1258 static int populate_table(struct dm_table *table,
1259                           struct dm_ioctl *param, size_t param_size)
1260 {
1261         int r;
1262         unsigned int i = 0;
1263         struct dm_target_spec *spec = (struct dm_target_spec *) param;
1264         uint32_t next = param->data_start;
1265         void *end = (void *) param + param_size;
1266         char *target_params;
1267
1268         if (!param->target_count) {
1269                 DMWARN("populate_table: no targets specified");
1270                 return -EINVAL;
1271         }
1272
1273         for (i = 0; i < param->target_count; i++) {
1274
1275                 r = next_target(spec, next, end, &spec, &target_params);
1276                 if (r) {
1277                         DMWARN("unable to find target");
1278                         return r;
1279                 }
1280
1281                 r = dm_table_add_target(table, spec->target_type,
1282                                         (sector_t) spec->sector_start,
1283                                         (sector_t) spec->length,
1284                                         target_params);
1285                 if (r) {
1286                         DMWARN("error adding target to table");
1287                         return r;
1288                 }
1289
1290                 next = spec->next;
1291         }
1292
1293         return dm_table_complete(table);
1294 }
1295
1296 static bool is_valid_type(enum dm_queue_mode cur, enum dm_queue_mode new)
1297 {
1298         if (cur == new ||
1299             (cur == DM_TYPE_BIO_BASED && new == DM_TYPE_DAX_BIO_BASED))
1300                 return true;
1301
1302         return false;
1303 }
1304
1305 static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
1306 {
1307         int r;
1308         struct hash_cell *hc;
1309         struct dm_table *t, *old_map = NULL;
1310         struct mapped_device *md;
1311         struct target_type *immutable_target_type;
1312
1313         md = find_device(param);
1314         if (!md)
1315                 return -ENXIO;
1316
1317         r = dm_table_create(&t, get_mode(param), param->target_count, md);
1318         if (r)
1319                 goto err;
1320
1321         /* Protect md->type and md->queue against concurrent table loads. */
1322         dm_lock_md_type(md);
1323         r = populate_table(t, param, param_size);
1324         if (r)
1325                 goto err_unlock_md_type;
1326
1327         immutable_target_type = dm_get_immutable_target_type(md);
1328         if (immutable_target_type &&
1329             (immutable_target_type != dm_table_get_immutable_target_type(t)) &&
1330             !dm_table_get_wildcard_target(t)) {
1331                 DMWARN("can't replace immutable target type %s",
1332                        immutable_target_type->name);
1333                 r = -EINVAL;
1334                 goto err_unlock_md_type;
1335         }
1336
1337         if (dm_get_md_type(md) == DM_TYPE_NONE) {
1338                 /* Initial table load: acquire type of table. */
1339                 dm_set_md_type(md, dm_table_get_type(t));
1340
1341                 /* setup md->queue to reflect md's type (may block) */
1342                 r = dm_setup_md_queue(md, t);
1343                 if (r) {
1344                         DMWARN("unable to set up device queue for new table.");
1345                         goto err_unlock_md_type;
1346                 }
1347         } else if (!is_valid_type(dm_get_md_type(md), dm_table_get_type(t))) {
1348                 DMWARN("can't change device type (old=%u vs new=%u) after initial table load.",
1349                        dm_get_md_type(md), dm_table_get_type(t));
1350                 r = -EINVAL;
1351                 goto err_unlock_md_type;
1352         }
1353
1354         dm_unlock_md_type(md);
1355
1356         /* stage inactive table */
1357         down_write(&_hash_lock);
1358         hc = dm_get_mdptr(md);
1359         if (!hc || hc->md != md) {
1360                 DMWARN("device has been removed from the dev hash table.");
1361                 up_write(&_hash_lock);
1362                 r = -ENXIO;
1363                 goto err_destroy_table;
1364         }
1365
1366         if (hc->new_map)
1367                 old_map = hc->new_map;
1368         hc->new_map = t;
1369         up_write(&_hash_lock);
1370
1371         param->flags |= DM_INACTIVE_PRESENT_FLAG;
1372         __dev_status(md, param);
1373
1374         if (old_map) {
1375                 dm_sync_table(md);
1376                 dm_table_destroy(old_map);
1377         }
1378
1379         dm_put(md);
1380
1381         return 0;
1382
1383 err_unlock_md_type:
1384         dm_unlock_md_type(md);
1385 err_destroy_table:
1386         dm_table_destroy(t);
1387 err:
1388         dm_put(md);
1389
1390         return r;
1391 }
1392
1393 static int table_clear(struct file *filp, struct dm_ioctl *param, size_t param_size)
1394 {
1395         struct hash_cell *hc;
1396         struct mapped_device *md;
1397         struct dm_table *old_map = NULL;
1398
1399         down_write(&_hash_lock);
1400
1401         hc = __find_device_hash_cell(param);
1402         if (!hc) {
1403                 DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1404                 up_write(&_hash_lock);
1405                 return -ENXIO;
1406         }
1407
1408         if (hc->new_map) {
1409                 old_map = hc->new_map;
1410                 hc->new_map = NULL;
1411         }
1412
1413         md = hc->md;
1414         up_write(&_hash_lock);
1415
1416         param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
1417         __dev_status(md, param);
1418
1419         if (old_map) {
1420                 dm_sync_table(md);
1421                 dm_table_destroy(old_map);
1422         }
1423         dm_put(md);
1424
1425         return 0;
1426 }
1427
1428 /*
1429  * Retrieves a list of devices used by a particular dm device.
1430  */
1431 static void retrieve_deps(struct dm_table *table,
1432                           struct dm_ioctl *param, size_t param_size)
1433 {
1434         unsigned int count = 0;
1435         struct list_head *tmp;
1436         size_t len, needed;
1437         struct dm_dev_internal *dd;
1438         struct dm_target_deps *deps;
1439
1440         deps = get_result_buffer(param, param_size, &len);
1441
1442         /*
1443          * Count the devices.
1444          */
1445         list_for_each (tmp, dm_table_get_devices(table))
1446                 count++;
1447
1448         /*
1449          * Check we have enough space.
1450          */
1451         needed = sizeof(*deps) + (sizeof(*deps->dev) * count);
1452         if (len < needed) {
1453                 param->flags |= DM_BUFFER_FULL_FLAG;
1454                 return;
1455         }
1456
1457         /*
1458          * Fill in the devices.
1459          */
1460         deps->count = count;
1461         count = 0;
1462         list_for_each_entry (dd, dm_table_get_devices(table), list)
1463                 deps->dev[count++] = huge_encode_dev(dd->dm_dev->bdev->bd_dev);
1464
1465         param->data_size = param->data_start + needed;
1466 }
1467
1468 static int table_deps(struct file *filp, struct dm_ioctl *param, size_t param_size)
1469 {
1470         struct mapped_device *md;
1471         struct dm_table *table;
1472         int srcu_idx;
1473
1474         md = find_device(param);
1475         if (!md)
1476                 return -ENXIO;
1477
1478         __dev_status(md, param);
1479
1480         table = dm_get_live_or_inactive_table(md, param, &srcu_idx);
1481         if (table)
1482                 retrieve_deps(table, param, param_size);
1483         dm_put_live_table(md, srcu_idx);
1484
1485         dm_put(md);
1486
1487         return 0;
1488 }
1489
1490 /*
1491  * Return the status of a device as a text string for each
1492  * target.
1493  */
1494 static int table_status(struct file *filp, struct dm_ioctl *param, size_t param_size)
1495 {
1496         struct mapped_device *md;
1497         struct dm_table *table;
1498         int srcu_idx;
1499
1500         md = find_device(param);
1501         if (!md)
1502                 return -ENXIO;
1503
1504         __dev_status(md, param);
1505
1506         table = dm_get_live_or_inactive_table(md, param, &srcu_idx);
1507         if (table)
1508                 retrieve_status(table, param, param_size);
1509         dm_put_live_table(md, srcu_idx);
1510
1511         dm_put(md);
1512
1513         return 0;
1514 }
1515
1516 /*
1517  * Process device-mapper dependent messages.  Messages prefixed with '@'
1518  * are processed by the DM core.  All others are delivered to the target.
1519  * Returns a number <= 1 if message was processed by device mapper.
1520  * Returns 2 if message should be delivered to the target.
1521  */
1522 static int message_for_md(struct mapped_device *md, unsigned argc, char **argv,
1523                           char *result, unsigned maxlen)
1524 {
1525         int r;
1526
1527         if (**argv != '@')
1528                 return 2; /* no '@' prefix, deliver to target */
1529
1530         if (!strcasecmp(argv[0], "@cancel_deferred_remove")) {
1531                 if (argc != 1) {
1532                         DMERR("Invalid arguments for @cancel_deferred_remove");
1533                         return -EINVAL;
1534                 }
1535                 return dm_cancel_deferred_remove(md);
1536         }
1537
1538         r = dm_stats_message(md, argc, argv, result, maxlen);
1539         if (r < 2)
1540                 return r;
1541
1542         DMERR("Unsupported message sent to DM core: %s", argv[0]);
1543         return -EINVAL;
1544 }
1545
1546 /*
1547  * Pass a message to the target that's at the supplied device offset.
1548  */
1549 static int target_message(struct file *filp, struct dm_ioctl *param, size_t param_size)
1550 {
1551         int r, argc;
1552         char **argv;
1553         struct mapped_device *md;
1554         struct dm_table *table;
1555         struct dm_target *ti;
1556         struct dm_target_msg *tmsg = (void *) param + param->data_start;
1557         size_t maxlen;
1558         char *result = get_result_buffer(param, param_size, &maxlen);
1559         int srcu_idx;
1560
1561         md = find_device(param);
1562         if (!md)
1563                 return -ENXIO;
1564
1565         if (tmsg < (struct dm_target_msg *) param->data ||
1566             invalid_str(tmsg->message, (void *) param + param_size)) {
1567                 DMWARN("Invalid target message parameters.");
1568                 r = -EINVAL;
1569                 goto out;
1570         }
1571
1572         r = dm_split_args(&argc, &argv, tmsg->message);
1573         if (r) {
1574                 DMWARN("Failed to split target message parameters");
1575                 goto out;
1576         }
1577
1578         if (!argc) {
1579                 DMWARN("Empty message received.");
1580                 r = -EINVAL;
1581                 goto out_argv;
1582         }
1583
1584         r = message_for_md(md, argc, argv, result, maxlen);
1585         if (r <= 1)
1586                 goto out_argv;
1587
1588         table = dm_get_live_table(md, &srcu_idx);
1589         if (!table)
1590                 goto out_table;
1591
1592         if (dm_deleting_md(md)) {
1593                 r = -ENXIO;
1594                 goto out_table;
1595         }
1596
1597         ti = dm_table_find_target(table, tmsg->sector);
1598         if (!dm_target_is_valid(ti)) {
1599                 DMWARN("Target message sector outside device.");
1600                 r = -EINVAL;
1601         } else if (ti->type->message)
1602                 r = ti->type->message(ti, argc, argv, result, maxlen);
1603         else {
1604                 DMWARN("Target type does not support messages");
1605                 r = -EINVAL;
1606         }
1607
1608  out_table:
1609         dm_put_live_table(md, srcu_idx);
1610  out_argv:
1611         kfree(argv);
1612  out:
1613         if (r >= 0)
1614                 __dev_status(md, param);
1615
1616         if (r == 1) {
1617                 param->flags |= DM_DATA_OUT_FLAG;
1618                 if (dm_message_test_buffer_overflow(result, maxlen))
1619                         param->flags |= DM_BUFFER_FULL_FLAG;
1620                 else
1621                         param->data_size = param->data_start + strlen(result) + 1;
1622                 r = 0;
1623         }
1624
1625         dm_put(md);
1626         return r;
1627 }
1628
1629 /*
1630  * The ioctl parameter block consists of two parts, a dm_ioctl struct
1631  * followed by a data buffer.  This flag is set if the second part,
1632  * which has a variable size, is not used by the function processing
1633  * the ioctl.
1634  */
1635 #define IOCTL_FLAGS_NO_PARAMS           1
1636 #define IOCTL_FLAGS_ISSUE_GLOBAL_EVENT  2
1637
1638 /*-----------------------------------------------------------------
1639  * Implementation of open/close/ioctl on the special char
1640  * device.
1641  *---------------------------------------------------------------*/
1642 static ioctl_fn lookup_ioctl(unsigned int cmd, int *ioctl_flags)
1643 {
1644         static const struct {
1645                 int cmd;
1646                 int flags;
1647                 ioctl_fn fn;
1648         } _ioctls[] = {
1649                 {DM_VERSION_CMD, 0, NULL}, /* version is dealt with elsewhere */
1650                 {DM_REMOVE_ALL_CMD, IOCTL_FLAGS_NO_PARAMS | IOCTL_FLAGS_ISSUE_GLOBAL_EVENT, remove_all},
1651                 {DM_LIST_DEVICES_CMD, 0, list_devices},
1652
1653                 {DM_DEV_CREATE_CMD, IOCTL_FLAGS_NO_PARAMS | IOCTL_FLAGS_ISSUE_GLOBAL_EVENT, dev_create},
1654                 {DM_DEV_REMOVE_CMD, IOCTL_FLAGS_NO_PARAMS | IOCTL_FLAGS_ISSUE_GLOBAL_EVENT, dev_remove},
1655                 {DM_DEV_RENAME_CMD, IOCTL_FLAGS_ISSUE_GLOBAL_EVENT, dev_rename},
1656                 {DM_DEV_SUSPEND_CMD, IOCTL_FLAGS_NO_PARAMS, dev_suspend},
1657                 {DM_DEV_STATUS_CMD, IOCTL_FLAGS_NO_PARAMS, dev_status},
1658                 {DM_DEV_WAIT_CMD, 0, dev_wait},
1659
1660                 {DM_TABLE_LOAD_CMD, 0, table_load},
1661                 {DM_TABLE_CLEAR_CMD, IOCTL_FLAGS_NO_PARAMS, table_clear},
1662                 {DM_TABLE_DEPS_CMD, 0, table_deps},
1663                 {DM_TABLE_STATUS_CMD, 0, table_status},
1664
1665                 {DM_LIST_VERSIONS_CMD, 0, list_versions},
1666
1667                 {DM_TARGET_MSG_CMD, 0, target_message},
1668                 {DM_DEV_SET_GEOMETRY_CMD, 0, dev_set_geometry},
1669                 {DM_DEV_ARM_POLL, IOCTL_FLAGS_NO_PARAMS, dev_arm_poll},
1670         };
1671
1672         if (unlikely(cmd >= ARRAY_SIZE(_ioctls)))
1673                 return NULL;
1674
1675         cmd = array_index_nospec(cmd, ARRAY_SIZE(_ioctls));
1676         *ioctl_flags = _ioctls[cmd].flags;
1677         return _ioctls[cmd].fn;
1678 }
1679
1680 /*
1681  * As well as checking the version compatibility this always
1682  * copies the kernel interface version out.
1683  */
1684 static int check_version(unsigned int cmd, struct dm_ioctl __user *user)
1685 {
1686         uint32_t version[3];
1687         int r = 0;
1688
1689         if (copy_from_user(version, user->version, sizeof(version)))
1690                 return -EFAULT;
1691
1692         if ((DM_VERSION_MAJOR != version[0]) ||
1693             (DM_VERSION_MINOR < version[1])) {
1694                 DMWARN("ioctl interface mismatch: "
1695                        "kernel(%u.%u.%u), user(%u.%u.%u), cmd(%d)",
1696                        DM_VERSION_MAJOR, DM_VERSION_MINOR,
1697                        DM_VERSION_PATCHLEVEL,
1698                        version[0], version[1], version[2], cmd);
1699                 r = -EINVAL;
1700         }
1701
1702         /*
1703          * Fill in the kernel version.
1704          */
1705         version[0] = DM_VERSION_MAJOR;
1706         version[1] = DM_VERSION_MINOR;
1707         version[2] = DM_VERSION_PATCHLEVEL;
1708         if (copy_to_user(user->version, version, sizeof(version)))
1709                 return -EFAULT;
1710
1711         return r;
1712 }
1713
1714 #define DM_PARAMS_MALLOC        0x0001  /* Params allocated with kvmalloc() */
1715 #define DM_WIPE_BUFFER          0x0010  /* Wipe input buffer before returning from ioctl */
1716
1717 static void free_params(struct dm_ioctl *param, size_t param_size, int param_flags)
1718 {
1719         if (param_flags & DM_WIPE_BUFFER)
1720                 memset(param, 0, param_size);
1721
1722         if (param_flags & DM_PARAMS_MALLOC)
1723                 kvfree(param);
1724 }
1725
1726 static int copy_params(struct dm_ioctl __user *user, struct dm_ioctl *param_kernel,
1727                        int ioctl_flags, struct dm_ioctl **param, int *param_flags)
1728 {
1729         struct dm_ioctl *dmi;
1730         int secure_data;
1731         const size_t minimum_data_size = offsetof(struct dm_ioctl, data);
1732         unsigned noio_flag;
1733
1734         if (copy_from_user(param_kernel, user, minimum_data_size))
1735                 return -EFAULT;
1736
1737         if (param_kernel->data_size < minimum_data_size)
1738                 return -EINVAL;
1739
1740         secure_data = param_kernel->flags & DM_SECURE_DATA_FLAG;
1741
1742         *param_flags = secure_data ? DM_WIPE_BUFFER : 0;
1743
1744         if (ioctl_flags & IOCTL_FLAGS_NO_PARAMS) {
1745                 dmi = param_kernel;
1746                 dmi->data_size = minimum_data_size;
1747                 goto data_copied;
1748         }
1749
1750         /*
1751          * Use __GFP_HIGH to avoid low memory issues when a device is
1752          * suspended and the ioctl is needed to resume it.
1753          * Use kmalloc() rather than vmalloc() when we can.
1754          */
1755         dmi = NULL;
1756         noio_flag = memalloc_noio_save();
1757         dmi = kvmalloc(param_kernel->data_size, GFP_KERNEL | __GFP_HIGH);
1758         memalloc_noio_restore(noio_flag);
1759
1760         if (!dmi) {
1761                 if (secure_data && clear_user(user, param_kernel->data_size))
1762                         return -EFAULT;
1763                 return -ENOMEM;
1764         }
1765
1766         *param_flags |= DM_PARAMS_MALLOC;
1767
1768         /* Copy from param_kernel (which was already copied from user) */
1769         memcpy(dmi, param_kernel, minimum_data_size);
1770
1771         if (copy_from_user(&dmi->data, (char __user *)user + minimum_data_size,
1772                            param_kernel->data_size - minimum_data_size))
1773                 goto bad;
1774 data_copied:
1775         /* Wipe the user buffer so we do not return it to userspace */
1776         if (secure_data && clear_user(user, param_kernel->data_size))
1777                 goto bad;
1778
1779         *param = dmi;
1780         return 0;
1781
1782 bad:
1783         free_params(dmi, param_kernel->data_size, *param_flags);
1784
1785         return -EFAULT;
1786 }
1787
1788 static int validate_params(uint cmd, struct dm_ioctl *param)
1789 {
1790         /* Always clear this flag */
1791         param->flags &= ~DM_BUFFER_FULL_FLAG;
1792         param->flags &= ~DM_UEVENT_GENERATED_FLAG;
1793         param->flags &= ~DM_SECURE_DATA_FLAG;
1794         param->flags &= ~DM_DATA_OUT_FLAG;
1795
1796         /* Ignores parameters */
1797         if (cmd == DM_REMOVE_ALL_CMD ||
1798             cmd == DM_LIST_DEVICES_CMD ||
1799             cmd == DM_LIST_VERSIONS_CMD)
1800                 return 0;
1801
1802         if (cmd == DM_DEV_CREATE_CMD) {
1803                 if (!*param->name) {
1804                         DMWARN("name not supplied when creating device");
1805                         return -EINVAL;
1806                 }
1807         } else if (*param->uuid && *param->name) {
1808                 DMWARN("only supply one of name or uuid, cmd(%u)", cmd);
1809                 return -EINVAL;
1810         }
1811
1812         /* Ensure strings are terminated */
1813         param->name[DM_NAME_LEN - 1] = '\0';
1814         param->uuid[DM_UUID_LEN - 1] = '\0';
1815
1816         return 0;
1817 }
1818
1819 static int ctl_ioctl(struct file *file, uint command, struct dm_ioctl __user *user)
1820 {
1821         int r = 0;
1822         int ioctl_flags;
1823         int param_flags;
1824         unsigned int cmd;
1825         struct dm_ioctl *param;
1826         ioctl_fn fn = NULL;
1827         size_t input_param_size;
1828         struct dm_ioctl param_kernel;
1829
1830         /* only root can play with this */
1831         if (!capable(CAP_SYS_ADMIN))
1832                 return -EACCES;
1833
1834         if (_IOC_TYPE(command) != DM_IOCTL)
1835                 return -ENOTTY;
1836
1837         cmd = _IOC_NR(command);
1838
1839         /*
1840          * Check the interface version passed in.  This also
1841          * writes out the kernel's interface version.
1842          */
1843         r = check_version(cmd, user);
1844         if (r)
1845                 return r;
1846
1847         /*
1848          * Nothing more to do for the version command.
1849          */
1850         if (cmd == DM_VERSION_CMD)
1851                 return 0;
1852
1853         fn = lookup_ioctl(cmd, &ioctl_flags);
1854         if (!fn) {
1855                 DMWARN("dm_ctl_ioctl: unknown command 0x%x", command);
1856                 return -ENOTTY;
1857         }
1858
1859         /*
1860          * Copy the parameters into kernel space.
1861          */
1862         r = copy_params(user, &param_kernel, ioctl_flags, &param, &param_flags);
1863
1864         if (r)
1865                 return r;
1866
1867         input_param_size = param->data_size;
1868         r = validate_params(cmd, param);
1869         if (r)
1870                 goto out;
1871
1872         param->data_size = offsetof(struct dm_ioctl, data);
1873         r = fn(file, param, input_param_size);
1874
1875         if (unlikely(param->flags & DM_BUFFER_FULL_FLAG) &&
1876             unlikely(ioctl_flags & IOCTL_FLAGS_NO_PARAMS))
1877                 DMERR("ioctl %d tried to output some data but has IOCTL_FLAGS_NO_PARAMS set", cmd);
1878
1879         if (!r && ioctl_flags & IOCTL_FLAGS_ISSUE_GLOBAL_EVENT)
1880                 dm_issue_global_event();
1881
1882         /*
1883          * Copy the results back to userland.
1884          */
1885         if (!r && copy_to_user(user, param, param->data_size))
1886                 r = -EFAULT;
1887
1888 out:
1889         free_params(param, input_param_size, param_flags);
1890         return r;
1891 }
1892
1893 static long dm_ctl_ioctl(struct file *file, uint command, ulong u)
1894 {
1895         return (long)ctl_ioctl(file, command, (struct dm_ioctl __user *)u);
1896 }
1897
1898 #ifdef CONFIG_COMPAT
1899 static long dm_compat_ctl_ioctl(struct file *file, uint command, ulong u)
1900 {
1901         return (long)dm_ctl_ioctl(file, command, (ulong) compat_ptr(u));
1902 }
1903 #else
1904 #define dm_compat_ctl_ioctl NULL
1905 #endif
1906
1907 static int dm_open(struct inode *inode, struct file *filp)
1908 {
1909         int r;
1910         struct dm_file *priv;
1911
1912         r = nonseekable_open(inode, filp);
1913         if (unlikely(r))
1914                 return r;
1915
1916         priv = filp->private_data = kmalloc(sizeof(struct dm_file), GFP_KERNEL);
1917         if (!priv)
1918                 return -ENOMEM;
1919
1920         priv->global_event_nr = atomic_read(&dm_global_event_nr);
1921
1922         return 0;
1923 }
1924
1925 static int dm_release(struct inode *inode, struct file *filp)
1926 {
1927         kfree(filp->private_data);
1928         return 0;
1929 }
1930
1931 static __poll_t dm_poll(struct file *filp, poll_table *wait)
1932 {
1933         struct dm_file *priv = filp->private_data;
1934         __poll_t mask = 0;
1935
1936         poll_wait(filp, &dm_global_eventq, wait);
1937
1938         if ((int)(atomic_read(&dm_global_event_nr) - priv->global_event_nr) > 0)
1939                 mask |= EPOLLIN;
1940
1941         return mask;
1942 }
1943
1944 static const struct file_operations _ctl_fops = {
1945         .open    = dm_open,
1946         .release = dm_release,
1947         .poll    = dm_poll,
1948         .unlocked_ioctl  = dm_ctl_ioctl,
1949         .compat_ioctl = dm_compat_ctl_ioctl,
1950         .owner   = THIS_MODULE,
1951         .llseek  = noop_llseek,
1952 };
1953
1954 static struct miscdevice _dm_misc = {
1955         .minor          = MAPPER_CTRL_MINOR,
1956         .name           = DM_NAME,
1957         .nodename       = DM_DIR "/" DM_CONTROL_NODE,
1958         .fops           = &_ctl_fops
1959 };
1960
1961 MODULE_ALIAS_MISCDEV(MAPPER_CTRL_MINOR);
1962 MODULE_ALIAS("devname:" DM_DIR "/" DM_CONTROL_NODE);
1963
1964 /*
1965  * Create misc character device and link to DM_DIR/control.
1966  */
1967 int __init dm_interface_init(void)
1968 {
1969         int r;
1970
1971         r = dm_hash_init();
1972         if (r)
1973                 return r;
1974
1975         r = misc_register(&_dm_misc);
1976         if (r) {
1977                 DMERR("misc_register failed for control device");
1978                 dm_hash_exit();
1979                 return r;
1980         }
1981
1982         DMINFO("%d.%d.%d%s initialised: %s", DM_VERSION_MAJOR,
1983                DM_VERSION_MINOR, DM_VERSION_PATCHLEVEL, DM_VERSION_EXTRA,
1984                DM_DRIVER_EMAIL);
1985         return 0;
1986 }
1987
1988 void dm_interface_exit(void)
1989 {
1990         misc_deregister(&_dm_misc);
1991         dm_hash_exit();
1992 }
1993
1994 /**
1995  * dm_copy_name_and_uuid - Copy mapped device name & uuid into supplied buffers
1996  * @md: Pointer to mapped_device
1997  * @name: Buffer (size DM_NAME_LEN) for name
1998  * @uuid: Buffer (size DM_UUID_LEN) for uuid or empty string if uuid not defined
1999  */
2000 int dm_copy_name_and_uuid(struct mapped_device *md, char *name, char *uuid)
2001 {
2002         int r = 0;
2003         struct hash_cell *hc;
2004
2005         if (!md)
2006                 return -ENXIO;
2007
2008         mutex_lock(&dm_hash_cells_mutex);
2009         hc = dm_get_mdptr(md);
2010         if (!hc || hc->md != md) {
2011                 r = -ENXIO;
2012                 goto out;
2013         }
2014
2015         if (name)
2016                 strcpy(name, hc->name);
2017         if (uuid)
2018                 strcpy(uuid, hc->uuid ? : "");
2019
2020 out:
2021         mutex_unlock(&dm_hash_cells_mutex);
2022
2023         return r;
2024 }