1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12 /*
13 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
14 * Use is subject to license terms.
15 */
16
17 #include <errno.h>
18 #include <libgen.h>
19 #include <libintl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <ctype.h>
24
25 #include "zpool_util.h"
26
27 /*
28 * Utility function to guarantee malloc() success.
29 */
30 void *
safe_malloc(size_t size)31 safe_malloc(size_t size)
32 {
33 void *data;
34
35 if ((data = calloc(1, size)) == NULL) {
36 (void) fprintf(stderr, "internal error: out of memory\n");
37 exit(1);
38 }
39
40 return (data);
41 }
42
43 /*
44 * Utility function to guarantee realloc() success.
45 */
46 void *
safe_realloc(void * from,size_t size)47 safe_realloc(void *from, size_t size)
48 {
49 void *data;
50
51 if ((data = realloc(from, size)) == NULL) {
52 (void) fprintf(stderr, "internal error: out of memory\n");
53 exit(1);
54 }
55
56 return (data);
57 }
58
59 /*
60 * Display an out of memory error message and abort the current program.
61 */
62 void
zpool_no_memory(void)63 zpool_no_memory(void)
64 {
65 assert(errno == ENOMEM);
66 (void) fprintf(stderr,
67 gettext("internal error: out of memory\n"));
68 exit(1);
69 }
70
71 /*
72 * Return the number of logs in supplied nvlist
73 */
74 uint_t
num_logs(nvlist_t * nv)75 num_logs(nvlist_t *nv)
76 {
77 uint_t nlogs = 0;
78 uint_t c, children;
79 nvlist_t **child;
80
81 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
82 &child, &children) != 0)
83 return (0);
84
85 for (c = 0; c < children; c++) {
86 uint64_t is_log = B_FALSE;
87
88 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
89 &is_log);
90 if (is_log)
91 nlogs++;
92 }
93 return (nlogs);
94 }
95
96 /* Find the max element in an array of uint64_t values */
97 uint64_t
array64_max(uint64_t array[],unsigned int len)98 array64_max(uint64_t array[], unsigned int len)
99 {
100 uint64_t max = 0;
101 int i;
102 for (i = 0; i < len; i++)
103 max = MAX(max, array[i]);
104
105 return (max);
106 }
107