Coverage Report

Created: 2026-10-16 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lvm2/libdm/libdevmapper.h
Line
Count
Source
1
/*
2
 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3
 * Copyright (C) 2004-2026 Red Hat, Inc. All rights reserved.
4
 * Copyright (C) 2006 Rackable Systems All rights reserved.
5
 *
6
 * This file is part of the device-mapper userspace tools.
7
 *
8
 * This copyrighted material is made available to anyone wishing to use,
9
 * modify, copy, or redistribute it subject to the terms and conditions
10
 * of the GNU Lesser General Public License v.2.1.
11
 *
12
 * You should have received a copy of the GNU Lesser General Public License
13
 * along with this program; if not, write to the Free Software Foundation,
14
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
15
 */
16
17
#ifndef LIB_DEVICE_MAPPER_H
18
#define LIB_DEVICE_MAPPER_H
19
20
#include <inttypes.h>
21
#include <stdarg.h>
22
#include <sys/types.h>
23
#include <sys/stat.h>
24
25
#ifdef __linux__
26
#  include <linux/types.h>
27
#endif
28
29
#include <limits.h>
30
#include <string.h>
31
#include <stdlib.h>
32
#include <stdio.h>
33
#include <stddef.h> /* offsetof */
34
35
#ifndef __GNUC__
36
# define __typeof__ typeof
37
#endif
38
39
/* Macros to make string defines */
40
#define DM_TO_STRING_EXP(A) #A
41
#define DM_TO_STRING(A) DM_TO_STRING_EXP(A)
42
43
0
#define DM_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
44
45
#ifdef __cplusplus
46
extern "C" {
47
#endif
48
49
/*****************************************************************
50
 * The first section of this file provides direct access to the
51
 * individual device-mapper ioctls.  Since it is quite laborious to
52
 * build the ioctl arguments for the device-mapper, people are
53
 * encouraged to use this library.
54
 ****************************************************************/
55
56
/*
57
 * The library user may wish to register their own
58
 * logging function.  By default errors go to stderr.
59
 * Use dm_log_with_errno_init(NULL) to restore the default log fn.
60
 * Error messages may have a non-zero errno.
61
 * Debug messages may have a non-zero class.
62
 * Aborts on internal error when env DM_ABORT_ON_INTERNAL_ERRORS is 1
63
 */
64
65
typedef void (*dm_log_with_errno_fn) (int level, const char *file, int line,
66
              int dm_errno_or_class, const char *f, ...)
67
    __attribute__ ((format(printf, 5, 6)));
68
69
void dm_log_with_errno_init(dm_log_with_errno_fn fn);
70
void dm_log_init_verbose(int level);
71
72
/*
73
 * Original version of this function.
74
 * dm_errno is set to 0.
75
 *
76
 * Deprecated: Use the _with_errno_ versions above instead.
77
 */
78
typedef void (*dm_log_fn) (int level, const char *file, int line,
79
         const char *f, ...)
80
    __attribute__ ((format(printf, 4, 5)));
81
82
void dm_log_init(dm_log_fn fn);
83
/*
84
 * For backward-compatibility, indicate that dm_log_init() was used
85
 * to set a non-default value of dm_log().
86
 */
87
int dm_log_is_non_default(void);
88
89
/*
90
 * Number of devices currently in suspended state (via the library).
91
 */
92
int dm_get_suspended_counter(void);
93
94
enum {
95
  DM_DEVICE_CREATE,
96
  DM_DEVICE_RELOAD,
97
  DM_DEVICE_REMOVE,
98
  DM_DEVICE_REMOVE_ALL,
99
100
  DM_DEVICE_SUSPEND,
101
  DM_DEVICE_RESUME,
102
103
  DM_DEVICE_INFO,
104
  DM_DEVICE_DEPS,
105
  DM_DEVICE_RENAME,
106
107
  DM_DEVICE_VERSION,
108
109
  DM_DEVICE_STATUS,
110
  DM_DEVICE_TABLE,
111
  DM_DEVICE_WAITEVENT,
112
113
  DM_DEVICE_LIST,
114
115
  DM_DEVICE_CLEAR,
116
117
  DM_DEVICE_MKNODES,
118
119
  DM_DEVICE_LIST_VERSIONS,
120
121
  DM_DEVICE_TARGET_MSG,
122
123
  DM_DEVICE_SET_GEOMETRY,
124
125
  DM_DEVICE_ARM_POLL,
126
127
  DM_DEVICE_GET_TARGET_VERSION
128
};
129
130
/*
131
 * You will need to build a struct dm_task for
132
 * each ioctl command you want to execute.
133
 */
134
135
struct dm_pool;
136
struct dm_task;
137
struct dm_timestamp;
138
139
struct dm_task *dm_task_create(int type);
140
void dm_task_destroy(struct dm_task *dmt);
141
142
int dm_task_set_name(struct dm_task *dmt, const char *name);
143
int dm_task_set_uuid(struct dm_task *dmt, const char *uuid);
144
145
/*
146
 * Retrieve attributes after an info.
147
 */
148
struct dm_info {
149
  int exists;
150
  int suspended;
151
  int live_table;
152
  int inactive_table;
153
  int32_t open_count;
154
  uint32_t event_nr;
155
  uint32_t major;
156
  uint32_t minor;   /* minor device number */
157
  int read_only;    /* 0:read-write; 1:read-only */
158
159
  int32_t target_count;
160
161
  int deferred_remove;
162
  int internal_suspend;
163
};
164
165
struct dm_deps {
166
  uint32_t count;
167
  uint32_t filler;
168
  uint64_t device[];
169
};
170
171
struct dm_names {
172
  uint64_t dev;
173
  uint32_t next;    /* Offset to next struct from start of this struct */
174
  char name[];
175
};
176
177
struct dm_versions {
178
  uint32_t next;    /* Offset to next struct from start of this struct */
179
  uint32_t version[3];
180
181
  char name[];
182
};
183
184
int dm_get_library_version(char *version, size_t size);
185
int dm_task_get_driver_version(struct dm_task *dmt, char *version, size_t size);
186
int dm_task_get_info(struct dm_task *dmt, struct dm_info *info);
187
188
/*
189
 * This function returns dm device's UUID based on the value
190
 * of the mangling mode set during preceding dm_task_run call:
191
 *   - unmangled UUID for DM_STRING_MANGLING_{AUTO, HEX},
192
 *   - UUID without any changes for DM_STRING_MANGLING_NONE.
193
 *
194
 * To get mangled or unmangled form of the UUID directly, use
195
 * dm_task_get_uuid_mangled or dm_task_get_uuid_unmangled function.
196
 */
197
const char *dm_task_get_uuid(const struct dm_task *dmt);
198
199
struct dm_deps *dm_task_get_deps(struct dm_task *dmt);
200
struct dm_versions *dm_task_get_versions(struct dm_task *dmt);
201
const char *dm_task_get_message_response(struct dm_task *dmt);
202
203
/*
204
 * These functions return device-mapper names based on the value
205
 * of the mangling mode set during preceding dm_task_run call:
206
 *   - unmangled name for DM_STRING_MANGLING_{AUTO, HEX},
207
 *   - name without any changes for DM_STRING_MANGLING_NONE.
208
 *
209
 * To get mangled or unmangled form of the name directly, use
210
 * dm_task_get_name_mangled or dm_task_get_name_unmangled function.
211
 */
212
const char *dm_task_get_name(const struct dm_task *dmt);
213
struct dm_names *dm_task_get_names(struct dm_task *dmt);
214
215
int dm_task_set_ro(struct dm_task *dmt);
216
int dm_task_set_newname(struct dm_task *dmt, const char *newname);
217
int dm_task_set_newuuid(struct dm_task *dmt, const char *newuuid);
218
int dm_task_set_minor(struct dm_task *dmt, int minor);
219
int dm_task_set_major(struct dm_task *dmt, int major);
220
int dm_task_set_major_minor(struct dm_task *dmt, int major, int minor, int allow_default_major_fallback);
221
int dm_task_set_uid(struct dm_task *dmt, uid_t uid);
222
int dm_task_set_gid(struct dm_task *dmt, gid_t gid);
223
int dm_task_set_mode(struct dm_task *dmt, mode_t mode);
224
/* See also description for DM_UDEV_DISABLE_LIBRARY_FALLBACK flag! */
225
int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags);
226
int dm_task_set_event_nr(struct dm_task *dmt, uint32_t event_nr);
227
int dm_task_set_geometry(struct dm_task *dmt, const char *cylinders, const char *heads, const char *sectors, const char *start);
228
int dm_task_set_message(struct dm_task *dmt, const char *message);
229
int dm_task_set_sector(struct dm_task *dmt, uint64_t sector);
230
int dm_task_no_flush(struct dm_task *dmt);
231
int dm_task_no_open_count(struct dm_task *dmt);
232
int dm_task_skip_lockfs(struct dm_task *dmt);
233
int dm_task_query_inactive_table(struct dm_task *dmt);
234
int dm_task_suppress_identical_reload(struct dm_task *dmt);
235
int dm_task_secure_data(struct dm_task *dmt);
236
int dm_task_retry_remove(struct dm_task *dmt);
237
int dm_task_deferred_remove(struct dm_task *dmt);
238
int dm_task_ima_measurement(struct dm_task *dmt);
239
240
/*
241
 * Record timestamp immediately after the ioctl returns.
242
 */
243
int dm_task_set_record_timestamp(struct dm_task *dmt);
244
struct dm_timestamp *dm_task_get_ioctl_timestamp(struct dm_task *dmt);
245
246
/*
247
 * Enable checks for common mistakes such as issuing ioctls in an unsafe order.
248
 */
249
int dm_task_enable_checks(struct dm_task *dmt);
250
251
typedef enum dm_add_node_e {
252
  DM_ADD_NODE_ON_RESUME, /* add /dev/mapper node with dmsetup resume */
253
  DM_ADD_NODE_ON_CREATE  /* add /dev/mapper node with dmsetup create */
254
} dm_add_node_t;
255
int dm_task_set_add_node(struct dm_task *dmt, dm_add_node_t add_node);
256
257
/*
258
 * Control read_ahead.
259
 */
260
0
#define DM_READ_AHEAD_AUTO UINT32_MAX  /* Use kernel default readahead */
261
0
#define DM_READ_AHEAD_NONE 0    /* Disable readahead */
262
263
0
#define DM_READ_AHEAD_MINIMUM_FLAG  0x1  /* Value supplied is minimum */
264
265
/*
266
 * Read ahead is set with DM_DEVICE_CREATE with a table or DM_DEVICE_RESUME.
267
 */
268
int dm_task_set_read_ahead(struct dm_task *dmt, uint32_t read_ahead,
269
         uint32_t read_ahead_flags);
270
uint32_t dm_task_get_read_ahead(const struct dm_task *dmt,
271
        uint32_t *read_ahead);
272
273
/*
274
 * Use these to prepare for a create or reload.
275
 */
276
int dm_task_add_target(struct dm_task *dmt,
277
           uint64_t start,
278
           uint64_t size, const char *ttype, const char *params);
279
280
/*
281
 * Format major/minor numbers correctly for input to driver.
282
 */
283
#define DM_FORMAT_DEV_BUFSIZE 13  /* Minimum bufsize to handle worst case. */
284
int dm_format_dev(char *buf, int bufsize, uint32_t dev_major, uint32_t dev_minor);
285
286
/* Use this to retrieve target information returned from a STATUS call */
287
void *dm_get_next_target(struct dm_task *dmt,
288
       void *next, uint64_t *start, uint64_t *length,
289
       char **target_type, char **params);
290
291
/*
292
 * Following dm_get_status_* functions will allocate appropriate status structure
293
 * from passed mempool together with the necessary character arrays.
294
 * Destroying the mempool will release all associated allocation.
295
 */
296
297
/* Parse params from STATUS call for mirror target */
298
typedef enum dm_status_mirror_health_e {
299
  DM_STATUS_MIRROR_ALIVE        = 'A',/* No failures */
300
  DM_STATUS_MIRROR_FLUSH_FAILED = 'F',/* Mirror out-of-sync */
301
  DM_STATUS_MIRROR_WRITE_FAILED = 'D',/* Mirror out-of-sync */
302
  DM_STATUS_MIRROR_SYNC_FAILED  = 'S',/* Mirror out-of-sync */
303
  DM_STATUS_MIRROR_READ_FAILED  = 'R',/* Mirror data unaffected */
304
  DM_STATUS_MIRROR_UNCLASSIFIED = 'U' /* Bug */
305
} dm_status_mirror_health_t;
306
307
struct dm_status_mirror {
308
  uint64_t total_regions;
309
  uint64_t insync_regions;
310
  uint32_t dev_count;             /* # of devs[] elements (<= 8) */
311
  struct dm_dev_leg_health_s {
312
    dm_status_mirror_health_t health;
313
    uint32_t major;
314
    uint32_t minor;
315
  } *devs;                        /* array with individual legs */
316
  const char *log_type;           /* core, disk,.... */
317
  uint32_t log_count;   /* # of logs[] elements */
318
  struct dm_dev_log_health_s {
319
    dm_status_mirror_health_t health;
320
    uint32_t major;
321
    uint32_t minor;
322
  } *logs;      /* array with individual logs */
323
};
324
325
int dm_get_status_mirror(struct dm_pool *mem, const char *params,
326
       struct dm_status_mirror **status);
327
328
/*
329
 * Parse params from STATUS call for raid target.
330
 *
331
 * With upstream dm-raid target versions 1.9.0 and 1.9.1, a failed component
332
 * may be omitted from the health string.  This was fixed in target 1.9.2
333
 * (upstream Linux 4.11).  For the affected versions, dev_count may be smaller
334
 * than the advertised RAID device count; callers mapping those chars to RAID
335
 * slots must handle the mismatch.
336
 */
337
struct dm_status_raid {
338
  uint64_t reserved;
339
  uint64_t total_regions;   /* sectors */
340
  uint64_t insync_regions;  /* sectors */
341
  uint64_t mismatch_count;
342
  uint32_t dev_count;
343
  char *raid_type;
344
  /* A - alive,  a - alive not in-sync,  D - dead/failed */
345
  char *dev_health;
346
  /* idle, frozen, resync, recover, check, repair */
347
  char *sync_action;
348
  uint64_t data_offset; /* RAID out-of-place reshaping */
349
  uint32_t advertised_dev_count; /* #devs field in status */
350
};
351
352
int dm_get_status_raid(struct dm_pool *mem, const char *params,
353
           struct dm_status_raid **status);
354
355
/* Parse params from STATUS call for cache target */
356
struct dm_status_cache {
357
  uint64_t version;  /* zero for now */
358
359
  uint32_t metadata_block_size;   /* in 512B sectors */
360
  uint32_t block_size;            /* AKA 'chunk_size' */
361
362
  uint64_t metadata_used_blocks;
363
  uint64_t metadata_total_blocks;
364
365
  uint64_t used_blocks;
366
  uint64_t dirty_blocks;
367
  uint64_t total_blocks;
368
369
  uint64_t read_hits;
370
  uint64_t read_misses;
371
  uint64_t write_hits;
372
  uint64_t write_misses;
373
374
  uint64_t demotions;
375
  uint64_t promotions;
376
377
  uint64_t feature_flags;   /* DM_CACHE_FEATURE_? */
378
379
  int core_argc;
380
  char **core_argv;
381
382
  char *policy_name;
383
  int policy_argc;
384
  char **policy_argv;
385
386
  unsigned error : 1;   /* detected error (switches to fail soon) */
387
  unsigned fail : 1;    /* all I/O fails */
388
  unsigned needs_check : 1; /* metadata needs check */
389
  unsigned read_only : 1;   /* metadata may not be changed */
390
  uint32_t reserved : 28;
391
};
392
393
int dm_get_status_cache(struct dm_pool *mem, const char *params,
394
      struct dm_status_cache **status);
395
396
struct dm_status_writecache {
397
  uint64_t error;
398
  uint64_t total_blocks;
399
  uint64_t free_blocks;
400
  uint64_t writeback_blocks;
401
};
402
403
int dm_get_status_writecache(struct dm_pool *mem, const char *params,
404
           struct dm_status_writecache **status);
405
406
struct dm_status_integrity {
407
  uint64_t number_of_mismatches;
408
  uint64_t provided_data_sectors;
409
  uint64_t recalc_sector;
410
};
411
412
int dm_get_status_integrity(struct dm_pool *mem, const char *params,
413
          struct dm_status_integrity **status);
414
415
/*
416
 * RAID target support
417
 */
418
int dm_raid_count_failed_devices(const char *dev_path, uint32_t *nr_failed);
419
int dm_raid_clear_failed_devices(const char *dev_path, uint32_t *nr_failed);
420
421
/*
422
 * Parse params from STATUS call for snapshot target
423
 *
424
 * Snapshot target's format:
425
 * <= 1.7.0: <used_sectors>/<total_sectors>
426
 * >= 1.8.0: <used_sectors>/<total_sectors> <metadata_sectors>
427
 */
428
struct dm_status_snapshot {
429
  uint64_t used_sectors;          /* in 512b units */
430
  uint64_t total_sectors;
431
  uint64_t metadata_sectors;
432
  unsigned has_metadata_sectors : 1; /* set when metadata_sectors is present */
433
  unsigned invalid : 1;   /* set when snapshot is invalidated */
434
  unsigned merge_failed : 1;  /* set when snapshot merge failed */
435
  unsigned overflow : 1;    /* set when snapshot overflows */
436
};
437
438
int dm_get_status_snapshot(struct dm_pool *mem, const char *params,
439
         struct dm_status_snapshot **status);
440
441
/* Parse params from STATUS call for thin_pool target */
442
typedef enum dm_thin_discards_e {
443
  DM_THIN_DISCARDS_IGNORE,
444
  DM_THIN_DISCARDS_NO_PASSDOWN,
445
  DM_THIN_DISCARDS_PASSDOWN
446
} dm_thin_discards_t;
447
448
struct dm_status_thin_pool {
449
  uint64_t transaction_id;
450
  uint64_t used_metadata_blocks;
451
  uint64_t total_metadata_blocks;
452
  uint64_t used_data_blocks;
453
  uint64_t total_data_blocks;
454
  uint64_t held_metadata_root;
455
  uint32_t read_only;   /* metadata may not be changed */
456
  dm_thin_discards_t discards;
457
  uint32_t fail : 1;    /* all I/O fails */
458
  uint32_t error_if_no_space : 1; /* otherwise queue_if_no_space */
459
  uint32_t out_of_data_space : 1; /* metadata may be changed, but data may not be allocated (no rw) */
460
  uint32_t needs_check : 1; /* metadata needs check */
461
  uint32_t error : 1;   /* detected error (switches to fail soon) */
462
  uint32_t reserved : 27;
463
};
464
465
int dm_get_status_thin_pool(struct dm_pool *mem, const char *params,
466
          struct dm_status_thin_pool **status);
467
468
/* Parse params from STATUS call for thin target */
469
struct dm_status_thin {
470
  uint64_t mapped_sectors;
471
  uint64_t highest_mapped_sector;
472
  uint32_t fail : 1;              /* Thin volume fails I/O */
473
  uint32_t reserved : 31;
474
};
475
476
int dm_get_status_thin(struct dm_pool *mem, const char *params,
477
           struct dm_status_thin **status);
478
479
/*
480
 * device-mapper statistics support
481
 */
482
483
/*
484
 * Statistics handle.
485
 *
486
 * Operations on dm_stats objects include managing statistics regions
487
 * and obtaining and manipulating current counter values from the
488
 * kernel. Methods are provided to return basic count values and to
489
 * derive time-based metrics when a suitable interval estimate is
490
 * provided.
491
 *
492
 * Internally the dm_stats handle contains a pointer to a table of one
493
 * or more dm_stats_region objects representing the regions registered
494
 * with the dm_stats_create_region() method. These in turn point to a
495
 * table of one or more dm_stats_counters objects containing the
496
 * counter sets for each defined area within the region:
497
 *
498
 * dm_stats->dm_stats_region[nr_regions]->dm_stats_counters[nr_areas]
499
 *
500
 * This structure is private to the library and may change in future
501
 * versions: all users should make use of the public interface and treat
502
 * the dm_stats type as an opaque handle.
503
 *
504
 * Regions and counter sets are stored in order of increasing region_id.
505
 * Depending on region specifications and the sequence of create and
506
 * delete operations this may not correspond to increasing sector
507
 * number: users of the library should not assume that this is the case
508
 * unless region creation is deliberately managed to ensure this (by
509
 * always creating regions in strict order of ascending sector address).
510
 *
511
 * Regions may also overlap so the same sector range may be included in
512
 * more than one region or area: applications should be prepared to deal
513
 * with this or manage regions such that it does not occur.
514
 */
515
struct dm_stats;
516
517
/*
518
 * Histogram handle.
519
 *
520
 * A histogram object represents the latency histogram values and bin
521
 * boundaries of the histogram associated with a particular area.
522
 *
523
 * Operations on the handle allow the number of bins, bin boundaries,
524
 * counts and relative proportions to be obtained as well as the
525
 * conversion of a histogram or its bounds to a compact string
526
 * representation.
527
 */
528
struct dm_histogram;
529
530
/*
531
 * Allocate a dm_stats handle to use for subsequent device-mapper
532
 * statistics operations. A program_id may be specified and will be
533
 * used by default for subsequent operations on this handle.
534
 *
535
 * If program_id is NULL or the empty string a program_id will be
536
 * automatically set to the value contained in /proc/self/comm.
537
 */
538
struct dm_stats *dm_stats_create(const char *program_id);
539
540
/*
541
 * Bind a dm_stats handle to the specified device major and minor
542
 * values. Any previous binding is cleared and any preexisting counter
543
 * data contained in the handle is released.
544
 */
545
int dm_stats_bind_devno(struct dm_stats *dms, int major, int minor);
546
547
/*
548
 * Bind a dm_stats handle to the specified device name.
549
 * Any previous binding is cleared and any preexisting counter
550
 * data contained in the handle is released.
551
 */
552
int dm_stats_bind_name(struct dm_stats *dms, const char *name);
553
554
/*
555
 * Bind a dm_stats handle to the specified device UUID.
556
 * Any previous binding is cleared and any preexisting counter
557
 * data contained in the handle is released.
558
 */
559
int dm_stats_bind_uuid(struct dm_stats *dms, const char *uuid);
560
561
/*
562
 * Bind a dm_stats handle to the device backing the file referenced
563
 * by the specified file descriptor.
564
 *
565
 * File descriptor fd must reference a regular file, open for reading,
566
 * in a local file system, backed by a device-mapper device, that
567
 * supports the FIEMAP ioctl, and that returns data describing the
568
 * physical location of extents.
569
 */
570
int dm_stats_bind_from_fd(struct dm_stats *dms, int fd);
571
/*
572
 * Test whether the running kernel supports the precise_timestamps
573
 * feature. Presence of this feature also implies histogram support.
574
 * The library will check this call internally and fails any attempt
575
 * to use nanosecond counters or histograms on kernels that fail to
576
 * meet this check.
577
 */
578
int dm_message_supports_precise_timestamps(void);
579
580
/*
581
 * Precise timestamps and histogram support.
582
 *
583
 * Test for the presence of precise_timestamps and histogram support.
584
 */
585
int dm_stats_driver_supports_precise(void);
586
int dm_stats_driver_supports_histogram(void);
587
588
/*
589
 * Returns 1 if the specified region has the precise_timestamps feature
590
 * enabled (i.e. produces nanosecond-precision counter values) or 0 for
591
 * a region using the default millisecond precision.
592
 */
593
int dm_stats_get_region_precise_timestamps(const struct dm_stats *dms,
594
             uint64_t region_id);
595
596
/*
597
 * Returns 1 if the region at the current cursor location has the
598
 * precise_timestamps feature enabled (i.e. produces
599
 * nanosecond-precision counter values) or 0 for a region using the
600
 * default millisecond precision.
601
 */
602
int dm_stats_get_current_region_precise_timestamps(const struct dm_stats *dms);
603
604
#define DM_STATS_ALL_PROGRAMS ""
605
/*
606
 * Parse the response from a @stats_list message. dm_stats_list will
607
 * allocate the necessary dm_stats and dm_stats region structures from
608
 * the embedded dm_pool. No counter data will be obtained (the counters
609
 * members of dm_stats_region objects are set to NULL).
610
 *
611
 * A program_id may optionally be supplied; if the argument is non-NULL
612
 * only regions with a matching program_id value will be considered. If
613
 * the argument is NULL then the default program_id associated with the
614
 * dm_stats handle will be used. Passing the special value
615
 * DM_STATS_ALL_PROGRAMS will cause all regions to be queried
616
 * regardless of region program_id.
617
 */
618
int dm_stats_list(struct dm_stats *dms, const char *program_id);
619
620
/*
621
 * Parse a @stats_list message response body without device I/O.
622
 * dm_stats_list() performs the same parsing after querying the kernel.
623
 */
624
int dm_stats_read_list(struct dm_stats *dms, const char *list_response);
625
626
#define DM_STATS_REGIONS_ALL UINT64_MAX
627
/*
628
 * Populate a dm_stats object with statistics for one or more regions of
629
 * the specified device.
630
 *
631
 * A program_id may optionally be supplied; if the argument is non-NULL
632
 * only regions with a matching program_id value will be considered. If
633
 * the argument is NULL then the default program_id associated with the
634
 * dm_stats handle will be used. Passing the special value
635
 * DM_STATS_ALL_PROGRAMS will cause all regions to be queried
636
 * regardless of region program_id.
637
 *
638
 * Passing the special value DM_STATS_REGIONS_ALL as the region_id
639
 * argument will attempt to retrieve all regions selected by the
640
 * program_id argument.
641
 *
642
 * If region_id is used to request a single region_id to be populated
643
 * the program_id is ignored.
644
 */
645
int dm_stats_populate(struct dm_stats *dms, const char *program_id,
646
          uint64_t region_id);
647
648
/*
649
 * Create a new statistics region on the device bound to dms.
650
 *
651
 * start and len specify the region start and length in 512b sectors.
652
 * Passing zero for both start and len will create a region spanning
653
 * the entire device.
654
 *
655
 * Step determines how to subdivide the region into discrete counter
656
 * sets: a positive value specifies the size of areas into which the
657
 * region should be split while a negative value will split the region
658
 * into a number of areas equal to the absolute value of step:
659
 *
660
 * - a region with one area spanning the entire device:
661
 *
662
 *   dm_stats_create_region(dms, 0, 0, -1, p, a);
663
 *
664
 * - a region with areas of 1MiB:
665
 *
666
 *   dm_stats_create_region(dms, 0, 0, 1 << 11, p, a);
667
 *
668
 * - one 1MiB region starting at 1024 sectors with two areas:
669
 *
670
 *   dm_stats_create_region(dms, 1024, 1 << 11, -2, p, a);
671
 *
672
 * If precise is non-zero attempt to create a region with nanosecond
673
 * precision counters using the kernel precise_timestamps feature.
674
 *
675
 * precise - A flag to request nanosecond precision counters
676
 * to be used for this region.
677
 *
678
 * histogram_bounds - specify the boundaries of a latency histogram to
679
 * be tracked for the region. The values are expressed as an array of
680
 * uint64_t terminated with a zero. Values must be in order of ascending
681
 * magnitude and specify the upper bounds of successive histogram bins
682
 * in nanoseconds (with an implicit lower bound of zero on the first bin
683
 * and an implicit upper bound of infinity on the final bin). For
684
 * example:
685
 *
686
 *   uint64_t bounds_ary[] = { 1000, 2000, 3000, 0 };
687
 *
688
 * Specifies a histogram with four bins: 0-1000ns, 1000-2000ns,
689
 * 2000-3000ns and >3000ns.
690
 *
691
 * The smallest latency value that can be tracked for a region not using
692
 * precise_timestamps is 1ms: attempting to create a region with
693
 * histogram boundaries < 1ms will cause the precise_timestamps feature
694
 * to be enabled for that region automatically if it was not requested
695
 * explicitly.
696
 *
697
 * program_id is an optional string argument that identifies the
698
 * program creating the region. If program_id is NULL or the empty
699
 * string the default program_id stored in the handle will be used.
700
 *
701
 * user_data is an optional string argument that is added to the
702
 * content of the aux_data field stored with the statistics region by
703
 * the kernel.
704
 *
705
 * The library may also use this space internally, for example, to
706
 * store a group descriptor or other metadata: in this case the
707
 * library will strip any internal data fields from the value before
708
 * it is returned via a call to dm_stats_get_region_aux_data().
709
 *
710
 * The user data stored is not accessed by the library or kernel and
711
 * may be used to store an arbitrary data word (embedded whitespace is
712
 * not permitted).
713
 *
714
 * An application using both the library and direct access to the
715
 * @stats_list device-mapper message may see the internal values stored
716
 * in this field by the library. In such cases any string up to and
717
 * including the first '#' in the field must be treated as an opaque
718
 * value and preserved across any external modification of aux_data.
719
 *
720
 * The region_id of the newly-created region is returned in *region_id
721
 * if it is non-NULL.
722
 */
723
int dm_stats_create_region(struct dm_stats *dms, uint64_t *region_id,
724
         uint64_t start, uint64_t len, int64_t step,
725
         int precise, struct dm_histogram *bounds,
726
         const char *program_id, const char *user_data);
727
728
/*
729
 * Delete the specified statistics region. This will also mark the
730
 * region as not-present and discard any existing statistics data.
731
 */
732
int dm_stats_delete_region(struct dm_stats *dms, uint64_t region_id);
733
734
/*
735
 * Clear the specified statistics region. This requests the kernel to
736
 * zero all counter values (except in-flight I/O). Note that this
737
 * operation is not atomic with respect to reads of the counters; any IO
738
 * events occurring between the last print operation and the clear will
739
 * be lost. This can be avoided by using the atomic print-and-clear
740
 * function of the dm_stats_print_region() call or by using the higher
741
 * level dm_stats_populate() interface.
742
 */
743
int dm_stats_clear_region(struct dm_stats *dms, uint64_t region_id);
744
745
/*
746
 * Print the current counter values for the specified statistics region
747
 * and return them as a string. The memory for the string buffer is
748
 * allocated for the caller and must be released by calling
749
 * dm_stats_buffer_destroy() when no longer required.
750
 *
751
 * Most users are recommended to use the dm_stats_populate() call
752
 * instead since this will automatically parse the statistics data into
753
 * numeric form accessible via the dm_stats_get_*() counter access
754
 * methods.
755
 *
756
 * A subset of the data lines may be requested by setting the
757
 * start_line and num_lines parameters. If both are zero all data
758
 * lines are returned.
759
 *
760
 * If the clear parameter is non-zero the operation will also
761
 * atomically reset all counter values to zero (except in-flight IO).
762
 */
763
char *dm_stats_print_region(struct dm_stats *dms, uint64_t region_id,
764
          unsigned start_line, unsigned num_lines,
765
          unsigned clear);
766
767
/*
768
 * Release a response buffer obtained from dm_stats_print_region() or
769
 * dm_stats_get_group_descriptor().
770
 *
771
 * The buffer belongs to the caller and is released independently of the
772
 * handle, so buffers may be released in any order and one release never
773
 * invalidates another.  The handle is not consulted; the dms argument is
774
 * retained for API compatibility.
775
 */
776
void dm_stats_buffer_destroy(struct dm_stats *dms, char *buffer);
777
778
/*
779
 * Determine the number of regions contained in a dm_stats handle
780
 * following a dm_stats_list() or dm_stats_populate() call.
781
 *
782
 * The value returned is the number of registered regions visible with the
783
 * program_id value used for the list or populate operation and may not be
784
 * equal to the highest present region_id (either due to program_id
785
 * filtering or gaps in the sequence of region_id values).
786
 *
787
 * Always returns zero on an empty handle.
788
 */
789
uint64_t dm_stats_get_nr_regions(const struct dm_stats *dms);
790
791
/*
792
 * Determine the number of groups contained in a dm_stats handle
793
 * following a dm_stats_list() or dm_stats_populate() call.
794
 *
795
 * The value returned is the number of registered groups visible with the
796
 * program_id value used for the list or populate operation and may not be
797
 * equal to the highest present group_id (either due to program_id
798
 * filtering or gaps in the sequence of group_id values).
799
 *
800
 * Always returns zero on an empty handle.
801
 */
802
uint64_t dm_stats_get_nr_groups(const struct dm_stats *dms);
803
804
/*
805
 * Test whether region_id is present in this dm_stats handle.
806
 */
807
int dm_stats_region_present(const struct dm_stats *dms, uint64_t region_id);
808
809
/*
810
 * Returns the number of areas (counter sets) contained in the specified
811
 * region_id of the supplied dm_stats handle.
812
 */
813
uint64_t dm_stats_get_region_nr_areas(const struct dm_stats *dms,
814
              uint64_t region_id);
815
816
/*
817
 * Returns the total number of areas (counter sets) in all regions of the
818
 * given dm_stats object.
819
 */
820
uint64_t dm_stats_get_nr_areas(const struct dm_stats *dms);
821
822
/*
823
 * Test whether group_id is present in this dm_stats handle.
824
 */
825
int dm_stats_group_present(const struct dm_stats *dms, uint64_t group_id);
826
827
/*
828
 * Return the number of bins in the histogram configuration for the
829
 * specified region or zero if no histogram specification is configured.
830
 * Valid following a dm_stats_list() or dm_stats_populate() operation.
831
 */
832
int dm_stats_get_region_nr_histogram_bins(const struct dm_stats *dms,
833
            uint64_t region_id);
834
835
/*
836
 * Parse a histogram string with optional unit suffixes into a
837
 * dm_histogram bounds description.
838
 *
839
 * A histogram string is a string of numbers "n1,n2,n3,..." that
840
 * represent the boundaries of a histogram. The first and final bins
841
 * have implicit lower and upper bounds of zero and infinity
842
 * respectively and boundary values must occur in order of ascending
843
 * magnitude.  Unless a unit suffix is given all values are specified in
844
 * nanoseconds.
845
 *
846
 * For example, if bounds_str="300,600,900", the region will be created
847
 * with a histogram containing four bins. Each report will include four
848
 * numbers a:b:c:d. a is the number of requests that took between 0 and
849
 * 300ns to complete, b is the number of requests that took 300-600ns to
850
 * complete, c is the number of requests that took 600-900ns to complete
851
 * and d is the number of requests that took more than 900ns to
852
 * complete.
853
 *
854
 * An optional unit suffix of 's', 'ms', 'us', or 'ns' may be used to
855
 * specify units of seconds, milliseconds, microseconds, or nanoseconds:
856
 *
857
 *   bounds_str="1ns,1us,1ms,1s"
858
 *   bounds_str="500us,1ms,1500us,2ms"
859
 *   bounds_str="200ms,400ms,600ms,800ms,1s"
860
 *
861
 * The smallest valid unit of time for a histogram specification depends
862
 * on whether the region uses precise timestamps: for a region with the
863
 * default millisecond precision the smallest possible histogram boundary
864
 * magnitude is one millisecond: attempting to use a histogram with a
865
 * boundary less than one millisecond when creating a region will cause
866
 * the region to be created with the precise_timestamps feature enabled.
867
 *
868
 * On success a pointer to the struct dm_histogram representing the
869
 * bounds values is returned, or NULL in the case of error. The returned
870
 * pointer should be freed using dm_free() when no longer required.
871
 */
872
struct dm_histogram *dm_histogram_bounds_from_string(const char *bounds_str);
873
874
/*
875
 * Parse a zero terminated array of uint64_t into a dm_histogram bounds
876
 * description.
877
 *
878
 * Each value in the array specifies the upper bound of a bin in the
879
 * latency histogram in nanoseconds. Values must appear in ascending
880
 * order of magnitude.
881
 *
882
 * The smallest valid unit of time for a histogram specification depends
883
 * on whether the region uses precise timestamps: for a region with the
884
 * default millisecond precision the smallest possible histogram boundary
885
 * magnitude is one millisecond: attempting to use a histogram with a
886
 * boundary less than one millisecond when creating a region will cause
887
 * the region to be created with the precise_timestamps feature enabled.
888
 */
889
struct dm_histogram *dm_histogram_bounds_from_uint64(const uint64_t *bounds);
890
891
/*
892
 * Destroy the histogram bounds array obtained from a call to
893
 * dm_histogram_bounds_from_string().
894
 */
895
void dm_histogram_bounds_destroy(struct dm_histogram *bounds);
896
897
/*
898
 * Destroy a dm_stats object and all associated regions, counter
899
 * sets and histograms.
900
 */
901
void dm_stats_destroy(struct dm_stats *dms);
902
903
/*
904
 * Counter sampling interval
905
 */
906
907
/*
908
 * Set the sampling interval for counter data to the specified value in
909
 * either nanoseconds or milliseconds.
910
 *
911
 * The interval is used to calculate time-based metrics from the basic
912
 * counter data: an interval must be set before calling any of the
913
 * metric methods.
914
 *
915
 * For best accuracy the duration should be measured and updated at the
916
 * end of each interval.
917
 *
918
 * All values are stored internally with nanosecond precision and are
919
 * converted to or from ms when the millisecond interfaces are used.
920
 */
921
void dm_stats_set_sampling_interval_ns(struct dm_stats *dms,
922
               uint64_t interval_ns);
923
924
void dm_stats_set_sampling_interval_ms(struct dm_stats *dms,
925
               uint64_t interval_ms);
926
927
/*
928
 * Retrieve the configured sampling interval in either nanoseconds or
929
 * milliseconds.
930
 */
931
uint64_t dm_stats_get_sampling_interval_ns(const struct dm_stats *dms);
932
uint64_t dm_stats_get_sampling_interval_ms(const struct dm_stats *dms);
933
934
/*
935
 * Override program_id. This may be used to change the default
936
 * program_id value for an existing handle. If the allow_empty argument
937
 * is non-zero a NULL or empty program_id is permitted.
938
 *
939
 * Use with caution! Most users of the library should set a valid,
940
 * non-NULL program_id for every statistics region created. Failing to
941
 * do so may result in confusing state when multiple programs are
942
 * creating and managing statistics regions.
943
 *
944
 * All users of the library are encouraged to choose an unambiguous,
945
 * unique program_id: this could be based on PID (for programs that
946
 * create, report, and delete regions in a single process), session id,
947
 * executable name, or some other distinguishing string.
948
 *
949
 * Use of the empty string as a program_id does not simplify use of the
950
 * library or the command line tools and use of this value is strongly
951
 * discouraged.
952
 */
953
int dm_stats_set_program_id(struct dm_stats *dms, int allow_empty,
954
          const char *program_id);
955
956
/*
957
 * Region properties: size, length & area_len.
958
 *
959
 * Region start and length are returned in units of 512b as specified
960
 * at region creation time. The area_len value gives the size of areas
961
 * into which the region has been subdivided. For regions with a single
962
 * area spanning the range this value is equal to the region length.
963
 *
964
 * For regions created with a specified number of areas the value
965
 * represents the size of the areas into which the kernel divided the
966
 * region excluding any rounding of the last area size. The number of
967
 * areas may be obtained using the dm_stats_nr_areas_region() call.
968
 *
969
 * All values are returned in units of 512b sectors.
970
 */
971
int dm_stats_get_region_start(const struct dm_stats *dms, uint64_t *start,
972
            uint64_t region_id);
973
974
int dm_stats_get_region_len(const struct dm_stats *dms, uint64_t *len,
975
          uint64_t region_id);
976
977
int dm_stats_get_region_area_len(const struct dm_stats *dms,
978
         uint64_t *len, uint64_t region_id);
979
980
/*
981
 * Area properties: start, offset and length.
982
 *
983
 * The area length is always equal to the area length of the region
984
 * that contains it and is obtained from dm_stats_get_region_area_len().
985
 *
986
 * The start of an area is a function of the area_id and the containing
987
 * region's start and area length: it gives the absolute offset into the
988
 * containing device of the beginning of the area.
989
 *
990
 * The offset expresses the area's relative offset into the current
991
 * region. I.e. the area start minus the start offset of the containing
992
 * region.
993
 *
994
 * All values are returned in units of 512b sectors.
995
 */
996
int dm_stats_get_area_start(const struct dm_stats *dms, uint64_t *start,
997
          uint64_t region_id, uint64_t area_id);
998
999
int dm_stats_get_area_offset(const struct dm_stats *dms, uint64_t *offset,
1000
           uint64_t region_id, uint64_t area_id);
1001
1002
/*
1003
 * Retrieve program_id and user aux_data for a specific region.
1004
 *
1005
 * Only valid following a call to dm_stats_list().
1006
 */
1007
1008
/*
1009
 * Retrieve program_id for the specified region.
1010
 *
1011
 * The returned pointer does not need to be freed separately from the
1012
 * dm_stats handle but will become invalid after a dm_stats_destroy(),
1013
 * dm_stats_list(), dm_stats_populate(), or dm_stats_bind*() of the
1014
 * handle from which it was obtained.
1015
 */
1016
const char *dm_stats_get_region_program_id(const struct dm_stats *dms,
1017
             uint64_t region_id);
1018
1019
/*
1020
 * Retrieve user aux_data set for the specified region. This function
1021
 * will return any stored user aux_data as a string in the memory
1022
 * pointed to by the aux_data argument.
1023
 *
1024
 * Any library internal aux_data fields, such as DMS_GROUP descriptors,
1025
 * are stripped before the value is returned.
1026
 *
1027
 * The returned pointer does not need to be freed separately from the
1028
 * dm_stats handle but will become invalid after a dm_stats_destroy(),
1029
 * dm_stats_list(), dm_stats_populate(), or dm_stats_bind*() of the
1030
 * handle from which it was obtained.
1031
 */
1032
const char *dm_stats_get_region_aux_data(const struct dm_stats *dms,
1033
           uint64_t region_id);
1034
1035
typedef enum dm_stats_obj_type_e {
1036
  DM_STATS_OBJECT_TYPE_NONE,
1037
  DM_STATS_OBJECT_TYPE_AREA,
1038
  DM_STATS_OBJECT_TYPE_REGION,
1039
  DM_STATS_OBJECT_TYPE_GROUP
1040
} dm_stats_obj_type_t;
1041
1042
/*
1043
 * Statistics cursor
1044
 *
1045
 * A dm_stats handle maintains an optional cursor into the statistics
1046
 * tables that it stores. Iterators are provided to visit each region,
1047
 * area, or group in a handle and accessor methods are provided to
1048
 * obtain properties and values for the object at the current cursor
1049
 * position.
1050
 *
1051
 * Using the cursor simplifies walking all regions or groups when
1052
 * the tables are sparse (i.e. contains some present and some
1053
 * non-present region_id or group_id values either due to program_id
1054
 * filtering or the ordering of region and group creation and deletion).
1055
 *
1056
 * Simple macros are provided to visit each area, region, or group,
1057
 * contained in a handle and applications are encouraged to use these
1058
 * where possible.
1059
 */
1060
1061
/*
1062
 * Walk flags are used to initialise a dm_stats handle's cursor control
1063
 * and to select region or group aggregation when calling a metric or
1064
 * counter property method with immediate group, region, and area ID
1065
 * values.
1066
 *
1067
 * Walk flags are stored in the uppermost word of a uint64_t so that
1068
 * a region_id or group_id may be encoded in the lower bits. This
1069
 * allows an aggregate region_id or group_id to be specified when
1070
 * retrieving counter or metric values.
1071
 *
1072
 * Flags may be ORred together when used to initialise a dm_stats_walk:
1073
 * the resulting walk will visit instance of each type specified by
1074
 * the flag combination.
1075
 */
1076
#define DM_STATS_WALK_AREA   0x1000000000000ULL
1077
#define DM_STATS_WALK_REGION 0x2000000000000ULL
1078
#define DM_STATS_WALK_GROUP  0x4000000000000ULL
1079
1080
#define DM_STATS_WALK_ALL    0x7000000000000ULL
1081
#define DM_STATS_WALK_DEFAULT (DM_STATS_WALK_AREA | DM_STATS_WALK_REGION)
1082
1083
/*
1084
 * Skip regions from a DM_STATS_WALK_REGION that contain only a single
1085
 * area: in this case the region's aggregate values are identical to
1086
 * the values of the single contained area. Setting this flag will
1087
 * suppress these duplicate entries during a dm_stats_walk_* with the
1088
 * DM_STATS_WALK_REGION flag set.
1089
 */
1090
#define DM_STATS_WALK_SKIP_SINGLE_AREA   0x8000000000000ULL
1091
1092
/*
1093
 * Initialise the cursor control of a dm_stats handle for the specified
1094
 * walk type(s). Including a walk flag in the flags argument will cause
1095
 * any subsequent walk to visit that type of object (until the next
1096
 * call to dm_stats_walk_init()).
1097
 */
1098
int dm_stats_walk_init(struct dm_stats *dms, uint64_t flags);
1099
1100
/*
1101
 * Set the cursor of a dm_stats handle to address the first present
1102
 * group, region, or area of the currently configured walk. It is
1103
 * valid to attempt to walk a NULL stats handle or a handle containing
1104
 * no present regions; in this case any call to dm_stats_walk_next()
1105
 * becomes a no-op and all calls to dm_stats_walk_end() return true.
1106
 */
1107
void dm_stats_walk_start(struct dm_stats *dms);
1108
1109
/*
1110
 * Advance the statistics cursor to the next area, or to the next
1111
 * present region if at the end of the current region. If the end of
1112
 * the region, area, or group tables is reached a subsequent call to
1113
 * dm_stats_walk_end() will return 1 and dm_stats_object_type() called
1114
 * on the location will return DM_STATS_OBJECT_TYPE_NONE,
1115
 */
1116
void dm_stats_walk_next(struct dm_stats *dms);
1117
1118
/*
1119
 * Force the statistics cursor to advance to the next region. This will
1120
 * stop any in-progress area walk (by clearing DM_STATS_WALK_AREA) and
1121
 * advance the cursor to the next present region, the first present
1122
 * group (if DM_STATS_GROUP_WALK is set), or to the end. In this case a
1123
 * subsequent call to dm_stats_walk_end() will return 1 and a call to
1124
 * dm_stats_object_type() for the location will return
1125
 * DM_STATS_OBJECT_TYPE_NONE.
1126
 */
1127
void dm_stats_walk_next_region(struct dm_stats *dms);
1128
1129
/*
1130
 * Test whether the end of a statistics walk has been reached.
1131
 */
1132
int dm_stats_walk_end(struct dm_stats *dms);
1133
1134
/*
1135
 * Return the type of object at the location specified by region_id
1136
 * and area_id. If either region_id or area_id uses one of the special
1137
 * values DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT the
1138
 * corresponding region or area identifier will be taken from the
1139
 * current cursor location. If the cursor location or the value encoded
1140
 * by region_id and area_id indicates an aggregate region or group,
1141
 * this will be reflected in the value returned.
1142
 */
1143
dm_stats_obj_type_t dm_stats_object_type(const struct dm_stats *dms,
1144
           uint64_t region_id,
1145
           uint64_t area_id);
1146
1147
/*
1148
 * Return the type of object at the current stats cursor location.
1149
 */
1150
dm_stats_obj_type_t dm_stats_current_object_type(const struct dm_stats *dms);
1151
1152
/*
1153
 * Stats iterators
1154
 *
1155
 * C 'for' and 'do'/'while' style iterators for dm_stats data.
1156
 *
1157
 * It is not safe to call any function that modifies the region table
1158
 * within the loop body (i.e. dm_stats_list(), dm_stats_populate(),
1159
 * dm_stats_init(), or dm_stats_destroy()).
1160
 *
1161
 * All counter and property (dm_stats_get_*) access methods, as well as
1162
 * dm_stats_populate_region() can be safely called from loops.
1163
 *
1164
 */
1165
1166
/*
1167
 * Iterate over the regions table visiting each region.
1168
 *
1169
 * If the region table is empty or unpopulated the loop body will not be
1170
 * executed.
1171
 */
1172
#define dm_stats_foreach_region(dms)        \
1173
for (dm_stats_walk_init((dms), DM_STATS_WALK_REGION),   \
1174
     dm_stats_walk_start((dms));        \
1175
     !dm_stats_walk_end((dms)); dm_stats_walk_next_region((dms)))
1176
1177
/*
1178
 * Iterate over the regions table visiting each area.
1179
 *
1180
 * If the region table is empty or unpopulated the loop body will not
1181
 * be executed.
1182
 */
1183
#define dm_stats_foreach_area(dms)        \
1184
for (dm_stats_walk_init((dms), DM_STATS_WALK_AREA),   \
1185
     dm_stats_walk_start((dms));        \
1186
     !dm_stats_walk_end((dms)); dm_stats_walk_next((dms)))
1187
1188
/*
1189
 * Iterate over the regions table visiting each group. Metric and
1190
 * counter methods will return values for the group.
1191
 *
1192
 * If the group table is empty or unpopulated the loop body will not
1193
 * be executed.
1194
 */
1195
#define dm_stats_foreach_group(dms)       \
1196
for (dm_stats_walk_init((dms), DM_STATS_WALK_GROUP),    \
1197
     dm_stats_walk_start((dms));        \
1198
     !dm_stats_walk_end((dms));         \
1199
     dm_stats_walk_next((dms)))
1200
1201
/*
1202
 * Start a walk iterating over the regions contained in dm_stats handle
1203
 * 'dms'.
1204
 *
1205
 * The body of the loop should call dm_stats_walk_next() or
1206
 * dm_stats_walk_next_region() to advance to the next element.
1207
 *
1208
 * The loop body is executed at least once even if the stats handle is
1209
 * empty.
1210
 */
1211
#define dm_stats_walk_do(dms)         \
1212
do {                \
1213
  dm_stats_walk_start((dms));       \
1214
  do
1215
1216
/*
1217
 * Start a 'while' style loop or end a 'do..while' loop iterating over the
1218
 * regions contained in dm_stats handle 'dms'.
1219
 */
1220
#define dm_stats_walk_while(dms)        \
1221
  while(!dm_stats_walk_end((dms)));     \
1222
} while (0)
1223
1224
/*
1225
 * Cursor relative property methods
1226
 *
1227
 * Calls with the prefix dm_stats_get_current_* operate relative to the
1228
 * current cursor location, returning properties for the current region
1229
 * or area of the supplied dm_stats handle.
1230
 *
1231
 */
1232
1233
/*
1234
 * Returns the number of areas (counter sets) contained in the current
1235
 * region of the supplied dm_stats handle.
1236
 */
1237
uint64_t dm_stats_get_current_nr_areas(const struct dm_stats *dms);
1238
1239
/*
1240
 * Retrieve the current values of the stats cursor.
1241
 */
1242
uint64_t dm_stats_get_current_region(const struct dm_stats *dms);
1243
uint64_t dm_stats_get_current_area(const struct dm_stats *dms);
1244
1245
/*
1246
 * Current region properties: size, length & area_len.
1247
 *
1248
 * See the comments for the equivalent dm_stats_get_* versions for a
1249
 * complete description of these methods.
1250
 *
1251
 * All values are returned in units of 512b sectors.
1252
 */
1253
int dm_stats_get_current_region_start(const struct dm_stats *dms,
1254
              uint64_t *start);
1255
1256
int dm_stats_get_current_region_len(const struct dm_stats *dms,
1257
            uint64_t *len);
1258
1259
int dm_stats_get_current_region_area_len(const struct dm_stats *dms,
1260
           uint64_t *area_len);
1261
1262
/*
1263
 * Current area properties: start and length.
1264
 *
1265
 * See the comments for the equivalent dm_stats_get_* versions for a
1266
 * complete description of these methods.
1267
 *
1268
 * All values are returned in units of 512b sectors.
1269
 */
1270
int dm_stats_get_current_area_start(const struct dm_stats *dms,
1271
            uint64_t *start);
1272
1273
int dm_stats_get_current_area_offset(const struct dm_stats *dms,
1274
             uint64_t *offset);
1275
1276
int dm_stats_get_current_area_len(const struct dm_stats *dms,
1277
               uint64_t *len);
1278
1279
/*
1280
 * Return a pointer to the program_id string for region at the current
1281
 * cursor location.
1282
 */
1283
const char *dm_stats_get_current_region_program_id(const struct dm_stats *dms);
1284
1285
/*
1286
 * Return a pointer to the user aux_data string for the region at the
1287
 * current cursor location.
1288
 */
1289
const char *dm_stats_get_current_region_aux_data(const struct dm_stats *dms);
1290
1291
/*
1292
 * Statistics groups and data aggregation.
1293
 */
1294
1295
/*
1296
 * Create a new group in stats handle dms from the group descriptor
1297
 * passed in group. The group descriptor is a string containing a list
1298
 * of region_id values that will be included in the group. The first
1299
 * region_id found will be the group leader. Ranges of identifiers may
1300
 * be expressed as "M-N", where M and N are the start and end region_id
1301
 * values for the range.
1302
 */
1303
int dm_stats_create_group(struct dm_stats *dms, const char *members,
1304
        const char *alias, uint64_t *group_id);
1305
1306
/*
1307
 * Remove the specified group_id. If the remove argument is zero the
1308
 * group will be removed but the regions that it contained will remain.
1309
 * If remove is non-zero then all regions that belong to the group will
1310
 * also be removed.
1311
 */
1312
int dm_stats_delete_group(struct dm_stats *dms, uint64_t group_id, int remove_regions);
1313
1314
/*
1315
 * Set an alias for this group or region. The alias will be returned
1316
 * instead of the normal dm-stats name for this region or group.
1317
 */
1318
int dm_stats_set_alias(struct dm_stats *dms, uint64_t group_id,
1319
           const char *alias);
1320
1321
/*
1322
 * Returns a pointer to the currently configured alias for id, or the
1323
 * name of the dm device the handle is bound to if no alias has been
1324
 * set. The pointer will be freed automatically when a new alias is set
1325
 * or when the stats handle is cleared.
1326
 */
1327
const char *dm_stats_get_alias(const struct dm_stats *dms, uint64_t id);
1328
1329
#define DM_STATS_GROUP_NONE UINT64_MAX
1330
/*
1331
 * Return the group_id that the specified region_id belongs to, or the
1332
 * special value DM_STATS_GROUP_NONE if the region does not belong
1333
 * to any group.
1334
 */
1335
uint64_t dm_stats_get_group_id(const struct dm_stats *dms, uint64_t region_id);
1336
1337
/*
1338
 * Store a pointer to a string describing the regions that are members
1339
 * of the group specified by group_id in the memory pointed to by buf.
1340
 * The string is in the same format as the 'group' argument to
1341
 * dm_stats_create_group().
1342
 *
1343
 * The buffer is allocated for the caller and must be released with
1344
 * dm_stats_buffer_destroy() when no longer required.
1345
 */
1346
int dm_stats_get_group_descriptor(const struct dm_stats *dms,
1347
          uint64_t group_id, char **buf);
1348
1349
/*
1350
 * Create regions that correspond to the extents of a file in the
1351
 * filesystem and optionally place them into a group.
1352
 *
1353
 * File descriptor fd must reference a regular file, open for reading,
1354
 * in a local file system that supports the FIEMAP ioctl, and that
1355
 * returns data describing the physical location of extents.
1356
 *
1357
 * The file descriptor can be closed by the caller following the call
1358
 * to dm_stats_create_regions_from_fd().
1359
 *
1360
 * Unless nogroup is non-zero the regions will be placed into a group
1361
 * and the group alias set to the value supplied (if alias is NULL no
1362
 * group alias will be assigned).
1363
 *
1364
 * On success the function returns a pointer to an array of uint64_t
1365
 * containing the IDs of the newly created regions. The region_id
1366
 * array is terminated by the value DM_STATS_REGION_NOT_PRESENT and
1367
 * should be freed using dm_free() when no longer required.
1368
 *
1369
 * On error NULL is returned.
1370
 *
1371
 * Following a call to dm_stats_create_regions_from_fd() the handle
1372
 * is guaranteed to be in a listed state, and to contain any region
1373
 * and group identifiers created by the operation.
1374
 *
1375
 * The group_id for the new group is equal to the region_id value in
1376
 * the first array element.
1377
 */
1378
uint64_t *dm_stats_create_regions_from_fd(struct dm_stats *dms, int fd,
1379
            int group, int precise,
1380
            struct dm_histogram *bounds,
1381
            const char *alias);
1382
/*
1383
 * Update a group of regions that correspond to the extents of a file
1384
 * in the filesystem, adding and removing regions to account for
1385
 * allocation changes in the underlying file.
1386
 *
1387
 * File descriptor fd must reference a regular file, open for reading,
1388
 * in a local file system that supports the FIEMAP ioctl, and that
1389
 * returns data describing the physical location of extents.
1390
 *
1391
 * The file descriptor can be closed by the caller following the call
1392
 * to dm_stats_update_regions_from_fd().
1393
 *
1394
 * On success the function returns a pointer to an array of uint64_t
1395
 * containing the IDs of the updated regions (including any existing
1396
 * regions that were not modified by the call).
1397
 *
1398
 * The region_id array is terminated by the special value
1399
 * DM_STATS_REGION_NOT_PRESENT and should be freed using dm_free()
1400
 * when no longer required.
1401
 *
1402
 * On error NULL is returned.
1403
 *
1404
 * Following a call to dm_stats_update_regions_from_fd() the handle
1405
 * is guaranteed to be in a listed state, and to contain any region
1406
 * and group identifiers created by the operation.
1407
 *
1408
 * This function cannot be used with file mapped regions that are
1409
 * not members of a group: either group the regions, or remove them
1410
 * and re-map them with dm_stats_create_regions_from_fd().
1411
 */
1412
uint64_t *dm_stats_update_regions_from_fd(struct dm_stats *dms, int fd,
1413
            uint64_t group_id);
1414
1415
1416
/*
1417
 * The file map monitoring daemon can monitor files in two distinct
1418
 * ways: the mode affects the behaviour of the daemon when a file
1419
 * under monitoring is renamed or unlinked, and the conditions which
1420
 * cause the daemon to terminate.
1421
 *
1422
 * In both modes, the daemon will always shut down when the group
1423
 * being monitored is deleted.
1424
 *
1425
 * Follow inode:
1426
 * The daemon follows the inode of the file, as it was at the time the
1427
 * daemon started. The file descriptor referencing the file is kept
1428
 * open at all times, and the daemon will exit when it detects that
1429
 * the file has been unlinked and it is the last holder of a reference
1430
 * to the file.
1431
 *
1432
 * This mode is useful if the file is expected to be renamed, or moved
1433
 * within the file system, while it is being monitored.
1434
 *
1435
 * Follow path:
1436
 * The daemon follows the path that was given on the daemon command
1437
 * line. The file descriptor referencing the file is re-opened on each
1438
 * iteration of the daemon, and the daemon will exit if no file exists
1439
 * at this location (a tolerance is allowed so that a brief delay
1440
 * between unlink() and creat() is permitted).
1441
 *
1442
 * This mode is useful if the file is updated by unlinking the original
1443
 * and placing a new file at the same path.
1444
 */
1445
1446
typedef enum dm_filemapd_mode_e {
1447
  DM_FILEMAPD_FOLLOW_INODE,
1448
  DM_FILEMAPD_FOLLOW_PATH,
1449
  DM_FILEMAPD_FOLLOW_NONE
1450
} dm_filemapd_mode_t;
1451
1452
/*
1453
 * Parse a string representation of a dmfilemapd mode.
1454
 *
1455
 * Returns a valid dm_filemapd_mode_t value on success, or
1456
 * DM_FILEMAPD_FOLLOW_NONE on error.
1457
 */
1458
dm_filemapd_mode_t dm_filemapd_mode_from_string(const char *mode_str);
1459
1460
/*
1461
 * Start the dmfilemapd filemap monitoring daemon for the specified
1462
 * file descriptor, group, and file system path. The daemon will
1463
 * monitor the file for allocation changes, and when a change is
1464
 * detected, call dm_stats_update_regions_from_fd() to update the
1465
 * mapped regions for the file.
1466
 *
1467
 * The path provided to dm_stats_start_filemapd() must be an absolute
1468
 * path, and should reflect the path of 'fd' at the time that it was
1469
 * opened.
1470
 *
1471
 * The mode parameter controls the behaviour of the daemon when the
1472
 * file being monitored is unlinked or moved: see the comments for
1473
 * dm_filemapd_mode_t for a full description and possible values.
1474
 *
1475
 * The daemon can be stopped at any time by sending SIGTERM to the
1476
 * daemon pid.
1477
 */
1478
int dm_stats_start_filemapd(int fd, uint64_t group_id, const char *path,
1479
          dm_filemapd_mode_t mode, unsigned foreground,
1480
          unsigned verbose);
1481
1482
/*
1483
 * Call this to actually run the ioctl.
1484
 */
1485
int dm_task_run(struct dm_task *dmt);
1486
1487
/*
1488
 * The errno from the last device-mapper ioctl performed by dm_task_run.
1489
 */
1490
int dm_task_get_errno(struct dm_task *dmt);
1491
1492
/*
1493
 * Call this to make or remove the device nodes associated with previously
1494
 * issued commands.
1495
 */
1496
void dm_task_update_nodes(void);
1497
1498
/*
1499
 * Mangling support
1500
 *
1501
 * Character whitelist: 0-9, A-Z, a-z, #+-.:=@_
1502
 * HEX mangling format: \xNN, NN being the hex value of the character.
1503
 * (whitelist and format supported by udev)
1504
*/
1505
typedef enum dm_string_mangling_e {
1506
  DM_STRING_MANGLING_NONE, /* do not mangle at all */
1507
  DM_STRING_MANGLING_AUTO, /* mangle only if not already mangled with hex, error when mixed */
1508
  DM_STRING_MANGLING_HEX   /* always mangle with hex encoding, no matter what the input is */
1509
} dm_string_mangling_t;
1510
1511
/*
1512
 * Set/get mangling mode used for device-mapper names and uuids.
1513
 */
1514
int dm_set_name_mangling_mode(dm_string_mangling_t name_mangling_mode);
1515
dm_string_mangling_t dm_get_name_mangling_mode(void);
1516
1517
/*
1518
 * Get mangled/unmangled form of the device-mapper name or uuid
1519
 * irrespective of the global setting (set by dm_set_name_mangling_mode).
1520
 * The name or uuid returned needs to be freed after use by calling dm_free!
1521
 */
1522
char *dm_task_get_name_mangled(const struct dm_task *dmt);
1523
char *dm_task_get_name_unmangled(const struct dm_task *dmt);
1524
char *dm_task_get_uuid_mangled(const struct dm_task *dmt);
1525
char *dm_task_get_uuid_unmangled(const struct dm_task *dmt);
1526
1527
/*
1528
 * Configure the device-mapper directory
1529
 */
1530
int dm_set_dev_dir(const char *dev_dir);
1531
const char *dm_dir(void);
1532
1533
/*
1534
 * Configure sysfs directory, /sys by default
1535
 */
1536
int dm_set_sysfs_dir(const char *sysfs_dir);
1537
const char *dm_sysfs_dir(void);
1538
1539
/*
1540
 * Configure default UUID prefix string.
1541
 * Conventionally this is a short capitalized prefix indicating the subsystem
1542
 * that is managing the devices, e.g. "LVM-" or "MPATH-".
1543
 * To support stacks of devices from different subsystems, recursive functions
1544
 * stop recursing if they reach a device with a different prefix.
1545
 */
1546
int dm_set_uuid_prefix(const char *uuid_prefix);
1547
const char *dm_uuid_prefix(void);
1548
1549
/*
1550
 * Determine whether a major number belongs to device-mapper or not.
1551
 */
1552
int dm_is_dm_major(uint32_t major);
1553
1554
/*
1555
 * Get associated device name for given major and minor number by reading
1556
 * the sysfs content. If this is a dm device, get associated dm name, the one
1557
 * that appears in /dev/mapper. DM names could be resolved this way only if
1558
 * kernel used >= 2.6.29, kernel name is found otherwise (e.g. dm-0).
1559
 * If prefer_kernel_name is set, the kernel name is always preferred over
1560
 * device-mapper name for dm devices no matter what the kernel version is.
1561
 * For non-dm devices, we always get associated kernel name, e.g sda, md0 etc.
1562
 * Returns 0 on error or if sysfs is not used (or configured incorrectly),
1563
 * otherwise returns 1 and the supplied buffer holds the device name.
1564
 */
1565
int dm_device_get_name(uint32_t major, uint32_t minor,
1566
           int prefer_kernel_name,
1567
           char *buf, size_t buf_size);
1568
1569
/*
1570
 * Determine whether a device has any holders (devices
1571
 * using this device). If sysfs is not used (or configured
1572
 * incorrectly), returns 0.
1573
 */
1574
int dm_device_has_holders(uint32_t major, uint32_t minor);
1575
1576
/*
1577
 * Determine whether a device contains mounted filesystem.
1578
 * If sysfs is not used (or configured incorrectly), returns 0.
1579
 */
1580
int dm_device_has_mounted_fs(uint32_t major, uint32_t minor);
1581
1582
1583
/*
1584
 * Callback is invoked for individual mountinfo lines,
1585
 * minor, major and mount target are parsed and unmangled.
1586
 */
1587
typedef int (*dm_mountinfo_line_callback_fn) (char *line, unsigned maj, unsigned min,
1588
                char *target, void *cb_data);
1589
1590
/*
1591
 * Read all lines from /proc/self/mountinfo,
1592
 * for each line calls read_fn callback.
1593
 */
1594
int dm_mountinfo_read(dm_mountinfo_line_callback_fn read_fn, void *cb_data);
1595
1596
/*
1597
 * Initialise library.  This is normally done automatically when the
1598
 * library is loaded.
1599
 */
1600
void dm_lib_init(void);
1601
1602
/* Release reusable library resources. */
1603
void dm_lib_release(void);
1604
1605
/*
1606
 * Compatibility wrapper for dm_lib_release().  Final library teardown is
1607
 * performed automatically when the library is unloaded.
1608
 */
1609
void dm_lib_exit(void);
1610
1611
/* An optimisation for clients making repeated calls involving dm ioctls */
1612
void dm_hold_control_dev(int hold_open);
1613
1614
/*
1615
 * Use NULL for all devices.
1616
 */
1617
int dm_mknodes(const char *name);
1618
int dm_driver_version(char *version, size_t size);
1619
1620
/******************************************************
1621
 * Functions to build and manipulate trees of devices *
1622
 ******************************************************/
1623
struct dm_tree;
1624
struct dm_tree_node;
1625
1626
/*
1627
 * Initialise an empty dependency tree.
1628
 *
1629
 * The tree consists of a root node together with one node for each mapped
1630
 * device which has child nodes for each device referenced in its table.
1631
 *
1632
 * Every node in the tree has one or more children and one or more parents.
1633
 *
1634
 * The root node is the parent/child of every node that doesn't have other
1635
 * parents/children.
1636
 */
1637
struct dm_tree *dm_tree_create(void);
1638
void dm_tree_free(struct dm_tree *dtree);
1639
1640
/*
1641
 * List of suffixes to be ignored when matching uuids against existing devices.
1642
 */
1643
void dm_tree_set_optional_uuid_suffixes(struct dm_tree *dtree, const char **optional_uuid_suffixes);
1644
1645
/*
1646
 * Add nodes to the tree for a given device and all the devices it uses.
1647
 */
1648
int dm_tree_add_dev(struct dm_tree *dtree, uint32_t major, uint32_t minor);
1649
int dm_tree_add_dev_with_udev_flags(struct dm_tree *dtree, uint32_t major,
1650
            uint32_t minor, uint16_t udev_flags);
1651
1652
/*
1653
 * Add a new node to the tree if it doesn't already exist.
1654
 */
1655
struct dm_tree_node *dm_tree_add_new_dev(struct dm_tree *dtree,
1656
           const char *name,
1657
           const char *uuid,
1658
           uint32_t major, uint32_t minor,
1659
           int read_only,
1660
           int clear_inactive,
1661
           void *context);
1662
struct dm_tree_node *dm_tree_add_new_dev_with_udev_flags(struct dm_tree *dtree,
1663
               const char *name,
1664
               const char *uuid,
1665
               uint32_t major,
1666
               uint32_t minor,
1667
               int read_only,
1668
               int clear_inactive,
1669
               void *context,
1670
               uint16_t udev_flags);
1671
1672
/*
1673
 * Search for a node in the tree.
1674
 * Set major and minor to 0 or uuid to NULL to get the root node.
1675
 */
1676
struct dm_tree_node *dm_tree_find_node(struct dm_tree *dtree,
1677
               uint32_t major,
1678
               uint32_t minor);
1679
struct dm_tree_node *dm_tree_find_node_by_uuid(struct dm_tree *dtree,
1680
                 const char *uuid);
1681
1682
/*
1683
 * Use this to walk through all children of a given node.
1684
 * Set handle to NULL in first call.
1685
 * Returns NULL after the last child.
1686
 * Set inverted to use inverted tree.
1687
 */
1688
struct dm_tree_node *dm_tree_next_child(void **handle,
1689
          const struct dm_tree_node *parent,
1690
          uint32_t inverted);
1691
1692
/*
1693
 * Get properties of a node.
1694
 */
1695
const char *dm_tree_node_get_name(const struct dm_tree_node *node);
1696
const char *dm_tree_node_get_uuid(const struct dm_tree_node *node);
1697
const struct dm_info *dm_tree_node_get_info(const struct dm_tree_node *node);
1698
void *dm_tree_node_get_context(const struct dm_tree_node *node);
1699
/*
1700
 * Returns  0 when node size and its children is unchanged.
1701
 * Returns  1 when node or any of its children has increased size.
1702
 * Returns -1 when node or any of its children has reduced size.
1703
 */
1704
int dm_tree_node_size_changed(const struct dm_tree_node *dnode);
1705
1706
/*
1707
 * Returns the number of children of the given node (excluding the root node).
1708
 * Set inverted for the number of parents.
1709
 */
1710
int dm_tree_node_num_children(const struct dm_tree_node *node, uint32_t inverted);
1711
1712
/*
1713
 * Deactivate a device plus all dependencies.
1714
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1715
 */
1716
int dm_tree_deactivate_children(struct dm_tree_node *dnode,
1717
        const char *uuid_prefix,
1718
        size_t uuid_prefix_len);
1719
/*
1720
 * Preload/create a device plus all dependencies.
1721
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1722
 */
1723
int dm_tree_preload_children(struct dm_tree_node *dnode,
1724
           const char *uuid_prefix,
1725
           size_t uuid_prefix_len);
1726
1727
/*
1728
 * Resume a device plus all dependencies.
1729
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1730
 */
1731
int dm_tree_activate_children(struct dm_tree_node *dnode,
1732
            const char *uuid_prefix,
1733
            size_t uuid_prefix_len);
1734
1735
/*
1736
 * Suspend a device plus all dependencies.
1737
 * Ignores devices that don't have a uuid starting with uuid_prefix.
1738
 */
1739
int dm_tree_suspend_children(struct dm_tree_node *dnode,
1740
           const char *uuid_prefix,
1741
           size_t uuid_prefix_len);
1742
1743
/*
1744
 * Skip the filesystem sync when suspending.
1745
 * Does nothing with other functions.
1746
 * Use this when no snapshots are involved.
1747
 */
1748
void dm_tree_skip_lockfs(struct dm_tree_node *dnode);
1749
1750
/*
1751
 * Set the 'noflush' flag when suspending devices.
1752
 * If the kernel supports it, instead of erroring outstanding I/O that
1753
 * cannot be completed, the I/O is queued and resubmitted when the
1754
 * device is resumed.  This affects multipath devices when all paths
1755
 * have failed and queue_if_no_path is set, and mirror devices when
1756
 * block_on_error is set and the mirror log has failed.
1757
 */
1758
void dm_tree_use_no_flush_suspend(struct dm_tree_node *dnode);
1759
1760
/*
1761
 * Retry removal of each device if not successful.
1762
 */
1763
void dm_tree_retry_remove(struct dm_tree_node *dnode);
1764
1765
/*
1766
 * Is the uuid prefix present in the tree?
1767
 * Only returns 0 if every node was checked successfully.
1768
 * Returns 1 if the tree walk has to be aborted.
1769
 */
1770
int dm_tree_children_use_uuid(struct dm_tree_node *dnode,
1771
            const char *uuid_prefix,
1772
            size_t uuid_prefix_len);
1773
1774
/*
1775
 * Construct tables for new nodes before activating them.
1776
 */
1777
int dm_tree_node_add_snapshot_origin_target(struct dm_tree_node *dnode,
1778
              uint64_t size,
1779
              const char *origin_uuid);
1780
int dm_tree_node_add_snapshot_target(struct dm_tree_node *node,
1781
             uint64_t size,
1782
             const char *origin_uuid,
1783
             const char *cow_uuid,
1784
             int persistent,
1785
             uint32_t chunk_size);
1786
int dm_tree_node_add_snapshot_merge_target(struct dm_tree_node *node,
1787
             uint64_t size,
1788
             const char *origin_uuid,
1789
             const char *cow_uuid,
1790
             const char *merge_uuid,
1791
             uint32_t chunk_size);
1792
int dm_tree_node_add_error_target(struct dm_tree_node *node,
1793
          uint64_t size);
1794
int dm_tree_node_add_zero_target(struct dm_tree_node *node,
1795
         uint64_t size);
1796
int dm_tree_node_add_linear_target(struct dm_tree_node *node,
1797
           uint64_t size);
1798
int dm_tree_node_add_striped_target(struct dm_tree_node *node,
1799
            uint64_t size,
1800
            uint32_t stripe_size);
1801
1802
#define DM_CRYPT_IV_DEFAULT UINT64_C(-1)  /* iv_offset == seg offset */
1803
/*
1804
 * Function accepts one string in cipher specification
1805
 * (chainmode and iv should be NULL because included in cipher string)
1806
 *   or
1807
 * separate arguments which will be joined to "cipher-chainmode-iv"
1808
 */
1809
int dm_tree_node_add_crypt_target(struct dm_tree_node *node,
1810
          uint64_t size,
1811
          const char *cipher,
1812
          const char *chainmode,
1813
          const char *iv,
1814
          uint64_t iv_offset,
1815
          const char *key);
1816
int dm_tree_node_add_mirror_target(struct dm_tree_node *node,
1817
           uint64_t size);
1818
1819
/* Mirror log flags */
1820
#define DM_NOSYNC   0x00000001  /* Known already in sync */
1821
#define DM_FORCESYNC    0x00000002  /* Force resync */
1822
#define DM_BLOCK_ON_ERROR 0x00000004  /* On error, suspend I/O */
1823
#define DM_CORELOG    0x00000008  /* In-memory log */
1824
1825
int dm_tree_node_add_mirror_target_log(struct dm_tree_node *node,
1826
               uint32_t region_size,
1827
               const char *log_uuid,
1828
               unsigned area_count,
1829
               uint32_t flags);
1830
1831
int dm_tree_node_add_raid_target(struct dm_tree_node *node,
1832
         uint64_t size,
1833
         const char *raid_type,
1834
         uint32_t region_size,
1835
         uint32_t stripe_size,
1836
         uint64_t rebuilds,
1837
         uint64_t flags);
1838
1839
/*
1840
 * Defines below are based on kernel's dm-cache.c defines
1841
 * DM_CACHE_MIN_DATA_BLOCK_SIZE (32 * 1024 >> SECTOR_SHIFT)
1842
 * DM_CACHE_MAX_DATA_BLOCK_SIZE (1024 * 1024 * 1024 >> SECTOR_SHIFT)
1843
 */
1844
#define DM_CACHE_MIN_DATA_BLOCK_SIZE (UINT32_C(64))
1845
#define DM_CACHE_MAX_DATA_BLOCK_SIZE (UINT32_C(2097152))
1846
/*
1847
 * Max supported size for cache pool metadata device.
1848
 * Limitation is hardcoded into the kernel and bigger device sizes
1849
 * are not accepted.
1850
 *
1851
 * Limit defined in drivers/md/dm-cache-metadata.h
1852
 */
1853
#define DM_CACHE_METADATA_MAX_SECTORS DM_THIN_METADATA_MAX_SECTORS
1854
1855
/*
1856
 * Define number of elements in rebuild and writemostly arrays
1857
 * 'of struct dm_tree_node_raid_params'.
1858
 */
1859
1860
struct dm_tree_node_raid_params {
1861
  const char *raid_type;
1862
1863
  uint32_t stripes;
1864
  uint32_t mirrors;
1865
  uint32_t region_size;
1866
  uint32_t stripe_size;
1867
1868
  /*
1869
   * 'rebuilds' and 'writemostly' are bitfields that signify
1870
   * which devices in the array are to be rebuilt or marked
1871
   * writemostly.  The kernel supports up to 253 legs.
1872
   * We limit ourselves by choosing a lower value
1873
   * for DEFAULT_RAID{1}_MAX_IMAGES in defaults.h.
1874
   */
1875
  uint64_t rebuilds;
1876
  uint64_t writemostly;
1877
  uint32_t writebehind;     /* I/Os (kernel default COUNTER_MAX / 2) */
1878
  uint32_t sync_daemon_sleep; /* ms (kernel default = 5sec) */
1879
  uint32_t max_recovery_rate; /* kB/sec/disk */
1880
  uint32_t min_recovery_rate; /* kB/sec/disk */
1881
  uint32_t stripe_cache;      /* sectors */
1882
1883
  uint64_t flags;             /* [no]sync */
1884
  uint32_t reserved2;
1885
};
1886
1887
/*
1888
 * Version 2 of above node raid params struct to keep API compatibility.
1889
 *
1890
 * Extended for more than 64 legs (max 253 in the MD kernel runtime!),
1891
 * delta_disks for disk add/remove reshaping,
1892
 * data_offset for out-of-place reshaping
1893
 * and data_copies for odd number of raid10 legs.
1894
 */
1895
#define RAID_BITMAP_SIZE 4 /* 4 * 64 bit elements in rebuilds/writemostly arrays */
1896
struct dm_tree_node_raid_params_v2 {
1897
  const char *raid_type;
1898
1899
  uint32_t stripes;
1900
  uint32_t mirrors;
1901
  uint32_t region_size;
1902
  uint32_t stripe_size;
1903
1904
  int delta_disks; /* +/- number of disks to add/remove (reshaping) */
1905
  int data_offset; /* data offset to set (out-of-place reshaping) */
1906
1907
  /*
1908
   * 'rebuilds' and 'writemostly' are bitfields that signify
1909
   * which devices in the array are to be rebuilt or marked
1910
   * writemostly.  The kernel supports up to 253 legs.
1911
   * We limit ourselves by choosing a lower value
1912
   * for DEFAULT_RAID_MAX_IMAGES.
1913
   */
1914
  uint64_t rebuilds[RAID_BITMAP_SIZE];
1915
  uint64_t writemostly[RAID_BITMAP_SIZE];
1916
  uint32_t writebehind;     /* I/Os (kernel default COUNTER_MAX / 2) */
1917
  uint32_t data_copies;     /* RAID # of data copies */
1918
  uint32_t sync_daemon_sleep; /* ms (kernel default = 5sec) */
1919
  uint32_t max_recovery_rate; /* kB/sec/disk */
1920
  uint32_t min_recovery_rate; /* kB/sec/disk */
1921
  uint32_t stripe_cache;      /* sectors */
1922
1923
  uint64_t flags;             /* [no]sync */
1924
};
1925
1926
int dm_tree_node_add_raid_target_with_params(struct dm_tree_node *node,
1927
               uint64_t size,
1928
               const struct dm_tree_node_raid_params *p);
1929
1930
/* Version 2 API function taking dm_tree_node_raid_params_v2 for aforementioned extensions. */
1931
int dm_tree_node_add_raid_target_with_params_v2(struct dm_tree_node *node,
1932
            uint64_t size,
1933
            const struct dm_tree_node_raid_params_v2 *p);
1934
1935
/* Cache feature_flags */
1936
#define DM_CACHE_FEATURE_WRITEBACK    0x00000001
1937
#define DM_CACHE_FEATURE_WRITETHROUGH 0x00000002
1938
#define DM_CACHE_FEATURE_PASSTHROUGH  0x00000004
1939
#define DM_CACHE_FEATURE_METADATA2    0x00000008 /* cache v1.10 */
1940
#define DM_CACHE_FEATURE_NO_DISCARD_PASSDOWN 0x00000010
1941
1942
struct dm_config_node;
1943
/*
1944
 * Use for passing cache policy and all its args e.g.:
1945
 *
1946
 * policy_settings {
1947
 *    migration_threshold=2048
1948
 *    sequential_threshold=100
1949
 *    ...
1950
 * }
1951
 *
1952
 * For policy without any parameters use NULL.
1953
 */
1954
int dm_tree_node_add_cache_target(struct dm_tree_node *node,
1955
          uint64_t size,
1956
          uint64_t feature_flags, /* DM_CACHE_FEATURE_* */
1957
          const char *metadata_uuid,
1958
          const char *data_uuid,
1959
          const char *origin_uuid,
1960
          const char *policy_name,
1961
          const struct dm_config_node *policy_settings,
1962
          uint32_t data_block_size);
1963
1964
/*
1965
 * Add a cache target using a cachevol (single LV with metadata and data).
1966
 * The cachevol_uuid refers to a single device containing both metadata and data,
1967
 * with metadata_start/metadata_len and data_start/data_len specifying the regions.
1968
 */
1969
int dm_tree_node_add_cachevol_target(struct dm_tree_node *node,
1970
             uint64_t size,
1971
             uint64_t feature_flags, /* DM_CACHE_FEATURE_* */
1972
             const char *metadata_uuid,
1973
             const char *data_uuid,
1974
             const char *cachevol_uuid,
1975
             const char *origin_uuid,
1976
             const char *policy_name,
1977
             const struct dm_config_node *policy_settings,
1978
             uint64_t metadata_start,
1979
             uint64_t metadata_len,
1980
             uint64_t data_start,
1981
             uint64_t data_len,
1982
             uint32_t data_block_size);
1983
1984
struct dm_writecache_settings {
1985
  /*
1986
   * Allow an unrecognized key and its val to be passed to the kernel for
1987
   * cases where a new kernel setting is added but lvm doesn't know about
1988
   * it yet.
1989
   */
1990
  char *new_key;
1991
  char *new_val;
1992
1993
  /*
1994
   * Flag is 1 if a value has been set.
1995
   */
1996
  unsigned high_watermark_set:1;
1997
  unsigned low_watermark_set:1;
1998
  unsigned writeback_jobs_set:1;
1999
  unsigned autocommit_blocks_set:1;
2000
  unsigned autocommit_time_set:1;
2001
  unsigned fua_set:1;
2002
  unsigned nofua_set:1;
2003
  unsigned cleaner_set:1;
2004
  unsigned max_age_set:1;
2005
  unsigned metadata_only_set:1;
2006
  unsigned pause_writeback_set:1;
2007
  uint32_t reserved : 21;
2008
2009
  uint64_t high_watermark;
2010
  uint64_t low_watermark;
2011
  uint64_t writeback_jobs;
2012
  uint64_t autocommit_blocks;
2013
  uint64_t autocommit_time; /* in milliseconds */
2014
  uint32_t fua;
2015
  uint32_t nofua;
2016
  uint32_t cleaner;
2017
  uint32_t max_age;         /* in milliseconds */
2018
  uint32_t metadata_only;
2019
  uint32_t pause_writeback; /* in milliseconds */
2020
};
2021
2022
int dm_tree_node_add_writecache_target(struct dm_tree_node *node,
2023
        uint64_t size,
2024
        const char *origin_uuid,
2025
        const char *cache_uuid,
2026
        int pmem,
2027
        uint32_t writecache_block_size,
2028
        struct dm_writecache_settings *settings);
2029
2030
struct dm_integrity_settings {
2031
  char mode[8];
2032
  uint32_t tag_size;
2033
  uint32_t block_size;       /* optional table param always set by lvm */
2034
  const char *internal_hash; /* optional table param always set by lvm */
2035
2036
  uint32_t journal_sectors;
2037
  uint32_t interleave_sectors;
2038
  uint32_t buffer_sectors;
2039
  uint32_t journal_watermark;
2040
  uint32_t commit_time;
2041
  uint32_t bitmap_flush_interval;
2042
  uint64_t sectors_per_bit;
2043
  uint32_t allow_discards;
2044
2045
  unsigned journal_sectors_set:1;
2046
  unsigned interleave_sectors_set:1;
2047
  unsigned buffer_sectors_set:1;
2048
  unsigned journal_watermark_set:1;
2049
  unsigned commit_time_set:1;
2050
  unsigned bitmap_flush_interval_set:1;
2051
  unsigned sectors_per_bit_set:1;
2052
  unsigned allow_discards_set:1;
2053
};
2054
2055
int dm_tree_node_add_integrity_target(struct dm_tree_node *node,
2056
        uint64_t size,
2057
        const char *origin_uuid,
2058
        const char *meta_uuid,
2059
        struct dm_integrity_settings *settings,
2060
        int recalculate);
2061
2062
/*
2063
 * VDO target support
2064
 */
2065
2066
#define DM_SECTOR_SHIFT 9L
2067
2068
#define DM_VDO_BLOCK_SIZE     UINT64_C(8)   // 4KiB in sectors
2069
#define DM_VDO_BLOCK_SIZE_KB      (DM_VDO_BLOCK_SIZE << DM_SECTOR_SHIFT)
2070
2071
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MINIMUM_MB  (128)     // 128MiB
2072
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MAXIMUM_MB  (16 * 1024 * 1024 - 1)  /* 16TiB - 1MiB */
2073
#define DM_VDO_BLOCK_MAP_CACHE_SIZE_MINIMUM_PER_LOGICAL_THREAD  (4096 * DM_VDO_BLOCK_SIZE_KB)
2074
2075
#define DM_VDO_BLOCK_MAP_ERA_LENGTH_MINIMUM 1
2076
#define DM_VDO_BLOCK_MAP_ERA_LENGTH_MAXIMUM 16380
2077
2078
#define DM_VDO_INDEX_MEMORY_SIZE_MINIMUM_MB 256     // 0.25 GiB
2079
#define DM_VDO_INDEX_MEMORY_SIZE_MAXIMUM_MB (1024 * 1024)   // 1TiB
2080
2081
#define DM_VDO_SLAB_SIZE_MINIMUM_MB   128     // 128MiB
2082
#define DM_VDO_SLAB_SIZE_MAXIMUM_MB   (32 * 1024)   // 32GiB
2083
#define DM_VDO_SLABS_MAXIMUM      8192
2084
2085
#define DM_VDO_LOGICAL_SIZE_MAXIMUM (UINT64_C(4) * 1024 * 1024 * 1024 * 1024 * 1024 >> DM_SECTOR_SHIFT) // 4PiB
2086
#define DM_VDO_PHYSICAL_SIZE_MAXIMUM  (UINT64_C(64) * DM_VDO_BLOCK_SIZE_KB * 1024 * 1024 * 1024 >> DM_SECTOR_SHIFT) // 256TiB
2087
2088
#define DM_VDO_ACK_THREADS_MINIMUM    0
2089
#define DM_VDO_ACK_THREADS_MAXIMUM    100
2090
2091
#define DM_VDO_BIO_THREADS_MINIMUM    1
2092
#define DM_VDO_BIO_THREADS_MAXIMUM    100
2093
2094
#define DM_VDO_BIO_ROTATION_MINIMUM   1
2095
#define DM_VDO_BIO_ROTATION_MAXIMUM   1024
2096
2097
#define DM_VDO_CPU_THREADS_MINIMUM    1
2098
#define DM_VDO_CPU_THREADS_MAXIMUM    100
2099
2100
#define DM_VDO_HASH_ZONE_THREADS_MINIMUM  0
2101
#define DM_VDO_HASH_ZONE_THREADS_MAXIMUM  100
2102
2103
#define DM_VDO_LOGICAL_THREADS_MINIMUM    0
2104
#define DM_VDO_LOGICAL_THREADS_MAXIMUM    60
2105
2106
#define DM_VDO_PHYSICAL_THREADS_MINIMUM   0
2107
#define DM_VDO_PHYSICAL_THREADS_MAXIMUM   16
2108
2109
#define DM_VDO_MAX_DISCARD_MINIMUM    1
2110
#define DM_VDO_MAX_DISCARD_MAXIMUM    (UINT32_MAX / (uint32_t)(DM_VDO_BLOCK_SIZE_KB))
2111
2112
enum dm_vdo_operating_mode {
2113
  DM_VDO_MODE_RECOVERING,
2114
  DM_VDO_MODE_READ_ONLY,
2115
  DM_VDO_MODE_NORMAL
2116
};
2117
2118
enum dm_vdo_compression_state {
2119
  DM_VDO_COMPRESSION_ONLINE,
2120
  DM_VDO_COMPRESSION_OFFLINE
2121
};
2122
2123
enum dm_vdo_index_state {
2124
  DM_VDO_INDEX_ERROR,
2125
  DM_VDO_INDEX_CLOSED,
2126
  DM_VDO_INDEX_OPENING,
2127
  DM_VDO_INDEX_CLOSING,
2128
  DM_VDO_INDEX_OFFLINE,
2129
  DM_VDO_INDEX_ONLINE,
2130
  DM_VDO_INDEX_UNKNOWN
2131
};
2132
2133
struct dm_vdo_status {
2134
  char *device;
2135
  enum dm_vdo_operating_mode operating_mode;
2136
  int recovering;
2137
  enum dm_vdo_index_state index_state;
2138
  enum dm_vdo_compression_state compression_state;
2139
  uint64_t used_blocks;
2140
  uint64_t total_blocks;
2141
};
2142
2143
#define DM_VDO_MAX_ERROR 256
2144
2145
struct dm_vdo_status_parse_result {
2146
  char error[DM_VDO_MAX_ERROR];
2147
  struct dm_vdo_status *status;
2148
};
2149
2150
enum dm_vdo_write_policy {
2151
  DM_VDO_WRITE_POLICY_AUTO = 0,
2152
  DM_VDO_WRITE_POLICY_SYNC,
2153
  DM_VDO_WRITE_POLICY_ASYNC,
2154
  DM_VDO_WRITE_POLICY_ASYNC_UNSAFE
2155
};
2156
2157
struct dm_vdo_target_params {
2158
  uint32_t minimum_io_size;       /* in sectors */
2159
  uint32_t block_map_cache_size_mb;
2160
  union {
2161
    uint32_t block_map_era_length;  /* format period */
2162
    uint32_t block_map_period;      /* supported alias */
2163
  };
2164
  uint32_t index_memory_size_mb;  /* format */
2165
2166
  uint32_t slab_size_mb;          /* format */
2167
2168
  uint32_t max_discard;
2169
  /* threads */
2170
  uint32_t ack_threads;
2171
  uint32_t bio_threads;
2172
  uint32_t bio_rotation;
2173
  uint32_t cpu_threads;
2174
  uint32_t hash_zone_threads;
2175
  uint32_t logical_threads;
2176
  uint32_t physical_threads;
2177
2178
  int use_compression;
2179
  int use_deduplication;
2180
  int use_metadata_hints;
2181
  int use_sparse_index;          /* format */
2182
2183
  /* write policy */
2184
  enum dm_vdo_write_policy write_policy;
2185
2186
  int use_kernel_format;         /* kernel direct format (added last for ABI compat) */
2187
};
2188
2189
int dm_vdo_validate_target_params(const struct dm_vdo_target_params *vtp,
2190
          uint64_t vdo_size);
2191
2192
int dm_tree_node_add_vdo_target(struct dm_tree_node *node,
2193
        uint64_t size,
2194
        uint32_t vdo_version,
2195
        const char *vdo_pool_name,
2196
        const char *data_uuid,
2197
        uint64_t data_size,
2198
        const struct dm_vdo_target_params *vtp);
2199
2200
int dm_vdo_parse_logical_size(const char *vdo_path, uint64_t *logical_blocks);
2201
2202
int dm_vdo_status_parse(struct dm_pool *mem, const char *input,
2203
      struct dm_vdo_status_parse_result *result);
2204
2205
struct dm_vdo_stats {
2206
  uint64_t physical_blocks;
2207
  uint64_t logical_blocks;
2208
  uint64_t bytes_per_physical_block;
2209
  uint64_t bytes_per_logical_block;
2210
  uint64_t data_blocks_used;
2211
  uint64_t overhead_blocks_used;
2212
  uint64_t logical_blocks_used;
2213
  uint64_t bios_in; /* write bios only (kernel: biosIn.write) */
2214
  uint64_t bios_out;  /* write bios only (kernel: biosOut.write) */
2215
  uint64_t bios_meta; /* write bios only (kernel: biosMeta.write) */
2216
  enum dm_vdo_operating_mode operating_mode;
2217
};
2218
2219
#define DM_VDO_STAT_FIELD_LEN 80
2220
2221
struct dm_vdo_stats_field {
2222
  char label[DM_VDO_STAT_FIELD_LEN];
2223
  char value[DM_VDO_STAT_FIELD_LEN];
2224
};
2225
2226
struct dm_vdo_stats_full {
2227
  struct dm_vdo_stats *stats;
2228
  unsigned field_count;
2229
  struct dm_vdo_stats_field fields[];
2230
};
2231
2232
#define DM_VDO_STATS_BASIC 0x0
2233
#define DM_VDO_STATS_FULL  0x1
2234
2235
struct dm_vdo_stats_full *dm_vdo_stats_parse(struct dm_pool *mem,
2236
               const char *stats_str,
2237
               unsigned flags);
2238
2239
/*
2240
 * FIXME Add individual cache policy pairs  <key> = value, like:
2241
 * int dm_tree_node_add_cache_policy_arg(struct dm_tree_node *dnode,
2242
 *              const char *key, uint64_t value);
2243
 */
2244
2245
/*
2246
 * Replicator operation mode
2247
 * Note: API for Replicator is not yet stable
2248
 */
2249
typedef enum dm_replicator_mode_e {
2250
  DM_REPLICATOR_SYNC,     /* Synchronous replication */
2251
  DM_REPLICATOR_ASYNC_WARN,   /* Warn if async replicator is slow */
2252
  DM_REPLICATOR_ASYNC_STALL,    /* Stall replicator if not fast enough */
2253
  DM_REPLICATOR_ASYNC_DROP,   /* Drop sites out of sync */
2254
  DM_REPLICATOR_ASYNC_FAIL,   /* Fail replicator if slow */
2255
  NUM_DM_REPLICATOR_MODES
2256
} dm_replicator_mode_t;
2257
2258
int dm_tree_node_add_replicator_target(struct dm_tree_node *node,
2259
               uint64_t size,
2260
               const char *rlog_uuid,
2261
               const char *rlog_type,
2262
               unsigned rsite_index,
2263
               dm_replicator_mode_t mode,
2264
               uint32_t async_timeout,
2265
               uint64_t fall_behind_data,
2266
               uint32_t fall_behind_ios);
2267
2268
int dm_tree_node_add_replicator_dev_target(struct dm_tree_node *node,
2269
             uint64_t size,
2270
             const char *replicator_uuid, /* Replicator control device */
2271
             uint64_t rdevice_index,
2272
             const char *rdev_uuid, /* Rimage device name/uuid */
2273
             unsigned rsite_index,
2274
             const char *slog_uuid,
2275
             uint32_t slog_flags,   /* Mirror log flags */
2276
             uint32_t slog_region_size);
2277
/* End of Replicator API */
2278
2279
/*
2280
 * FIXME: Defines below are based on kernel's dm-thin.c defines
2281
 * DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
2282
 * DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
2283
 */
2284
#define DM_THIN_MIN_DATA_BLOCK_SIZE (UINT32_C(128))
2285
#define DM_THIN_MAX_DATA_BLOCK_SIZE (UINT32_C(2097152))
2286
/*
2287
 * This does not match kernel THIN_METADATA_MAX_SECTORS (33292800 sectors).
2288
 * The correct formula is (UINT64_C(255) * ((1 << 14) - 64) * (4096 / (1 << 9)))
2289
 * but this older incorrect value (33161216) is used by crop_metadata logic
2290
 * (DEFAULT_THIN_POOL_MAX_METADATA_SIZE in defaults.h) and cannot be changed
2291
 * without breaking existing thin pool metadata cropping behavior.
2292
 */
2293
#define DM_THIN_MAX_METADATA_SIZE   (UINT64_C(255) * (1 << 14) * (4096 / (1 << 9)) - 256 * 1024)
2294
2295
int dm_tree_node_add_thin_pool_target(struct dm_tree_node *node,
2296
              uint64_t size,
2297
              uint64_t transaction_id,
2298
              const char *metadata_uuid,
2299
              const char *pool_uuid,
2300
              uint32_t data_block_size,
2301
              uint64_t low_water_mark,
2302
              unsigned skip_block_zeroing);
2303
2304
int dm_tree_node_add_thin_pool_target_v1(struct dm_tree_node *node,
2305
           uint64_t size,
2306
           uint64_t transaction_id,
2307
           const char *metadata_uuid,
2308
           const char *pool_uuid,
2309
           uint32_t data_block_size,
2310
           uint64_t low_water_mark,
2311
           unsigned skip_block_zeroing,
2312
           unsigned crop_metadata);
2313
2314
/* Supported messages for thin provision target */
2315
typedef enum dm_thin_message_e {
2316
  DM_THIN_MESSAGE_CREATE_SNAP,    /* device_id, origin_id */
2317
  DM_THIN_MESSAGE_CREATE_THIN,    /* device_id */
2318
  DM_THIN_MESSAGE_DELETE,     /* device_id */
2319
  DM_THIN_MESSAGE_SET_TRANSACTION_ID, /* current_id, new_id */
2320
  DM_THIN_MESSAGE_RESERVE_METADATA_SNAP,  /* target version >= 1.1 */
2321
  DM_THIN_MESSAGE_RELEASE_METADATA_SNAP,  /* target version >= 1.1 */
2322
} dm_thin_message_t;
2323
2324
int dm_tree_node_add_thin_pool_message(struct dm_tree_node *node,
2325
               dm_thin_message_t type,
2326
               uint64_t id1, uint64_t id2);
2327
2328
/*
2329
 * Set thin pool discard features
2330
 *   ignore      - Disable support for discards
2331
 *   no_passdown - Don't pass discards down to underlying data device,
2332
 *                 just remove the mapping
2333
 * Feature is available since version 1.1 of the thin target.
2334
 */
2335
int dm_tree_node_set_thin_pool_discard(struct dm_tree_node *node,
2336
               unsigned ignore,
2337
               unsigned no_passdown);
2338
/*
2339
 * Set error if no space, instead of queueing for thin pool.
2340
 */
2341
int dm_tree_node_set_thin_pool_error_if_no_space(struct dm_tree_node *node,
2342
             unsigned error_if_no_space);
2343
/* Start thin pool with metadata in read-only mode */
2344
int dm_tree_node_set_thin_pool_read_only(struct dm_tree_node *node,
2345
           unsigned read_only);
2346
/*
2347
 * Based on kernel's dm-thin.c MAX_DEV_ID ((1 << 24) - 1)
2348
 */
2349
#define DM_THIN_MAX_DEVICE_ID ((UINT32_C(1) << 24) - 1)
2350
int dm_tree_node_add_thin_target(struct dm_tree_node *node,
2351
         uint64_t size,
2352
         const char *pool_uuid,
2353
         uint32_t device_id);
2354
2355
int dm_tree_node_set_thin_external_origin(struct dm_tree_node *node,
2356
            const char *external_uuid);
2357
2358
void dm_tree_node_set_udev_flags(struct dm_tree_node *dnode, uint16_t udev_flags);
2359
2360
void dm_tree_node_set_presuspend_node(struct dm_tree_node *node,
2361
              struct dm_tree_node *presuspend_node);
2362
2363
int dm_tree_node_add_target_area(struct dm_tree_node *node,
2364
         const char *dev_name,
2365
         const char *uuid,
2366
         uint64_t offset);
2367
2368
/*
2369
 * Only for temporarily-missing raid devices where changes are tracked.
2370
 */
2371
int dm_tree_node_add_null_area(struct dm_tree_node *node, uint64_t offset);
2372
2373
/*
2374
 * Set readahead (in sectors) after loading the node.
2375
 */
2376
void dm_tree_node_set_read_ahead(struct dm_tree_node *dnode,
2377
         uint32_t read_ahead,
2378
         uint32_t read_ahead_flags);
2379
2380
/*
2381
 * Set node callback hook before de/activation.
2382
 * Callback is called before 'activation' of node for activation tree,
2383
 * or 'deactivation' of node for deactivation tree.
2384
 */
2385
typedef enum dm_node_callback_e {
2386
  DM_NODE_CALLBACK_PRELOADED,   /* Node has preload deps */
2387
  DM_NODE_CALLBACK_DEACTIVATED, /* Node is deactivated */
2388
} dm_node_callback_t;
2389
typedef int (*dm_node_callback_fn) (struct dm_tree_node *node,
2390
            dm_node_callback_t type, void *cb_data);
2391
void dm_tree_node_set_callback(struct dm_tree_node *dnode,
2392
             dm_node_callback_fn cb, void *cb_data);
2393
2394
void dm_tree_set_cookie(struct dm_tree_node *node, uint32_t cookie);
2395
uint32_t dm_tree_get_cookie(struct dm_tree_node *node);
2396
2397
/*****************************************************************************
2398
 * Library functions
2399
 *****************************************************************************/
2400
2401
/*******************
2402
 * Memory management
2403
 *******************/
2404
2405
/*
2406
 * Never use these functions directly - use the macros following instead.
2407
 */
2408
void *dm_malloc_wrapper(size_t s, const char *file, int line)
2409
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2410
void *dm_malloc_aligned_wrapper(size_t s, size_t a, const char *file, int line)
2411
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2412
void *dm_zalloc_wrapper(size_t s, const char *file, int line)
2413
  __attribute__((__malloc__)) __attribute__((__warn_unused_result__));
2414
void *dm_realloc_wrapper(void *p, unsigned int s, const char *file, int line)
2415
  __attribute__((__warn_unused_result__));
2416
void dm_free_wrapper(void *ptr);
2417
char *dm_strdup_wrapper(const char *str, const char *file, int line)
2418
  __attribute__((__warn_unused_result__));
2419
int dm_dump_memory_wrapper(void);
2420
void dm_bounds_check_wrapper(void);
2421
2422
0
#define dm_malloc(s) dm_malloc_wrapper((s), __FILE__, __LINE__)
2423
#define dm_malloc_aligned(s, a) dm_malloc_aligned_wrapper((s), (a),  __FILE__, __LINE__)
2424
0
#define dm_zalloc(s) dm_zalloc_wrapper((s), __FILE__, __LINE__)
2425
0
#define dm_strdup(s) dm_strdup_wrapper((s), __FILE__, __LINE__)
2426
0
#define dm_free(p) dm_free_wrapper(p)
2427
#define dm_realloc(p, s) dm_realloc_wrapper((p), (s), __FILE__, __LINE__)
2428
0
#define dm_dump_memory() dm_dump_memory_wrapper()
2429
0
#define dm_bounds_check() dm_bounds_check_wrapper()
2430
2431
/*
2432
 * The pool allocator is useful when you are going to allocate
2433
 * lots of memory, use the memory for a bit, and then free the
2434
 * memory in one go.  A surprising amount of code has this usage
2435
 * profile.
2436
 *
2437
 * You should think of the pool as an infinite, contiguous chunk
2438
 * of memory.  The front of this chunk of memory contains
2439
 * allocated objects, the second half is free.  dm_pool_alloc grabs
2440
 * the next 'size' bytes from the free half, in effect moving it
2441
 * into the allocated half.  This operation is very efficient.
2442
 *
2443
 * dm_pool_free frees the allocated object *and* all objects
2444
 * allocated after it.  It is important to note this semantic
2445
 * difference from malloc/free.  This is also extremely
2446
 * efficient, since a single dm_pool_free can dispose of a large
2447
 * complex object.
2448
 *
2449
 * dm_pool_destroy frees all allocated memory.
2450
 *
2451
 * eg, If you are building a binary tree in your program, and
2452
 * know that you are only ever going to insert into your tree,
2453
 * and not delete (eg, maintaining a symbol table for a
2454
 * compiler).  You can create yourself a pool, allocate the nodes
2455
 * from it, and when the tree becomes redundant call dm_pool_destroy
2456
 * (no nasty iterating through the tree to free nodes).
2457
 *
2458
 * eg, On the other hand if you wanted to repeatedly insert and
2459
 * remove objects into the tree, you would be better off
2460
 * allocating the nodes from a free list; you cannot free a
2461
 * single arbitrary node with pool.
2462
 */
2463
2464
struct dm_pool;
2465
2466
/* constructor and destructor */
2467
struct dm_pool *dm_pool_create(const char *name, size_t chunk_hint)
2468
  __attribute__((__warn_unused_result__));
2469
void dm_pool_destroy(struct dm_pool *p);
2470
2471
/* simple allocation/free routines */
2472
void *dm_pool_alloc(struct dm_pool *p, size_t s)
2473
  __attribute__((__warn_unused_result__));
2474
void *dm_pool_alloc_aligned(struct dm_pool *p, size_t s, unsigned alignment)
2475
  __attribute__((__warn_unused_result__));
2476
void dm_pool_empty(struct dm_pool *p);
2477
void dm_pool_free(struct dm_pool *p, void *ptr);
2478
2479
/*
2480
 * To aid debugging, a pool can be locked. Any modifications made
2481
 * to the content of the pool while it is locked can be detected.
2482
 * Default compilation is using a crc checksum to notice modifications.
2483
 * The pool locking is using the mprotect with the compilation flag
2484
 * DEBUG_ENFORCE_POOL_LOCKING to enforce the memory protection.
2485
 */
2486
/* query pool lock status */
2487
int dm_pool_locked(struct dm_pool *p);
2488
/* mark pool as locked */
2489
int dm_pool_lock(struct dm_pool *p, int crc)
2490
  __attribute__((__warn_unused_result__));
2491
/* mark pool as unlocked */
2492
int dm_pool_unlock(struct dm_pool *p, int crc)
2493
  __attribute__((__warn_unused_result__));
2494
2495
/*
2496
 * Object building routines:
2497
 *
2498
 * These allow you to 'grow' an object, useful for
2499
 * building strings, or filling in dynamic
2500
 * arrays.
2501
 *
2502
 * It's probably best explained with an example:
2503
 *
2504
 * char *build_string(struct dm_pool *mem)
2505
 * {
2506
 *      int i;
2507
 *      char buffer[16];
2508
 *
2509
 *      if (!dm_pool_begin_object(mem, 128))
2510
 *              return NULL;
2511
 *
2512
 *      for (i = 0; i < 50; i++) {
2513
 *              snprintf(buffer, sizeof(buffer), "%d, ", i);
2514
 *              if (!dm_pool_grow_object(mem, buffer, 0))
2515
 *                      goto bad;
2516
 *      }
2517
 *
2518
 *  // add null
2519
 *      if (!dm_pool_grow_object(mem, "\0", 1))
2520
 *              goto bad;
2521
 *
2522
 *      return dm_pool_end_object(mem);
2523
 *
2524
 * bad:
2525
 *
2526
 *      dm_pool_abandon_object(mem);
2527
 *      return NULL;
2528
 *}
2529
 *
2530
 * So start an object by calling dm_pool_begin_object
2531
 * with a guess at the final object size - if in
2532
 * doubt make the guess too small.
2533
 *
2534
 * Then append chunks of data to your object with
2535
 * dm_pool_grow_object.  Finally get your object with
2536
 * a call to dm_pool_end_object.
2537
 *
2538
 * Setting delta to 0 means it will use strlen(extra).
2539
 */
2540
int dm_pool_begin_object(struct dm_pool *p, size_t hint);
2541
int dm_pool_grow_object(struct dm_pool *p, const void *extra, size_t delta);
2542
void *dm_pool_end_object(struct dm_pool *p);
2543
void dm_pool_abandon_object(struct dm_pool *p);
2544
2545
/* utilities */
2546
char *dm_pool_strdup(struct dm_pool *p, const char *str)
2547
  __attribute__((__warn_unused_result__));
2548
char *dm_pool_strndup(struct dm_pool *p, const char *str, size_t n)
2549
  __attribute__((__warn_unused_result__));
2550
void *dm_pool_zalloc(struct dm_pool *p, size_t s)
2551
  __attribute__((__warn_unused_result__));
2552
2553
/******************
2554
 * bitset functions
2555
 ******************/
2556
2557
typedef uint32_t *dm_bitset_t;
2558
2559
dm_bitset_t dm_bitset_create(struct dm_pool *mem, unsigned num_bits);
2560
void dm_bitset_destroy(dm_bitset_t bs);
2561
2562
int dm_bitset_equal(dm_bitset_t in1, dm_bitset_t in2);
2563
2564
void dm_bit_and(dm_bitset_t out, dm_bitset_t in1, dm_bitset_t in2);
2565
void dm_bit_union(dm_bitset_t out, dm_bitset_t in1, dm_bitset_t in2);
2566
int dm_bit_get_first(dm_bitset_t bs);
2567
int dm_bit_get_next(dm_bitset_t bs, int last_bit);
2568
int dm_bit_get_last(dm_bitset_t bs);
2569
int dm_bit_get_prev(dm_bitset_t bs, int last_bit);
2570
2571
0
#define DM_BITS_PER_INT ((unsigned)sizeof(int) * CHAR_BIT)
2572
2573
#define dm_bit(bs, i) \
2574
0
   ((bs)[((i) / DM_BITS_PER_INT) + 1] & (0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2575
2576
#define dm_bit_set(bs, i) \
2577
0
   ((bs)[((i) / DM_BITS_PER_INT) + 1] |= (0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2578
2579
#define dm_bit_clear(bs, i) \
2580
   ((bs)[((i) / DM_BITS_PER_INT) + 1] &= ~(0x1U << ((i) & (DM_BITS_PER_INT - 1))))
2581
2582
#define dm_bit_set_all(bs) \
2583
   memset((bs) + 1, -1, ((*(bs) / DM_BITS_PER_INT) + 1) * sizeof(int))
2584
2585
#define dm_bit_clear_all(bs) \
2586
   memset((bs) + 1, 0, ((*(bs) / DM_BITS_PER_INT) + 1) * sizeof(int))
2587
2588
#define dm_bit_copy(bs1, bs2) \
2589
   memcpy((bs1) + 1, (bs2) + 1, ((*(bs2) / DM_BITS_PER_INT) + 1) * sizeof(int))
2590
2591
/*
2592
 * Parse a string representation of a bitset into a dm_bitset_t. The
2593
 * notation used is identical to the kernel bitmap parser (cpuset etc.)
2594
 * and supports both lists ("1,2,3") and ranges ("1-2,5-8"). If the mem
2595
 * parameter is NULL memory for the bitset will be allocated using
2596
 * dm_malloc(). Otherwise the bitset will be allocated using the supplied
2597
 * dm_pool.
2598
 */
2599
dm_bitset_t dm_bitset_parse_list(const char *str, struct dm_pool *mem,
2600
         size_t min_num_bits);
2601
2602
/* Returns number of set bits */
2603
static inline unsigned hweight32(uint32_t i)
2604
0
{
2605
0
  unsigned r = (i & 0x55555555) + ((i >> 1) & 0x55555555);
2606
0
2607
0
  r =    (r & 0x33333333) + ((r >>  2) & 0x33333333);
2608
0
  r =    (r & 0x0F0F0F0F) + ((r >>  4) & 0x0F0F0F0F);
2609
0
  r =    (r & 0x00FF00FF) + ((r >>  8) & 0x00FF00FF);
2610
0
  return (r & 0x0000FFFF) + ((r >> 16) & 0x0000FFFF);
2611
0
}
Unexecuted instantiation: libdm-common.c:hweight32
Unexecuted instantiation: libdm-file.c:hweight32
Unexecuted instantiation: libdm-string.c:hweight32
Unexecuted instantiation: dbg_malloc.c:hweight32
Unexecuted instantiation: pool.c:hweight32
Unexecuted instantiation: libdm-iface.c:hweight32
Unexecuted instantiation: bitset.c:hweight32
Unexecuted instantiation: list.c:hweight32
Unexecuted instantiation: libdm-timestamp.c:hweight32
2612
2613
/****************
2614
 * hash functions
2615
 ****************/
2616
2617
struct dm_hash_table;
2618
struct dm_hash_node;
2619
2620
typedef void (*dm_hash_iterate_fn) (void *data);
2621
2622
struct dm_hash_table *dm_hash_create(unsigned size_hint)
2623
  __attribute__((__warn_unused_result__));
2624
void dm_hash_destroy(struct dm_hash_table *t);
2625
void dm_hash_wipe(struct dm_hash_table *t);
2626
2627
void *dm_hash_lookup(struct dm_hash_table *t, const char *key);
2628
int dm_hash_insert(struct dm_hash_table *t, const char *key, void *data);
2629
void dm_hash_remove(struct dm_hash_table *t, const char *key);
2630
2631
void *dm_hash_lookup_binary(struct dm_hash_table *t, const void *key, uint32_t len);
2632
int dm_hash_insert_binary(struct dm_hash_table *t, const void *key, uint32_t len,
2633
        void *data);
2634
void dm_hash_remove_binary(struct dm_hash_table *t, const void *key, uint32_t len);
2635
2636
unsigned dm_hash_get_num_entries(struct dm_hash_table *t);
2637
void dm_hash_iter(struct dm_hash_table *t, dm_hash_iterate_fn f);
2638
2639
char *dm_hash_get_key(struct dm_hash_table *t, struct dm_hash_node *n);
2640
void *dm_hash_get_data(struct dm_hash_table *t, struct dm_hash_node *n);
2641
struct dm_hash_node *dm_hash_get_first(struct dm_hash_table *t);
2642
struct dm_hash_node *dm_hash_get_next(struct dm_hash_table *t, struct dm_hash_node *n);
2643
2644
/*
2645
 * dm_hash_insert() replaces the value of an existing
2646
 * entry with a matching key if one exists.  Otherwise
2647
 * it adds a new entry.
2648
 *
2649
 * dm_hash_insert_with_val() inserts a new entry if
2650
 * another entry with the same key already exists.
2651
 * val_len is the size of the data being inserted.
2652
 *
2653
 * If two entries with the same key exist,
2654
 * (added using dm_hash_insert_allow_multiple), then:
2655
 * . dm_hash_lookup() returns the first one it finds, and
2656
 *   dm_hash_lookup_with_val() returns the one with a matching
2657
 *   val_len/val.
2658
 * . dm_hash_remove() removes the first one it finds, and
2659
 *   dm_hash_remove_with_val() removes the one with a matching
2660
 *   val_len/val.
2661
 *
2662
 * If a single entry with a given key exists, and it has
2663
 * zero val_len, then:
2664
 * . dm_hash_lookup() returns it
2665
 * . dm_hash_lookup_with_val(val_len=0) returns it
2666
 * . dm_hash_remove() removes it
2667
 * . dm_hash_remove_with_val(val_len=0) removes it
2668
 *
2669
 * dm_hash_lookup_with_count() is a single call that will
2670
 * both lookup a key's value and check if there is more
2671
 * than one entry with the given key.
2672
 *
2673
 * (It is not meant to retrieve all the entries with the
2674
 * given key.  In the common case where a single entry exists
2675
 * for the key, it is useful to have a single call that will
2676
 * both look up the value and indicate if multiple values
2677
 * exist for the key.)
2678
 *
2679
 * dm_hash_lookup_with_count:
2680
 * . If no entries exist, the function returns NULL, and
2681
 *   the count is set to 0.
2682
 * . If only one entry exists, the value of that entry is
2683
 *   returned and count is set to 1.
2684
 * . If N entries exists, the value of the first entry is
2685
 *   returned and count is set to N.
2686
 */
2687
2688
void *dm_hash_lookup_with_val(struct dm_hash_table *t, const char *key,
2689
            const void *val, uint32_t val_len);
2690
void dm_hash_remove_with_val(struct dm_hash_table *t, const char *key,
2691
           const void *val, uint32_t val_len);
2692
int dm_hash_insert_allow_multiple(struct dm_hash_table *t, const char *key,
2693
          const void *val, uint32_t val_len);
2694
void *dm_hash_lookup_with_count(struct dm_hash_table *t, const char *key, int *count);
2695
2696
2697
#define dm_hash_iterate(v, h) \
2698
  for (v = dm_hash_get_first((h)); v; \
2699
       v = dm_hash_get_next((h), v))
2700
2701
/****************
2702
 * list functions
2703
 ****************/
2704
2705
/*
2706
 * A list consists of a list head plus elements.
2707
 * Each element has 'next' and 'previous' pointers.
2708
 * The list head's pointers point to the first and the last element.
2709
 */
2710
2711
struct dm_list {
2712
  struct dm_list *n, *p;
2713
};
2714
2715
/*
2716
 * String list.
2717
 */
2718
struct dm_str_list {
2719
  struct dm_list list;
2720
  const char *str;
2721
};
2722
2723
/*
2724
 * Active device element returned dm_task_get_device_list()
2725
 * Only for accessing structure members.
2726
 * Do NOT allocate this structure locally.
2727
 * More elements can be added later (with DM_DEVICE_LIST_HAS_FLAG).
2728
 */
2729
struct dm_active_device {
2730
  struct dm_list list;
2731
  dev_t devno;
2732
  const char *name; /* device name */
2733
2734
  uint32_t event_nr;  /* valid when DM_DEVICE_LIST_HAS_EVENT_NR is set */
2735
  const char *uuid; /* valid uuid when DM_DEVICE_LIST_HAS_UUID is set */
2736
};
2737
2738
/*
2739
 * Initialise a list before use.
2740
 * The list head's next and previous pointers point back to itself.
2741
 */
2742
#define DM_LIST_HEAD_INIT(name)  { &(name), &(name) }
2743
#define DM_LIST_INIT(name)  struct dm_list name = DM_LIST_HEAD_INIT(name)
2744
void dm_list_init(struct dm_list *head);
2745
2746
/*
2747
 * Insert an element before 'head'.
2748
 * If 'head' is the list head, this adds an element to the end of the list.
2749
 */
2750
void dm_list_add(struct dm_list *head, struct dm_list *elem);
2751
2752
/*
2753
 * Insert an element after 'head'.
2754
 * If 'head' is the list head, this adds an element to the front of the list.
2755
 */
2756
void dm_list_add_h(struct dm_list *head, struct dm_list *elem);
2757
2758
/*
2759
 * Delete an element from its list.
2760
 * Note that this doesn't change the element itself - it may still be safe
2761
 * to follow its pointers.
2762
 */
2763
void dm_list_del(struct dm_list *elem);
2764
2765
/*
2766
 * Remove an element from existing list and insert before 'head'.
2767
 */
2768
void dm_list_move(struct dm_list *head, struct dm_list *elem);
2769
2770
/*
2771
 * Join 'head1' to the end of 'head'.
2772
 */
2773
void dm_list_splice(struct dm_list *head, struct dm_list *head1);
2774
2775
/*
2776
 * Is the list empty?
2777
 */
2778
int dm_list_empty(const struct dm_list *head);
2779
2780
/*
2781
 * Is this the first element of the list?
2782
 */
2783
int dm_list_start(const struct dm_list *head, const struct dm_list *elem);
2784
2785
/*
2786
 * Is this the last element of the list?
2787
 */
2788
int dm_list_end(const struct dm_list *head, const struct dm_list *elem);
2789
2790
/*
2791
 * Return first element of the list or NULL if empty
2792
 */
2793
struct dm_list *dm_list_first(const struct dm_list *head);
2794
2795
/*
2796
 * Return last element of the list or NULL if empty
2797
 */
2798
struct dm_list *dm_list_last(const struct dm_list *head);
2799
2800
/*
2801
 * Return the previous element of the list, or NULL if we've reached the start.
2802
 */
2803
struct dm_list *dm_list_prev(const struct dm_list *head, const struct dm_list *elem);
2804
2805
/*
2806
 * Return the next element of the list, or NULL if we've reached the end.
2807
 */
2808
struct dm_list *dm_list_next(const struct dm_list *head, const struct dm_list *elem);
2809
2810
/*
2811
 * Given the address v of an instance of 'struct dm_list' called 'head'
2812
 * contained in a structure of type t, return the containing structure.
2813
 */
2814
#define dm_list_struct_base(v, t, head) \
2815
0
    ((t *)((char *)(v) - offsetof(t, head)))
2816
2817
/*
2818
 * Given the address v of an instance of 'struct dm_list list' contained in
2819
 * a structure of type t, return the containing structure.
2820
 */
2821
0
#define dm_list_item(v, t) dm_list_struct_base((v), t, list)
2822
2823
/*
2824
 * Given the address v of one known element e in a known structure of type t,
2825
 * return another element f.
2826
 */
2827
#define dm_struct_field(v, t, e, f) \
2828
    (((t *)((uintptr_t)(v) - offsetof(t, e)))->f)
2829
2830
/*
2831
 * Given the address v of a known element e in a known structure of type t,
2832
 * return the list head 'list'
2833
 */
2834
#define dm_list_head(v, t, e) dm_struct_field(v, t, e, list)
2835
2836
/*
2837
 * Set v to each element of a list in turn.
2838
 */
2839
#define dm_list_iterate(v, head) \
2840
0
  for (v = (head)->n; v != head; v = v->n)
2841
2842
/*
2843
 * Set v to each element in a list in turn, starting from the element
2844
 * in front of 'start'.
2845
 * You can use this to 'unwind' a list_iterate and back out actions on
2846
 * already-processed elements.
2847
 * If 'start' is 'head' it walks the list backwards.
2848
 */
2849
#define dm_list_uniterate(v, head, start) \
2850
  for (v = (start)->p; v != head; v = v->p)
2851
2852
/*
2853
 * A safe way to walk a list and delete and free some elements along
2854
 * the way.
2855
 * t must be defined as a temporary variable of the same type as v.
2856
 */
2857
#define dm_list_iterate_safe(v, t, head) \
2858
0
  for (v = (head)->n, t = v->n; v != head; v = t, t = v->n)
2859
2860
/*
2861
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2862
 * The containing structure should be the same type as 'v'.
2863
 * The 'struct dm_list' variable within the containing structure is 'field'.
2864
 */
2865
#define dm_list_iterate_items_gen(v, head, field) \
2866
0
  for (v = dm_list_struct_base((head)->n, __typeof__(*v), field); \
2867
0
       &v->field != (head); \
2868
0
       v = dm_list_struct_base(v->field.n, __typeof__(*v), field))
2869
2870
/*
2871
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2872
 * The containing structure should be the same type as 'v'.
2873
 * The list should be 'struct dm_list list' within the containing structure.
2874
 */
2875
0
#define dm_list_iterate_items(v, head) dm_list_iterate_items_gen(v, (head), list)
2876
2877
/*
2878
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2879
 * The containing structure should be the same type as 'v'.
2880
 * The 'struct dm_list' variable within the containing structure is 'field'.
2881
 * t must be defined as a temporary variable of the same type as v.
2882
 */
2883
#define dm_list_iterate_items_gen_safe(v, t, head, field) \
2884
  for (v = dm_list_struct_base((head)->n, __typeof__(*v), field), \
2885
       t = dm_list_struct_base(v->field.n, __typeof__(*v), field); \
2886
       &v->field != (head); \
2887
       v = t, t = dm_list_struct_base(v->field.n, __typeof__(*v), field))
2888
/*
2889
 * Walk a list, setting 'v' in turn to the containing structure of each item.
2890
 * The containing structure should be the same type as 'v'.
2891
 * The list should be 'struct dm_list list' within the containing structure.
2892
 * t must be defined as a temporary variable of the same type as v.
2893
 */
2894
#define dm_list_iterate_items_safe(v, t, head) \
2895
  dm_list_iterate_items_gen_safe(v, t, (head), list)
2896
2897
/*
2898
 * Walk a list backwards, setting 'v' in turn to the containing structure
2899
 * of each item.
2900
 * The containing structure should be the same type as 'v'.
2901
 * The 'struct dm_list' variable within the containing structure is 'field'.
2902
 */
2903
#define dm_list_iterate_back_items_gen(v, head, field) \
2904
  for (v = dm_list_struct_base((head)->p, __typeof__(*v), field); \
2905
       &v->field != (head); \
2906
       v = dm_list_struct_base(v->field.p, __typeof__(*v), field))
2907
2908
/*
2909
 * Walk a list backwards, setting 'v' in turn to the containing structure
2910
 * of each item.
2911
 * The containing structure should be the same type as 'v'.
2912
 * The list should be 'struct dm_list list' within the containing structure.
2913
 */
2914
#define dm_list_iterate_back_items(v, head) dm_list_iterate_back_items_gen(v, (head), list)
2915
2916
/*
2917
 * Return the number of elements in a list by walking it.
2918
 */
2919
unsigned int dm_list_size(const struct dm_list *head);
2920
2921
/*
2922
 * Retrieve the list of devices and put them into easily accessible
2923
 * struct dm_active_device list elements.
2924
 * devs_features provides flag-set with used features so it's easy to check
2925
 * whether the kernel provides i.e. UUID info together with DM names
2926
 */
2927
0
#define DM_DEVICE_LIST_HAS_EVENT_NR 1
2928
0
#define DM_DEVICE_LIST_HAS_UUID   2
2929
int dm_task_get_device_list(struct dm_task *dmt, struct dm_list **devs_list,
2930
          unsigned *devs_features);
2931
/* Release all associated memory with list of active DM devices */
2932
void dm_device_list_destroy(struct dm_list **devs_list);
2933
/*
2934
 * Compare two dm_list structures containing dm_active_device elements.
2935
 * Returns 1 if both lists contain identical devices (same devno and uuid in same order),
2936
 * 0 if lists differ.
2937
 */
2938
int dm_device_list_equal(const struct dm_list *list1, const struct dm_list *list2);
2939
2940
/*********
2941
 * selinux
2942
 *********/
2943
2944
/*
2945
 * Obtain SELinux security context assigned for the path and set this
2946
 * context for creating a new file system object. This security context
2947
 * is global and it is used until reset to default policy behaviour
2948
 * by calling 'dm_prepare_selinux_context(NULL, 0)'.
2949
 */
2950
int dm_prepare_selinux_context(const char *path, mode_t mode);
2951
/*
2952
 * Set SELinux context for existing file system object.
2953
 */
2954
int dm_set_selinux_context(const char *path, mode_t mode);
2955
2956
/*********************
2957
 * string manipulation
2958
 *********************/
2959
2960
/*
2961
 * Break up the name of a mapped device into its constituent
2962
 * Volume Group, Logical Volume and Layer (if present).
2963
 * If mem is supplied, the result is allocated from the mempool.
2964
 * Otherwise the strings are changed in situ.
2965
 */
2966
int dm_split_lvm_name(struct dm_pool *mem, const char *dmname,
2967
          char **vgname, char **lvname, char **layer);
2968
2969
/*
2970
 * Destructively split buffer into NULL-separated words in argv.
2971
 * Returns number of words.
2972
 */
2973
int dm_split_words(char *buffer, unsigned max,
2974
       unsigned ignore_comments, /* Not implemented */
2975
       char **argv);
2976
2977
/*
2978
 * Returns -1 if buffer too small
2979
 */
2980
int dm_snprintf(char *buf, size_t bufsize, const char *format, ...)
2981
    __attribute__ ((format(printf, 3, 4)));
2982
2983
/*
2984
 * Returns pointer to the last component of the path.
2985
 */
2986
const char *dm_basename(const char *path);
2987
2988
/*
2989
 * Returns number of occurrences of 'c' in 'str' of length 'size'.
2990
 */
2991
unsigned dm_count_chars(const char *str, size_t len, const int c);
2992
2993
/*
2994
 * Length of string after escaping double quotes and backslashes.
2995
 */
2996
size_t dm_escaped_len(const char *str);
2997
2998
/*
2999
 * <vg>-<lv>-<layer> or if !layer just <vg>-<lv>.
3000
 */
3001
char *dm_build_dm_name(struct dm_pool *mem, const char *vgname,
3002
           const char *lvname, const char *layer);
3003
char *dm_build_dm_uuid(struct dm_pool *mem, const char *uuid_prefix, const char *lvid, const char *layer);
3004
3005
/*
3006
 * Copies a string, quoting double quotes with backslashes.
3007
 */
3008
char *dm_escape_double_quotes(char *out, const char *src);
3009
3010
/*
3011
 * Undo quoting in situ.
3012
 */
3013
void dm_unescape_double_quotes(char *src);
3014
3015
/*
3016
 * Unescape colons and "at" signs in situ and save the substrings
3017
 * starting at the position of the first unescaped colon and the
3018
 * first unescaped "at" sign. This is normally used to unescape
3019
 * device names used as PVs.
3020
 */
3021
void dm_unescape_colons_and_at_signs(char *src,
3022
             char **substr_first_unquoted_colon,
3023
             char **substr_first_unquoted_at_sign);
3024
3025
/*
3026
 * Replacement for strncpy() function.
3027
 *
3028
 * Copies no more than n bytes from string pointed by src to the buffer
3029
 * pointed by dest and ensure string is finished with '\0'.
3030
 * Returns 0 if the whole string does not fit.
3031
 */
3032
int dm_strncpy(char *dest, const char *src, size_t n);
3033
3034
/*
3035
 * Recognize unit specifier in the 'units' arg and return a factor
3036
 * representing that unit. If the 'units' contains a prefix with digits,
3037
 * the 'units' is considered to be a custom unit.
3038
 *
3039
 * Also, set 'unit_type' output arg to the character that represents
3040
 * the unit specified. The 'unit_type' character equals to the unit
3041
 * character itself recognized in the 'units' arg for canonical units.
3042
 * Otherwise, the 'unit_type' character is set to 'U' for custom unit.
3043
 *
3044
 * An example for k/K canonical units and 8k/8K custom units:
3045
 *
3046
 *   units  unit_type  return value (factor)
3047
 *   k      k          1024
3048
 *   K      K          1000
3049
 *   8k     U          1024*8
3050
 *   8K     U          1000*8
3051
 *   etc...
3052
 *
3053
 * Recognized units:
3054
 *
3055
 *   h/H - human readable (returns 1 for both)
3056
 *   b/B - byte (returns 1 for both)
3057
 *   s/S - sector (returns 512 for both)
3058
 *   k/K - kilo (returns 1024/1000 respectively)
3059
 *   m/M - mega (returns 1024^2/1000^2 respectively)
3060
 *   g/G - giga (returns 1024^3/1000^3 respectively)
3061
 *   t/T - tera (returns 1024^4/1000^4 respectively)
3062
 *   p/P - peta (returns 1024^5/1000^5 respectively)
3063
 *   e/E - exa (returns 1024^6/1000^6 respectively)
3064
 *
3065
 * Only one units character is allowed in the 'units' arg
3066
 * if strict mode is enabled by 'strict' arg.
3067
 *
3068
 * The 'endptr' output arg, if not NULL, saves the pointer
3069
 * in the 'units' string which follows the unit specifier
3070
 * recognized (IOW the position where the parsing of the
3071
 * unit specifier stopped).
3072
 *
3073
 * Returns the unit factor or 0 if no unit is recognized.
3074
 */
3075
uint64_t dm_units_to_factor(const char *units, char *unit_type,
3076
          int strict, const char **endptr);
3077
3078
/*
3079
 * Type of unit specifier used by dm_size_to_string().
3080
 */
3081
typedef enum dm_size_suffix_e {
3082
  DM_SIZE_LONG = 0, /* Megabyte */
3083
  DM_SIZE_SHORT = 1,  /* MB or MiB */
3084
  DM_SIZE_UNIT = 2  /* M or m */
3085
} dm_size_suffix_t;
3086
3087
/*
3088
 * Convert a size (in 512-byte sectors) into a printable string using units of unit_type.
3089
 * An upper-case unit_type indicates output units based on powers of 1000 are
3090
 * required; a lower-case unit_type indicates powers of 1024.
3091
 * For correct operation, unit_factor must be one of:
3092
 *  0 - the correct value will be calculated internally;
3093
 *   or the output from dm_units_to_factor() corresponding to unit_type;
3094
 *   or 'u' or 'U', an arbitrary number of bytes to use as the power base.
3095
 * Set include_suffix to 1 to include a suffix of suffix_type.
3096
 * Set use_si_units to 0 for suffixes that don't distinguish between 1000 and 1024.
3097
 * Set use_si_units to 1 for a suffix that does distinguish.
3098
 */
3099
const char *dm_size_to_string(struct dm_pool *mem, uint64_t size,
3100
            char unit_type, int use_si_units,
3101
            uint64_t unit_factor, int include_suffix,
3102
            dm_size_suffix_t suffix_type);
3103
3104
/**************************
3105
 * file/stream manipulation
3106
 **************************/
3107
3108
/*
3109
 * Create a directory (with parent directories if necessary).
3110
 * Returns 1 on success, 0 on failure.
3111
 */
3112
int dm_create_dir(const char *dir);
3113
3114
int dm_is_empty_dir(const char *dir);
3115
3116
/*
3117
 * Close a stream, with nicer error checking than fclose's.
3118
 * Derived from gnulib's close-stream.c.
3119
 *
3120
 * Close "stream".  Return 0 if successful, and EOF (setting errno)
3121
 * otherwise.  Upon failure, set errno to 0 if the error number
3122
 * cannot be determined.  Useful mainly for writable streams.
3123
 */
3124
int dm_fclose(FILE *stream);
3125
3126
/*
3127
 * Returns size of a buffer which is allocated with dm_malloc.
3128
 * Pointer to the buffer is stored in *buf.
3129
 * Returns -1 on failure leaving buf undefined.
3130
 */
3131
int dm_asprintf(char **result, const char *format, ...)
3132
    __attribute__ ((format(printf, 2, 3)));
3133
int dm_vasprintf(char **result, const char *format, va_list aq)
3134
    __attribute__ ((format(printf, 2, 0)));
3135
3136
/*
3137
 * create lockfile (pidfile) - create and lock a lock file
3138
 * @lockfile: location of lock file
3139
 *
3140
 * Returns: 1 on success, 0 otherwise, errno is handled internally
3141
 */
3142
int dm_create_lockfile(const char* lockfile);
3143
3144
/*
3145
 * Query whether a daemon is running based on its lockfile
3146
 *
3147
 * Returns: 1 if running, 0 if not
3148
 */
3149
int dm_daemon_is_running(const char* lockfile);
3150
3151
/*********************
3152
 * regular expressions
3153
 *********************/
3154
struct dm_regex;
3155
3156
/*
3157
 * Initialise an array of num patterns for matching.
3158
 * Uses memory from mem.
3159
 */
3160
struct dm_regex *dm_regex_create(struct dm_pool *mem, const char * const *patterns,
3161
         unsigned num_patterns);
3162
3163
/*
3164
 * Match string s against the patterns.
3165
 * Returns the index of the highest pattern in the array that matches,
3166
 * or -1 if none match.
3167
 */
3168
int dm_regex_match(struct dm_regex *regex, const char *s);
3169
3170
/*
3171
 * This is useful for regression testing only.  The idea is if two
3172
 * fingerprints are different, then the two dfas are certainly not
3173
 * isomorphic.  If two fingerprints _are_ the same then it's very likely
3174
 * that the dfas are isomorphic.
3175
 *
3176
 * This function must be called before any matching is done.
3177
 */
3178
uint32_t dm_regex_fingerprint(struct dm_regex *regex);
3179
3180
/******************
3181
 * percent handling
3182
 ******************/
3183
/*
3184
 * A fixed-point representation of percent values. One percent equals to
3185
 * DM_PERCENT_1 as defined below. Values that are not multiples of DM_PERCENT_1
3186
 * represent fractions, with precision of 1/1000000 of a percent. See
3187
 * dm_percent_to_float for a conversion to a floating-point representation.
3188
 *
3189
 * You should always use dm_make_percent when building dm_percent_t values. The
3190
 * implementation of dm_make_percent is biased towards the middle: it ensures that
3191
 * the result is DM_PERCENT_0 or DM_PERCENT_100 if and only if this is the actual
3192
 * value -- it never rounds any intermediate value (> 0 or < 100) to either 0
3193
 * or 100.
3194
*/
3195
#define DM_PERCENT_CHAR '%'
3196
3197
typedef enum dm_percent_range_e {
3198
  DM_PERCENT_0 = 0,
3199
  DM_PERCENT_1 = 1000000,
3200
  DM_PERCENT_100 = 100 * DM_PERCENT_1,
3201
  DM_PERCENT_INVALID = -1,
3202
  DM_PERCENT_FAILED = -2
3203
} dm_percent_range_t;
3204
3205
typedef int32_t dm_percent_t;
3206
3207
float dm_percent_to_float(dm_percent_t percent);
3208
/*
3209
 * Return adjusted/rounded float for better percent value printing.
3210
 * Function ensures for given precision of digits:
3211
 * 100.0% returns only when the value is DM_PERCENT_100
3212
 *        for close smaller values rounds to nearest smaller value
3213
 * 0.0% returns only for value DM_PERCENT_0
3214
 *        for close bigger values rounds to nearest bigger value
3215
 * In all other cases returns same value as dm_percent_to_float()
3216
 */
3217
float dm_percent_to_round_float(dm_percent_t percent, unsigned digits);
3218
dm_percent_t dm_make_percent(uint64_t numerator, uint64_t denominator);
3219
3220
/********************
3221
 * timestamp handling
3222
 ********************/
3223
3224
/*
3225
 * Create a dm_timestamp object to use with dm_timestamp_get.
3226
 */
3227
struct dm_timestamp *dm_timestamp_alloc(void);
3228
3229
/*
3230
 * Update dm_timestamp object to represent the current time.
3231
 */
3232
int dm_timestamp_get(struct dm_timestamp *ts);
3233
3234
/*
3235
 * Copy a timestamp from ts_old to ts_new.
3236
 */
3237
void dm_timestamp_copy(struct dm_timestamp *ts_new, struct dm_timestamp *ts_old);
3238
3239
/*
3240
 * Compare two timestamps.
3241
 *
3242
 * Return: -1 if ts1 is less than ts2
3243
 *        0 if ts1 is equal to ts2
3244
 *          1 if ts1 is greater than ts2
3245
 */
3246
int dm_timestamp_compare(struct dm_timestamp *ts1, struct dm_timestamp *ts2);
3247
3248
/*
3249
 * Return the absolute difference in nanoseconds between
3250
 * the dm_timestamp objects ts1 and ts2.
3251
 *
3252
 * Callers that need to know whether ts1 is before, equal to, or after ts2
3253
 * in addition to the magnitude should use dm_timestamp_compare.
3254
 */
3255
uint64_t dm_timestamp_delta(struct dm_timestamp *ts1, struct dm_timestamp *ts2);
3256
3257
/*
3258
 * Destroy a dm_timestamp object.
3259
 */
3260
void dm_timestamp_destroy(struct dm_timestamp *ts);
3261
3262
/*********************
3263
 * reporting functions
3264
 *********************/
3265
3266
struct dm_report_object_type {
3267
  uint32_t id;      /* Powers of 2 */
3268
  const char *desc;
3269
  const char *prefix;   /* field id string prefix (optional) */
3270
  /* FIXME: convert to proper usage of const pointers here */
3271
  void *(*data_fn)(void *object); /* callback from report_object() */
3272
};
3273
3274
struct dm_report_field;
3275
3276
/*
3277
 * dm_report_field_type flags
3278
 */
3279
#define DM_REPORT_FIELD_MASK        0x00000FFF
3280
#define DM_REPORT_FIELD_ALIGN_MASK      0x0000000F
3281
#define DM_REPORT_FIELD_ALIGN_LEFT      0x00000001
3282
#define DM_REPORT_FIELD_ALIGN_RIGHT     0x00000002
3283
#define DM_REPORT_FIELD_TYPE_MASK     0x00000FF0
3284
#define DM_REPORT_FIELD_TYPE_NONE     0x00000000
3285
#define DM_REPORT_FIELD_TYPE_STRING     0x00000010
3286
#define DM_REPORT_FIELD_TYPE_NUMBER     0x00000020
3287
#define DM_REPORT_FIELD_TYPE_SIZE     0x00000040
3288
#define DM_REPORT_FIELD_TYPE_PERCENT      0x00000080
3289
#define DM_REPORT_FIELD_TYPE_STRING_LIST    0x00000100
3290
#define DM_REPORT_FIELD_TYPE_TIME     0x00000200
3291
3292
/* For use with reserved values only! */
3293
#define DM_REPORT_FIELD_RESERVED_VALUE_MASK   0x0000000F
3294
#define DM_REPORT_FIELD_RESERVED_VALUE_NAMED    0x00000001 /* only named value, less strict form of reservation */
3295
#define DM_REPORT_FIELD_RESERVED_VALUE_RANGE    0x00000002 /* value is range - low and high value defined */
3296
#define DM_REPORT_FIELD_RESERVED_VALUE_DYNAMIC_VALUE  0x00000004 /* value is computed in runtime */
3297
#define DM_REPORT_FIELD_RESERVED_VALUE_FUZZY_NAMES  0x00000008 /* value names are recognized in runtime */
3298
3299
#define DM_REPORT_FIELD_TYPE_ID_LEN 32
3300
#define DM_REPORT_FIELD_TYPE_HEADING_LEN 32
3301
3302
struct dm_report;
3303
struct dm_report_field_type {
3304
  uint32_t type;    /* object type id */
3305
  uint32_t flags;   /* DM_REPORT_FIELD_* */
3306
  uint32_t offset;  /* byte offset in the object */
3307
  int32_t width;    /* default width */
3308
  /* string used to specify the field */
3309
  const char id[DM_REPORT_FIELD_TYPE_ID_LEN];
3310
  /* string printed in header */
3311
  const char heading[DM_REPORT_FIELD_TYPE_HEADING_LEN];
3312
  int (*report_fn)(struct dm_report *rh, struct dm_pool *mem,
3313
       struct dm_report_field *field, const void *data,
3314
       void *private_data);
3315
  const char *desc; /* description of the field */
3316
};
3317
3318
/*
3319
 * Per-field reserved value.
3320
 */
3321
struct dm_report_field_reserved_value {
3322
  /* field_num is the position of the field in 'fields'
3323
     array passed to dm_report_init_with_selection */
3324
  uint32_t field_num;
3325
  /* the value is of the same type as the field
3326
     identified by field_num */
3327
  const void *value;
3328
};
3329
3330
/*
3331
 * Reserved value is a 'value' that is used directly if any of the 'names' is hit
3332
 * or in case of fuzzy names, if such fuzzy name matches.
3333
 *
3334
 * If type is any of DM_REPORT_FIELD_TYPE_*, the reserved value is recognized
3335
 * for all fields of that type.
3336
 *
3337
 * If type is DM_REPORT_FIELD_TYPE_NONE, the reserved value is recognized
3338
 * for the exact field specified - hence the type of the value is automatically
3339
 * the same as the type of the field itself.
3340
 *
3341
 * The array of reserved values is used to initialize reporting with
3342
 * selection enabled (see also dm_report_init_with_selection function).
3343
 */
3344
struct dm_report_reserved_value {
3345
  const uint32_t type;    /* DM_REPORT_FIELD_RESERVED_VALUE_* and DM_REPORT_FIELD_TYPE_*  */
3346
  const void *value;    /* reserved value:
3347
            uint64_t for DM_REPORT_FIELD_TYPE_NUMBER
3348
            uint64_t for DM_REPORT_FIELD_TYPE_SIZE (number of 512-byte sectors)
3349
            uint64_t for DM_REPORT_FIELD_TYPE_PERCENT
3350
            const char* for DM_REPORT_FIELD_TYPE_STRING
3351
            struct dm_report_field_reserved_value for DM_REPORT_FIELD_TYPE_NONE
3352
            dm_report_reserved_handler* if DM_REPORT_FIELD_RESERVED_VALUE_{DYNAMIC_VALUE,FUZZY_NAMES} is used */
3353
  const char **names;   /* null-terminated array of static names for this reserved value */
3354
  const char *description;  /* description of the reserved value */
3355
};
3356
3357
/*
3358
 * Available actions for dm_report_reserved_value_handler.
3359
 */
3360
typedef enum dm_report_reserved_action_e {
3361
  DM_REPORT_RESERVED_PARSE_FUZZY_NAME,
3362
  DM_REPORT_RESERVED_GET_DYNAMIC_VALUE,
3363
} dm_report_reserved_action_t;
3364
3365
/*
3366
 * Generic reserved value handler to process reserved value names and/or values.
3367
 *
3368
 * Actions and their input/output:
3369
 *
3370
 *  DM_REPORT_RESERVED_PARSE_FUZZY_NAME
3371
 *    data_in:  const char *fuzzy_name
3372
 *    data_out: const char *canonical_name, NULL if fuzzy_name not recognized
3373
 *
3374
 *  DM_REPORT_RESERVED_GET_DYNAMIC_VALUE
3375
 *    data_in:  const char *canonical_name
3376
 *    data_out: void *value, NULL if canonical_name not recognized
3377
 *
3378
 * All actions return:
3379
 *
3380
 *  -1 if action not implemented
3381
 *  0 on error
3382
 *  1 on success
3383
 */
3384
typedef int (*dm_report_reserved_handler) (struct dm_report *rh,
3385
             struct dm_pool *mem,
3386
             uint32_t field_num,
3387
             dm_report_reserved_action_t action,
3388
             const void *data_in,
3389
             const void **data_out);
3390
3391
/*
3392
 * The dm_report_value_cache_{set,get} are helper functions to store and retrieve
3393
 * various values used during reporting (dm_report_field_type.report_fn) and/or
3394
 * selection processing (dm_report_reserved_handler instances) to avoid
3395
 * recalculation of these values or to share values among calls.
3396
 */
3397
int dm_report_value_cache_set(struct dm_report *rh, const char *name, const void *data);
3398
const void *dm_report_value_cache_get(struct dm_report *rh, const char *name);
3399
/*
3400
 * dm_report_init output_flags
3401
 */
3402
#define DM_REPORT_OUTPUT_MASK     0x000000FF
3403
#define DM_REPORT_OUTPUT_ALIGNED    0x00000001
3404
#define DM_REPORT_OUTPUT_BUFFERED   0x00000002
3405
#define DM_REPORT_OUTPUT_HEADINGS   0x00000004
3406
#define DM_REPORT_OUTPUT_FIELD_NAME_PREFIX  0x00000008
3407
#define DM_REPORT_OUTPUT_FIELD_UNQUOTED   0x00000010
3408
#define DM_REPORT_OUTPUT_COLUMNS_AS_ROWS  0x00000020
3409
#define DM_REPORT_OUTPUT_MULTIPLE_TIMES   0x00000040
3410
#define DM_REPORT_OUTPUT_FIELD_IDS_IN_HEADINGS  0x00000080
3411
3412
struct dm_report *dm_report_init(uint32_t *report_types,
3413
         const struct dm_report_object_type *types,
3414
         const struct dm_report_field_type *fields,
3415
         const char *output_fields,
3416
         const char *output_separator,
3417
         uint32_t output_flags,
3418
         const char *sort_keys,
3419
         void *private_data);
3420
struct dm_report *dm_report_init_with_selection(uint32_t *report_types,
3421
            const struct dm_report_object_type *types,
3422
            const struct dm_report_field_type *fields,
3423
            const char *output_fields,
3424
            const char *output_separator,
3425
            uint32_t output_flags,
3426
            const char *sort_keys,
3427
            const char *selection,
3428
            const struct dm_report_reserved_value reserved_values[],
3429
            void *private_data);
3430
/*
3431
 * Report an object, pass it through the selection criteria if they
3432
 * are present and display the result on output if it passes the criteria.
3433
 */
3434
int dm_report_object(struct dm_report *rh, void *object);
3435
/*
3436
 * The same as dm_report_object, but display the result on output only if
3437
 * 'do_output' arg is set. Also, save the result of selection in 'selected'
3438
 * arg if it's not NULL (either 1 if the object passes, otherwise 0).
3439
 */
3440
int dm_report_object_is_selected(struct dm_report *rh, void *object, int do_output, int *selected);
3441
3442
/*
3443
 * Compact report output so that if field value is empty for all rows in
3444
 * the report, drop the field from output completely (including headers).
3445
 * Compact output is applicable only if report is buffered, otherwise
3446
 * this function has no effect.
3447
 */
3448
int dm_report_compact_fields(struct dm_report *rh);
3449
3450
/*
3451
 * The same as dm_report_compact_fields, but for selected fields only.
3452
 * The "fields" arg is comma separated list of field names (the same format
3453
 * as used for "output_fields" arg in dm_report_init fn).
3454
 */
3455
int dm_report_compact_given_fields(struct dm_report *rh, const char *fields);
3456
3457
/*
3458
 * Returns 1 if there is no data waiting to be output.
3459
 */
3460
int dm_report_is_empty(struct dm_report *rh);
3461
3462
/*
3463
 * Destroy report content without doing output.
3464
 */
3465
void dm_report_destroy_rows(struct dm_report *rh);
3466
3467
int dm_report_output(struct dm_report *rh);
3468
3469
/*
3470
 * Output the report headings for a columns-based report, even if they
3471
 * have already been shown. Useful for repeating reports that wish to
3472
 * issue a periodic reminder of the column headings.
3473
 */
3474
int dm_report_column_headings(struct dm_report *rh);
3475
3476
void dm_report_free(struct dm_report *rh);
3477
3478
/*
3479
 * Prefix added to each field name with DM_REPORT_OUTPUT_FIELD_NAME_PREFIX
3480
 */
3481
int dm_report_set_output_field_name_prefix(struct dm_report *rh,
3482
             const char *output_field_name_prefix);
3483
3484
int dm_report_set_selection(struct dm_report *rh, const char *selection);
3485
3486
/*
3487
 * Report functions are provided for simple data types.
3488
 * They take care of allocating copies of the data.
3489
 */
3490
int dm_report_field_string(struct dm_report *rh, struct dm_report_field *field,
3491
         const char *const *data);
3492
int dm_report_field_string_list(struct dm_report *rh, struct dm_report_field *field,
3493
        const struct dm_list *data, const char *delimiter);
3494
int dm_report_field_string_list_unsorted(struct dm_report *rh, struct dm_report_field *field,
3495
           const struct dm_list *data, const char *delimiter);
3496
int dm_report_field_int32(struct dm_report *rh, struct dm_report_field *field,
3497
        const int32_t *data);
3498
int dm_report_field_uint32(struct dm_report *rh, struct dm_report_field *field,
3499
         const uint32_t *data);
3500
int dm_report_field_int(struct dm_report *rh, struct dm_report_field *field,
3501
      const int *data);
3502
int dm_report_field_uint64(struct dm_report *rh, struct dm_report_field *field,
3503
         const uint64_t *data);
3504
int dm_report_field_percent(struct dm_report *rh, struct dm_report_field *field,
3505
          const dm_percent_t *data);
3506
3507
/*
3508
 * For custom fields, allocate the data in 'mem' and use
3509
 * dm_report_field_set_value().
3510
 * 'sortvalue' may be NULL if it matches 'value'
3511
 */
3512
void dm_report_field_set_value(struct dm_report_field *field, const void *value,
3513
             const void *sortvalue);
3514
3515
/*
3516
 * Report group support.
3517
 */
3518
struct dm_report_group;
3519
3520
typedef enum dm_report_group_type_e {
3521
  DM_REPORT_GROUP_SINGLE,
3522
  DM_REPORT_GROUP_BASIC,
3523
  DM_REPORT_GROUP_JSON,
3524
  DM_REPORT_GROUP_JSON_STD
3525
} dm_report_group_type_t;
3526
3527
struct dm_report_group *dm_report_group_create(dm_report_group_type_t type, void *data);
3528
int dm_report_group_push(struct dm_report_group *group, struct dm_report *report, void *data);
3529
int dm_report_group_pop(struct dm_report_group *group);
3530
int dm_report_group_output_and_pop_all(struct dm_report_group *group);
3531
int dm_report_group_destroy(struct dm_report_group *group);
3532
3533
/*
3534
 * Stats counter access methods
3535
 *
3536
 * Each method returns the corresponding stats counter value from the
3537
 * supplied dm_stats handle for the specified region_id and area_id.
3538
 * If either region_id or area_id uses one of the special values
3539
 * DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT then the region
3540
 * or area is selected according to the current state of the dm_stats
3541
 * handle's embedded cursor.
3542
 *
3543
 * Two methods are provided to access counter values: a named function
3544
 * for each available counter field and a single function that accepts
3545
 * an enum value specifying the required field. New code is encouraged
3546
 * to use the enum based interface as calls to the named functions are
3547
 * implemented using the enum method internally.
3548
 *
3549
 * See the kernel documentation for complete descriptions of each
3550
 * counter field:
3551
 *
3552
 * Documentation/device-mapper/statistics.txt
3553
 * Documentation/iostats.txt
3554
 *
3555
 * reads: the number of reads completed
3556
 * reads_merged: the number of reads merged
3557
 * read_sectors: the number of sectors read
3558
 * read_nsecs: the number of nanoseconds spent reading
3559
 * writes: the number of writes completed
3560
 * writes_merged: the number of writes merged
3561
 * write_sectors: the number of sectors written
3562
 * write_nsecs: the number of nanoseconds spent writing
3563
 * io_in_progress: the number of I/Os currently in progress
3564
 * io_nsecs: the number of nanoseconds spent doing I/Os
3565
 * weighted_io_nsecs: the weighted number of nanoseconds spent doing I/Os
3566
 * total_read_nsecs: the total time spent reading in nanoseconds
3567
 * total_write_nsecs: the total time spent writing in nanoseconds
3568
 */
3569
3570
#define DM_STATS_REGION_CURRENT UINT64_MAX
3571
#define DM_STATS_AREA_CURRENT UINT64_MAX
3572
3573
typedef enum dm_stats_counter_e {
3574
  DM_STATS_READS_COUNT,
3575
  DM_STATS_READS_MERGED_COUNT,
3576
  DM_STATS_READ_SECTORS_COUNT,
3577
  DM_STATS_READ_NSECS,
3578
  DM_STATS_WRITES_COUNT,
3579
  DM_STATS_WRITES_MERGED_COUNT,
3580
  DM_STATS_WRITE_SECTORS_COUNT,
3581
  DM_STATS_WRITE_NSECS,
3582
  DM_STATS_IO_IN_PROGRESS_COUNT,
3583
  DM_STATS_IO_NSECS,
3584
  DM_STATS_WEIGHTED_IO_NSECS,
3585
  DM_STATS_TOTAL_READ_NSECS,
3586
  DM_STATS_TOTAL_WRITE_NSECS,
3587
  DM_STATS_NR_COUNTERS
3588
} dm_stats_counter_t;
3589
3590
uint64_t dm_stats_get_counter(const struct dm_stats *dms,
3591
            dm_stats_counter_t counter,
3592
            uint64_t region_id, uint64_t area_id);
3593
3594
uint64_t dm_stats_get_reads(const struct dm_stats *dms,
3595
          uint64_t region_id, uint64_t area_id);
3596
3597
uint64_t dm_stats_get_reads_merged(const struct dm_stats *dms,
3598
           uint64_t region_id, uint64_t area_id);
3599
3600
uint64_t dm_stats_get_read_sectors(const struct dm_stats *dms,
3601
           uint64_t region_id, uint64_t area_id);
3602
3603
uint64_t dm_stats_get_read_nsecs(const struct dm_stats *dms,
3604
         uint64_t region_id, uint64_t area_id);
3605
3606
uint64_t dm_stats_get_writes(const struct dm_stats *dms,
3607
           uint64_t region_id, uint64_t area_id);
3608
3609
uint64_t dm_stats_get_writes_merged(const struct dm_stats *dms,
3610
            uint64_t region_id, uint64_t area_id);
3611
3612
uint64_t dm_stats_get_write_sectors(const struct dm_stats *dms,
3613
            uint64_t region_id, uint64_t area_id);
3614
3615
uint64_t dm_stats_get_write_nsecs(const struct dm_stats *dms,
3616
          uint64_t region_id, uint64_t area_id);
3617
3618
uint64_t dm_stats_get_io_in_progress(const struct dm_stats *dms,
3619
             uint64_t region_id, uint64_t area_id);
3620
3621
uint64_t dm_stats_get_io_nsecs(const struct dm_stats *dms,
3622
             uint64_t region_id, uint64_t area_id);
3623
3624
uint64_t dm_stats_get_weighted_io_nsecs(const struct dm_stats *dms,
3625
          uint64_t region_id, uint64_t area_id);
3626
3627
uint64_t dm_stats_get_total_read_nsecs(const struct dm_stats *dms,
3628
               uint64_t region_id, uint64_t area_id);
3629
3630
uint64_t dm_stats_get_total_write_nsecs(const struct dm_stats *dms,
3631
          uint64_t region_id, uint64_t area_id);
3632
3633
/*
3634
 * Derived statistics access methods
3635
 *
3636
 * Each method returns the corresponding value calculated from the
3637
 * counters stored in the supplied dm_stats handle for the specified
3638
 * region_id and area_id. If either region_id or area_id uses one of the
3639
 * special values DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT then
3640
 * the region or area is selected according to the current state of the
3641
 * dm_stats handle's embedded cursor.
3642
 *
3643
 * The set of metrics is based on the fields provided by the Linux
3644
 * iostats program.
3645
 *
3646
 * rd_merges_per_sec: the number of reads merged per second
3647
 * wr_merges_per_sec: the number of writes merged per second
3648
 * reads_per_sec: the number of reads completed per second
3649
 * writes_per_sec: the number of writes completed per second
3650
 * read_sectors_per_sec: the number of sectors read per second
3651
 * write_sectors_per_sec: the number of sectors written per second
3652
 * average_request_size: the average size of requests submitted
3653
 * service_time: the average service time (in ns) for requests issued
3654
 * average_queue_size: the average queue length
3655
 * average_wait_time: the average time for requests to be served (in ns)
3656
 * average_rd_wait_time: the average read wait time
3657
 * average_wr_wait_time: the average write wait time
3658
 */
3659
3660
typedef enum dm_stats_metric_e {
3661
  DM_STATS_RD_MERGES_PER_SEC,
3662
  DM_STATS_WR_MERGES_PER_SEC,
3663
  DM_STATS_READS_PER_SEC,
3664
  DM_STATS_WRITES_PER_SEC,
3665
  DM_STATS_READ_SECTORS_PER_SEC,
3666
  DM_STATS_WRITE_SECTORS_PER_SEC,
3667
  DM_STATS_AVERAGE_REQUEST_SIZE,
3668
  DM_STATS_AVERAGE_QUEUE_SIZE,
3669
  DM_STATS_AVERAGE_WAIT_TIME,
3670
  DM_STATS_AVERAGE_RD_WAIT_TIME,
3671
  DM_STATS_AVERAGE_WR_WAIT_TIME,
3672
  DM_STATS_SERVICE_TIME,
3673
  DM_STATS_THROUGHPUT,
3674
  DM_STATS_UTILIZATION,
3675
  DM_STATS_NR_METRICS
3676
} dm_stats_metric_t;
3677
3678
int dm_stats_get_metric(const struct dm_stats *dms, int metric,
3679
      uint64_t region_id, uint64_t area_id, double *value);
3680
3681
int dm_stats_get_rd_merges_per_sec(const struct dm_stats *dms, double *rrqm,
3682
           uint64_t region_id, uint64_t area_id);
3683
3684
int dm_stats_get_wr_merges_per_sec(const struct dm_stats *dms, double *wrqm,
3685
           uint64_t region_id, uint64_t area_id);
3686
3687
int dm_stats_get_reads_per_sec(const struct dm_stats *dms, double *rd_s,
3688
             uint64_t region_id, uint64_t area_id);
3689
3690
int dm_stats_get_writes_per_sec(const struct dm_stats *dms, double *wr_s,
3691
        uint64_t region_id, uint64_t area_id);
3692
3693
int dm_stats_get_read_sectors_per_sec(const struct dm_stats *dms,
3694
              double *rsec_s, uint64_t region_id,
3695
              uint64_t area_id);
3696
3697
int dm_stats_get_write_sectors_per_sec(const struct dm_stats *dms,
3698
               double *wsec_s, uint64_t region_id,
3699
               uint64_t area_id);
3700
3701
int dm_stats_get_average_request_size(const struct dm_stats *dms,
3702
              double *arqsz, uint64_t region_id,
3703
              uint64_t area_id);
3704
3705
int dm_stats_get_service_time(const struct dm_stats *dms, double *svctm,
3706
            uint64_t region_id, uint64_t area_id);
3707
3708
int dm_stats_get_average_queue_size(const struct dm_stats *dms, double *qusz,
3709
            uint64_t region_id, uint64_t area_id);
3710
3711
int dm_stats_get_average_wait_time(const struct dm_stats *dms, double *await,
3712
           uint64_t region_id, uint64_t area_id);
3713
3714
int dm_stats_get_average_rd_wait_time(const struct dm_stats *dms,
3715
              double *await, uint64_t region_id,
3716
              uint64_t area_id);
3717
3718
int dm_stats_get_average_wr_wait_time(const struct dm_stats *dms,
3719
              double *await, uint64_t region_id,
3720
              uint64_t area_id);
3721
3722
int dm_stats_get_throughput(const struct dm_stats *dms, double *tput,
3723
          uint64_t region_id, uint64_t area_id);
3724
3725
int dm_stats_get_utilization(const struct dm_stats *dms, dm_percent_t *util,
3726
           uint64_t region_id, uint64_t area_id);
3727
3728
/*
3729
 * Statistics histogram access methods.
3730
 *
3731
 * Methods to access latency histograms for regions that have them
3732
 * enabled. Each histogram contains a configurable number of bins
3733
 * spanning a user defined latency interval.
3734
 *
3735
 * The bin count, upper and lower bin bounds, and bin values are
3736
 * made available via the following area methods.
3737
 *
3738
 * Methods to obtain a simple string representation of the histogram
3739
 * and its bounds are also provided.
3740
 */
3741
3742
/*
3743
 * Retrieve a pointer to the histogram associated with the specified
3744
 * area. If the area does not have a histogram configured this function
3745
 * returns NULL.
3746
 *
3747
 * The pointer does not need to be freed explicitly by the caller: it
3748
 * will become invalid following a subsequent dm_stats_list(),
3749
 * dm_stats_populate() or dm_stats_destroy() of the corresponding
3750
 * dm_stats handle.
3751
 *
3752
 * If region_id or area_id is one of the special values
3753
 * DM_STATS_REGION_CURRENT or DM_STATS_AREA_CURRENT the current cursor
3754
 * value is used to select the region or area.
3755
 */
3756
struct dm_histogram *dm_stats_get_histogram(const struct dm_stats *dms,
3757
              uint64_t region_id,
3758
              uint64_t area_id);
3759
3760
/*
3761
 * Return the number of bins in the specified histogram handle.
3762
 */
3763
int dm_histogram_get_nr_bins(const struct dm_histogram *dmh);
3764
3765
/*
3766
 * Get the lower bound of the specified bin of the histogram for the
3767
 * area specified by region_id and area_id. The value is returned in
3768
 * nanoseconds.
3769
 */
3770
uint64_t dm_histogram_get_bin_lower(const struct dm_histogram *dmh, int bin);
3771
3772
/*
3773
 * Get the upper bound of the specified bin of the histogram for the
3774
 * area specified by region_id and area_id. The value is returned in
3775
 * nanoseconds.
3776
 */
3777
uint64_t dm_histogram_get_bin_upper(const struct dm_histogram *dmh, int bin);
3778
3779
/*
3780
 * Get the width of the specified bin of the histogram for the area
3781
 * specified by region_id and area_id. The width is equal to the bin
3782
 * upper bound minus the lower bound and yields the range of latency
3783
 * values covered by this bin. The value is returned in nanoseconds.
3784
 */
3785
uint64_t dm_histogram_get_bin_width(const struct dm_histogram *dmh, int bin);
3786
3787
/*
3788
 * Get the value of the specified bin of the histogram for the area
3789
 * specified by region_id and area_id.
3790
 */
3791
uint64_t dm_histogram_get_bin_count(const struct dm_histogram *dmh, int bin);
3792
3793
/*
3794
 * Get the percentage (relative frequency) of the specified bin of the
3795
 * histogram for the area specified by region_id and area_id.
3796
 */
3797
dm_percent_t dm_histogram_get_bin_percent(const struct dm_histogram *dmh,
3798
            int bin);
3799
3800
/*
3801
 * Return the total observations (sum of bin counts) for the histogram
3802
 * of the area specified by region_id and area_id.
3803
 */
3804
uint64_t dm_histogram_get_sum(const struct dm_histogram *dmh);
3805
3806
/*
3807
 * Histogram formatting flags.
3808
 */
3809
#define DM_HISTOGRAM_SUFFIX  0x1
3810
#define DM_HISTOGRAM_VALUES  0x2
3811
#define DM_HISTOGRAM_PERCENT 0X4
3812
#define DM_HISTOGRAM_BOUNDS_LOWER 0x10
3813
#define DM_HISTOGRAM_BOUNDS_UPPER 0x20
3814
#define DM_HISTOGRAM_BOUNDS_RANGE 0x30
3815
3816
/*
3817
 * Return a string representation of the supplied histogram's values and
3818
 * bin boundaries.
3819
 *
3820
 * The bin argument selects the bin to format. If this argument is less
3821
 * than zero all bins will be included in the resulting string.
3822
 *
3823
 * width specifies a minimum width for the field in characters; if it is
3824
 * zero the width will be determined automatically based on the options
3825
 * selected for formatting. A value less than zero disables field width
3826
 * control: bin boundaries and values will be output with a minimum
3827
 * amount of whitespace.
3828
 *
3829
 * flags is a collection of flag arguments that control the string format:
3830
 *
3831
 * DM_HISTOGRAM_VALUES  - Include bin values in the string.
3832
 * DM_HISTOGRAM_SUFFIX  - Include time unit suffixes when printing bounds.
3833
 * DM_HISTOGRAM_PERCENT - Format bin values as a percentage.
3834
 *
3835
 * DM_HISTOGRAM_BOUNDS_LOWER - Include the lower bound of each bin.
3836
 * DM_HISTOGRAM_BOUNDS_UPPER - Include the upper bound of each bin.
3837
 * DM_HISTOGRAM_BOUNDS_RANGE - Show the span of each bin as "lo-up".
3838
 *
3839
 * The returned pointer does not need to be freed explicitly by the
3840
 * caller: it will become invalid following a subsequent
3841
 * dm_stats_list(), dm_stats_populate() or dm_stats_destroy() of the
3842
 * corresponding dm_stats handle.
3843
 */
3844
const char *dm_histogram_to_string(const struct dm_histogram *dmh, int bin,
3845
           int width, int flags);
3846
3847
/*************************
3848
 * config file parse/print
3849
 *************************/
3850
typedef enum dm_config_value_type_e {
3851
  DM_CFG_INT,
3852
  DM_CFG_FLOAT,
3853
  DM_CFG_STRING,
3854
  DM_CFG_EMPTY_ARRAY
3855
} dm_config_value_type_t;
3856
3857
struct dm_config_value {
3858
  dm_config_value_type_t type;
3859
3860
  union dm_config_value_u {
3861
    int64_t i;
3862
    float f;
3863
    double d;         /* Unused. */
3864
    const char *str;
3865
  } v;
3866
3867
  struct dm_config_value *next; /* For arrays */
3868
  uint32_t format_flags;
3869
};
3870
3871
struct dm_config_node {
3872
  const char *key;
3873
  struct dm_config_node *parent, *sib, *child;
3874
  struct dm_config_value *v;
3875
  int id;
3876
};
3877
3878
struct dm_config_tree {
3879
  struct dm_config_node *root;
3880
  struct dm_config_tree *cascade;
3881
  struct dm_pool *mem;
3882
  void *custom;
3883
};
3884
3885
struct dm_config_tree *dm_config_create(void);
3886
struct dm_config_tree *dm_config_from_string(const char *config_settings);
3887
int dm_config_parse(struct dm_config_tree *cft, const char *start, const char *end);
3888
int dm_config_parse_without_dup_node_check(struct dm_config_tree *cft, const char *start, const char *end);
3889
int dm_config_parse_only_section(struct dm_config_tree *cft, const char *start, const char *end, const char *section);
3890
3891
void *dm_config_get_custom(struct dm_config_tree *cft);
3892
void dm_config_set_custom(struct dm_config_tree *cft, void *custom);
3893
3894
/*
3895
 * When searching, first_cft is checked before second_cft.
3896
 */
3897
struct dm_config_tree *dm_config_insert_cascaded_tree(struct dm_config_tree *first_cft, struct dm_config_tree *second_cft);
3898
3899
/*
3900
 * If there's a cascaded dm_config_tree, remove the top layer
3901
 * and return the layer below.  Otherwise return NULL.
3902
 */
3903
struct dm_config_tree *dm_config_remove_cascaded_tree(struct dm_config_tree *cft);
3904
3905
/*
3906
 * Create a new, uncascaded config tree equivalent to the input cascade.
3907
 */
3908
struct dm_config_tree *dm_config_flatten(struct dm_config_tree *cft);
3909
3910
void dm_config_destroy(struct dm_config_tree *cft);
3911
3912
/* Simple output line by line. */
3913
typedef int (*dm_putline_fn)(const char *line, void *baton);
3914
/* More advanced output with config node reference. */
3915
typedef int (*dm_config_node_out_fn)(const struct dm_config_node *cn, const char *line, void *baton);
3916
3917
/*
3918
 * Specification for advanced config node output.
3919
 */
3920
struct dm_config_node_out_spec {
3921
  dm_config_node_out_fn prefix_fn; /* called before processing config node lines */
3922
  dm_config_node_out_fn line_fn; /* called for each config node line */
3923
  dm_config_node_out_fn suffix_fn; /* called after processing config node lines */
3924
};
3925
3926
/* Write the node and any subsequent siblings it has. */
3927
int dm_config_write_node(const struct dm_config_node *cn, dm_putline_fn putline, void *baton);
3928
int dm_config_write_node_out(const struct dm_config_node *cn, const struct dm_config_node_out_spec *out_spec, void *baton);
3929
3930
/* Write given node only without subsequent siblings. */
3931
int dm_config_write_one_node(const struct dm_config_node *cn, dm_putline_fn putline, void *baton);
3932
int dm_config_write_one_node_out(const struct dm_config_node *cn, const struct dm_config_node_out_spec *out_spec, void *baton);
3933
3934
struct dm_config_node *dm_config_find_node(const struct dm_config_node *cn, const char *path);
3935
int dm_config_has_node(const struct dm_config_node *cn, const char *path);
3936
int dm_config_remove_node(struct dm_config_node *parent, struct dm_config_node *rem_node);
3937
const char *dm_config_find_str(const struct dm_config_node *cn, const char *path, const char *fail);
3938
const char *dm_config_find_str_allow_empty(const struct dm_config_node *cn, const char *path, const char *fail);
3939
int dm_config_find_int(const struct dm_config_node *cn, const char *path, int fail);
3940
int64_t dm_config_find_int64(const struct dm_config_node *cn, const char *path, int64_t fail);
3941
float dm_config_find_float(const struct dm_config_node *cn, const char *path, float fail);
3942
3943
const struct dm_config_node *dm_config_tree_find_node(const struct dm_config_tree *cft, const char *path);
3944
const char *dm_config_tree_find_str(const struct dm_config_tree *cft, const char *path, const char *fail);
3945
const char *dm_config_tree_find_str_allow_empty(const struct dm_config_tree *cft, const char *path, const char *fail);
3946
int dm_config_tree_find_int(const struct dm_config_tree *cft, const char *path, int fail);
3947
int64_t dm_config_tree_find_int64(const struct dm_config_tree *cft, const char *path, int64_t fail);
3948
float dm_config_tree_find_float(const struct dm_config_tree *cft, const char *path, float fail);
3949
int dm_config_tree_find_bool(const struct dm_config_tree *cft, const char *path, int fail);
3950
3951
/*
3952
 * Understands (0, ~0), (y, n), (yes, no), (on,
3953
 * off), (true, false).
3954
 */
3955
int dm_config_find_bool(const struct dm_config_node *cn, const char *path, int fail);
3956
int dm_config_value_is_bool(const struct dm_config_value *v);
3957
3958
int dm_config_get_uint32(const struct dm_config_node *cn, const char *path, uint32_t *result);
3959
int dm_config_get_uint64(const struct dm_config_node *cn, const char *path, uint64_t *result);
3960
int dm_config_get_str(const struct dm_config_node *cn, const char *path, const char **result);
3961
int dm_config_get_list(const struct dm_config_node *cn, const char *path, const struct dm_config_value **result);
3962
int dm_config_get_section(const struct dm_config_node *cn, const char *path, const struct dm_config_node **result);
3963
3964
unsigned dm_config_maybe_section(const char *str, unsigned len);
3965
3966
const char *dm_config_parent_name(const struct dm_config_node *n);
3967
3968
struct dm_config_node *dm_config_clone_node_with_mem(struct dm_pool *mem, const struct dm_config_node *cn, int siblings);
3969
struct dm_config_node *dm_config_create_node(struct dm_config_tree *cft, const char *key);
3970
struct dm_config_value *dm_config_create_value(struct dm_config_tree *cft);
3971
struct dm_config_node *dm_config_clone_node(struct dm_config_tree *cft, const struct dm_config_node *cn, int siblings);
3972
3973
/*
3974
 * Common formatting flags applicable to all config node types (lower 16 bits).
3975
 */
3976
#define DM_CONFIG_VALUE_FMT_COMMON_ARRAY             0x00000001 /* value is array */
3977
#define DM_CONFIG_VALUE_FMT_COMMON_EXTRA_SPACES      0x00000002 /* add spaces in "key = value" pairs in contrast to "key=value" for better readability */
3978
3979
/*
3980
 * Type-related config node formatting flags (higher 16 bits).
3981
 */
3982
/* int-related formatting flags */
3983
#define DM_CONFIG_VALUE_FMT_INT_OCTAL                0x00010000 /* print number in octal form */
3984
3985
/* string-related formatting flags */
3986
#define DM_CONFIG_VALUE_FMT_STRING_NO_QUOTES         0x00010000 /* do not print quotes around string value */
3987
3988
void dm_config_value_set_format_flags(struct dm_config_value *cv, uint32_t format_flags);
3989
uint32_t dm_config_value_get_format_flags(struct dm_config_value *cv);
3990
3991
struct dm_pool *dm_config_memory(struct dm_config_tree *cft);
3992
3993
/* Udev device directory. */
3994
#define DM_UDEV_DEV_DIR "/dev/"
3995
3996
/* Cookie prefixes.
3997
 *
3998
 * The cookie value consists of a prefix (16 bits) and a base (16 bits).
3999
 * We can use the prefix to store the flags. These flags are sent to
4000
 * kernel within given dm task. When returned back to userspace in
4001
 * DM_COOKIE udev environment variable, we can control several aspects
4002
 * of udev rules we use by decoding the cookie prefix. When doing the
4003
 * notification, we replace the cookie prefix with DM_COOKIE_MAGIC,
4004
 * so we notify the right semaphore.
4005
 *
4006
 * It is still possible to use cookies for passing the flags to udev
4007
 * rules even when udev_sync is disabled. The base part of the cookie
4008
 * will be zero (there's no notification semaphore) and prefix will be
4009
 * set then. However, having udev_sync enabled is highly recommended.
4010
 */
4011
0
#define DM_COOKIE_MAGIC 0x0D4D
4012
0
#define DM_UDEV_FLAGS_MASK 0xFFFF0000
4013
0
#define DM_UDEV_FLAGS_SHIFT 16
4014
4015
/*
4016
 * DM_UDEV_DISABLE_DM_RULES_FLAG is set in case we need to disable
4017
 * basic device-mapper udev rules that create symlinks in /dev/<DM_DIR>
4018
 * directory. However, we can't reliably prevent creating default
4019
 * nodes by udev (commonly /dev/dm-X, where X is a number).
4020
 */
4021
0
#define DM_UDEV_DISABLE_DM_RULES_FLAG 0x0001
4022
/*
4023
 * DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG is set in case we need to disable
4024
 * subsystem udev rules, but still we need the general DM udev rules to
4025
 * be applied (to create the nodes and symlinks under /dev and /dev/disk).
4026
 */
4027
0
#define DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG 0x0002
4028
/*
4029
 * DM_UDEV_DISABLE_DISK_RULES_FLAG is set in case we need to disable
4030
 * general DM rules that set symlinks in /dev/disk directory.
4031
 */
4032
#define DM_UDEV_DISABLE_DISK_RULES_FLAG 0x0004
4033
/*
4034
 * DM_UDEV_DISABLE_OTHER_RULES_FLAG is set in case we need to disable
4035
 * all the other rules that are not general device-mapper nor subsystem
4036
 * related (the rules belong to other software or packages). All foreign
4037
 * rules should check this flag directly and they should ignore further
4038
 * rule processing for such event.
4039
 */
4040
#define DM_UDEV_DISABLE_OTHER_RULES_FLAG 0x0008
4041
/*
4042
 * DM_UDEV_LOW_PRIORITY_FLAG is set in case we need to instruct the
4043
 * udev rules to give low priority to the device that is currently
4044
 * processed. For example, this provides a way to select which symlinks
4045
 * could be overwritten by high priority ones if their names are equal.
4046
 * Common situation is a name based on FS UUID while using origin and
4047
 * snapshot devices.
4048
 */
4049
#define DM_UDEV_LOW_PRIORITY_FLAG 0x0010
4050
/*
4051
 * DM_UDEV_DISABLE_LIBRARY_FALLBACK is set in case we need to disable
4052
 * libdevmapper's node management. We will rely on udev completely
4053
 * and there will be no fallback action provided by libdevmapper if
4054
 * udev does something improperly. Using the library fallback code has
4055
 * a consequence that you need to take into account: any device node
4056
 * or symlink created without udev is not recorded in udev database
4057
 * which other applications may read to get complete list of devices.
4058
 * For this reason, use of DM_UDEV_DISABLE_LIBRARY_FALLBACK is
4059
 * recommended on systems where udev is used. Keep library fallback
4060
 * enabled just for exceptional cases where you need to debug udev-related
4061
 * problems. If you hit such problems, please contact us through upstream
4062
 * LVM2 development mailing list (see also README file). This flag is
4063
 * currently not set by default in libdevmapper so you need to set it
4064
 * explicitly if you're sure that udev is behaving correctly on your
4065
 * setups.
4066
 */
4067
0
#define DM_UDEV_DISABLE_LIBRARY_FALLBACK 0x0020
4068
/*
4069
 * DM_UDEV_PRIMARY_SOURCE_FLAG is automatically appended by
4070
 * libdevmapper for all ioctls generating udev uevents. Once used in
4071
 * udev rules, we know if this is a real "primary sourced" event or not.
4072
 * We need to distinguish real events originated in libdevmapper from
4073
 * any spurious events to gather all missing information (e.g. events
4074
 * generated as a result of "udevadm trigger" command or as a result
4075
 * of the "watch" udev rule).
4076
 */
4077
0
#define DM_UDEV_PRIMARY_SOURCE_FLAG 0x0040
4078
4079
/*
4080
 * Udev flags reserved for use by any device-mapper subsystem.
4081
 */
4082
#define DM_SUBSYSTEM_UDEV_FLAG0 0x0100
4083
#define DM_SUBSYSTEM_UDEV_FLAG1 0x0200
4084
#define DM_SUBSYSTEM_UDEV_FLAG2 0x0400
4085
#define DM_SUBSYSTEM_UDEV_FLAG3 0x0800
4086
#define DM_SUBSYSTEM_UDEV_FLAG4 0x1000
4087
#define DM_SUBSYSTEM_UDEV_FLAG5 0x2000
4088
#define DM_SUBSYSTEM_UDEV_FLAG6 0x4000
4089
#define DM_SUBSYSTEM_UDEV_FLAG7 0x8000
4090
4091
int dm_cookie_supported(void);
4092
4093
/*
4094
 * Udev synchronization functions.
4095
 */
4096
void dm_udev_set_sync_support(int sync_with_udev);
4097
int dm_udev_get_sync_support(void);
4098
void dm_udev_set_checking(int checking);
4099
int dm_udev_get_checking(void);
4100
4101
/*
4102
 * Default value to get new auto generated cookie created
4103
 */
4104
#define DM_COOKIE_AUTO_CREATE 0
4105
int dm_udev_create_cookie(uint32_t *cookie);
4106
int dm_udev_complete(uint32_t cookie);
4107
int dm_udev_wait(uint32_t cookie);
4108
4109
/*
4110
 * dm_dev_wait_immediate
4111
 * If *ready is 1 on return, the wait is complete.
4112
 * If *ready is 0 on return, the wait is incomplete and either
4113
 * this function or dm_udev_wait() must be called again.
4114
 * Returns 0 on error, when neither function should be called again.
4115
 */
4116
int dm_udev_wait_immediate(uint32_t cookie, int *ready);
4117
4118
0
#define DM_DEV_DIR_UMASK 0022
4119
0
#define DM_CONTROL_NODE_UMASK 0177
4120
4121
#ifdef __cplusplus
4122
}
4123
#endif
4124
#endif        /* LIB_DEVICE_MAPPER_H */