Index: user/ngie/stable-10-libnv/lib/libdpv/dialogrc.c =================================================================== --- user/ngie/stable-10-libnv/lib/libdpv/dialogrc.c (revision 293638) +++ user/ngie/stable-10-libnv/lib/libdpv/dialogrc.c (revision 293639) @@ -1,359 +1,360 @@ /*- - * Copyright (c) 2013-2014 Devin Teske + * Copyright (c) 2013-2015 Devin Teske * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include "dialogrc.h" #define STR_BUFSIZE 255 /* dialog(1) `.dialogrc' characteristics */ uint8_t use_colors = 1; uint8_t use_shadow = 1; char gauge_color[STR_BUFSIZE] = "47b"; /* (BLUE,WHITE,ON) */ char separator[STR_BUFSIZE] = ""; /* Function prototypes */ -static int setattr(struct fp_config *, uint32_t, char *, char *); -static int setbool(struct fp_config *, uint32_t, char *, char *); -static int setnum(struct fp_config *, uint32_t, char *, char *); -static int setstr(struct fp_config *, uint32_t, char *, char *); +static int setattr(struct figpar_config *, uint32_t, char *, char *); +static int setbool(struct figpar_config *, uint32_t, char *, char *); +static int setnum(struct figpar_config *, uint32_t, char *, char *); +static int setstr(struct figpar_config *, uint32_t, char *, char *); /* * Anatomy of DIALOGRC (~/.dialogrc by default) * NOTE: Must appear after private function prototypes (above) * NB: Brace-initialization of union requires cast to *first* member of union */ -static struct fp_config dialogrc_config[] = { - /* TYPE Directive DEFAULT HANDLER */ - {FP_TYPE_INT, "aspect", {(void *)0}, &setnum}, - {FP_TYPE_STR, "separate_widget", {separator}, &setstr}, - {FP_TYPE_INT, "tab_len", {(void *)0}, &setnum}, - {FP_TYPE_BOOL, "visit_items", {(void *)0}, &setbool}, - {FP_TYPE_BOOL, "use_shadow", {(void *)1}, &setbool}, - {FP_TYPE_BOOL, "use_colors", {(void *)1}, &setbool}, - {FP_TYPE_STR, "screen_color", {NULL}, &setattr}, - {FP_TYPE_STR, "shadow_color", {NULL}, &setattr}, - {FP_TYPE_STR, "dialog_color", {NULL}, &setattr}, - {FP_TYPE_STR, "title_color", {NULL}, &setattr}, - {FP_TYPE_STR, "border_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_active_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_inactive_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_key_active_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_key_inactive_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_label_active_color", {NULL}, &setattr}, - {FP_TYPE_STR, "button_label_inactive_color",{NULL}, &setattr}, - {FP_TYPE_STR, "inputbox_color", {NULL}, &setattr}, - {FP_TYPE_STR, "inputbox_border_color", {NULL}, &setattr}, - {FP_TYPE_STR, "searchbox_color", {NULL}, &setattr}, - {FP_TYPE_STR, "searchbox_title_color", {NULL}, &setattr}, - {FP_TYPE_STR, "searchbox_border_color", {NULL}, &setattr}, - {FP_TYPE_STR, "position_indicator_color", {NULL}, &setattr}, - {FP_TYPE_STR, "menubox_color", {NULL}, &setattr}, - {FP_TYPE_STR, "menubox_border_color", {NULL}, &setattr}, - {FP_TYPE_STR, "item_color", {NULL}, &setattr}, - {FP_TYPE_STR, "item_selected_color", {NULL}, &setattr}, - {FP_TYPE_STR, "tag_color", {NULL}, &setattr}, - {FP_TYPE_STR, "tag_selected_color", {NULL}, &setattr}, - {FP_TYPE_STR, "tag_key_color", {NULL}, &setattr}, - {FP_TYPE_STR, "tag_key_selected_color", {NULL}, &setattr}, - {FP_TYPE_STR, "check_color", {NULL}, &setattr}, - {FP_TYPE_STR, "check_selected_color", {NULL}, &setattr}, - {FP_TYPE_STR, "uarrow_color", {NULL}, &setattr}, - {FP_TYPE_STR, "darrow_color", {NULL}, &setattr}, - {FP_TYPE_STR, "itemhelp_color", {NULL}, &setattr}, - {FP_TYPE_STR, "form_active_text_color", {NULL}, &setattr}, - {FP_TYPE_STR, "form_text_color", {NULL}, &setattr}, - {FP_TYPE_STR, "form_item_readonly_color", {NULL}, &setattr}, - {FP_TYPE_STR, "gauge_color", {gauge_color}, &setattr}, +static struct figpar_config dialogrc_config[] = { + /* TYPE DIRECTIVE DEFAULT HANDLER */ + {FIGPAR_TYPE_INT, "aspect", {(void *)0}, &setnum}, + {FIGPAR_TYPE_STR, "separate_widget", {separator}, &setstr}, + {FIGPAR_TYPE_INT, "tab_len", {(void *)0}, &setnum}, + {FIGPAR_TYPE_BOOL, "visit_items", {(void *)0}, &setbool}, + {FIGPAR_TYPE_BOOL, "use_shadow", {(void *)1}, &setbool}, + {FIGPAR_TYPE_BOOL, "use_colors", {(void *)1}, &setbool}, + {FIGPAR_TYPE_STR, "screen_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "shadow_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "dialog_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "title_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "border_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_active_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_inactive_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_key_active_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_key_inactive_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_label_active_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "button_label_inactive_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "inputbox_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "inputbox_border_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "searchbox_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "searchbox_title_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "searchbox_border_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "position_indicator_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "menubox_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "menubox_border_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "item_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "item_selected_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "tag_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "tag_selected_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "tag_key_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "tag_key_selected_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "check_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "check_selected_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "uarrow_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "darrow_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "itemhelp_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "form_active_text_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "form_text_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "form_item_readonly_color", {NULL}, &setattr}, + {FIGPAR_TYPE_STR, "gauge_color", {gauge_color}, &setattr}, {0, NULL, {0}, NULL} }; /* * figpar call-back for interpreting value as .dialogrc `Attribute' */ static int -setattr(struct fp_config *option, uint32_t line __unused, +setattr(struct figpar_config *option, uint32_t line __unused, char *directive __unused, char *value) { char *cp = value; char *val; size_t len; char attrbuf[4]; if (option == NULL) { warnx("%s:%d:%s: Missing callback parameter", __FILE__, __LINE__, __func__); return (-1); /* Abort processing */ } /* Allocate memory for the data if not already done */ if (option->value.str == NULL) { if ((option->value.str = malloc(STR_BUFSIZE)) == NULL) return (-1); } /* * If the first character is left-parenthesis, the format is * `(background,foreground,highlight)' otherwise, we should take it * as a reference to another color. */ if (*cp != '(') { /* Copy the [current] value from the referenced color */ val = dialogrc_config_option(cp)->value.str; if (val != NULL) snprintf(option->value.str, STR_BUFSIZE, "%s", val); return (0); } else cp++; strtolower(cp); /* Initialize the attrbuf (fg,bg,hi,NUL) */ attrbuf[0] = '0'; attrbuf[1] = '0'; attrbuf[2] = 'B'; /* \ZB = disable; \Zb = enable (see dialog(1)) */ attrbuf[3] = '\0'; /* Interpret the foreground color */ if (strncmp(cp, "red,", 4) == 0) attrbuf[0] = '1'; else if (strncmp(cp, "green,", 6) == 0) attrbuf[0] = '2'; else if (strncmp(cp, "yellow,", 7) == 0) attrbuf[0] = '3'; else if (strncmp(cp, "blue,", 5) == 0) attrbuf[0] = '4'; else if (strncmp(cp, "magenta,", 8) == 0) attrbuf[0] = '5'; else if (strncmp(cp, "cyan,", 5) == 0) attrbuf[0] = '6'; else if (strncmp(cp, "white,", 6) == 0) attrbuf[0] = '7'; else if (strncmp(cp, "black,", 6) == 0) attrbuf[0] = '8'; /* Advance to the background color */ cp = strchr(cp, ','); if (cp == NULL) goto write_attrbuf; else cp++; /* Interpret the background color */ if (strncmp(cp, "red,", 4) == 0) attrbuf[1] = '1'; else if (strncmp(cp, "green,", 6) == 0) attrbuf[1] = '2'; else if (strncmp(cp, "yellow,", 7) == 0) attrbuf[1] = '3'; else if (strncmp(cp, "blue,", 5) == 0) attrbuf[1] = '4'; else if (strncmp(cp, "magenta,", 8) == 0) attrbuf[1] = '5'; else if (strncmp(cp, "cyan,", 5) == 0) attrbuf[1] = '6'; else if (strncmp(cp, "white,", 6) == 0) attrbuf[1] = '7'; else if (strncmp(cp, "black,", 6) == 0) attrbuf[1] = '8'; /* Advance to the highlight */ cp = strchr(cp, ','); if (cp == NULL) goto write_attrbuf; else cp++; /* Trim trailing parenthesis */ len = strlen(cp); if (cp[len - 1] == ')') cp[len - 1] = '\0'; /* Interpret the highlight (initialized to off above) */ if (strcmp(cp, "on") == 0 || strncmp(cp, "on,", 3) == 0) attrbuf[2] = 'b'; /* \Zb = enable bold (see dialog(1)) */ write_attrbuf: sprintf(option->value.str, "%s", attrbuf); return (0); } /* * figpar call-back for interpreting value as .dialogrc `Boolean' */ static int -setbool(struct fp_config *option, uint32_t line __unused, +setbool(struct figpar_config *option, uint32_t line __unused, char *directive __unused, char *value) { if (option == NULL) { warnx("%s:%d:%s: Missing callback parameter", __FILE__, __LINE__, __func__); return (-1); /* Abort processing */ } /* Assume ON, check for OFF (case-insensitive) */ option->value.boolean = 1; strtolower(value); if (strcmp(value, "off") == 0) option->value.boolean = 0; return (0); } /* * figpar call-back for interpreting value as .dialogrc `Number' */ static int -setnum(struct fp_config *option, uint32_t line __unused, +setnum(struct figpar_config *option, uint32_t line __unused, char *directive __unused, char *value) { if (option == NULL) { warnx("%s:%d:%s: Missing callback parameter", __FILE__, __LINE__, __func__); return (-1); /* Abort processing */ } /* Convert the string to a 32-bit signed integer */ option->value.num = (int32_t)strtol(value, (char **)NULL, 10); return (0); } /* * figpar call-back for interpreting value as .dialogrc `String' */ static int -setstr(struct fp_config *option, uint32_t line __unused, +setstr(struct figpar_config *option, uint32_t line __unused, char *directive __unused, char *value) { size_t len; if (option == NULL) { warnx("%s:%d:%s: Missing callback parameter", __FILE__, __LINE__, __func__); return (-1); /* Abort processing */ } /* Allocate memory for the data if not already done */ if (option->value.str == NULL) { if ((option->value.str = malloc(STR_BUFSIZE)) == NULL) return (-1); } /* Trim leading quote */ if (*value == '"') value++; /* Write the data into the buffer */ snprintf(option->value.str, STR_BUFSIZE, "%s", value); /* Trim trailing quote */ len = strlen(option->value.str); if (option->value.str[len - 1] == '"') option->value.str[len - 1] = '\0'; return (0); } /* * Parse (in order of preference) $DIALOGRC or `$HOME/.dialogrc'. Returns zero * on success, -1 on failure (and errno should be consulted). */ int parse_dialogrc(void) { char *cp; int res; size_t len; char path[PATH_MAX]; /* Allow $DIALOGRC to override `$HOME/.dialogrc' default */ if ((cp = getenv(ENV_DIALOGRC)) != NULL && *cp != '\0') snprintf(path, PATH_MAX, "%s", cp); else if ((cp = getenv(ENV_HOME)) != NULL) { /* Copy $HOME into buffer and append trailing `/' if missing */ snprintf(path, PATH_MAX, "%s", cp); len = strlen(path); cp = path + len; if (len > 0 && len < (PATH_MAX - 1) && *(cp - 1) != '/') { *cp++ = '/'; *cp = '\0'; len++; } /* If we still have room, shove in the name of rc file */ if (len < (PATH_MAX - 1)) snprintf(cp, PATH_MAX - len, "%s", DIALOGRC); } else { /* Like dialog(1), don't process a file if $HOME is unset */ errno = ENOENT; return (-1); } /* Process file (either $DIALOGRC if set, or `$HOME/.dialogrc') */ - res = parse_config(dialogrc_config, path, NULL, FP_BREAK_ON_EQUALS); + res = parse_config(dialogrc_config, + path, NULL, FIGPAR_BREAK_ON_EQUALS); /* Set some globals based on what we parsed */ use_shadow = dialogrc_config_option("use_shadow")->value.boolean; use_colors = dialogrc_config_option("use_colors")->value.boolean; snprintf(gauge_color, STR_BUFSIZE, "%s", dialogrc_config_option("gauge_color")->value.str); return (res); } /* * Return a pointer to the `.dialogrc' config option specific to `directive' or - * static fp_dummy_config (full of NULLs) if none found (see + * static figpar_dummy_config (full of NULLs) if none found (see * get_config_option(3); part of figpar(3)). */ -struct fp_config * +struct figpar_config * dialogrc_config_option(const char *directive) { return (get_config_option(dialogrc_config, directive)); } /* * Free allocated items initialized by setattr() (via parse_config() callback * matrix [dialogrc_config] used in parse_dialogrc() above). */ void dialogrc_free(void) { char *value; uint32_t n; for (n = 0; dialogrc_config[n].directive != NULL; n++) { if (dialogrc_config[n].action != &setattr) continue; value = dialogrc_config[n].value.str; if (value != NULL && value != gauge_color) { free(dialogrc_config[n].value.str); dialogrc_config[n].value.str = NULL; } } } Index: user/ngie/stable-10-libnv/lib/libdpv/dialogrc.h =================================================================== --- user/ngie/stable-10-libnv/lib/libdpv/dialogrc.h (revision 293638) +++ user/ngie/stable-10-libnv/lib/libdpv/dialogrc.h (revision 293639) @@ -1,56 +1,56 @@ /*- - * Copyright (c) 2013-2014 Devin Teske + * Copyright (c) 2013-2015 Devin Teske * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _DIALOGRC_H_ #define _DIALOGRC_H_ #include #include /* dialog(3) dlg_color_table[] attributes */ #define GAUGE_ATTR 33 /* entry used for gauge_color */ /* dialog(1) characteristics */ #define DIALOGRC ".dialogrc" #define ENV_DIALOGRC "DIALOGRC" #define ENV_HOME "HOME" /* dialog(1) `.dialogrc' characteristics */ extern uint8_t use_colors; extern uint8_t use_shadow; extern char gauge_color[]; extern char separator[]; __BEGIN_DECLS void dialogrc_free(void); int parse_dialogrc(void); -struct fp_config *dialogrc_config_option(const char *_directive); +struct figpar_config *dialogrc_config_option(const char *_directive); __END_DECLS #endif /* !_DIALOGRC_H_ */ Index: user/ngie/stable-10-libnv/lib/libdpv/util.h =================================================================== --- user/ngie/stable-10-libnv/lib/libdpv/util.h (revision 293638) +++ user/ngie/stable-10-libnv/lib/libdpv/util.h (revision 293639) @@ -1,50 +1,50 @@ /*- - * Copyright (c) 2013-2014 Devin Teske + * Copyright (c) 2013-2016 Devin Teske * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _UTIL_H_ #define _UTIL_H_ #include #include #define SHELL_SPAWN_DEBUG 0 /* Debug spawning of sh(1) commands */ #ifdef _PATH_BSHELL #define PATH_SHELL _PATH_BSHELL #else #define PATH_SHELL "/bin/sh" #endif -#define CMDBUFMAX 4096 +#define CMDBUFMAX 65536 __BEGIN_DECLS int shell_spawn_pipecmd(const char *_cmd, const char *_label, pid_t *_pid); __END_DECLS #endif /* !_UTIL_H_ */ Index: user/ngie/stable-10-libnv/lib/libfigpar/figpar.3 =================================================================== --- user/ngie/stable-10-libnv/lib/libfigpar/figpar.3 (revision 293638) +++ user/ngie/stable-10-libnv/lib/libfigpar/figpar.3 (revision 293639) @@ -1,251 +1,251 @@ .\" Copyright (c) 2013-2015 Devin Teske .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" -.Dd Oct 22, 2015 +.Dd Nov 2, 2015 .Dt FIGPAR 3 .Os .Sh NAME .Nm figpar , .Nm parse_config , .Nm get_config_option .Nd configuration file parsing library .Sh LIBRARY .Lb libfigpar .Sh SYNOPSIS .In figpar.h .Ft int .Fo parse_config -.Fa "struct fp_config options[], const char *path" -.Fa "int \*[lp]*unknown\*[rp]\*[lp]struct fp_config *option, uint32_t line" +.Fa "struct figpar_config options[], const char *path" +.Fa "int \*[lp]*unknown\*[rp]\*[lp]struct figpar_config *option, uint32_t line" .Fa "char *directive, char *value\*[rp], uint8_t processing_options" .Fc -.Ft "struct fp_config *" +.Ft "struct figpar_config *" .Fo get_config_option -.Fa "struct fp_config options[], const char *directive" +.Fa "struct figpar_config options[], const char *directive" .Fc .In string_m.h .Ft int .Fo replaceall .Fa "char *source, const char *find, const char *replace" .Fc .Ft unsigned int .Fo strcount .Fa "const char *source, const char *find" .Fc .Ft void .Fo strexpand .Fa "char *source" .Fc .Ft void .Fo strexpandnl .Fa "char *source" .Fc .Ft void .Fo strtolower .Fa "char *source" .Fc .Sh DESCRIPTION The .Nm library provides a light-weight, portable framework for parsing configuration files. The library uses .Xr open 2 , .Xr read 2 , and .Xr lseek 2 within the file pointed to by .Fa path to find directives and values which are then made available to the application. .Pp Due to the fact that configuration files may have basic syntax differences, the library does not attempt to impose any structure on the data but instead provides raw data to a set of callback functions. These callback functions can in-turn initiate abort through their return value, allowing custom syntax validation during parsing. .Pp Configuration directives, types, and callback functions are provided through data structures defined in .In figpar.h : .Bd -literal -offset indent -struct fp_config { - enum fp_cfgtype type; /* value type */ - const char *directive; /* keyword */ - union fp_cfgvalue value; /* value */ +struct figpar_config { + enum figpar_cfgtype type; /* value type */ + const char *directive; /* keyword */ + union figpar_cfgvalue value; /* value */ /* Pointer to function used when directive is found */ - int (*action)(struct fp_config *option, uint32_t line, + int (*action)(struct figpar_config *option, uint32_t line, char *directive, char *value); }; -enum fp_cfgtype { - FP_TYPE_NONE = 0x0000, /* for directives with no value */ - FP_TYPE_BOOL = 0x0001, /* boolean */ - FP_TYPE_INT = 0x0002, /* signed 32 bit integer */ - FP_TYPE_UINT = 0x0004, /* unsigned 32 bit integer */ - FP_TYPE_STR = 0x0008, /* string pointer */ - FP_TYPE_STRARRAY = 0x0010, /* string array pointer */ - FP_TYPE_DATA1 = 0x0020, /* void data type-1 (whatever) */ - FP_TYPE_DATA2 = 0x0040, /* void data type-2 (whatever) */ - FP_TYPE_DATA3 = 0x0080, /* void data type-3 (whatever) */ - FP_TYPE_RESERVED1 = 0x0100, /* reserved data type-1 (future) */ - FP_TYPE_RESERVED2 = 0x0200, /* reserved data type-2 (future) */ - FP_TYPE_RESERVED3 = 0x0400, /* reserved data type-3 (future) */ +enum figpar_cfgtype { + FIGPAR_TYPE_NONE = 0x0000, /* directives with no value */ + FIGPAR_TYPE_BOOL = 0x0001, /* boolean */ + FIGPAR_TYPE_INT = 0x0002, /* signed 32 bit integer */ + FIGPAR_TYPE_UINT = 0x0004, /* unsigned 32 bit integer */ + FIGPAR_TYPE_STR = 0x0008, /* string pointer */ + FIGPAR_TYPE_STRARRAY = 0x0010, /* string array pointer */ + FIGPAR_TYPE_DATA1 = 0x0020, /* void data type-1 (open) */ + FIGPAR_TYPE_DATA2 = 0x0040, /* void data type-2 (open) */ + FIGPAR_TYPE_DATA3 = 0x0080, /* void data type-3 (open) */ + FIGPAR_TYPE_RESERVED1 = 0x0100, /* reserved data type-1 */ + FIGPAR_TYPE_RESERVED2 = 0x0200, /* reserved data type-2 */ + FIGPAR_TYPE_RESERVED3 = 0x0400, /* reserved data type-3 */ }; -union fp_cfgvalue { +union figpar_cfgvalue { void *data; /* Pointer to NUL-terminated string */ char *str; /* Pointer to NUL-terminated string */ char **strarray; /* Pointer to an array of strings */ int32_t num; /* Signed 32-bit integer value */ uint32_t u_num; /* Unsigned 32-bit integer value */ uint32_t boolean:1; /* Boolean integer value (0 or 1) */ }; .Ed .Pp The .Fa processing_options argument to .Fn parse_config is a mask of bit fields which indicate various processing options. The possible flags are as follows: -.Bl -tag -width FP_BREAK_ON_SEMICOLON -.It Dv FP_BREAK_ON_EQUALS +.Bl -tag -width FIGPAR_BREAK_ON_SEMICOLON +.It Dv FIGPAR_BREAK_ON_EQUALS An equals sign .Pq Ql Li = is normally considered part of the directive. This flag enables terminating the directive at the equals sign. Also makes equals sign optional and transient. -.It Dv FP_BREAK_ON_SEMICOLON +.It Dv FIGPAR_BREAK_ON_SEMICOLON A semicolon .Pq Ql Li \; is normally considered part of the value. This flag enables terminating the value at the semicolon. Also allows multiple statements on a single line separated by semicolon. -.It Dv FP_CASE_SENSITIVE +.It Dv FIGPAR_CASE_SENSITIVE Normally directives are matched case insensitively using .Xr fnmatch 3 . This flag enables directive matching to be case sensitive. -.It Dv FP_REQUIRE_EQUALS +.It Dv FIGPAR_REQUIRE_EQUALS If a directive is not followed by an equals, processing is aborted. -.It Dv FP_STRICT_EQUALS +.It Dv FIGPAR_STRICT_EQUALS Equals must be part of the directive to be considered a delimiter between directive and value. .El .Pp The .Fa options struct array pointer can be NULL and every directive will invoke the .Fn unknown function argument. .Pp -The directive for each fp_config item in the +The directive for each figpar_config item in the .Fn parse_config options argument is matched against each parsed directive using .Xr fnmatch 3 until a match is found. If a match is found, the .Fn action -function for that fp_config directive is invoked with the line number, +function for that figpar_config directive is invoked with the line number, directive, and value. Otherwise if no match, the .Fn unknown function is invoked .Pq with the same arguments . .Pp If either .Fa action or .Fa unknown return non-zero, .Fn parse_config aborts reading the file and returns the error value to its caller. .Pp .Fn get_config_option traverses the options-array and returns the option that matches via .Xr strcmp 3 , or if no match a pointer to a static dummy struct is returned .Pq whose values are all zero or NULL . .Pp The use of -.Fa "struct fp_config" +.Fa "struct figpar_config" is entirely optional as-is the use of -.Fa "enum fp_cfgtype" +.Fa "enum figpar_cfgtype" or -.Fa "union fp_cfgvalue" . +.Fa "union figpar_cfgvalue" . For example, you could choose to pass a NULL pointer to .Fn parse_config for the first argument and then provide a simple .Fa unknown function based on .Xr queue 3 that populates a singly-linked list of your own struct containing the .Fa directive and .Fa value . .Pp In addition, the following miscellaneous string manipulation routines are provided by .In string_m.h : .Bl -tag -width strexpandnl() .It Fn replaceall Replace all occurrences of .Fa find in .Fa source with .Fa replace . .It Fn strcount Count the number of occurrences of one string that appear in the .Fa source string. Return value is the total count. An example use would be if you need to know how large a block of memory needs to be for a .Fn replaceall series. .It Fn strexpand Expand escape sequences in a buffer pointed to by .Fa source . .It Fn strexpandnl Expand only the escaped newlines in a buffer pointed to by .Fa source . .It Fn strtolower Convert a string to lower case. .El .Sh SEE ALSO .Xr queue 3 .Sh HISTORY The .Nm library first appeared in .Fx 10.2 . .Sh AUTHORS .An Devin Teske Aq dteske@FreeBSD.org .Sh BUGS This is the first implementation of the library, and the interface may be subject to refinement. Index: user/ngie/stable-10-libnv/lib/libfigpar/figpar.c =================================================================== --- user/ngie/stable-10-libnv/lib/libfigpar/figpar.c (revision 293638) +++ user/ngie/stable-10-libnv/lib/libfigpar/figpar.c (revision 293639) @@ -1,469 +1,474 @@ /*- - * Copyright (c) 2002-2014 Devin Teske + * Copyright (c) 2002-2015 Devin Teske * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include "figpar.h" #include "string_m.h" -struct fp_config fp_dummy_config = {0, NULL, {0}, NULL}; +struct figpar_config figpar_dummy_config = {0, NULL, {0}, NULL}; /* - * Search for config option (struct fp_config) in the array of config options, - * returning the struct whose directive matches the given parameter. If no - * match is found, a pointer to the static dummy array (above) is returned. + * Search for config option (struct figpar_config) in the array of config + * options, returning the struct whose directive matches the given parameter. + * If no match is found, a pointer to the static dummy array (above) is + * returned. * * This is to eliminate dependency on the index position of an item in the * array, since the index position is more apt to be changed as code grows. */ -struct fp_config * -get_config_option(struct fp_config options[], const char *directive) +struct figpar_config * +get_config_option(struct figpar_config options[], const char *directive) { uint32_t n; /* Check arguments */ if (options == NULL || directive == NULL) - return (&fp_dummy_config); + return (&figpar_dummy_config); /* Loop through the array, return the index of the first match */ for (n = 0; options[n].directive != NULL; n++) if (strcmp(options[n].directive, directive) == 0) return (&(options[n])); /* Re-initialize the dummy variable in case it was written to */ - fp_dummy_config.directive = NULL; - fp_dummy_config.type = 0; - fp_dummy_config.action = NULL; - fp_dummy_config.value.u_num = 0; + figpar_dummy_config.directive = NULL; + figpar_dummy_config.type = 0; + figpar_dummy_config.action = NULL; + figpar_dummy_config.value.u_num = 0; - return (&fp_dummy_config); + return (&figpar_dummy_config); } /* * Parse the configuration file at `path' and execute the `action' call-back * functions for any directives defined by the array of config options (first * argument). * * For unknown directives that are encountered, you can optionally pass a * call-back function for the third argument to be called for unknowns. * * Returns zero on success; otherwise returns -1 and errno should be consulted. */ int -parse_config(struct fp_config options[], const char *path, - int (*unknown)(struct fp_config *option, uint32_t line, char *directive, - char *value), uint16_t processing_options) +parse_config(struct figpar_config options[], const char *path, + int (*unknown)(struct figpar_config *option, uint32_t line, + char *directive, char *value), uint16_t processing_options) { uint8_t bequals; uint8_t bsemicolon; uint8_t case_sensitive; uint8_t comment = 0; uint8_t end; uint8_t found; uint8_t have_equals = 0; uint8_t quote; uint8_t require_equals; uint8_t strict_equals; char p[2]; char *directive; char *t; char *value; int error; int fd; ssize_t r = 1; uint32_t dsize; uint32_t line = 1; uint32_t n; uint32_t vsize; uint32_t x; off_t charpos; off_t curpos; char rpath[PATH_MAX]; /* Sanity check: if no options and no unknown function, return */ if (options == NULL && unknown == NULL) return (-1); /* Processing options */ - bequals = (processing_options & FP_BREAK_ON_EQUALS) == 0 ? 0 : 1; - bsemicolon = (processing_options & FP_BREAK_ON_SEMICOLON) == 0 ? 0 : 1; - case_sensitive = (processing_options & FP_CASE_SENSITIVE) == 0 ? 0 : 1; - require_equals = (processing_options & FP_REQUIRE_EQUALS) == 0 ? 0 : 1; - strict_equals = (processing_options & FP_STRICT_EQUALS) == 0 ? 0 : 1; + bequals = (processing_options & FIGPAR_BREAK_ON_EQUALS) == 0 ? 0 : 1; + bsemicolon = + (processing_options & FIGPAR_BREAK_ON_SEMICOLON) == 0 ? 0 : 1; + case_sensitive = + (processing_options & FIGPAR_CASE_SENSITIVE) == 0 ? 0 : 1; + require_equals = + (processing_options & FIGPAR_REQUIRE_EQUALS) == 0 ? 0 : 1; + strict_equals = + (processing_options & FIGPAR_STRICT_EQUALS) == 0 ? 0 : 1; /* Initialize strings */ directive = value = 0; vsize = dsize = 0; /* Resolve the file path */ if (realpath(path, rpath) == 0) return (-1); /* Open the file */ if ((fd = open(rpath, O_RDONLY)) < 0) return (-1); /* Read the file until EOF */ while (r != 0) { r = read(fd, p, 1); /* skip to the beginning of a directive */ while (r != 0 && (isspace(*p) || *p == '#' || comment || (bsemicolon && *p == ';'))) { if (*p == '#') comment = 1; else if (*p == '\n') { comment = 0; line++; } r = read(fd, p, 1); } /* Test for EOF; if EOF then no directive was found */ if (r == 0) { close(fd); return (0); } /* Get the current offset */ curpos = lseek(fd, 0, SEEK_CUR) - 1; if (curpos == -1) { close(fd); return (-1); } /* Find the length of the directive */ for (n = 0; r != 0; n++) { if (isspace(*p)) break; if (bequals && *p == '=') { have_equals = 1; break; } if (bsemicolon && *p == ';') break; r = read(fd, p, 1); } /* Test for EOF, if EOF then no directive was found */ if (n == 0 && r == 0) { close(fd); return (0); } /* Go back to the beginning of the directive */ error = (int)lseek(fd, curpos, SEEK_SET); if (error == (curpos - 1)) { close(fd); return (-1); } /* Allocate and read the directive into memory */ if (n > dsize) { if ((directive = realloc(directive, n + 1)) == NULL) { close(fd); return (-1); } dsize = n; } r = read(fd, directive, n); /* Advance beyond the equals sign if appropriate/desired */ if (bequals && *p == '=') { if (lseek(fd, 1, SEEK_CUR) != -1) r = read(fd, p, 1); if (strict_equals && isspace(*p)) *p = '\n'; } /* Terminate the string */ directive[n] = '\0'; /* Convert directive to lower case before comparison */ if (!case_sensitive) strtolower(directive); /* Move to what may be the start of the value */ if (!(bsemicolon && *p == ';') && !(strict_equals && *p == '=')) { while (r != 0 && isspace(*p) && *p != '\n') r = read(fd, p, 1); } /* An equals sign may have stopped us, should we eat it? */ if (r != 0 && bequals && *p == '=' && !strict_equals) { have_equals = 1; r = read(fd, p, 1); while (r != 0 && isspace(*p) && *p != '\n') r = read(fd, p, 1); } /* If no value, allocate a dummy value and jump to action */ if (r == 0 || *p == '\n' || *p == '#' || (bsemicolon && *p == ';')) { /* Initialize the value if not already done */ if (value == NULL && (value = malloc(1)) == NULL) { close(fd); return (-1); } value[0] = '\0'; goto call_function; } /* Get the current offset */ curpos = lseek(fd, 0, SEEK_CUR) - 1; if (curpos == -1) { close(fd); return (-1); } /* Find the end of the value */ quote = 0; end = 0; while (r != 0 && end == 0) { /* Advance to the next character if we know we can */ if (*p != '\"' && *p != '#' && *p != '\n' && (!bsemicolon || *p != ';')) { r = read(fd, p, 1); continue; } /* * If we get this far, we've hit an end-key */ /* Get the current offset */ charpos = lseek(fd, 0, SEEK_CUR) - 1; if (charpos == -1) { close(fd); return (-1); } /* * Go back so we can read the character before the key * to check if the character is escaped (which means we * should continue). */ error = (int)lseek(fd, -2, SEEK_CUR); if (error == -3) { close(fd); return (-1); } r = read(fd, p, 1); /* * Count how many backslashes there are (an odd number * means the key is escaped, even means otherwise). */ for (n = 1; *p == '\\'; n++) { /* Move back another offset to read */ error = (int)lseek(fd, -2, SEEK_CUR); if (error == -3) { close(fd); return (-1); } r = read(fd, p, 1); } /* Move offset back to the key and read it */ error = (int)lseek(fd, charpos, SEEK_SET); if (error == (charpos - 1)) { close(fd); return (-1); } r = read(fd, p, 1); /* * If an even number of backslashes was counted meaning * key is not escaped, we should evaluate what to do. */ if ((n & 1) == 1) { switch (*p) { case '\"': /* * Flag current sequence of characters * to follow as being quoted (hashes * are not considered comments). */ quote = !quote; break; case '#': /* * If we aren't in a quoted series, we * just hit an inline comment and have * found the end of the value. */ if (!quote) end = 1; break; case '\n': /* * Newline characters must always be * escaped, whether inside a quoted * series or not, otherwise they * terminate the value. */ end = 1; case ';': if (!quote && bsemicolon) end = 1; break; } } else if (*p == '\n') /* Escaped newline character. increment */ line++; /* Advance to the next character */ r = read(fd, p, 1); } /* Get the current offset */ charpos = lseek(fd, 0, SEEK_CUR) - 1; if (charpos == -1) { close(fd); return (-1); } /* Get the length of the value */ n = (uint32_t)(charpos - curpos); if (r != 0) /* more to read, but don't read ending key */ n--; /* Move offset back to the beginning of the value */ error = (int)lseek(fd, curpos, SEEK_SET); if (error == (curpos - 1)) { close(fd); return (-1); } /* Allocate and read the value into memory */ if (n > vsize) { if ((value = realloc(value, n + 1)) == NULL) { close(fd); return (-1); } vsize = n; } r = read(fd, value, n); /* Terminate the string */ value[n] = '\0'; /* Cut trailing whitespace off by termination */ t = value + n; while (isspace(*--t)) *t = '\0'; /* Escape the escaped quotes (replaceall is in string_m.c) */ x = strcount(value, "\\\""); /* in string_m.c */ if (x != 0 && (n + x) > vsize) { if ((value = realloc(value, n + x + 1)) == NULL) { close(fd); return (-1); } vsize = n + x; } if (replaceall(value, "\\\"", "\\\\\"") < 0) { /* Replace operation failed for some unknown reason */ close(fd); return (-1); } /* Remove all new line characters */ if (replaceall(value, "\\\n", "") < 0) { /* Replace operation failed for some unknown reason */ close(fd); return (-1); } /* Resolve escape sequences */ strexpand(value); /* in string_m.c */ call_function: /* Abort if we're seeking only assignments */ if (require_equals && !have_equals) return (-1); found = have_equals = 0; /* reset */ /* If there are no options defined, call unknown and loop */ if (options == NULL && unknown != NULL) { error = unknown(NULL, line, directive, value); if (error != 0) { close(fd); return (error); } continue; } /* Loop through the array looking for a match for the value */ for (n = 0; options[n].directive != NULL; n++) { error = fnmatch(options[n].directive, directive, FNM_NOESCAPE); if (error == 0) { found = 1; /* Call function for array index item */ if (options[n].action != NULL) { error = options[n].action( &options[n], line, directive, value); if (error != 0) { close(fd); return (error); } } } else if (error != FNM_NOMATCH) { /* An error has occurred */ close(fd); return (-1); } } if (!found && unknown != NULL) { /* * No match was found for the value we read from the * file; call function designated for unknown values. */ error = unknown(NULL, line, directive, value); if (error != 0) { close(fd); return (error); } } } close(fd); return (0); } Index: user/ngie/stable-10-libnv/lib/libfigpar/figpar.h =================================================================== --- user/ngie/stable-10-libnv/lib/libfigpar/figpar.h (revision 293638) +++ user/ngie/stable-10-libnv/lib/libfigpar/figpar.h (revision 293639) @@ -1,99 +1,99 @@ /*- - * Copyright (c) 2002-2014 Devin Teske + * Copyright (c) 2002-2015 Devin Teske * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _FIGPAR_H_ #define _FIGPAR_H_ #include /* * Union for storing various types of data in a single common container. */ -union fp_cfgvalue { +union figpar_cfgvalue { void *data; /* Pointer to NUL-terminated string */ char *str; /* Pointer to NUL-terminated string */ char **strarray; /* Pointer to an array of strings */ int32_t num; /* Signed 32-bit integer value */ uint32_t u_num; /* Unsigned 32-bit integer value */ uint32_t boolean:1; /* Boolean integer value (0 or 1) */ }; /* * Option types (based on above cfgvalue union) */ -enum fp_cfgtype { - FP_TYPE_NONE = 0x0000, /* for directives with no value */ - FP_TYPE_BOOL = 0x0001, /* boolean */ - FP_TYPE_INT = 0x0002, /* signed 32 bit integer */ - FP_TYPE_UINT = 0x0004, /* unsigned 32 bit integer */ - FP_TYPE_STR = 0x0008, /* string pointer */ - FP_TYPE_STRARRAY = 0x0010, /* string array pointer */ - FP_TYPE_DATA1 = 0x0020, /* void data type-1 (whatever) */ - FP_TYPE_DATA2 = 0x0040, /* void data type-2 (whatever) */ - FP_TYPE_DATA3 = 0x0080, /* void data type-3 (whatever) */ - FP_TYPE_RESERVED1 = 0x0100, /* reserved data type-1 (future) */ - FP_TYPE_RESERVED2 = 0x0200, /* reserved data type-2 (future) */ - FP_TYPE_RESERVED3 = 0x0400, /* reserved data type-3 (future) */ +enum figpar_cfgtype { + FIGPAR_TYPE_NONE = 0x0000, /* directives with no value */ + FIGPAR_TYPE_BOOL = 0x0001, /* boolean */ + FIGPAR_TYPE_INT = 0x0002, /* signed 32 bit integer */ + FIGPAR_TYPE_UINT = 0x0004, /* unsigned 32 bit integer */ + FIGPAR_TYPE_STR = 0x0008, /* string pointer */ + FIGPAR_TYPE_STRARRAY = 0x0010, /* string array pointer */ + FIGPAR_TYPE_DATA1 = 0x0020, /* void data type-1 (open) */ + FIGPAR_TYPE_DATA2 = 0x0040, /* void data type-2 (open) */ + FIGPAR_TYPE_DATA3 = 0x0080, /* void data type-3 (open) */ + FIGPAR_TYPE_RESERVED1 = 0x0100, /* reserved data type-1 */ + FIGPAR_TYPE_RESERVED2 = 0x0200, /* reserved data type-2 */ + FIGPAR_TYPE_RESERVED3 = 0x0400, /* reserved data type-3 */ }; /* * Options to parse_config() for processing_options bitmask */ -#define FP_BREAK_ON_EQUALS 0x0001 /* stop reading directive at `=' */ -#define FP_BREAK_ON_SEMICOLON 0x0002 /* `;' starts a new line */ -#define FP_CASE_SENSITIVE 0x0004 /* directives are case sensitive */ -#define FP_REQUIRE_EQUALS 0x0008 /* assignment directives only */ -#define FP_STRICT_EQUALS 0x0010 /* `=' must be part of directive */ +#define FIGPAR_BREAK_ON_EQUALS 0x0001 /* stop reading directive at `=' */ +#define FIGPAR_BREAK_ON_SEMICOLON 0x0002 /* `;' starts a new line */ +#define FIGPAR_CASE_SENSITIVE 0x0004 /* directives are case sensitive */ +#define FIGPAR_REQUIRE_EQUALS 0x0008 /* assignment directives only */ +#define FIGPAR_STRICT_EQUALS 0x0010 /* `=' must be part of directive */ /* * Anatomy of a config file option */ -struct fp_config { - enum fp_cfgtype type; /* Option value type */ +struct figpar_config { + enum figpar_cfgtype type; /* Option value type */ const char *directive; /* config file keyword */ - union fp_cfgvalue value; /* NB: set by action */ + union figpar_cfgvalue value; /* NB: set by action */ /* * Function pointer; action to be taken when the directive is found */ - int (*action)(struct fp_config *option, uint32_t line, char *directive, - char *value); + int (*action)(struct figpar_config *option, uint32_t line, + char *directive, char *value); }; -extern struct fp_config fp_dummy_config; +extern struct figpar_config figpar_dummy_config; __BEGIN_DECLS -int parse_config(struct fp_config _options[], +int parse_config(struct figpar_config _options[], const char *_path, - int (*_unknown)(struct fp_config *_option, + int (*_unknown)(struct figpar_config *_option, uint32_t _line, char *_directive, char *_value), uint16_t _processing_options); -struct fp_config *get_config_option(struct fp_config _options[], +struct figpar_config *get_config_option(struct figpar_config _options[], const char *_directive); __END_DECLS #endif /* _FIGPAR_H_ */ Index: user/ngie/stable-10-libnv/sbin/geom/class/part/gpart.8 =================================================================== --- user/ngie/stable-10-libnv/sbin/geom/class/part/gpart.8 (revision 293638) +++ user/ngie/stable-10-libnv/sbin/geom/class/part/gpart.8 (revision 293639) @@ -1,1344 +1,1334 @@ .\" Copyright (c) 2007, 2008 Marcel Moolenaar .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" -.Dd July 14, 2015 +.Dd December 10, 2015 .Dt GPART 8 .Os .Sh NAME .Nm gpart .Nd "control utility for the disk partitioning GEOM class" .Sh SYNOPSIS .\" ==== ADD ==== .Nm .Cm add .Fl t Ar type .Op Fl a Ar alignment .Op Fl b Ar start .Op Fl s Ar size .Op Fl i Ar index .Op Fl l Ar label .Op Fl f Ar flags .Ar geom .\" ==== BACKUP ==== .Nm .Cm backup .Ar geom .\" ==== BOOTCODE ==== .Nm .Cm bootcode .Op Fl b Ar bootcode .Op Fl p Ar partcode Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== COMMIT ==== .Nm .Cm commit .Ar geom .\" ==== CREATE ==== .Nm .Cm create .Fl s Ar scheme .Op Fl n Ar entries .Op Fl f Ar flags .Ar provider .\" ==== DELETE ==== .Nm .Cm delete .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== DESTROY ==== .Nm .Cm destroy .Op Fl F .Op Fl f Ar flags .Ar geom .\" ==== MODIFY ==== .Nm .Cm modify .Fl i Ar index .Op Fl l Ar label .Op Fl t Ar type .Op Fl f Ar flags .Ar geom .\" ==== RECOVER ==== .Nm .Cm recover .Op Fl f Ar flags .Ar geom .\" ==== RESIZE ==== .Nm .Cm resize .Fl i Ar index .Op Fl a Ar alignment .Op Fl s Ar size .Op Fl f Ar flags .Ar geom .\" ==== RESTORE ==== .Nm .Cm restore .Op Fl lF .Op Fl f Ar flags .Ar provider .Op Ar ... .\" ==== SET ==== .Nm .Cm set .Fl a Ar attrib .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== SHOW ==== .Nm .Cm show .Op Fl l | r .Op Fl p .Op Ar geom ... .\" ==== UNDO ==== .Nm .Cm undo .Ar geom .\" ==== UNSET ==== .Nm .Cm unset .Fl a Ar attrib .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" .Nm .Cm list .Nm .Cm status .Nm .Cm load .Nm .Cm unload .Sh DESCRIPTION The .Nm utility is used to partition GEOM providers, normally disks. The first argument is the action to be taken: .Bl -tag -width ".Cm bootcode" .\" ==== ADD ==== .It Cm add Add a new partition to the partitioning scheme given by .Ar geom . The partition begins on the logical block address given by the .Fl b Ar start option. Its size is given by the .Fl s Ar size option. SI unit suffixes are allowed. One or both .Fl b and .Fl s options can be omitted. If so they are automatically calculated. The type of the partition is given by the .Fl t Ar type option. Partition types are discussed below in the section entitled .Sx "PARTITION TYPES" . .Pp Additional options include: .Bl -tag -width 12n .It Fl a Ar alignment If specified, then .Nm utility tries to align .Ar start offset and partition .Ar size to be multiple of .Ar alignment value. .It Fl i Ar index The index in the partition table at which the new partition is to be placed. The index determines the name of the device special file used to represent the partition. .It Fl l Ar label The label attached to the partition. This option is only valid when used on partitioning schemes that support partition labels. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== BACKUP ==== .It Cm backup Dump a partition table to standard output in a special format used by the .Cm restore action. .\" ==== BOOTCODE ==== .It Cm bootcode Embed bootstrap code into the partitioning scheme's metadata on the .Ar geom (using .Fl b Ar bootcode ) or write bootstrap code into a partition (using .Fl p Ar partcode and .Fl i Ar index ) . Not all partitioning schemes have embedded bootstrap code, so the .Fl b Ar bootcode option is scheme-specific in nature (see the section entitled .Sx BOOTSTRAPPING below). The .Fl b Ar bootcode option specifies a file that contains the bootstrap code. The contents and size of the file are determined by the partitioning scheme. The .Fl p Ar partcode option specifies a file that contains the bootstrap code intended to be written to a partition. The partition is specified by the .Fl i Ar index option. The size of the file must be smaller than the size of the partition. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== COMMIT ==== .It Cm commit Commit any pending changes for geom .Ar geom . All actions are committed by default and will not result in pending changes. Actions can be modified with the .Fl f Ar flags option so that they are not committed, but become pending. Pending changes are reflected by the geom and the .Nm utility, but they are not actually written to disk. The .Cm commit action will write all pending changes to disk. .\" ==== CREATE ==== .It Cm create Create a new partitioning scheme on a provider given by .Ar provider . The .Fl s Ar scheme option determines the scheme to use. The kernel must have support for a particular scheme before that scheme can be used to partition a disk. .Pp Additional options include: .Bl -tag -width 10n .It Fl n Ar entries The number of entries in the partition table. Every partitioning scheme has a minimum and maximum number of entries. This option allows tables to be created with a number of entries that is within the limits. Some schemes have a maximum equal to the minimum and some schemes have a maximum large enough to be considered unlimited. By default, partition tables are created with the minimum number of entries. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== DELETE ==== .It Cm delete Delete a partition from geom .Ar geom and further identified by the .Fl i Ar index option. The partition cannot be actively used by the kernel. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== DESTROY ==== .It Cm destroy Destroy the partitioning scheme as implemented by geom .Ar geom . .Pp Additional options include: .Bl -tag -width 10n .It Fl F Forced destroying of the partition table even if it is not empty. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== MODIFY ==== .It Cm modify Modify a partition from geom .Ar geom and further identified by the .Fl i Ar index option. Only the type and/or label of the partition can be modified. To change the type of a partition, specify the new type with the .Fl t Ar type option. To change the label of a partition, specify the new label with the .Fl l Ar label option. Not all partitioning schemes support labels and it is invalid to try to change a partition label in such cases. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== RECOVER ==== .It Cm recover Recover a corrupt partition's scheme metadata on the geom .Ar geom . See the section entitled .Sx RECOVERING below for the additional information. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== RESIZE ==== .It Cm resize Resize a partition from geom .Ar geom and further identified by the .Fl i Ar index option. New partition size is expressed in logical block numbers and can be given by the .Fl s Ar size option. If .Fl s option is omitted then new size is automatically calculated to maximum available from given geom .Ar geom . .Pp Additional options include: .Bl -tag -width 12n .It Fl a Ar alignment If specified, then .Nm utility tries to align partition .Ar size to be multiple of .Ar alignment value. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== RESTORE ==== .It Cm restore Restore the partition table from a backup previously created by the .Cm backup action and read from standard input. Only the partition table is restored. This action does not affect the content of partitions. After restoring the partition table and writing bootcode if needed, user data must be restored from backup. .Pp Additional options include: .Bl -tag -width 10n .It Fl F Destroy partition table on the given .Ar provider before doing restore. .It Fl l Restore partition labels for partitioning schemes that support them. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== SET ==== .It Cm set Set the named attribute on the partition entry. See the section entitled .Sx ATTRIBUTES below for a list of available attributes. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== SHOW ==== .It Cm show Show current partition information for the specified geoms, or all geoms if none are specified. The default output includes the logical starting block of each partition, the partition size in blocks, the partition index number, the partition type, and a human readable partition size. Block sizes and locations are based on the device's Sectorsize as shown by .Cm gpart list . Additional options include: .Bl -tag -width 10n .It Fl l For partitioning schemes that support partition labels, print them instead of partition type. .It Fl p Show provider names instead of partition indexes. .It Fl r Show raw partition type instead of symbolic name. .El .\" ==== UNDO ==== .It Cm undo Revert any pending changes for geom .Ar geom . This action is the opposite of the .Cm commit action and can be used to undo any changes that have not been committed. .\" ==== UNSET ==== .It Cm unset Clear the named attribute on the partition entry. See the section entitled .Sx ATTRIBUTES below for a list of available attributes. .Pp Additional options include: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .It Cm list See .Xr geom 8 . .It Cm status See .Xr geom 8 . .It Cm load See .Xr geom 8 . .It Cm unload See .Xr geom 8 . .El .Sh PARTITIONING SCHEMES Several partitioning schemes are supported by the .Nm utility: .Bl -tag -width ".Cm VTOC8" .It Cm APM Apple Partition Map, used by PowerPC(R) Macintosh(R) computers. Requires the .Cd GEOM_PART_APM kernel option. .It Cm BSD Traditional BSD disklabel, usually used to subdivide MBR partitions. .Po This scheme can also be used as the sole partitioning method, without an MBR. Partition editing tools from other operating systems often do not understand the bare disklabel partition layout, so this is sometimes called .Dq dangerously dedicated . .Pc Requires the .Cm GEOM_PART_BSD kernel option. .It Cm BSD64 64-bit implementation of BSD disklabel used in DragonFlyBSD to subdivide MBR or GPT partitions. Requires the .Cm GEOM_PART_BSD64 kernel option. .It Cm LDM The Logical Disk Manager is an implementation of volume manager for Microsoft Windows NT. Requires the .Cd GEOM_PART_LDM kernel option. .It Cm GPT GUID Partition Table is used on Intel-based Macintosh computers and gradually replacing MBR on most PCs and other systems. Requires the .Cm GEOM_PART_GPT kernel option. .It Cm MBR Master Boot Record is used on PCs and removable media. Requires the .Cm GEOM_PART_MBR kernel option. The .Cm GEOM_PART_EBR option adds support for the Extended Boot Record (EBR), which is used to define a logical partition. The .Cm GEOM_PART_EBR_COMPAT option enables backward compatibility for partition names in the EBR scheme. It also prevents any type of actions on such partitions. .It Cm PC98 An MBR variant for NEC PC-98 and compatible computers. Requires the .Cm GEOM_PART_PC98 kernel option. .It Cm VTOC8 Sun's SMI Volume Table Of Contents, used by .Tn SPARC64 and .Tn UltraSPARC computers. Requires the .Cm GEOM_PART_VTOC8 kernel option. .El .Sh PARTITION TYPES Partition types are identified on disk by particular strings or magic values. The .Nm utility uses symbolic names for common partition types so the user does not need to know these values or other details of the partitioning scheme in question. The .Nm utility also allows the user to specify scheme-specific partition types for partition types that do not have symbolic names. Symbolic names currently understood and used by .Fx are: .Bl -tag -width ".Cm dragonfly-disklabel64" .It Cm apple-boot The system partition dedicated to storing boot loaders on some Apple systems. The scheme-specific types are .Qq Li "!171" for MBR, .Qq Li "!Apple_Bootstrap" for APM, and .Qq Li "!426f6f74-0000-11aa-aa11-00306543ecac" for GPT. .It Cm bios-boot The system partition dedicated to second stage of the boot loader program. Usually it is used by the GRUB 2 loader for GPT partitioning schemes. The scheme-specific type is .Qq Li "!21686148-6449-6E6F-744E-656564454649" . .It Cm efi The system partition for computers that use the Extensible Firmware Interface (EFI). In such cases, the GPT partitioning scheme is used and the actual partition type for the system partition can also be specified as .Qq Li "!c12a7328-f81f-11d2-ba4b-00a0c93ec93b" . .It Cm freebsd A .Fx partition subdivided into filesystems with a .Bx disklabel. This is a legacy partition type and should not be used for the APM or GPT schemes. The scheme-specific types are .Qq Li "!165" for MBR, .Qq Li "!FreeBSD" for APM, and .Qq Li "!516e7cb4-6ecf-11d6-8ff8-00022d09712b" for GPT. .It Cm freebsd-boot A .Fx partition dedicated to bootstrap code. The scheme-specific type is .Qq Li "!83bd6b9d-7f41-11dc-be0b-001560b84f0f" for GPT. .It Cm freebsd-swap A .Fx partition dedicated to swap space. The scheme-specific types are .Qq Li "!FreeBSD-swap" for APM, .Qq Li "!516e7cb5-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0901 for VTOC8. .It Cm freebsd-ufs A .Fx partition that contains a UFS or UFS2 filesystem. The scheme-specific types are .Qq Li "!FreeBSD-UFS" for APM, .Qq Li "!516e7cb6-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0902 for VTOC8. .It Cm freebsd-vinum A .Fx partition that contains a Vinum volume. The scheme-specific types are .Qq Li "!FreeBSD-Vinum" for APM, .Qq Li "!516e7cb8-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0903 for VTOC8. .It Cm freebsd-zfs A .Fx partition that contains a ZFS volume. The scheme-specific types are .Qq Li "!FreeBSD-ZFS" for APM, .Qq Li "!516e7cba-6ecf-11d6-8ff8-00022d09712b" for GPT, and 0x0904 for VTOC8. .El .Pp Another symbolic names that can be used with .Cm gpart utility are: .Bl -tag -width ".Cm dragonfly-disklabel64" .It Cm apple-core-storage An Apple Mac OS X partition used by logical volume manager known as Core Storage. The scheme-specific type is .Qq Li "!53746f72-6167-11aa-aa11-00306543ecac" for GPT. .It Cm apple-hfs An Apple Mac OS X partition that contains a HFS or HFS+ filesystem. The scheme-specific types are .Qq Li "!175" for MBR, .Qq Li "!Apple_HFS" for APM and .Qq Li "!48465300-0000-11aa-aa11-00306543ecac" for GPT. .It Cm apple-label An Apple Mac OS X partition dedicated to partition metadata that descibes disk device. The scheme-specific type is .Qq Li "!4c616265-6c00-11aa-aa11-00306543ecac" for GPT. .It Cm apple-raid An Apple Mac OS X partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!52414944-0000-11aa-aa11-00306543ecac" for GPT. .It Cm apple-raid-offline An Apple Mac OS X partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!52414944-5f4f-11aa-aa11-00306543ecac" for GPT. .It Cm apple-tv-recovery An Apple Mac OS X partition used by Apple TV. The scheme-specific type is .Qq Li "!5265636f-7665-11aa-aa11-00306543ecac" for GPT. .It Cm apple-ufs An Apple Mac OS X partition that contains a UFS filesystem. The scheme-specific types are .Qq Li "!168" for MBR, .Qq Li "!Apple_UNIX_SVR2" for APM and .Qq Li "!55465300-0000-11aa-aa11-00306543ecac" for GPT. .It Cm dragonfly-label32 A DragonFlyBSD partition subdivided into filesystems with a .Bx disklabel. The scheme-specific type is .Qq Li "!9d087404-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-label64 A DragonFlyBSD partition subdivided into filesystems with a disklabel64. The scheme-specific type is .Qq Li "!3d48ce54-1d16-11dc-8696-01301bb8a9f5" for GPT. .It Cm dragonfly-legacy A legacy partition type used in DragonFlyBSD. The scheme-specific type is .Qq Li "!bd215ab2-1d16-11dc-8696-01301bb8a9f5" for GPT. .It Cm dragonfly-ccd A DragonFlyBSD partition used with Concatenated Disk driver. The scheme-specific type is .Qq Li "!dbd5211b-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-hammer A DragonFlyBSD partition that contains a Hammer filesystem. The scheme-specific type is .Qq Li "!61dc63ac-6e38-11dc-8513-01301bb8a9f5" for GPT. .It Cm dragonfly-hammer2 A DragonFlyBSD partition that contains a Hammer2 filesystem. The scheme-specific type is .Qq Li "!5cbb9ad1-862d-11dc-a94d-01301bb8a9f5" for GPT. .It Cm dragonfly-swap A DragonFlyBSD partition dedicated to swap space. The scheme-specific type is .Qq Li "!9d58fdbd-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-ufs A DragonFlyBSD partition that contains an UFS1 filesystem. The scheme-specific type is .Qq Li "!9d94ce7c-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-vinum A DragonFlyBSD partition used with Logical Volume Manager. The scheme-specific type is .Qq Li "!9dd4478f-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm ebr A partition subdivided into filesystems with a EBR. The scheme-specific type is .Qq Li "!5" for MBR. .It Cm fat16 A partition that contains a FAT16 filesystem. The scheme-specific type is .Qq Li "!6" for MBR. .It Cm fat32 A partition that contains a FAT32 filesystem. The scheme-specific type is .Qq Li "!11" for MBR. .It Cm linux-data A Linux partition that contains some filesystem with data. The scheme-specific types are .Qq Li "!131" for MBR and .Qq Li "!0fc63daf-8483-4772-8e79-3d69d8477de4" for GPT. .It Cm linux-lvm A Linux partition dedicated to Logical Volume Manager. The scheme-specific types are .Qq Li "!142" for MBR and .Qq Li "!e6d6d379-f507-44c2-a23c-238f2a3df928" for GPT. .It Cm linux-raid A Linux partition used in a software RAID configuration. The scheme-specific types are .Qq Li "!253" for MBR and .Qq Li "!a19d880f-05fc-4d3b-a006-743f0f84911e" for GPT. .It Cm linux-swap A Linux partition dedicated to swap space. The scheme-specific types are .Qq Li "!130" for MBR and .Qq Li "!0657fd6d-a4ab-43c4-84e5-0933c84b4f4f" for GPT. .It Cm mbr A partition that is sub-partitioned by a Master Boot Record (MBR). This type is known as .Qq Li "!024dee41-33e7-11d3-9d69-0008c781f39f" by GPT. .It Cm ms-basic-data A basic data partition (BDP) for Microsoft operating systems. In the GPT this type is the equivalent to partition types .Cm fat16 , fat32 and .Cm ntfs in MBR. The scheme-specific type is .Qq Li "!ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" for GPT. .It Cm ms-ldm-data A partition that contains Logical Disk Manager (LDM) volumes. The scheme-specific types are .Qq Li "!66" for MBR, .Qq Li "!af9b60a0-1431-4f62-bc68-3311714a69ad" for GPT. .It Cm ms-ldm-metadata A partition that contains Logical Disk Manager (LDM) database. The scheme-specific type is .Qq Li "!5808c8aa-7e8f-42e0-85d2-e1e90434cfb3" for GPT. .It Cm netbsd-ccd A NetBSD partition used with Concatenated Disk driver. The scheme-specific type is .Qq Li "!2db519c4-b10f-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-cgd An encrypted NetBSD partition. The scheme-specific type is .Qq Li "!2db519ec-b10f-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-ffs A NetBSD partition that contains an UFS filesystem. The scheme-specific type is .Qq Li "!49f48d5a-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-lfs A NetBSD partition that contains an LFS filesystem. The scheme-specific type is .Qq Li "!49f48d82-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-raid A NetBSD partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!49f48daa-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-swap A NetBSD partition dedicated to swap space. The scheme-specific type is .Qq Li "!49f48d32-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm ntfs A partition that contains a NTFS or exFAT filesystem. The scheme-specific type is .Qq Li "!7" for MBR. .It Cm prep-boot The system partition dedicated to storing boot loaders on some PowerPC systems, notably those made by IBM. The scheme-specific types are .Qq Li "!65" for MBR and .Qq Li "!0x9e1a2d38-c612-4316-aa26-8b49521e5a8b" for GPT. .It Cm vmware-vmfs A partition that contains a VMware File System (VMFS). The scheme-specific types are .Qq Li "!251" for MBR and .Qq Li "!aa31e02a-400f-11db-9590-000c2911d1b8" for GPT. .It Cm vmware-vmkdiag A partition that contains a VMware diagostic filesystem. The scheme-specific types are .Qq Li "!252" for MBR and .Qq Li "!9d275380-40ad-11db-bf97-000c2911d1b8" for GPT. .It Cm vmware-reserved A VMware reserved partition. The scheme-specific type is .Qq Li "!9198effc-31c0-11db-8f-78-000c2911d1b8" for GPT. .It Cm vmware-vsanhdr A partition claimed by VMware VSAN. The scheme-specific type is .Qq Li "!381cfccc-7288-11e0-92ee-000c2911d0b2" for GPT. .El .Sh ATTRIBUTES The scheme-specific attributes for EBR: .Bl -tag -width ".Cm active" .It Cm active .El .Pp The scheme-specific attributes for GPT: .Bl -tag -width ".Cm bootfailed" .It Cm bootme When set, the .Nm gptboot stage 1 boot loader will try to boot the system from this partition. Multiple partitions can be marked with the .Cm bootme attribute. See .Xr gptboot 8 for more details. .It Cm bootonce Setting this attribute automatically sets the .Cm bootme attribute. When set, the .Nm gptboot stage 1 boot loader will try to boot the system from this partition only once. Multiple partitions can be marked with the .Cm bootonce and .Cm bootme attribute pairs. See .Xr gptboot 8 for more details. .It Cm bootfailed This attribute should not be manually managed. It is managed by the .Nm gptboot stage 1 boot loader and the .Pa /etc/rc.d/gptboot start-up script. See .Xr gptboot 8 for more details. .It Cm lenovofix Setting this attribute overwrites the Protective MBR with a new one where the 0xee partition is the second, rather than the first record. This resolves a BIOS compatibility issue with some Lenovo models including the X220, T420, and T520, allowing them to boot from GPT partitioned disks without using EFI. .El .Pp The scheme-specific attributes for MBR: .Bl -tag -width ".Cm active" .It Cm active .El .Pp The scheme-specific attributes for PC98: .Bl -tag -width ".Cm bootable" .It Cm active .It Cm bootable .El .Sh BOOTSTRAPPING .Fx supports several partitioning schemes and each scheme uses different bootstrap code. The bootstrap code is located in a specific disk area for each partitioning scheme, and may vary in size for different schemes. .Pp Bootstrap code can be separated into two types. The first type is embedded in the partitioning scheme's metadata, while the second type is located on a specific partition. Embedding bootstrap code should only be done with the .Cm gpart bootcode command with the .Fl b Ar bootcode option. The GEOM PART class knows how to safely embed bootstrap code into specific partitioning scheme metadata without causing any damage. .Pp The Master Boot Record (MBR) uses a 512-byte bootstrap code image, embedded into the partition table's metadata area. There are two variants of this bootstrap code: .Pa /boot/mbr and .Pa /boot/boot0 . .Pa /boot/mbr searches for a partition with the .Cm active attribute (see the .Sx ATTRIBUTES section) in the partition table. Then it runs next bootstrap stage. The .Pa /boot/boot0 image contains a boot manager with some additional interactive functions for multi-booting from a user-selected partition. .Pp A BSD disklabel is usually created inside an MBR partition (slice) with type .Cm freebsd (see the .Sx "PARTITION TYPES" section). It uses 8 KB size bootstrap code image .Pa /boot/boot , embedded into the partition table's metadata area. .Pp Both types of bootstrap code are used to boot from the GUID Partition Table. First, a protective MBR is embedded into the first disk sector from the .Pa /boot/pmbr image. It searches through the GPT for a .Cm freebsd-boot partition (see the .Sx "PARTITION TYPES" section) and runs the next bootstrap stage from it. The .Cm freebsd-boot partition should be smaller than 545 KB. It can be located either before or after other .Fx partitions on the disk. There are two variants of bootstrap code to write to this partition: .Pa /boot/gptboot and .Pa /boot/gptzfsboot . .Pp .Pa /boot/gptboot is used to boot from UFS partitions. .Cm gptboot searches through .Cm freebsd-ufs partitions in the GPT and selects one to boot based on the .Cm bootonce and .Cm bootme attributes. If neither attribute is found, .Pa /boot/gptboot boots from the first .Cm freebsd-ufs partition. .Pa /boot/loader .Pq the third bootstrap stage is loaded from the first partition that matches these conditions. See .Xr gptboot 8 for more information. .Pp .Pa /boot/gptzfsboot is used to boot from ZFS. It searches through the GPT for .Cm freebsd-zfs partitions, trying to detect ZFS pools. After all pools are detected, .Pa /boot/zfsloader is started from the first one found. .Pp The VTOC8 scheme does not support embedding bootstrap code. Instead, the 8 KBytes bootstrap code image .Pa /boot/boot1 should be written with the .Cm gpart bootcode command with the .Fl p Ar bootcode option to all sufficiently large VTOC8 partitions. To do this the .Fl i Ar index option could be omitted. .Pp The APM scheme also does not support embedding bootstrap code. Instead, the 800 KBytes bootstrap code image .Pa /boot/boot1.hfs should be written with the .Cm gpart bootcode command to a partition of type .Cm apple-boot , which should also be 800 KB in size. .Sh OPERATIONAL FLAGS Actions other than the .Cm commit and .Cm undo actions take an optional .Fl f Ar flags option. This option is used to specify action-specific operational flags. By default, the .Nm utility defines the .Ql C flag so that the action is immediately committed. The user can specify .Dq Fl f Cm x to have the action result in a pending change that can later, with other pending changes, be committed as a single compound change with the .Cm commit action or reverted with the .Cm undo action. .Sh RECOVERING The GEOM PART class supports recovering of partition tables only for GPT. The GPT primary metadata is stored at the beginning of the device. For redundancy, a secondary .Pq backup copy of the metadata is stored at the end of the device. As a result of having two copies, some corruption of metadata is not fatal to the working of GPT. When the kernel detects corrupt metadata, it marks this table as corrupt and reports the problem. .Cm destroy and .Cm recover are the only operations allowed on corrupt tables. .Pp -If the first sector of a provider is corrupt, the kernel can not detect GPT -even if the partition table itself is not corrupt. -The protective MBR can be rewritten using the -.Xr dd 1 -command, to restore the ability to detect the GPT. -The copy of the protective MBR is usually located in the -.Pa /boot/pmbr -file. -.Pp If one GPT header appears to be corrupt but the other copy remains intact, the kernel will log the following: .Bd -literal -offset indent GEOM: provider: the primary GPT table is corrupt or invalid. GEOM: provider: using the secondary instead -- recovery strongly advised. .Ed .Pp or .Bd -literal -offset indent GEOM: provider: the secondary GPT table is corrupt or invalid. GEOM: provider: using the primary only -- recovery suggested. .Ed .Pp Also .Nm commands such as .Cm show , status and .Cm list will report about corrupt tables. .Pp If the size of the device has changed (e.g.,\& volume expansion) the secondary GPT header will no longer be located in the last sector. This is not a metadata corruption, but it is dangerous because any corruption of the primary GPT will lead to loss of the partition table. This problem is reported by the kernel with the message: .Bd -literal -offset indent GEOM: provider: the secondary GPT header is not in the last LBA. .Ed .Pp This situation can be recovered with the .Cm recover command. This command reconstructs the corrupt metadata using known valid metadata and relocates the secondary GPT to the end of the device. .Pp .Em NOTE : The GEOM PART class can detect the same partition table visible through different GEOM providers, and some of them will be marked as corrupt. Be careful when choosing a provider for recovery. If you choose incorrectly you can destroy the metadata of another GEOM class, e.g.,\& GEOM MIRROR or GEOM LABEL. .Sh SYSCTL VARIABLES The following .Xr sysctl 8 variables can be used to control the behavior of the .Nm PART GEOM class. The default value is shown next to each variable. .Bl -tag -width indent .It Va kern.geom.part.check_integrity : No 1 This variable controls the behaviour of metadata integrity checks. When integrity checks are enabled, the .Nm PART GEOM class verifies all generic partition parameters obtained from the disk metadata. If some inconsistency is detected, the partition table will be rejected with a diagnostic message: .Sy "GEOM_PART: Integrity check failed (provider, scheme)" . .It Va kern.geom.part.ldm.debug : No 0 Debug level of the Logical Disk Manager (LDM) module. This can be set to a number between 0 and 2 inclusive. If set to 0 minimal debug information is printed, and if set to 2 the maximum amount of debug information is printed. .It Va kern.geom.part.ldm.show_mirrors : No 0 This variable controls how the Logical Disk Manager (LDM) module handles mirrored volumes. By default mirrored volumes are shown as partitions with type .Cm ms-ldm-data (see the .Sx "PARTITION TYPES" section). If this variable set to 1 each component of the mirrored volume will be present as independent partition. .Em NOTE : This may break a mirrored volume and lead to data damage. .It Va kern.geom.part.mbr.enforce_chs : No 1 Specify how the Master Boot Record (MBR) module does alignment. If this variable is set to a non-zero value, the module will automatically recalculate the user-specified offset and size for alignment with the CHS geometry. Otherwise the values will be left unchanged. .El .Sh EXIT STATUS Exit status is 0 on success, and 1 if the command fails. .Sh EXAMPLES Create a GPT scheme on .Pa ada0 : .Bd -literal -offset indent /sbin/gpart create -s GPT ada0 .Ed .Pp Embed GPT bootstrap code into a protective MBR: .Bd -literal -offset indent /sbin/gpart bootcode -b /boot/pmbr ada0 .Ed .Pp Create a dedicated .Cm freebsd-boot partition that can boot .Fx from a .Cm freebsd-ufs partition, and install bootstrap code into it. This partition must be larger than the bootstrap code .Po usually either .Pa /boot/gptboot or .Pa /boot/gptzfsboot .Pc , but smaller than 545 kB since the first-stage loader will load the entire partition into memory during boot, regardless of how much data it actually contains. This example uses 88 blocks (44 kB) so the next partition will be aligned on a 64 kB boundary without the need to specify an explicit offset or alignment. The boot partition itself is aligned on a 4 kB boundary. .Bd -literal -offset indent /sbin/gpart add -b 40 -s 88 -t freebsd-boot ada0 /sbin/gpart bootcode -p /boot/gptboot -i 1 ada0 .Ed .Pp Create a 512MB-sized .Cm freebsd-ufs partition to contain a UFS filesystem from which the system can boot. .Bd -literal -offset indent /sbin/gpart add -s 512M -t freebsd-ufs ada0 .Ed .Pp Create an MBR scheme on .Pa ada0 , then create a 30GB-sized .Fx slice, mark it active and install the .Nm boot0 boot manager: .Bd -literal -offset indent /sbin/gpart create -s MBR ada0 /sbin/gpart add -t freebsd -s 30G ada0 /sbin/gpart set -a active -i 1 ada0 /sbin/gpart bootcode -b /boot/boot0 ada0 .Ed .Pp Now create a .Bx scheme .Pf ( Bx label) with space for up to 20 partitions: .Bd -literal -offset indent /sbin/gpart create -s BSD -n 20 ada0s1 .Ed .Pp Create a 1GB-sized UFS partition and a 4GB-sized swap partition: .Bd -literal -offset indent /sbin/gpart add -t freebsd-ufs -s 1G ada0s1 /sbin/gpart add -t freebsd-swap -s 4G ada0s1 .Ed .Pp Install bootstrap code for the .Bx label: .Bd -literal -offset indent /sbin/gpart bootcode -b /boot/boot ada0s1 .Ed .Pp Create a VTOC8 scheme on .Pa da0 : .Bd -literal -offset indent /sbin/gpart create -s VTOC8 da0 .Ed .Pp Create a 512MB-sized .Cm freebsd-ufs partition to contain a UFS filesystem from which the system can boot. .Bd -literal -offset indent /sbin/gpart add -s 512M -t freebsd-ufs da0 .Ed .Pp Create a 15GB-sized .Cm freebsd-ufs partition to contain a UFS filesystem and aligned on 4KB boundaries: .Bd -literal -offset indent /sbin/gpart add -s 15G -t freebsd-ufs -a 4k da0 .Ed .Pp After creating all required partitions, embed bootstrap code into them: .Bd -literal -offset indent /sbin/gpart bootcode -p /boot/boot1 da0 .Ed .Pp Create a backup of the partition table from .Pa da0 : .Bd -literal -offset indent /sbin/gpart backup da0 > da0.backup .Ed .Pp Restore the partition table from the backup to .Pa da0 : .Bd -literal -offset indent /sbin/gpart restore -l da0 < /mnt/da0.backup .Ed .Pp Clone the partition table from .Pa ada0 to .Pa ada1 and .Pa ada2 : .Bd -literal -offset indent /sbin/gpart backup ada0 | /sbin/gpart restore -F ada1 ada2 .Ed .Sh SEE ALSO -.Xr dd 1 , .Xr geom 4 , .Xr boot0cfg 8 , .Xr geom 8 , .Xr gptboot 8 .Sh HISTORY The .Nm utility appeared in .Fx 7.0 . .Sh AUTHORS .An Marcel Moolenaar Aq marcel@FreeBSD.org Index: user/ngie/stable-10-libnv/sys/boot/common/part.c =================================================================== --- user/ngie/stable-10-libnv/sys/boot/common/part.c (revision 293638) +++ user/ngie/stable-10-libnv/sys/boot/common/part.c (revision 293639) @@ -1,851 +1,857 @@ /*- * Copyright (c) 2012 Andrey V. Elsukov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #ifdef PART_DEBUG #define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else #define DEBUG(fmt, args...) #endif #ifdef LOADER_GPT_SUPPORT #define MAXTBLSZ 64 static const uuid_t gpt_uuid_unused = GPT_ENT_TYPE_UNUSED; static const uuid_t gpt_uuid_ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA; static const uuid_t gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS; static const uuid_t gpt_uuid_efi = GPT_ENT_TYPE_EFI; static const uuid_t gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD; static const uuid_t gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT; static const uuid_t gpt_uuid_freebsd_nandfs = GPT_ENT_TYPE_FREEBSD_NANDFS; static const uuid_t gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP; static const uuid_t gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS; static const uuid_t gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM; #endif struct pentry { struct ptable_entry part; uint64_t flags; union { uint8_t bsd; uint8_t mbr; uuid_t gpt; uint16_t vtoc8; } type; STAILQ_ENTRY(pentry) entry; }; struct ptable { enum ptable_type type; uint16_t sectorsize; uint64_t sectors; STAILQ_HEAD(, pentry) entries; }; static struct parttypes { enum partition_type type; const char *desc; } ptypes[] = { { PART_UNKNOWN, "Unknown" }, { PART_EFI, "EFI" }, { PART_FREEBSD, "FreeBSD" }, { PART_FREEBSD_BOOT, "FreeBSD boot" }, { PART_FREEBSD_NANDFS, "FreeBSD nandfs" }, { PART_FREEBSD_UFS, "FreeBSD UFS" }, { PART_FREEBSD_ZFS, "FreeBSD ZFS" }, { PART_FREEBSD_SWAP, "FreeBSD swap" }, { PART_FREEBSD_VINUM, "FreeBSD vinum" }, { PART_LINUX, "Linux" }, { PART_LINUX_SWAP, "Linux swap" }, { PART_DOS, "DOS/Windows" }, }; const char * parttype2str(enum partition_type type) { int i; for (i = 0; i < sizeof(ptypes) / sizeof(ptypes[0]); i++) if (ptypes[i].type == type) return (ptypes[i].desc); return (ptypes[0].desc); } #ifdef LOADER_GPT_SUPPORT static void uuid_letoh(uuid_t *uuid) { uuid->time_low = le32toh(uuid->time_low); uuid->time_mid = le16toh(uuid->time_mid); uuid->time_hi_and_version = le16toh(uuid->time_hi_and_version); } static enum partition_type gpt_parttype(uuid_t type) { if (uuid_equal(&type, &gpt_uuid_efi, NULL)) return (PART_EFI); else if (uuid_equal(&type, &gpt_uuid_ms_basic_data, NULL)) return (PART_DOS); else if (uuid_equal(&type, &gpt_uuid_freebsd_boot, NULL)) return (PART_FREEBSD_BOOT); else if (uuid_equal(&type, &gpt_uuid_freebsd_ufs, NULL)) return (PART_FREEBSD_UFS); else if (uuid_equal(&type, &gpt_uuid_freebsd_zfs, NULL)) return (PART_FREEBSD_ZFS); else if (uuid_equal(&type, &gpt_uuid_freebsd_swap, NULL)) return (PART_FREEBSD_SWAP); else if (uuid_equal(&type, &gpt_uuid_freebsd_vinum, NULL)) return (PART_FREEBSD_VINUM); else if (uuid_equal(&type, &gpt_uuid_freebsd_nandfs, NULL)) return (PART_FREEBSD_NANDFS); else if (uuid_equal(&type, &gpt_uuid_freebsd, NULL)) return (PART_FREEBSD); return (PART_UNKNOWN); } static struct gpt_hdr* gpt_checkhdr(struct gpt_hdr *hdr, uint64_t lba_self, uint64_t lba_last, uint16_t sectorsize) { uint32_t sz, crc; if (memcmp(hdr->hdr_sig, GPT_HDR_SIG, sizeof(hdr->hdr_sig)) != 0) { DEBUG("no GPT signature"); return (NULL); } sz = le32toh(hdr->hdr_size); if (sz < 92 || sz > sectorsize) { DEBUG("invalid GPT header size: %d", sz); return (NULL); } crc = le32toh(hdr->hdr_crc_self); hdr->hdr_crc_self = 0; if (crc32(hdr, sz) != crc) { DEBUG("GPT header's CRC doesn't match"); return (NULL); } hdr->hdr_crc_self = crc; hdr->hdr_revision = le32toh(hdr->hdr_revision); if (hdr->hdr_revision < GPT_HDR_REVISION) { DEBUG("unsupported GPT revision %d", hdr->hdr_revision); return (NULL); } hdr->hdr_lba_self = le64toh(hdr->hdr_lba_self); if (hdr->hdr_lba_self != lba_self) { DEBUG("self LBA doesn't match"); return (NULL); } hdr->hdr_lba_alt = le64toh(hdr->hdr_lba_alt); if (hdr->hdr_lba_alt == hdr->hdr_lba_self) { DEBUG("invalid alternate LBA"); return (NULL); } hdr->hdr_entries = le32toh(hdr->hdr_entries); hdr->hdr_entsz = le32toh(hdr->hdr_entsz); if (hdr->hdr_entries == 0 || hdr->hdr_entsz < sizeof(struct gpt_ent) || sectorsize % hdr->hdr_entsz != 0) { DEBUG("invalid entry size or number of entries"); return (NULL); } hdr->hdr_lba_start = le64toh(hdr->hdr_lba_start); hdr->hdr_lba_end = le64toh(hdr->hdr_lba_end); hdr->hdr_lba_table = le64toh(hdr->hdr_lba_table); hdr->hdr_crc_table = le32toh(hdr->hdr_crc_table); uuid_letoh(&hdr->hdr_uuid); return (hdr); } static int gpt_checktbl(const struct gpt_hdr *hdr, u_char *tbl, size_t size, uint64_t lba_last) { struct gpt_ent *ent; int i, cnt; cnt = size / hdr->hdr_entsz; if (hdr->hdr_entries <= cnt) { cnt = hdr->hdr_entries; /* Check CRC only when buffer size is enough for table. */ if (hdr->hdr_crc_table != crc32(tbl, hdr->hdr_entries * hdr->hdr_entsz)) { DEBUG("GPT table's CRC doesn't match"); return (-1); } } for (i = 0; i < cnt; i++) { ent = (struct gpt_ent *)(tbl + i * hdr->hdr_entsz); uuid_letoh(&ent->ent_type); if (uuid_equal(&ent->ent_type, &gpt_uuid_unused, NULL)) continue; ent->ent_lba_start = le64toh(ent->ent_lba_start); ent->ent_lba_end = le64toh(ent->ent_lba_end); } return (0); } static struct ptable* ptable_gptread(struct ptable *table, void *dev, diskread_t dread) { struct pentry *entry; struct gpt_hdr *phdr, hdr; struct gpt_ent *ent; u_char *buf, *tbl; uint64_t offset; int pri, sec, i; size_t size; buf = malloc(table->sectorsize); if (buf == NULL) return (NULL); tbl = malloc(table->sectorsize * MAXTBLSZ); if (tbl == NULL) { free(buf); return (NULL); } /* Read the primary GPT header. */ if (dread(dev, buf, 1, 1) != 0) { ptable_close(table); table = NULL; goto out; } pri = sec = 0; /* Check the primary GPT header. */ phdr = gpt_checkhdr((struct gpt_hdr *)buf, 1, table->sectors - 1, table->sectorsize); if (phdr != NULL) { /* Read the primary GPT table. */ size = MIN(MAXTBLSZ, (phdr->hdr_entries * phdr->hdr_entsz + table->sectorsize - 1) / table->sectorsize); if (dread(dev, tbl, size, phdr->hdr_lba_table) == 0 && gpt_checktbl(phdr, tbl, size * table->sectorsize, table->sectors - 1) == 0) { memcpy(&hdr, phdr, sizeof(hdr)); pri = 1; } } offset = pri ? hdr.hdr_lba_alt: table->sectors - 1; /* Read the backup GPT header. */ if (dread(dev, buf, 1, offset) != 0) phdr = NULL; else phdr = gpt_checkhdr((struct gpt_hdr *)buf, offset, table->sectors - 1, table->sectorsize); if (phdr != NULL) { /* * Compare primary and backup headers. * If they are equal, then we do not need to read backup * table. If they are different, then prefer backup header * and try to read backup table. */ if (pri == 0 || uuid_equal(&hdr.hdr_uuid, &phdr->hdr_uuid, NULL) == 0 || hdr.hdr_revision != phdr->hdr_revision || hdr.hdr_size != phdr->hdr_size || hdr.hdr_lba_start != phdr->hdr_lba_start || hdr.hdr_lba_end != phdr->hdr_lba_end || hdr.hdr_entries != phdr->hdr_entries || hdr.hdr_entsz != phdr->hdr_entsz || hdr.hdr_crc_table != phdr->hdr_crc_table) { /* Read the backup GPT table. */ size = MIN(MAXTBLSZ, (phdr->hdr_entries * phdr->hdr_entsz + table->sectorsize - 1) / table->sectorsize); if (dread(dev, tbl, size, phdr->hdr_lba_table) == 0 && gpt_checktbl(phdr, tbl, size * table->sectorsize, table->sectors - 1) == 0) { memcpy(&hdr, phdr, sizeof(hdr)); sec = 1; } } } if (pri == 0 && sec == 0) { /* Both primary and backup tables are invalid. */ table->type = PTABLE_NONE; goto out; } + DEBUG("GPT detected"); size = MIN(hdr.hdr_entries * hdr.hdr_entsz, MAXTBLSZ * table->sectorsize); for (i = 0; i < size / hdr.hdr_entsz; i++) { ent = (struct gpt_ent *)(tbl + i * hdr.hdr_entsz); if (uuid_equal(&ent->ent_type, &gpt_uuid_unused, NULL)) continue; entry = malloc(sizeof(*entry)); if (entry == NULL) break; entry->part.start = ent->ent_lba_start; entry->part.end = ent->ent_lba_end; entry->part.index = i + 1; entry->part.type = gpt_parttype(ent->ent_type); entry->flags = le64toh(ent->ent_attr); memcpy(&entry->type.gpt, &ent->ent_type, sizeof(uuid_t)); STAILQ_INSERT_TAIL(&table->entries, entry, entry); DEBUG("new GPT partition added"); } out: free(buf); free(tbl); return (table); } #endif /* LOADER_GPT_SUPPORT */ #ifdef LOADER_MBR_SUPPORT /* We do not need to support too many EBR partitions in the loader */ #define MAXEBRENTRIES 8 static enum partition_type mbr_parttype(uint8_t type) { switch (type) { case DOSPTYP_386BSD: return (PART_FREEBSD); case DOSPTYP_LINSWP: return (PART_LINUX_SWAP); case DOSPTYP_LINUX: return (PART_LINUX); case 0x01: case 0x04: case 0x06: case 0x07: case 0x0b: case 0x0c: case 0x0e: return (PART_DOS); } return (PART_UNKNOWN); } struct ptable* ptable_ebrread(struct ptable *table, void *dev, diskread_t dread) { struct dos_partition *dp; struct pentry *e1, *entry; uint32_t start, end, offset; u_char *buf; int i, index; STAILQ_FOREACH(e1, &table->entries, entry) { if (e1->type.mbr == DOSPTYP_EXT || e1->type.mbr == DOSPTYP_EXTLBA) break; } if (e1 == NULL) return (table); index = 5; offset = e1->part.start; buf = malloc(table->sectorsize); if (buf == NULL) return (table); for (i = 0; i < MAXEBRENTRIES; i++) { #if 0 /* Some BIOSes return an incorrect number of sectors */ if (offset >= table->sectors) break; #endif if (dread(dev, buf, 1, offset) != 0) break; dp = (struct dos_partition *)(buf + DOSPARTOFF); if (dp[0].dp_typ == 0) break; start = le32toh(dp[0].dp_start); if (dp[0].dp_typ == DOSPTYP_EXT && dp[1].dp_typ == 0) { offset = e1->part.start + start; continue; } end = le32toh(dp[0].dp_size); entry = malloc(sizeof(*entry)); if (entry == NULL) break; entry->part.start = offset + start; entry->part.end = entry->part.start + end - 1; entry->part.index = index++; entry->part.type = mbr_parttype(dp[0].dp_typ); entry->flags = dp[0].dp_flag; entry->type.mbr = dp[0].dp_typ; STAILQ_INSERT_TAIL(&table->entries, entry, entry); DEBUG("new EBR partition added"); if (dp[1].dp_typ == 0) break; offset = e1->part.start + le32toh(dp[1].dp_start); } free(buf); return (table); } #endif /* LOADER_MBR_SUPPORT */ static enum partition_type bsd_parttype(uint8_t type) { switch (type) { case FS_NANDFS: return (PART_FREEBSD_NANDFS); case FS_SWAP: return (PART_FREEBSD_SWAP); case FS_BSDFFS: return (PART_FREEBSD_UFS); case FS_VINUM: return (PART_FREEBSD_VINUM); case FS_ZFS: return (PART_FREEBSD_ZFS); } return (PART_UNKNOWN); } struct ptable* ptable_bsdread(struct ptable *table, void *dev, diskread_t dread) { struct disklabel *dl; struct partition *part; struct pentry *entry; u_char *buf; uint32_t raw_offset; int i; if (table->sectorsize < sizeof(struct disklabel)) { DEBUG("Too small sectorsize"); return (table); } buf = malloc(table->sectorsize); if (buf == NULL) return (table); if (dread(dev, buf, 1, 1) != 0) { DEBUG("read failed"); ptable_close(table); table = NULL; goto out; } dl = (struct disklabel *)buf; if (le32toh(dl->d_magic) != DISKMAGIC && le32toh(dl->d_magic2) != DISKMAGIC) goto out; if (le32toh(dl->d_secsize) != table->sectorsize) { DEBUG("unsupported sector size"); goto out; } dl->d_npartitions = le16toh(dl->d_npartitions); if (dl->d_npartitions > 20 || dl->d_npartitions < 8) { DEBUG("invalid number of partitions"); goto out; } part = &dl->d_partitions[0]; raw_offset = le32toh(part[RAW_PART].p_offset); for (i = 0; i < dl->d_npartitions; i++, part++) { if (i == RAW_PART) continue; if (part->p_size == 0) continue; entry = malloc(sizeof(*entry)); if (entry == NULL) break; entry->part.start = le32toh(part->p_offset) - raw_offset; entry->part.end = entry->part.start + le32toh(part->p_size) + 1; entry->part.type = bsd_parttype(part->p_fstype); entry->part.index = i; /* starts from zero */ entry->type.bsd = part->p_fstype; STAILQ_INSERT_TAIL(&table->entries, entry, entry); DEBUG("new BSD partition added"); } table->type = PTABLE_BSD; out: free(buf); return (table); } #ifdef LOADER_VTOC8_SUPPORT static enum partition_type vtoc8_parttype(uint16_t type) { switch (type) { case VTOC_TAG_FREEBSD_NANDFS: return (PART_FREEBSD_NANDFS); case VTOC_TAG_FREEBSD_SWAP: return (PART_FREEBSD_SWAP); case VTOC_TAG_FREEBSD_UFS: return (PART_FREEBSD_UFS); case VTOC_TAG_FREEBSD_VINUM: return (PART_FREEBSD_VINUM); case VTOC_TAG_FREEBSD_ZFS: return (PART_FREEBSD_ZFS); }; return (PART_UNKNOWN); } static struct ptable* ptable_vtoc8read(struct ptable *table, void *dev, diskread_t dread) { struct pentry *entry; struct vtoc8 *dl; u_char *buf; uint16_t sum, heads, sectors; int i; if (table->sectorsize != sizeof(struct vtoc8)) return (table); buf = malloc(table->sectorsize); if (buf == NULL) return (table); if (dread(dev, buf, 1, 0) != 0) { DEBUG("read failed"); ptable_close(table); table = NULL; goto out; } dl = (struct vtoc8 *)buf; /* Check the sum */ for (i = sum = 0; i < sizeof(struct vtoc8); i += sizeof(sum)) sum ^= be16dec(buf + i); if (sum != 0) { DEBUG("incorrect checksum"); goto out; } if (be16toh(dl->nparts) != VTOC8_NPARTS) { DEBUG("invalid number of entries"); goto out; } sectors = be16toh(dl->nsecs); heads = be16toh(dl->nheads); if (sectors * heads == 0) { DEBUG("invalid geometry"); goto out; } for (i = 0; i < VTOC8_NPARTS; i++) { dl->part[i].tag = be16toh(dl->part[i].tag); if (i == VTOC_RAW_PART || dl->part[i].tag == VTOC_TAG_UNASSIGNED) continue; entry = malloc(sizeof(*entry)); if (entry == NULL) break; entry->part.start = be32toh(dl->map[i].cyl) * heads * sectors; entry->part.end = be32toh(dl->map[i].nblks) + entry->part.start - 1; entry->part.type = vtoc8_parttype(dl->part[i].tag); entry->part.index = i; /* starts from zero */ entry->type.vtoc8 = dl->part[i].tag; STAILQ_INSERT_TAIL(&table->entries, entry, entry); DEBUG("new VTOC8 partition added"); } table->type = PTABLE_VTOC8; out: free(buf); return (table); } #endif /* LOADER_VTOC8_SUPPORT */ struct ptable* ptable_open(void *dev, off_t sectors, uint16_t sectorsize, diskread_t *dread) { struct dos_partition *dp; struct ptable *table; u_char *buf; int i, count; #ifdef LOADER_MBR_SUPPORT struct pentry *entry; uint32_t start, end; int has_ext; #endif table = NULL; buf = malloc(sectorsize); if (buf == NULL) return (NULL); /* First, read the MBR. */ if (dread(dev, buf, 1, DOSBBSECTOR) != 0) { DEBUG("read failed"); goto out; } table = malloc(sizeof(*table)); if (table == NULL) goto out; table->sectors = sectors; table->sectorsize = sectorsize; table->type = PTABLE_NONE; STAILQ_INIT(&table->entries); #ifdef LOADER_VTOC8_SUPPORT if (be16dec(buf + offsetof(struct vtoc8, magic)) == VTOC_MAGIC) { if (ptable_vtoc8read(table, dev, dread) == NULL) { /* Read error. */ table = NULL; goto out; } else if (table->type == PTABLE_VTOC8) goto out; } #endif /* Check the BSD label. */ if (ptable_bsdread(table, dev, dread) == NULL) { /* Read error. */ table = NULL; goto out; } else if (table->type == PTABLE_BSD) goto out; #if defined(LOADER_GPT_SUPPORT) || defined(LOADER_MBR_SUPPORT) /* Check the MBR magic. */ if (buf[DOSMAGICOFFSET] != 0x55 || buf[DOSMAGICOFFSET + 1] != 0xaa) { DEBUG("magic sequence not found"); +#if defined(LOADER_GPT_SUPPORT) + /* There is no PMBR, check that we have backup GPT */ + table->type = PTABLE_GPT; + table = ptable_gptread(table, dev, dread); +#endif goto out; } /* Check that we have PMBR. Also do some validation. */ dp = (struct dos_partition *)(buf + DOSPARTOFF); for (i = 0, count = 0; i < NDOSPART; i++) { if (dp[i].dp_flag != 0 && dp[i].dp_flag != 0x80) { DEBUG("invalid partition flag %x", dp[i].dp_flag); goto out; } #ifdef LOADER_GPT_SUPPORT if (dp[i].dp_typ == DOSPTYP_PMBR) { table->type = PTABLE_GPT; DEBUG("PMBR detected"); } #endif if (dp[i].dp_typ != 0) count++; } /* Do we have some invalid values? */ if (table->type == PTABLE_GPT && count > 1) { if (dp[1].dp_typ != DOSPTYP_HFS) { table->type = PTABLE_NONE; DEBUG("Incorrect PMBR, ignore it"); } else DEBUG("Bootcamp detected"); } #ifdef LOADER_GPT_SUPPORT if (table->type == PTABLE_GPT) { table = ptable_gptread(table, dev, dread); goto out; } #endif #ifdef LOADER_MBR_SUPPORT /* Read MBR. */ table->type = PTABLE_MBR; for (i = has_ext = 0; i < NDOSPART; i++) { if (dp[i].dp_typ == 0) continue; start = le32dec(&(dp[i].dp_start)); end = le32dec(&(dp[i].dp_size)); if (start == 0 || end == 0) continue; #if 0 /* Some BIOSes return an incorrect number of sectors */ if (start + end - 1 >= sectors) continue; /* XXX: ignore */ #endif if (dp[i].dp_typ == DOSPTYP_EXT || dp[i].dp_typ == DOSPTYP_EXTLBA) has_ext = 1; entry = malloc(sizeof(*entry)); if (entry == NULL) break; entry->part.start = start; entry->part.end = start + end - 1; entry->part.index = i + 1; entry->part.type = mbr_parttype(dp[i].dp_typ); entry->flags = dp[i].dp_flag; entry->type.mbr = dp[i].dp_typ; STAILQ_INSERT_TAIL(&table->entries, entry, entry); DEBUG("new MBR partition added"); } if (has_ext) { table = ptable_ebrread(table, dev, dread); /* FALLTHROUGH */ } #endif /* LOADER_MBR_SUPPORT */ #endif /* LOADER_MBR_SUPPORT || LOADER_GPT_SUPPORT */ out: free(buf); return (table); } void ptable_close(struct ptable *table) { struct pentry *entry; while (!STAILQ_EMPTY(&table->entries)) { entry = STAILQ_FIRST(&table->entries); STAILQ_REMOVE_HEAD(&table->entries, entry); free(entry); } free(table); } enum ptable_type ptable_gettype(const struct ptable *table) { return (table->type); } int ptable_getpart(const struct ptable *table, struct ptable_entry *part, int index) { struct pentry *entry; if (part == NULL || table == NULL) return (EINVAL); STAILQ_FOREACH(entry, &table->entries, entry) { if (entry->part.index != index) continue; memcpy(part, &entry->part, sizeof(*part)); return (0); } return (ENOENT); } /* * Search for a slice with the following preferences: * * 1: Active FreeBSD slice * 2: Non-active FreeBSD slice * 3: Active Linux slice * 4: non-active Linux slice * 5: Active FAT/FAT32 slice * 6: non-active FAT/FAT32 slice */ #define PREF_RAWDISK 0 #define PREF_FBSD_ACT 1 #define PREF_FBSD 2 #define PREF_LINUX_ACT 3 #define PREF_LINUX 4 #define PREF_DOS_ACT 5 #define PREF_DOS 6 #define PREF_NONE 7 int ptable_getbestpart(const struct ptable *table, struct ptable_entry *part) { struct pentry *entry, *best; int pref, preflevel; if (part == NULL || table == NULL) return (EINVAL); best = NULL; preflevel = pref = PREF_NONE; STAILQ_FOREACH(entry, &table->entries, entry) { #ifdef LOADER_MBR_SUPPORT if (table->type == PTABLE_MBR) { switch (entry->type.mbr) { case DOSPTYP_386BSD: pref = entry->flags & 0x80 ? PREF_FBSD_ACT: PREF_FBSD; break; case DOSPTYP_LINUX: pref = entry->flags & 0x80 ? PREF_LINUX_ACT: PREF_LINUX; break; case 0x01: /* DOS/Windows */ case 0x04: case 0x06: case 0x0c: case 0x0e: case DOSPTYP_FAT32: pref = entry->flags & 0x80 ? PREF_DOS_ACT: PREF_DOS; break; default: pref = PREF_NONE; } } #endif /* LOADER_MBR_SUPPORT */ #ifdef LOADER_GPT_SUPPORT if (table->type == PTABLE_GPT) { if (entry->part.type == PART_DOS) pref = PREF_DOS; else if (entry->part.type == PART_FREEBSD_UFS || entry->part.type == PART_FREEBSD_ZFS) pref = PREF_FBSD; else pref = PREF_NONE; } #endif /* LOADER_GPT_SUPPORT */ if (pref < preflevel) { preflevel = pref; best = entry; } } if (best != NULL) { memcpy(part, &best->part, sizeof(*part)); return (0); } return (ENOENT); } void ptable_iterate(const struct ptable *table, void *arg, ptable_iterate_t *iter) { struct pentry *entry; char name[32]; name[0] = '\0'; STAILQ_FOREACH(entry, &table->entries, entry) { #ifdef LOADER_MBR_SUPPORT if (table->type == PTABLE_MBR) sprintf(name, "s%d", entry->part.index); else #endif #ifdef LOADER_GPT_SUPPORT if (table->type == PTABLE_GPT) sprintf(name, "p%d", entry->part.index); else #endif #ifdef LOADER_VTOC8_SUPPORT if (table->type == PTABLE_VTOC8) sprintf(name, "%c", (u_char) 'a' + entry->part.index); else #endif if (table->type == PTABLE_BSD) sprintf(name, "%c", (u_char) 'a' + entry->part.index); iter(arg, name, &entry->part); } } Index: user/ngie/stable-10-libnv/sys/geom/part/g_part_gpt.c =================================================================== --- user/ngie/stable-10-libnv/sys/geom/part/g_part_gpt.c (revision 293638) +++ user/ngie/stable-10-libnv/sys/geom/part/g_part_gpt.c (revision 293639) @@ -1,1354 +1,1355 @@ /*- * Copyright (c) 2002, 2005-2007, 2011 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "g_part_if.h" FEATURE(geom_part_gpt, "GEOM partitioning class for GPT partitions support"); CTASSERT(offsetof(struct gpt_hdr, padding) == 92); CTASSERT(sizeof(struct gpt_ent) == 128); #define EQUUID(a,b) (memcmp(a, b, sizeof(struct uuid)) == 0) #define MBRSIZE 512 enum gpt_elt { GPT_ELT_PRIHDR, GPT_ELT_PRITBL, GPT_ELT_SECHDR, GPT_ELT_SECTBL, GPT_ELT_COUNT }; enum gpt_state { GPT_STATE_UNKNOWN, /* Not determined. */ GPT_STATE_MISSING, /* No signature found. */ GPT_STATE_CORRUPT, /* Checksum mismatch. */ GPT_STATE_INVALID, /* Nonconformant/invalid. */ GPT_STATE_OK /* Perfectly fine. */ }; struct g_part_gpt_table { struct g_part_table base; u_char mbr[MBRSIZE]; struct gpt_hdr *hdr; quad_t lba[GPT_ELT_COUNT]; enum gpt_state state[GPT_ELT_COUNT]; int bootcamp; }; struct g_part_gpt_entry { struct g_part_entry base; struct gpt_ent ent; }; static void g_gpt_printf_utf16(struct sbuf *, uint16_t *, size_t); static void g_gpt_utf8_to_utf16(const uint8_t *, uint16_t *, size_t); static void g_gpt_set_defaults(struct g_part_table *, struct g_provider *); static int g_part_gpt_add(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static int g_part_gpt_bootcode(struct g_part_table *, struct g_part_parms *); static int g_part_gpt_create(struct g_part_table *, struct g_part_parms *); static int g_part_gpt_destroy(struct g_part_table *, struct g_part_parms *); static void g_part_gpt_dumpconf(struct g_part_table *, struct g_part_entry *, struct sbuf *, const char *); static int g_part_gpt_dumpto(struct g_part_table *, struct g_part_entry *); static int g_part_gpt_modify(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static const char *g_part_gpt_name(struct g_part_table *, struct g_part_entry *, char *, size_t); static int g_part_gpt_probe(struct g_part_table *, struct g_consumer *); static int g_part_gpt_read(struct g_part_table *, struct g_consumer *); static int g_part_gpt_setunset(struct g_part_table *table, struct g_part_entry *baseentry, const char *attrib, unsigned int set); static const char *g_part_gpt_type(struct g_part_table *, struct g_part_entry *, char *, size_t); static int g_part_gpt_write(struct g_part_table *, struct g_consumer *); static int g_part_gpt_resize(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static int g_part_gpt_recover(struct g_part_table *); static kobj_method_t g_part_gpt_methods[] = { KOBJMETHOD(g_part_add, g_part_gpt_add), KOBJMETHOD(g_part_bootcode, g_part_gpt_bootcode), KOBJMETHOD(g_part_create, g_part_gpt_create), KOBJMETHOD(g_part_destroy, g_part_gpt_destroy), KOBJMETHOD(g_part_dumpconf, g_part_gpt_dumpconf), KOBJMETHOD(g_part_dumpto, g_part_gpt_dumpto), KOBJMETHOD(g_part_modify, g_part_gpt_modify), KOBJMETHOD(g_part_resize, g_part_gpt_resize), KOBJMETHOD(g_part_name, g_part_gpt_name), KOBJMETHOD(g_part_probe, g_part_gpt_probe), KOBJMETHOD(g_part_read, g_part_gpt_read), KOBJMETHOD(g_part_recover, g_part_gpt_recover), KOBJMETHOD(g_part_setunset, g_part_gpt_setunset), KOBJMETHOD(g_part_type, g_part_gpt_type), KOBJMETHOD(g_part_write, g_part_gpt_write), { 0, 0 } }; static struct g_part_scheme g_part_gpt_scheme = { "GPT", g_part_gpt_methods, sizeof(struct g_part_gpt_table), .gps_entrysz = sizeof(struct g_part_gpt_entry), .gps_minent = 128, .gps_maxent = 4096, .gps_bootcodesz = MBRSIZE, }; G_PART_SCHEME_DECLARE(g_part_gpt); static struct uuid gpt_uuid_apple_boot = GPT_ENT_TYPE_APPLE_BOOT; static struct uuid gpt_uuid_apple_core_storage = GPT_ENT_TYPE_APPLE_CORE_STORAGE; static struct uuid gpt_uuid_apple_hfs = GPT_ENT_TYPE_APPLE_HFS; static struct uuid gpt_uuid_apple_label = GPT_ENT_TYPE_APPLE_LABEL; static struct uuid gpt_uuid_apple_raid = GPT_ENT_TYPE_APPLE_RAID; static struct uuid gpt_uuid_apple_raid_offline = GPT_ENT_TYPE_APPLE_RAID_OFFLINE; static struct uuid gpt_uuid_apple_tv_recovery = GPT_ENT_TYPE_APPLE_TV_RECOVERY; static struct uuid gpt_uuid_apple_ufs = GPT_ENT_TYPE_APPLE_UFS; static struct uuid gpt_uuid_bios_boot = GPT_ENT_TYPE_BIOS_BOOT; static struct uuid gpt_uuid_efi = GPT_ENT_TYPE_EFI; static struct uuid gpt_uuid_freebsd = GPT_ENT_TYPE_FREEBSD; static struct uuid gpt_uuid_freebsd_boot = GPT_ENT_TYPE_FREEBSD_BOOT; static struct uuid gpt_uuid_freebsd_nandfs = GPT_ENT_TYPE_FREEBSD_NANDFS; static struct uuid gpt_uuid_freebsd_swap = GPT_ENT_TYPE_FREEBSD_SWAP; static struct uuid gpt_uuid_freebsd_ufs = GPT_ENT_TYPE_FREEBSD_UFS; static struct uuid gpt_uuid_freebsd_vinum = GPT_ENT_TYPE_FREEBSD_VINUM; static struct uuid gpt_uuid_freebsd_zfs = GPT_ENT_TYPE_FREEBSD_ZFS; static struct uuid gpt_uuid_linux_data = GPT_ENT_TYPE_LINUX_DATA; static struct uuid gpt_uuid_linux_lvm = GPT_ENT_TYPE_LINUX_LVM; static struct uuid gpt_uuid_linux_raid = GPT_ENT_TYPE_LINUX_RAID; static struct uuid gpt_uuid_linux_swap = GPT_ENT_TYPE_LINUX_SWAP; static struct uuid gpt_uuid_vmfs = GPT_ENT_TYPE_VMFS; static struct uuid gpt_uuid_vmkdiag = GPT_ENT_TYPE_VMKDIAG; static struct uuid gpt_uuid_vmreserved = GPT_ENT_TYPE_VMRESERVED; static struct uuid gpt_uuid_vmvsanhdr = GPT_ENT_TYPE_VMVSANHDR; static struct uuid gpt_uuid_ms_basic_data = GPT_ENT_TYPE_MS_BASIC_DATA; static struct uuid gpt_uuid_ms_reserved = GPT_ENT_TYPE_MS_RESERVED; static struct uuid gpt_uuid_ms_ldm_data = GPT_ENT_TYPE_MS_LDM_DATA; static struct uuid gpt_uuid_ms_ldm_metadata = GPT_ENT_TYPE_MS_LDM_METADATA; static struct uuid gpt_uuid_netbsd_ccd = GPT_ENT_TYPE_NETBSD_CCD; static struct uuid gpt_uuid_netbsd_cgd = GPT_ENT_TYPE_NETBSD_CGD; static struct uuid gpt_uuid_netbsd_ffs = GPT_ENT_TYPE_NETBSD_FFS; static struct uuid gpt_uuid_netbsd_lfs = GPT_ENT_TYPE_NETBSD_LFS; static struct uuid gpt_uuid_netbsd_raid = GPT_ENT_TYPE_NETBSD_RAID; static struct uuid gpt_uuid_netbsd_swap = GPT_ENT_TYPE_NETBSD_SWAP; static struct uuid gpt_uuid_mbr = GPT_ENT_TYPE_MBR; static struct uuid gpt_uuid_unused = GPT_ENT_TYPE_UNUSED; static struct uuid gpt_uuid_dfbsd_swap = GPT_ENT_TYPE_DRAGONFLY_SWAP; static struct uuid gpt_uuid_dfbsd_ufs1 = GPT_ENT_TYPE_DRAGONFLY_UFS1; static struct uuid gpt_uuid_dfbsd_vinum = GPT_ENT_TYPE_DRAGONFLY_VINUM; static struct uuid gpt_uuid_dfbsd_ccd = GPT_ENT_TYPE_DRAGONFLY_CCD; static struct uuid gpt_uuid_dfbsd_legacy = GPT_ENT_TYPE_DRAGONFLY_LEGACY; static struct uuid gpt_uuid_dfbsd_hammer = GPT_ENT_TYPE_DRAGONFLY_HAMMER; static struct uuid gpt_uuid_dfbsd_hammer2 = GPT_ENT_TYPE_DRAGONFLY_HAMMER2; static struct uuid gpt_uuid_dfbsd_label32 = GPT_ENT_TYPE_DRAGONFLY_LABEL32; static struct uuid gpt_uuid_dfbsd_label64 = GPT_ENT_TYPE_DRAGONFLY_LABEL64; static struct uuid gpt_uuid_prep_boot = GPT_ENT_TYPE_PREP_BOOT; static struct g_part_uuid_alias { struct uuid *uuid; int alias; int mbrtype; } gpt_uuid_alias_match[] = { { &gpt_uuid_apple_boot, G_PART_ALIAS_APPLE_BOOT, 0xab }, { &gpt_uuid_apple_core_storage, G_PART_ALIAS_APPLE_CORE_STORAGE, 0 }, { &gpt_uuid_apple_hfs, G_PART_ALIAS_APPLE_HFS, 0xaf }, { &gpt_uuid_apple_label, G_PART_ALIAS_APPLE_LABEL, 0 }, { &gpt_uuid_apple_raid, G_PART_ALIAS_APPLE_RAID, 0 }, { &gpt_uuid_apple_raid_offline, G_PART_ALIAS_APPLE_RAID_OFFLINE, 0 }, { &gpt_uuid_apple_tv_recovery, G_PART_ALIAS_APPLE_TV_RECOVERY, 0 }, { &gpt_uuid_apple_ufs, G_PART_ALIAS_APPLE_UFS, 0 }, { &gpt_uuid_bios_boot, G_PART_ALIAS_BIOS_BOOT, 0 }, { &gpt_uuid_efi, G_PART_ALIAS_EFI, 0xee }, { &gpt_uuid_freebsd, G_PART_ALIAS_FREEBSD, 0xa5 }, { &gpt_uuid_freebsd_boot, G_PART_ALIAS_FREEBSD_BOOT, 0 }, { &gpt_uuid_freebsd_nandfs, G_PART_ALIAS_FREEBSD_NANDFS, 0 }, { &gpt_uuid_freebsd_swap, G_PART_ALIAS_FREEBSD_SWAP, 0 }, { &gpt_uuid_freebsd_ufs, G_PART_ALIAS_FREEBSD_UFS, 0 }, { &gpt_uuid_freebsd_vinum, G_PART_ALIAS_FREEBSD_VINUM, 0 }, { &gpt_uuid_freebsd_zfs, G_PART_ALIAS_FREEBSD_ZFS, 0 }, { &gpt_uuid_linux_data, G_PART_ALIAS_LINUX_DATA, 0x0b }, { &gpt_uuid_linux_lvm, G_PART_ALIAS_LINUX_LVM, 0 }, { &gpt_uuid_linux_raid, G_PART_ALIAS_LINUX_RAID, 0 }, { &gpt_uuid_linux_swap, G_PART_ALIAS_LINUX_SWAP, 0 }, { &gpt_uuid_vmfs, G_PART_ALIAS_VMFS, 0 }, { &gpt_uuid_vmkdiag, G_PART_ALIAS_VMKDIAG, 0 }, { &gpt_uuid_vmreserved, G_PART_ALIAS_VMRESERVED, 0 }, { &gpt_uuid_vmvsanhdr, G_PART_ALIAS_VMVSANHDR, 0 }, { &gpt_uuid_mbr, G_PART_ALIAS_MBR, 0 }, { &gpt_uuid_ms_basic_data, G_PART_ALIAS_MS_BASIC_DATA, 0x0b }, { &gpt_uuid_ms_ldm_data, G_PART_ALIAS_MS_LDM_DATA, 0 }, { &gpt_uuid_ms_ldm_metadata, G_PART_ALIAS_MS_LDM_METADATA, 0 }, { &gpt_uuid_ms_reserved, G_PART_ALIAS_MS_RESERVED, 0 }, { &gpt_uuid_netbsd_ccd, G_PART_ALIAS_NETBSD_CCD, 0 }, { &gpt_uuid_netbsd_cgd, G_PART_ALIAS_NETBSD_CGD, 0 }, { &gpt_uuid_netbsd_ffs, G_PART_ALIAS_NETBSD_FFS, 0 }, { &gpt_uuid_netbsd_lfs, G_PART_ALIAS_NETBSD_LFS, 0 }, { &gpt_uuid_netbsd_raid, G_PART_ALIAS_NETBSD_RAID, 0 }, { &gpt_uuid_netbsd_swap, G_PART_ALIAS_NETBSD_SWAP, 0 }, { &gpt_uuid_dfbsd_swap, G_PART_ALIAS_DFBSD_SWAP, 0 }, { &gpt_uuid_dfbsd_ufs1, G_PART_ALIAS_DFBSD_UFS, 0 }, { &gpt_uuid_dfbsd_vinum, G_PART_ALIAS_DFBSD_VINUM, 0 }, { &gpt_uuid_dfbsd_ccd, G_PART_ALIAS_DFBSD_CCD, 0 }, { &gpt_uuid_dfbsd_legacy, G_PART_ALIAS_DFBSD_LEGACY, 0 }, { &gpt_uuid_dfbsd_hammer, G_PART_ALIAS_DFBSD_HAMMER, 0 }, { &gpt_uuid_dfbsd_hammer2, G_PART_ALIAS_DFBSD_HAMMER2, 0 }, { &gpt_uuid_dfbsd_label32, G_PART_ALIAS_DFBSD, 0xa5 }, { &gpt_uuid_dfbsd_label64, G_PART_ALIAS_DFBSD64, 0xa5 }, { &gpt_uuid_prep_boot, G_PART_ALIAS_PREP_BOOT, 0x41 }, { NULL, 0, 0 } }; static int gpt_write_mbr_entry(u_char *mbr, int idx, int typ, quad_t start, quad_t end) { if (typ == 0 || start > UINT32_MAX || end > UINT32_MAX) return (EINVAL); mbr += DOSPARTOFF + idx * DOSPARTSIZE; mbr[0] = 0; if (start == 1) { /* * Treat the PMBR partition specially to maximize * interoperability with BIOSes. */ mbr[1] = mbr[3] = 0; mbr[2] = 2; } else mbr[1] = mbr[2] = mbr[3] = 0xff; mbr[4] = typ; mbr[5] = mbr[6] = mbr[7] = 0xff; le32enc(mbr + 8, (uint32_t)start); le32enc(mbr + 12, (uint32_t)(end - start + 1)); return (0); } static int gpt_map_type(struct uuid *t) { struct g_part_uuid_alias *uap; for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) { if (EQUUID(t, uap->uuid)) return (uap->mbrtype); } return (0); } static void gpt_create_pmbr(struct g_part_gpt_table *table, struct g_provider *pp) { bzero(table->mbr + DOSPARTOFF, DOSPARTSIZE * NDOSPART); gpt_write_mbr_entry(table->mbr, 0, 0xee, 1, MIN(pp->mediasize / pp->sectorsize - 1, UINT32_MAX)); le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC); } /* * Under Boot Camp the PMBR partition (type 0xEE) doesn't cover the * whole disk anymore. Rather, it covers the GPT table and the EFI * system partition only. This way the HFS+ partition and any FAT * partitions can be added to the MBR without creating an overlap. */ static int gpt_is_bootcamp(struct g_part_gpt_table *table, const char *provname) { uint8_t *p; p = table->mbr + DOSPARTOFF; if (p[4] != 0xee || le32dec(p + 8) != 1) return (0); p += DOSPARTSIZE; if (p[4] != 0xaf) return (0); printf("GEOM: %s: enabling Boot Camp\n", provname); return (1); } static void gpt_update_bootcamp(struct g_part_table *basetable, struct g_provider *pp) { struct g_part_entry *baseentry; struct g_part_gpt_entry *entry; struct g_part_gpt_table *table; int bootable, error, index, slices, typ; table = (struct g_part_gpt_table *)basetable; bootable = -1; for (index = 0; index < NDOSPART; index++) { if (table->mbr[DOSPARTOFF + DOSPARTSIZE * index]) bootable = index; } bzero(table->mbr + DOSPARTOFF, DOSPARTSIZE * NDOSPART); slices = 0; LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) { if (baseentry->gpe_deleted) continue; index = baseentry->gpe_index - 1; if (index >= NDOSPART) continue; entry = (struct g_part_gpt_entry *)baseentry; switch (index) { case 0: /* This must be the EFI system partition. */ if (!EQUUID(&entry->ent.ent_type, &gpt_uuid_efi)) goto disable; error = gpt_write_mbr_entry(table->mbr, index, 0xee, 1ull, entry->ent.ent_lba_end); break; case 1: /* This must be the HFS+ partition. */ if (!EQUUID(&entry->ent.ent_type, &gpt_uuid_apple_hfs)) goto disable; error = gpt_write_mbr_entry(table->mbr, index, 0xaf, entry->ent.ent_lba_start, entry->ent.ent_lba_end); break; default: typ = gpt_map_type(&entry->ent.ent_type); error = gpt_write_mbr_entry(table->mbr, index, typ, entry->ent.ent_lba_start, entry->ent.ent_lba_end); break; } if (error) continue; if (index == bootable) table->mbr[DOSPARTOFF + DOSPARTSIZE * index] = 0x80; slices |= 1 << index; } if ((slices & 3) == 3) return; disable: table->bootcamp = 0; gpt_create_pmbr(table, pp); } static struct gpt_hdr * gpt_read_hdr(struct g_part_gpt_table *table, struct g_consumer *cp, enum gpt_elt elt) { struct gpt_hdr *buf, *hdr; struct g_provider *pp; quad_t lba, last; int error; uint32_t crc, sz; pp = cp->provider; last = (pp->mediasize / pp->sectorsize) - 1; table->state[elt] = GPT_STATE_MISSING; /* * If the primary header is valid look for secondary * header in AlternateLBA, otherwise in the last medium's LBA. */ if (elt == GPT_ELT_SECHDR) { if (table->state[GPT_ELT_PRIHDR] != GPT_STATE_OK) table->lba[elt] = last; } else table->lba[elt] = 1; buf = g_read_data(cp, table->lba[elt] * pp->sectorsize, pp->sectorsize, &error); if (buf == NULL) return (NULL); hdr = NULL; if (memcmp(buf->hdr_sig, GPT_HDR_SIG, sizeof(buf->hdr_sig)) != 0) goto fail; table->state[elt] = GPT_STATE_CORRUPT; sz = le32toh(buf->hdr_size); if (sz < 92 || sz > pp->sectorsize) goto fail; hdr = g_malloc(sz, M_WAITOK | M_ZERO); bcopy(buf, hdr, sz); hdr->hdr_size = sz; crc = le32toh(buf->hdr_crc_self); buf->hdr_crc_self = 0; if (crc32(buf, sz) != crc) goto fail; hdr->hdr_crc_self = crc; table->state[elt] = GPT_STATE_INVALID; hdr->hdr_revision = le32toh(buf->hdr_revision); if (hdr->hdr_revision < GPT_HDR_REVISION) goto fail; hdr->hdr_lba_self = le64toh(buf->hdr_lba_self); if (hdr->hdr_lba_self != table->lba[elt]) goto fail; hdr->hdr_lba_alt = le64toh(buf->hdr_lba_alt); if (hdr->hdr_lba_alt == hdr->hdr_lba_self || hdr->hdr_lba_alt > last) goto fail; /* Check the managed area. */ hdr->hdr_lba_start = le64toh(buf->hdr_lba_start); if (hdr->hdr_lba_start < 2 || hdr->hdr_lba_start >= last) goto fail; hdr->hdr_lba_end = le64toh(buf->hdr_lba_end); if (hdr->hdr_lba_end < hdr->hdr_lba_start || hdr->hdr_lba_end >= last) goto fail; /* Check the table location and size of the table. */ hdr->hdr_entries = le32toh(buf->hdr_entries); hdr->hdr_entsz = le32toh(buf->hdr_entsz); if (hdr->hdr_entries == 0 || hdr->hdr_entsz < 128 || (hdr->hdr_entsz & 7) != 0) goto fail; hdr->hdr_lba_table = le64toh(buf->hdr_lba_table); if (hdr->hdr_lba_table < 2 || hdr->hdr_lba_table >= last) goto fail; if (hdr->hdr_lba_table >= hdr->hdr_lba_start && hdr->hdr_lba_table <= hdr->hdr_lba_end) goto fail; lba = hdr->hdr_lba_table + (hdr->hdr_entries * hdr->hdr_entsz + pp->sectorsize - 1) / pp->sectorsize - 1; if (lba >= last) goto fail; if (lba >= hdr->hdr_lba_start && lba <= hdr->hdr_lba_end) goto fail; table->state[elt] = GPT_STATE_OK; le_uuid_dec(&buf->hdr_uuid, &hdr->hdr_uuid); hdr->hdr_crc_table = le32toh(buf->hdr_crc_table); /* save LBA for secondary header */ if (elt == GPT_ELT_PRIHDR) table->lba[GPT_ELT_SECHDR] = hdr->hdr_lba_alt; g_free(buf); return (hdr); fail: if (hdr != NULL) g_free(hdr); g_free(buf); return (NULL); } static struct gpt_ent * gpt_read_tbl(struct g_part_gpt_table *table, struct g_consumer *cp, enum gpt_elt elt, struct gpt_hdr *hdr) { struct g_provider *pp; struct gpt_ent *ent, *tbl; char *buf, *p; unsigned int idx, sectors, tblsz, size; int error; if (hdr == NULL) return (NULL); pp = cp->provider; table->lba[elt] = hdr->hdr_lba_table; table->state[elt] = GPT_STATE_MISSING; tblsz = hdr->hdr_entries * hdr->hdr_entsz; sectors = (tblsz + pp->sectorsize - 1) / pp->sectorsize; buf = g_malloc(sectors * pp->sectorsize, M_WAITOK | M_ZERO); for (idx = 0; idx < sectors; idx += MAXPHYS / pp->sectorsize) { size = (sectors - idx > MAXPHYS / pp->sectorsize) ? MAXPHYS: (sectors - idx) * pp->sectorsize; p = g_read_data(cp, (table->lba[elt] + idx) * pp->sectorsize, size, &error); if (p == NULL) { g_free(buf); return (NULL); } bcopy(p, buf + idx * pp->sectorsize, size); g_free(p); } table->state[elt] = GPT_STATE_CORRUPT; if (crc32(buf, tblsz) != hdr->hdr_crc_table) { g_free(buf); return (NULL); } table->state[elt] = GPT_STATE_OK; tbl = g_malloc(hdr->hdr_entries * sizeof(struct gpt_ent), M_WAITOK | M_ZERO); for (idx = 0, ent = tbl, p = buf; idx < hdr->hdr_entries; idx++, ent++, p += hdr->hdr_entsz) { le_uuid_dec(p, &ent->ent_type); le_uuid_dec(p + 16, &ent->ent_uuid); ent->ent_lba_start = le64dec(p + 32); ent->ent_lba_end = le64dec(p + 40); ent->ent_attr = le64dec(p + 48); /* Keep UTF-16 in little-endian. */ bcopy(p + 56, ent->ent_name, sizeof(ent->ent_name)); } g_free(buf); return (tbl); } static int gpt_matched_hdrs(struct gpt_hdr *pri, struct gpt_hdr *sec) { if (pri == NULL || sec == NULL) return (0); if (!EQUUID(&pri->hdr_uuid, &sec->hdr_uuid)) return (0); return ((pri->hdr_revision == sec->hdr_revision && pri->hdr_size == sec->hdr_size && pri->hdr_lba_start == sec->hdr_lba_start && pri->hdr_lba_end == sec->hdr_lba_end && pri->hdr_entries == sec->hdr_entries && pri->hdr_entsz == sec->hdr_entsz && pri->hdr_crc_table == sec->hdr_crc_table) ? 1 : 0); } static int gpt_parse_type(const char *type, struct uuid *uuid) { struct uuid tmp; const char *alias; int error; struct g_part_uuid_alias *uap; if (type[0] == '!') { error = parse_uuid(type + 1, &tmp); if (error) return (error); if (EQUUID(&tmp, &gpt_uuid_unused)) return (EINVAL); *uuid = tmp; return (0); } for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) { alias = g_part_alias_name(uap->alias); if (!strcasecmp(type, alias)) { *uuid = *uap->uuid; return (0); } } return (EINVAL); } static int g_part_gpt_add(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_gpt_entry *entry; int error; entry = (struct g_part_gpt_entry *)baseentry; error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type); if (error) return (error); kern_uuidgen(&entry->ent.ent_uuid, 1); entry->ent.ent_lba_start = baseentry->gpe_start; entry->ent.ent_lba_end = baseentry->gpe_end; if (baseentry->gpe_deleted) { entry->ent.ent_attr = 0; bzero(entry->ent.ent_name, sizeof(entry->ent.ent_name)); } if (gpp->gpp_parms & G_PART_PARM_LABEL) g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name, sizeof(entry->ent.ent_name) / sizeof(entry->ent.ent_name[0])); return (0); } static int g_part_gpt_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp) { struct g_part_gpt_table *table; size_t codesz; codesz = DOSPARTOFF; table = (struct g_part_gpt_table *)basetable; bzero(table->mbr, codesz); codesz = MIN(codesz, gpp->gpp_codesize); if (codesz > 0) bcopy(gpp->gpp_codeptr, table->mbr, codesz); return (0); } static int g_part_gpt_create(struct g_part_table *basetable, struct g_part_parms *gpp) { struct g_provider *pp; struct g_part_gpt_table *table; size_t tblsz; /* We don't nest, which means that our depth should be 0. */ if (basetable->gpt_depth != 0) return (ENXIO); table = (struct g_part_gpt_table *)basetable; pp = gpp->gpp_provider; tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) + pp->sectorsize - 1) / pp->sectorsize; if (pp->sectorsize < MBRSIZE || pp->mediasize < (3 + 2 * tblsz + basetable->gpt_entries) * pp->sectorsize) return (ENOSPC); gpt_create_pmbr(table, pp); /* Allocate space for the header */ table->hdr = g_malloc(sizeof(struct gpt_hdr), M_WAITOK | M_ZERO); bcopy(GPT_HDR_SIG, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig)); table->hdr->hdr_revision = GPT_HDR_REVISION; table->hdr->hdr_size = offsetof(struct gpt_hdr, padding); kern_uuidgen(&table->hdr->hdr_uuid, 1); table->hdr->hdr_entries = basetable->gpt_entries; table->hdr->hdr_entsz = sizeof(struct gpt_ent); g_gpt_set_defaults(basetable, pp); return (0); } static int g_part_gpt_destroy(struct g_part_table *basetable, struct g_part_parms *gpp) { struct g_part_gpt_table *table; struct g_provider *pp; table = (struct g_part_gpt_table *)basetable; pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider; g_free(table->hdr); table->hdr = NULL; /* * Wipe the first 2 sectors to clear the partitioning. Wipe the last * sector only if it has valid secondary header. */ basetable->gpt_smhead |= 3; if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK && table->lba[GPT_ELT_SECHDR] == pp->mediasize / pp->sectorsize - 1) basetable->gpt_smtail |= 1; return (0); } static void g_part_gpt_dumpconf(struct g_part_table *table, struct g_part_entry *baseentry, struct sbuf *sb, const char *indent) { struct g_part_gpt_entry *entry; entry = (struct g_part_gpt_entry *)baseentry; if (indent == NULL) { /* conftxt: libdisk compatibility */ sbuf_printf(sb, " xs GPT xt "); sbuf_printf_uuid(sb, &entry->ent.ent_type); } else if (entry != NULL) { /* confxml: partition entry information */ sbuf_printf(sb, "%s\n"); if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTME) sbuf_printf(sb, "%sbootme\n", indent); if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTONCE) { sbuf_printf(sb, "%sbootonce\n", indent); } if (entry->ent.ent_attr & GPT_ENT_ATTR_BOOTFAILED) { sbuf_printf(sb, "%sbootfailed\n", indent); } sbuf_printf(sb, "%s", indent); sbuf_printf_uuid(sb, &entry->ent.ent_type); sbuf_printf(sb, "\n"); sbuf_printf(sb, "%s", indent); sbuf_printf_uuid(sb, &entry->ent.ent_uuid); sbuf_printf(sb, "\n"); } else { /* confxml: scheme information */ } } static int g_part_gpt_dumpto(struct g_part_table *table, struct g_part_entry *baseentry) { struct g_part_gpt_entry *entry; entry = (struct g_part_gpt_entry *)baseentry; return ((EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd_swap) || EQUUID(&entry->ent.ent_type, &gpt_uuid_linux_swap) || EQUUID(&entry->ent.ent_type, &gpt_uuid_dfbsd_swap)) ? 1 : 0); } static int g_part_gpt_modify(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_gpt_entry *entry; int error; entry = (struct g_part_gpt_entry *)baseentry; if (gpp->gpp_parms & G_PART_PARM_TYPE) { error = gpt_parse_type(gpp->gpp_type, &entry->ent.ent_type); if (error) return (error); } if (gpp->gpp_parms & G_PART_PARM_LABEL) g_gpt_utf8_to_utf16(gpp->gpp_label, entry->ent.ent_name, sizeof(entry->ent.ent_name) / sizeof(entry->ent.ent_name[0])); return (0); } static int g_part_gpt_resize(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_gpt_entry *entry; if (baseentry == NULL) return (g_part_gpt_recover(basetable)); entry = (struct g_part_gpt_entry *)baseentry; baseentry->gpe_end = baseentry->gpe_start + gpp->gpp_size - 1; entry->ent.ent_lba_end = baseentry->gpe_end; return (0); } static const char * g_part_gpt_name(struct g_part_table *table, struct g_part_entry *baseentry, char *buf, size_t bufsz) { struct g_part_gpt_entry *entry; char c; entry = (struct g_part_gpt_entry *)baseentry; c = (EQUUID(&entry->ent.ent_type, &gpt_uuid_freebsd)) ? 's' : 'p'; snprintf(buf, bufsz, "%c%d", c, baseentry->gpe_index); return (buf); } static int g_part_gpt_probe(struct g_part_table *table, struct g_consumer *cp) { struct g_provider *pp; u_char *buf; int error, index, pri, res; /* We don't nest, which means that our depth should be 0. */ if (table->gpt_depth != 0) return (ENXIO); pp = cp->provider; /* * Sanity-check the provider. Since the first sector on the provider * must be a PMBR and a PMBR is 512 bytes large, the sector size * must be at least 512 bytes. Also, since the theoretical minimum * number of sectors needed by GPT is 6, any medium that has less * than 6 sectors is never going to be able to hold a GPT. The * number 6 comes from: * 1 sector for the PMBR * 2 sectors for the GPT headers (each 1 sector) * 2 sectors for the GPT tables (each 1 sector) * 1 sector for an actual partition * It's better to catch this pathological case early than behaving * pathologically later on... */ if (pp->sectorsize < MBRSIZE || pp->mediasize < 6 * pp->sectorsize) return (ENOSPC); /* * Check that there's a MBR or a PMBR. If it's a PMBR, we return * as the highest priority on a match, otherwise we assume some * GPT-unaware tool has destroyed the GPT by recreating a MBR and * we really want the MBR scheme to take precedence. */ buf = g_read_data(cp, 0L, pp->sectorsize, &error); if (buf == NULL) return (error); res = le16dec(buf + DOSMAGICOFFSET); pri = G_PART_PROBE_PRI_LOW; - for (index = 0; index < NDOSPART; index++) { - if (buf[DOSPARTOFF + DOSPARTSIZE * index + 4] == 0xee) - pri = G_PART_PROBE_PRI_HIGH; - } - g_free(buf); - if (res != DOSMAGIC) - return (ENXIO); + if (res == DOSMAGIC) { + for (index = 0; index < NDOSPART; index++) { + if (buf[DOSPARTOFF + DOSPARTSIZE * index + 4] == 0xee) + pri = G_PART_PROBE_PRI_HIGH; + } + g_free(buf); - /* Check that there's a primary header. */ - buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error); - if (buf == NULL) - return (error); - res = memcmp(buf, GPT_HDR_SIG, 8); - g_free(buf); - if (res == 0) - return (pri); + /* Check that there's a primary header. */ + buf = g_read_data(cp, pp->sectorsize, pp->sectorsize, &error); + if (buf == NULL) + return (error); + res = memcmp(buf, GPT_HDR_SIG, 8); + g_free(buf); + if (res == 0) + return (pri); + } else + g_free(buf); /* No primary? Check that there's a secondary. */ buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize, &error); if (buf == NULL) return (error); res = memcmp(buf, GPT_HDR_SIG, 8); g_free(buf); return ((res == 0) ? pri : ENXIO); } static int g_part_gpt_read(struct g_part_table *basetable, struct g_consumer *cp) { struct gpt_hdr *prihdr, *sechdr; struct gpt_ent *tbl, *pritbl, *sectbl; struct g_provider *pp; struct g_part_gpt_table *table; struct g_part_gpt_entry *entry; u_char *buf; uint64_t last; int error, index; table = (struct g_part_gpt_table *)basetable; pp = cp->provider; last = (pp->mediasize / pp->sectorsize) - 1; /* Read the PMBR */ buf = g_read_data(cp, 0, pp->sectorsize, &error); if (buf == NULL) return (error); bcopy(buf, table->mbr, MBRSIZE); g_free(buf); /* Read the primary header and table. */ prihdr = gpt_read_hdr(table, cp, GPT_ELT_PRIHDR); if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK) { pritbl = gpt_read_tbl(table, cp, GPT_ELT_PRITBL, prihdr); } else { table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING; pritbl = NULL; } /* Read the secondary header and table. */ sechdr = gpt_read_hdr(table, cp, GPT_ELT_SECHDR); if (table->state[GPT_ELT_SECHDR] == GPT_STATE_OK) { sectbl = gpt_read_tbl(table, cp, GPT_ELT_SECTBL, sechdr); } else { table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING; sectbl = NULL; } /* Fail if we haven't got any good tables at all. */ if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK && table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) { printf("GEOM: %s: corrupt or invalid GPT detected.\n", pp->name); printf("GEOM: %s: GPT rejected -- may not be recoverable.\n", pp->name); return (EINVAL); } /* * If both headers are good but they disagree with each other, * then invalidate one. We prefer to keep the primary header, * unless the primary table is corrupt. */ if (table->state[GPT_ELT_PRIHDR] == GPT_STATE_OK && table->state[GPT_ELT_SECHDR] == GPT_STATE_OK && !gpt_matched_hdrs(prihdr, sechdr)) { if (table->state[GPT_ELT_PRITBL] == GPT_STATE_OK) { table->state[GPT_ELT_SECHDR] = GPT_STATE_INVALID; table->state[GPT_ELT_SECTBL] = GPT_STATE_MISSING; g_free(sechdr); sechdr = NULL; } else { table->state[GPT_ELT_PRIHDR] = GPT_STATE_INVALID; table->state[GPT_ELT_PRITBL] = GPT_STATE_MISSING; g_free(prihdr); prihdr = NULL; } } if (table->state[GPT_ELT_PRITBL] != GPT_STATE_OK) { printf("GEOM: %s: the primary GPT table is corrupt or " "invalid.\n", pp->name); printf("GEOM: %s: using the secondary instead -- recovery " "strongly advised.\n", pp->name); table->hdr = sechdr; basetable->gpt_corrupt = 1; if (prihdr != NULL) g_free(prihdr); tbl = sectbl; if (pritbl != NULL) g_free(pritbl); } else { if (table->state[GPT_ELT_SECTBL] != GPT_STATE_OK) { printf("GEOM: %s: the secondary GPT table is corrupt " "or invalid.\n", pp->name); printf("GEOM: %s: using the primary only -- recovery " "suggested.\n", pp->name); basetable->gpt_corrupt = 1; } else if (table->lba[GPT_ELT_SECHDR] != last) { printf( "GEOM: %s: the secondary GPT header is not in " "the last LBA.\n", pp->name); basetable->gpt_corrupt = 1; } table->hdr = prihdr; if (sechdr != NULL) g_free(sechdr); tbl = pritbl; if (sectbl != NULL) g_free(sectbl); } basetable->gpt_first = table->hdr->hdr_lba_start; basetable->gpt_last = table->hdr->hdr_lba_end; basetable->gpt_entries = (table->hdr->hdr_lba_start - 2) * pp->sectorsize / table->hdr->hdr_entsz; for (index = table->hdr->hdr_entries - 1; index >= 0; index--) { if (EQUUID(&tbl[index].ent_type, &gpt_uuid_unused)) continue; entry = (struct g_part_gpt_entry *)g_part_new_entry( basetable, index + 1, tbl[index].ent_lba_start, tbl[index].ent_lba_end); entry->ent = tbl[index]; } g_free(tbl); /* * Under Mac OS X, the MBR mirrors the first 4 GPT partitions * if (and only if) any FAT32 or FAT16 partitions have been * created. This happens irrespective of whether Boot Camp is * used/enabled, though it's generally understood to be done * to support legacy Windows under Boot Camp. We refer to this * mirroring simply as Boot Camp. We try to detect Boot Camp * so that we can update the MBR if and when GPT changes have * been made. Note that we do not enable Boot Camp if not * previously enabled because we can't assume that we're on a * Mac alongside Mac OS X. */ table->bootcamp = gpt_is_bootcamp(table, pp->name); return (0); } static int g_part_gpt_recover(struct g_part_table *basetable) { struct g_part_gpt_table *table; struct g_provider *pp; table = (struct g_part_gpt_table *)basetable; pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider; gpt_create_pmbr(table, pp); g_gpt_set_defaults(basetable, pp); basetable->gpt_corrupt = 0; return (0); } static int g_part_gpt_setunset(struct g_part_table *basetable, struct g_part_entry *baseentry, const char *attrib, unsigned int set) { struct g_part_gpt_entry *entry; struct g_part_gpt_table *table; struct g_provider *pp; uint8_t *p; uint64_t attr; int i; table = (struct g_part_gpt_table *)basetable; entry = (struct g_part_gpt_entry *)baseentry; if (strcasecmp(attrib, "active") == 0) { if (table->bootcamp) { /* The active flag must be set on a valid entry. */ if (entry == NULL) return (ENXIO); if (baseentry->gpe_index > NDOSPART) return (EINVAL); for (i = 0; i < NDOSPART; i++) { p = &table->mbr[DOSPARTOFF + i * DOSPARTSIZE]; p[0] = (i == baseentry->gpe_index - 1) ? ((set) ? 0x80 : 0) : 0; } } else { /* The PMBR is marked as active without an entry. */ if (entry != NULL) return (ENXIO); for (i = 0; i < NDOSPART; i++) { p = &table->mbr[DOSPARTOFF + i * DOSPARTSIZE]; p[0] = (p[4] == 0xee) ? ((set) ? 0x80 : 0) : 0; } } return (0); } else if (strcasecmp(attrib, "lenovofix") == 0) { /* * Write the 0xee GPT entry to slot #1 (2nd slot) in the pMBR. * This workaround allows Lenovo X220, T420, T520, etc to boot * from GPT Partitions in BIOS mode. */ if (entry != NULL) return (ENXIO); pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider; bzero(table->mbr + DOSPARTOFF, DOSPARTSIZE * NDOSPART); gpt_write_mbr_entry(table->mbr, ((set) ? 1 : 0), 0xee, 1, MIN(pp->mediasize / pp->sectorsize - 1, UINT32_MAX)); return (0); } if (entry == NULL) return (ENODEV); attr = 0; if (strcasecmp(attrib, "bootme") == 0) { attr |= GPT_ENT_ATTR_BOOTME; } else if (strcasecmp(attrib, "bootonce") == 0) { attr |= GPT_ENT_ATTR_BOOTONCE; if (set) attr |= GPT_ENT_ATTR_BOOTME; } else if (strcasecmp(attrib, "bootfailed") == 0) { /* * It should only be possible to unset BOOTFAILED, but it might * be useful for test purposes to also be able to set it. */ attr |= GPT_ENT_ATTR_BOOTFAILED; } if (attr == 0) return (EINVAL); if (set) attr = entry->ent.ent_attr | attr; else attr = entry->ent.ent_attr & ~attr; if (attr != entry->ent.ent_attr) { entry->ent.ent_attr = attr; if (!baseentry->gpe_created) baseentry->gpe_modified = 1; } return (0); } static const char * g_part_gpt_type(struct g_part_table *basetable, struct g_part_entry *baseentry, char *buf, size_t bufsz) { struct g_part_gpt_entry *entry; struct uuid *type; struct g_part_uuid_alias *uap; entry = (struct g_part_gpt_entry *)baseentry; type = &entry->ent.ent_type; for (uap = &gpt_uuid_alias_match[0]; uap->uuid; uap++) if (EQUUID(type, uap->uuid)) return (g_part_alias_name(uap->alias)); buf[0] = '!'; snprintf_uuid(buf + 1, bufsz - 1, type); return (buf); } static int g_part_gpt_write(struct g_part_table *basetable, struct g_consumer *cp) { unsigned char *buf, *bp; struct g_provider *pp; struct g_part_entry *baseentry; struct g_part_gpt_entry *entry; struct g_part_gpt_table *table; size_t tblsz; uint32_t crc; int error, index; pp = cp->provider; table = (struct g_part_gpt_table *)basetable; tblsz = (table->hdr->hdr_entries * table->hdr->hdr_entsz + pp->sectorsize - 1) / pp->sectorsize; /* Reconstruct the MBR from the GPT if under Boot Camp. */ if (table->bootcamp) gpt_update_bootcamp(basetable, pp); /* Write the PMBR */ buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO); bcopy(table->mbr, buf, MBRSIZE); error = g_write_data(cp, 0, buf, pp->sectorsize); g_free(buf); if (error) return (error); /* Allocate space for the header and entries. */ buf = g_malloc((tblsz + 1) * pp->sectorsize, M_WAITOK | M_ZERO); memcpy(buf, table->hdr->hdr_sig, sizeof(table->hdr->hdr_sig)); le32enc(buf + 8, table->hdr->hdr_revision); le32enc(buf + 12, table->hdr->hdr_size); le64enc(buf + 40, table->hdr->hdr_lba_start); le64enc(buf + 48, table->hdr->hdr_lba_end); le_uuid_enc(buf + 56, &table->hdr->hdr_uuid); le32enc(buf + 80, table->hdr->hdr_entries); le32enc(buf + 84, table->hdr->hdr_entsz); LIST_FOREACH(baseentry, &basetable->gpt_entry, gpe_entry) { if (baseentry->gpe_deleted) continue; entry = (struct g_part_gpt_entry *)baseentry; index = baseentry->gpe_index - 1; bp = buf + pp->sectorsize + table->hdr->hdr_entsz * index; le_uuid_enc(bp, &entry->ent.ent_type); le_uuid_enc(bp + 16, &entry->ent.ent_uuid); le64enc(bp + 32, entry->ent.ent_lba_start); le64enc(bp + 40, entry->ent.ent_lba_end); le64enc(bp + 48, entry->ent.ent_attr); memcpy(bp + 56, entry->ent.ent_name, sizeof(entry->ent.ent_name)); } crc = crc32(buf + pp->sectorsize, table->hdr->hdr_entries * table->hdr->hdr_entsz); le32enc(buf + 88, crc); /* Write primary meta-data. */ le32enc(buf + 16, 0); /* hdr_crc_self. */ le64enc(buf + 24, table->lba[GPT_ELT_PRIHDR]); /* hdr_lba_self. */ le64enc(buf + 32, table->lba[GPT_ELT_SECHDR]); /* hdr_lba_alt. */ le64enc(buf + 72, table->lba[GPT_ELT_PRITBL]); /* hdr_lba_table. */ crc = crc32(buf, table->hdr->hdr_size); le32enc(buf + 16, crc); for (index = 0; index < tblsz; index += MAXPHYS / pp->sectorsize) { error = g_write_data(cp, (table->lba[GPT_ELT_PRITBL] + index) * pp->sectorsize, buf + (index + 1) * pp->sectorsize, (tblsz - index > MAXPHYS / pp->sectorsize) ? MAXPHYS: (tblsz - index) * pp->sectorsize); if (error) goto out; } error = g_write_data(cp, table->lba[GPT_ELT_PRIHDR] * pp->sectorsize, buf, pp->sectorsize); if (error) goto out; /* Write secondary meta-data. */ le32enc(buf + 16, 0); /* hdr_crc_self. */ le64enc(buf + 24, table->lba[GPT_ELT_SECHDR]); /* hdr_lba_self. */ le64enc(buf + 32, table->lba[GPT_ELT_PRIHDR]); /* hdr_lba_alt. */ le64enc(buf + 72, table->lba[GPT_ELT_SECTBL]); /* hdr_lba_table. */ crc = crc32(buf, table->hdr->hdr_size); le32enc(buf + 16, crc); for (index = 0; index < tblsz; index += MAXPHYS / pp->sectorsize) { error = g_write_data(cp, (table->lba[GPT_ELT_SECTBL] + index) * pp->sectorsize, buf + (index + 1) * pp->sectorsize, (tblsz - index > MAXPHYS / pp->sectorsize) ? MAXPHYS: (tblsz - index) * pp->sectorsize); if (error) goto out; } error = g_write_data(cp, table->lba[GPT_ELT_SECHDR] * pp->sectorsize, buf, pp->sectorsize); out: g_free(buf); return (error); } static void g_gpt_set_defaults(struct g_part_table *basetable, struct g_provider *pp) { struct g_part_gpt_table *table; quad_t last; size_t tblsz; table = (struct g_part_gpt_table *)basetable; last = pp->mediasize / pp->sectorsize - 1; tblsz = (basetable->gpt_entries * sizeof(struct gpt_ent) + pp->sectorsize - 1) / pp->sectorsize; table->lba[GPT_ELT_PRIHDR] = 1; table->lba[GPT_ELT_PRITBL] = 2; table->lba[GPT_ELT_SECHDR] = last; table->lba[GPT_ELT_SECTBL] = last - tblsz; table->state[GPT_ELT_PRIHDR] = GPT_STATE_OK; table->state[GPT_ELT_PRITBL] = GPT_STATE_OK; table->state[GPT_ELT_SECHDR] = GPT_STATE_OK; table->state[GPT_ELT_SECTBL] = GPT_STATE_OK; table->hdr->hdr_lba_start = 2 + tblsz; table->hdr->hdr_lba_end = last - tblsz - 1; basetable->gpt_first = table->hdr->hdr_lba_start; basetable->gpt_last = table->hdr->hdr_lba_end; } static void g_gpt_printf_utf16(struct sbuf *sb, uint16_t *str, size_t len) { u_int bo; uint32_t ch; uint16_t c; bo = LITTLE_ENDIAN; /* GPT is little-endian */ while (len > 0 && *str != 0) { ch = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str); str++, len--; if ((ch & 0xf800) == 0xd800) { if (len > 0) { c = (bo == BIG_ENDIAN) ? be16toh(*str) : le16toh(*str); str++, len--; } else c = 0xfffd; if ((ch & 0x400) == 0 && (c & 0xfc00) == 0xdc00) { ch = ((ch & 0x3ff) << 10) + (c & 0x3ff); ch += 0x10000; } else ch = 0xfffd; } else if (ch == 0xfffe) { /* BOM (U+FEFF) swapped. */ bo = (bo == BIG_ENDIAN) ? LITTLE_ENDIAN : BIG_ENDIAN; continue; } else if (ch == 0xfeff) /* BOM (U+FEFF) unswapped. */ continue; /* Write the Unicode character in UTF-8 */ if (ch < 0x80) g_conf_printf_escaped(sb, "%c", ch); else if (ch < 0x800) g_conf_printf_escaped(sb, "%c%c", 0xc0 | (ch >> 6), 0x80 | (ch & 0x3f)); else if (ch < 0x10000) g_conf_printf_escaped(sb, "%c%c%c", 0xe0 | (ch >> 12), 0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f)); else if (ch < 0x200000) g_conf_printf_escaped(sb, "%c%c%c%c", 0xf0 | (ch >> 18), 0x80 | ((ch >> 12) & 0x3f), 0x80 | ((ch >> 6) & 0x3f), 0x80 | (ch & 0x3f)); } } static void g_gpt_utf8_to_utf16(const uint8_t *s8, uint16_t *s16, size_t s16len) { size_t s16idx, s8idx; uint32_t utfchar; unsigned int c, utfbytes; s8idx = s16idx = 0; utfchar = 0; utfbytes = 0; bzero(s16, s16len << 1); while (s8[s8idx] != 0 && s16idx < s16len) { c = s8[s8idx++]; if ((c & 0xc0) != 0x80) { /* Initial characters. */ if (utfbytes != 0) { /* Incomplete encoding of previous char. */ s16[s16idx++] = htole16(0xfffd); } if ((c & 0xf8) == 0xf0) { utfchar = c & 0x07; utfbytes = 3; } else if ((c & 0xf0) == 0xe0) { utfchar = c & 0x0f; utfbytes = 2; } else if ((c & 0xe0) == 0xc0) { utfchar = c & 0x1f; utfbytes = 1; } else { utfchar = c & 0x7f; utfbytes = 0; } } else { /* Followup characters. */ if (utfbytes > 0) { utfchar = (utfchar << 6) + (c & 0x3f); utfbytes--; } else if (utfbytes == 0) utfbytes = ~0; } /* * Write the complete Unicode character as UTF-16 when we * have all the UTF-8 charactars collected. */ if (utfbytes == 0) { /* * If we need to write 2 UTF-16 characters, but * we only have room for 1, then we truncate the * string by writing a 0 instead. */ if (utfchar >= 0x10000 && s16idx < s16len - 1) { s16[s16idx++] = htole16(0xd800 | ((utfchar >> 10) - 0x40)); s16[s16idx++] = htole16(0xdc00 | (utfchar & 0x3ff)); } else s16[s16idx++] = (utfchar >= 0x10000) ? 0 : htole16(utfchar); } } /* * If our input string was truncated, append an invalid encoding * character to the output string. */ if (utfbytes != 0 && s16idx < s16len) s16[s16idx++] = htole16(0xfffd); } Index: user/ngie/stable-10-libnv/sys/sys/param.h =================================================================== --- user/ngie/stable-10-libnv/sys/sys/param.h (revision 293638) +++ user/ngie/stable-10-libnv/sys/sys/param.h (revision 293639) @@ -1,361 +1,361 @@ /*- * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)param.h 8.3 (Berkeley) 4/4/95 * $FreeBSD$ */ #ifndef _SYS_PARAM_H_ #define _SYS_PARAM_H_ #include #define BSD 199506 /* System version (year & month). */ #define BSD4_3 1 #define BSD4_4 1 /* * __FreeBSD_version numbers are documented in the Porter's Handbook. * If you bump the version for any reason, you should update the documentation * there. * Currently this lives here in the doc/ repository: * * head/en_US.ISO8859-1/books/porters-handbook/book.xml * * scheme is: Rxx * 'R' is in the range 0 to 4 if this is a release branch or * x.0-CURRENT before RELENG_*_0 is created, otherwise 'R' is * in the range 5 to 9. */ #undef __FreeBSD_version -#define __FreeBSD_version 1002507 /* Master, propagated to newvers */ +#define __FreeBSD_version 1002508 /* Master, propagated to newvers */ /* * __FreeBSD_kernel__ indicates that this system uses the kernel of FreeBSD, * which by definition is always true on FreeBSD. This macro is also defined * on other systems that use the kernel of FreeBSD, such as GNU/kFreeBSD. * * It is tempting to use this macro in userland code when we want to enable * kernel-specific routines, and in fact it's fine to do this in code that * is part of FreeBSD itself. However, be aware that as presence of this * macro is still not widespread (e.g. older FreeBSD versions, 3rd party * compilers, etc), it is STRONGLY DISCOURAGED to check for this macro in * external applications without also checking for __FreeBSD__ as an * alternative. */ #undef __FreeBSD_kernel__ #define __FreeBSD_kernel__ #ifdef _KERNEL #define P_OSREL_SIGWAIT 700000 #define P_OSREL_SIGSEGV 700004 #define P_OSREL_MAP_ANON 800104 #define P_OSREL_MAJOR(x) ((x) / 100000) #endif #ifndef LOCORE #include #endif /* * Machine-independent constants (some used in following include files). * Redefined constants are from POSIX 1003.1 limits file. * * MAXCOMLEN should be >= sizeof(ac_comm) (see ) */ #include #define MAXCOMLEN 19 /* max command name remembered */ #define MAXINTERP PATH_MAX /* max interpreter file name length */ #define MAXLOGNAME 33 /* max login name length (incl. NUL) */ #define MAXUPRC CHILD_MAX /* max simultaneous processes */ #define NCARGS ARG_MAX /* max bytes for an exec function */ #define NGROUPS (NGROUPS_MAX+1) /* max number groups */ #define NOFILE OPEN_MAX /* max open files per process */ #define NOGROUP 65535 /* marker for empty group set member */ #define MAXHOSTNAMELEN 256 /* max hostname size */ #define SPECNAMELEN 63 /* max length of devicename */ /* More types and definitions used throughout the kernel. */ #ifdef _KERNEL #include #include #ifndef LOCORE #include #include #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #endif #ifndef _KERNEL /* Signals. */ #include #endif /* Machine type dependent parameters. */ #include #ifndef _KERNEL #include #endif #ifndef DEV_BSHIFT #define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ #endif #define DEV_BSIZE (1<>PAGE_SHIFT) #endif /* * btodb() is messy and perhaps slow because `bytes' may be an off_t. We * want to shift an unsigned type to avoid sign extension and we don't * want to widen `bytes' unnecessarily. Assume that the result fits in * a daddr_t. */ #ifndef btodb #define btodb(bytes) /* calculates (bytes / DEV_BSIZE) */ \ (sizeof (bytes) > sizeof(long) \ ? (daddr_t)((unsigned long long)(bytes) >> DEV_BSHIFT) \ : (daddr_t)((unsigned long)(bytes) >> DEV_BSHIFT)) #endif #ifndef dbtob #define dbtob(db) /* calculates (db * DEV_BSIZE) */ \ ((off_t)(db) << DEV_BSHIFT) #endif #define PRIMASK 0x0ff #define PCATCH 0x100 /* OR'd with pri for tsleep to check signals */ #define PDROP 0x200 /* OR'd with pri to stop re-entry of interlock mutex */ #define NZERO 0 /* default "nice" */ #define NBBY 8 /* number of bits in a byte */ #define NBPW sizeof(int) /* number of bytes per word (integer) */ #define CMASK 022 /* default file mask: S_IWGRP|S_IWOTH */ #define NODEV (dev_t)(-1) /* non-existent device */ /* * File system parameters and macros. * * MAXBSIZE - Filesystems are made out of blocks of at most MAXBSIZE bytes * per block. MAXBSIZE may be made larger without effecting * any existing filesystems as long as it does not exceed MAXPHYS, * and may be made smaller at the risk of not being able to use * filesystems which require a block size exceeding MAXBSIZE. * * MAXBCACHEBUF - Maximum size of a buffer in the buffer cache. This must * be >= MAXBSIZE and can be set differently for different * architectures by defining it in . * Making this larger allows NFS to do larger reads/writes. * * BKVASIZE - Nominal buffer space per buffer, in bytes. BKVASIZE is the * minimum KVM memory reservation the kernel is willing to make. * Filesystems can of course request smaller chunks. Actual * backing memory uses a chunk size of a page (PAGE_SIZE). * The default value here can be overridden on a per-architecture * basis by defining it in . This should * probably be done to increase its value, when MAXBCACHEBUF is * defined as a larger value in . * * If you make BKVASIZE too small you risk seriously fragmenting * the buffer KVM map which may slow things down a bit. If you * make it too big the kernel will not be able to optimally use * the KVM memory reserved for the buffer cache and will wind * up with too-few buffers. * * The default is 16384, roughly 2x the block size used by a * normal UFS filesystem. */ #define MAXBSIZE 65536 /* must be power of 2 */ #ifndef MAXBCACHEBUF #define MAXBCACHEBUF MAXBSIZE /* must be a power of 2 >= MAXBSIZE */ #endif #ifndef BKVASIZE #define BKVASIZE 16384 /* must be power of 2 */ #endif #define BKVAMASK (BKVASIZE-1) /* * MAXPATHLEN defines the longest permissible path length after expanding * symbolic links. It is used to allocate a temporary buffer from the buffer * pool in which to do the name expansion, hence should be a power of two, * and must be less than or equal to MAXBSIZE. MAXSYMLINKS defines the * maximum number of symbolic links that may be expanded in a path name. * It should be set high enough to allow all legitimate uses, but halt * infinite loops reasonably quickly. */ #define MAXPATHLEN PATH_MAX #define MAXSYMLINKS 32 /* Bit map related macros. */ #define setbit(a,i) (((unsigned char *)(a))[(i)/NBBY] |= 1<<((i)%NBBY)) #define clrbit(a,i) (((unsigned char *)(a))[(i)/NBBY] &= ~(1<<((i)%NBBY))) #define isset(a,i) \ (((const unsigned char *)(a))[(i)/NBBY] & (1<<((i)%NBBY))) #define isclr(a,i) \ ((((const unsigned char *)(a))[(i)/NBBY] & (1<<((i)%NBBY))) == 0) /* Macros for counting and rounding. */ #ifndef howmany #define howmany(x, y) (((x)+((y)-1))/(y)) #endif #define nitems(x) (sizeof((x)) / sizeof((x)[0])) #define rounddown(x, y) (((x)/(y))*(y)) #define rounddown2(x, y) ((x)&(~((y)-1))) /* if y is power of two */ #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */ #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #define powerof2(x) ((((x)-1)&(x))==0) /* Macros for min/max. */ #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #ifdef _KERNEL /* * Basic byte order function prototypes for non-inline functions. */ #ifndef LOCORE #ifndef _BYTEORDER_PROTOTYPED #define _BYTEORDER_PROTOTYPED __BEGIN_DECLS __uint32_t htonl(__uint32_t); __uint16_t htons(__uint16_t); __uint32_t ntohl(__uint32_t); __uint16_t ntohs(__uint16_t); __END_DECLS #endif #endif #ifndef lint #ifndef _BYTEORDER_FUNC_DEFINED #define _BYTEORDER_FUNC_DEFINED #define htonl(x) __htonl(x) #define htons(x) __htons(x) #define ntohl(x) __ntohl(x) #define ntohs(x) __ntohs(x) #endif /* !_BYTEORDER_FUNC_DEFINED */ #endif /* lint */ #endif /* _KERNEL */ /* * Scale factor for scaled integers used to count %cpu time and load avgs. * * The number of CPU `tick's that map to a unique `%age' can be expressed * by the formula (1 / (2 ^ (FSHIFT - 11))). The maximum load average that * can be calculated (assuming 32 bits) can be closely approximated using * the formula (2 ^ (2 * (16 - FSHIFT))) for (FSHIFT < 15). * * For the scheduler to maintain a 1:1 mapping of CPU `tick' to `%age', * FSHIFT must be at least 11; this gives us a maximum load avg of ~1024. */ #define FSHIFT 11 /* bits to right of fixed binary point */ #define FSCALE (1<> (PAGE_SHIFT - DEV_BSHIFT)) #define ctodb(db) /* calculates pages to devblks */ \ ((db) << (PAGE_SHIFT - DEV_BSHIFT)) /* * Old spelling of __containerof(). */ #define member2struct(s, m, x) \ ((struct s *)(void *)((char *)(x) - offsetof(struct s, m))) /* * Access a variable length array that has been declared as a fixed * length array. */ #define __PAST_END(array, offset) (((__typeof__(*(array)) *)(array))[offset]) #endif /* _SYS_PARAM_H_ */ Index: user/ngie/stable-10-libnv/usr.bin/netstat/inet.c =================================================================== --- user/ngie/stable-10-libnv/usr.bin/netstat/inet.c (revision 293638) +++ user/ngie/stable-10-libnv/usr.bin/netstat/inet.c (revision 293639) @@ -1,1238 +1,1197 @@ /*- * Copyright (c) 1983, 1988, 1993, 1995 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if 0 #ifndef lint static char sccsid[] = "@(#)inet.c 8.5 (Berkeley) 5/24/95"; #endif /* not lint */ #endif #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef INET6 #include #endif /* INET6 */ #include #include #include #include #include #include #include #include #include #define TCPSTATES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "netstat.h" char *inetname(struct in_addr *); void inetprint(struct in_addr *, int, const char *, int); #ifdef INET6 static int udp_done, tcp_done, sdp_done; #endif /* INET6 */ static int pcblist_sysctl(int proto, const char *name, char **bufp, int istcp __unused) { const char *mibvar; char *buf; size_t len; switch (proto) { case IPPROTO_TCP: mibvar = "net.inet.tcp.pcblist"; break; case IPPROTO_UDP: mibvar = "net.inet.udp.pcblist"; break; case IPPROTO_DIVERT: mibvar = "net.inet.divert.pcblist"; break; default: mibvar = "net.inet.raw.pcblist"; break; } if (strncmp(name, "sdp", 3) == 0) mibvar = "net.inet.sdp.pcblist"; len = 0; if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) { if (errno != ENOENT) warn("sysctl: %s", mibvar); return (0); } if ((buf = malloc(len)) == 0) { warnx("malloc %lu bytes", (u_long)len); return (0); } if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) { warn("sysctl: %s", mibvar); free(buf); return (0); } *bufp = buf; return (1); } /* * Copied directly from uipc_socket2.c. We leave out some fields that are in * nested structures that aren't used to avoid extra work. */ static void sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb) { xsb->sb_cc = sb->sb_cc; xsb->sb_hiwat = sb->sb_hiwat; xsb->sb_mbcnt = sb->sb_mbcnt; xsb->sb_mcnt = sb->sb_mcnt; xsb->sb_ccnt = sb->sb_ccnt; xsb->sb_mbmax = sb->sb_mbmax; xsb->sb_lowat = sb->sb_lowat; xsb->sb_flags = sb->sb_flags; xsb->sb_timeo = sb->sb_timeo; } int sotoxsocket(struct socket *so, struct xsocket *xso) { struct protosw proto; struct domain domain; bzero(xso, sizeof *xso); xso->xso_len = sizeof *xso; xso->xso_so = so; xso->so_type = so->so_type; xso->so_options = so->so_options; xso->so_linger = so->so_linger; xso->so_state = so->so_state; xso->so_pcb = so->so_pcb; if (kread((uintptr_t)so->so_proto, &proto, sizeof(proto)) != 0) return (-1); xso->xso_protocol = proto.pr_protocol; if (kread((uintptr_t)proto.pr_domain, &domain, sizeof(domain)) != 0) return (-1); xso->xso_family = domain.dom_family; xso->so_qlen = so->so_qlen; xso->so_incqlen = so->so_incqlen; xso->so_qlimit = so->so_qlimit; xso->so_timeo = so->so_timeo; xso->so_error = so->so_error; xso->so_oobmark = so->so_oobmark; sbtoxsockbuf(&so->so_snd, &xso->so_snd); sbtoxsockbuf(&so->so_rcv, &xso->so_rcv); return (0); } static int pcblist_kvm(u_long off, char **bufp, int istcp) { struct inpcbinfo pcbinfo; struct inpcbhead listhead; struct inpcb *inp; struct xinpcb xi; struct xinpgen xig; struct xtcpcb xt; struct socket so; struct xsocket *xso; char *buf, *p; size_t len; if (off == 0) return (0); kread(off, &pcbinfo, sizeof(pcbinfo)); if (istcp) len = 2 * sizeof(xig) + (pcbinfo.ipi_count + pcbinfo.ipi_count / 8) * sizeof(struct xtcpcb); else len = 2 * sizeof(xig) + (pcbinfo.ipi_count + pcbinfo.ipi_count / 8) * sizeof(struct xinpcb); if ((buf = malloc(len)) == 0) { warnx("malloc %lu bytes", (u_long)len); return (0); } p = buf; #define COPYOUT(obj, size) do { \ if (len < (size)) { \ warnx("buffer size exceeded"); \ goto fail; \ } \ bcopy((obj), p, (size)); \ len -= (size); \ p += (size); \ } while (0) #define KREAD(off, buf, len) do { \ if (kread((uintptr_t)(off), (buf), (len)) != 0) \ goto fail; \ } while (0) /* Write out header. */ xig.xig_len = sizeof xig; xig.xig_count = pcbinfo.ipi_count; xig.xig_gen = pcbinfo.ipi_gencnt; xig.xig_sogen = 0; COPYOUT(&xig, sizeof xig); /* Walk the PCB list. */ xt.xt_len = sizeof xt; xi.xi_len = sizeof xi; if (istcp) xso = &xt.xt_socket; else xso = &xi.xi_socket; KREAD(pcbinfo.ipi_listhead, &listhead, sizeof(listhead)); LIST_FOREACH(inp, &listhead, inp_list) { if (istcp) { KREAD(inp, &xt.xt_inp, sizeof(*inp)); inp = &xt.xt_inp; } else { KREAD(inp, &xi.xi_inp, sizeof(*inp)); inp = &xi.xi_inp; } if (inp->inp_gencnt > pcbinfo.ipi_gencnt) continue; if (istcp) { if (inp->inp_ppcb == NULL) bzero(&xt.xt_tp, sizeof xt.xt_tp); else if (inp->inp_flags & INP_TIMEWAIT) { bzero(&xt.xt_tp, sizeof xt.xt_tp); xt.xt_tp.t_state = TCPS_TIME_WAIT; } else KREAD(inp->inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp); } if (inp->inp_socket) { KREAD(inp->inp_socket, &so, sizeof(so)); if (sotoxsocket(&so, xso) != 0) goto fail; } else { bzero(xso, sizeof(*xso)); if (istcp) xso->xso_protocol = IPPROTO_TCP; } if (istcp) COPYOUT(&xt, sizeof xt); else COPYOUT(&xi, sizeof xi); } /* Reread the pcbinfo and write out the footer. */ kread(off, &pcbinfo, sizeof(pcbinfo)); xig.xig_count = pcbinfo.ipi_count; xig.xig_gen = pcbinfo.ipi_gencnt; COPYOUT(&xig, sizeof xig); *bufp = buf; return (1); fail: free(buf); return (0); #undef COPYOUT #undef KREAD } /* * Print a summary of connections related to an Internet * protocol. For TCP, also give state of connection. * Listening processes (aflag) are suppressed unless the * -a (all) flag is specified. */ void protopr(u_long off, const char *name, int af1, int proto) { int istcp; static int first = 1; char *buf; const char *vchar; struct tcpcb *tp = NULL; struct inpcb *inp; struct xinpgen *xig, *oxig; struct xsocket *so; struct xtcp_timer *timer; istcp = 0; switch (proto) { case IPPROTO_TCP: #ifdef INET6 if (strncmp(name, "sdp", 3) != 0) { if (tcp_done != 0) return; else tcp_done = 1; } else { if (sdp_done != 0) return; else sdp_done = 1; } #endif istcp = 1; break; case IPPROTO_UDP: #ifdef INET6 if (udp_done != 0) return; else udp_done = 1; #endif break; } if (live) { if (!pcblist_sysctl(proto, name, &buf, istcp)) return; } else { if (!pcblist_kvm(off, &buf, istcp)) return; } oxig = xig = (struct xinpgen *)buf; for (xig = (struct xinpgen *)((char *)xig + xig->xig_len); xig->xig_len > sizeof(struct xinpgen); xig = (struct xinpgen *)((char *)xig + xig->xig_len)) { if (istcp) { timer = &((struct xtcpcb *)xig)->xt_timer; tp = &((struct xtcpcb *)xig)->xt_tp; inp = &((struct xtcpcb *)xig)->xt_inp; so = &((struct xtcpcb *)xig)->xt_socket; } else { inp = &((struct xinpcb *)xig)->xi_inp; so = &((struct xinpcb *)xig)->xi_socket; timer = NULL; } /* Ignore sockets for protocols other than the desired one. */ if (so->xso_protocol != proto) continue; /* Ignore PCBs which were freed during copyout. */ if (inp->inp_gencnt > oxig->xig_gen) continue; if ((af1 == AF_INET && (inp->inp_vflag & INP_IPV4) == 0) #ifdef INET6 || (af1 == AF_INET6 && (inp->inp_vflag & INP_IPV6) == 0) #endif /* INET6 */ || (af1 == AF_UNSPEC && ((inp->inp_vflag & INP_IPV4) == 0 #ifdef INET6 && (inp->inp_vflag & INP_IPV6) == 0 #endif /* INET6 */ )) ) continue; if (!aflag && ( (istcp && tp->t_state == TCPS_LISTEN) || (af1 == AF_INET && inet_lnaof(inp->inp_laddr) == INADDR_ANY) #ifdef INET6 || (af1 == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) #endif /* INET6 */ || (af1 == AF_UNSPEC && (((inp->inp_vflag & INP_IPV4) != 0 && inet_lnaof(inp->inp_laddr) == INADDR_ANY) #ifdef INET6 || ((inp->inp_vflag & INP_IPV6) != 0 && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) #endif )) )) continue; if (first) { if (!Lflag) { printf("Active Internet connections"); if (aflag) printf(" (including servers)"); } else printf( "Current listen queue sizes (qlen/incqlen/maxqlen)"); putchar('\n'); if (Aflag) printf("%-*s ", 2 * (int)sizeof(void *), "Tcpcb"); if (Lflag) printf((Aflag && !Wflag) ? "%-5.5s %-14.14s %-18.18s" : "%-5.5s %-14.14s %-22.22s", "Proto", "Listen", "Local Address"); else if (Tflag) printf((Aflag && !Wflag) ? "%-5.5s %-6.6s %-6.6s %-6.6s %-18.18s %s" : "%-5.5s %-6.6s %-6.6s %-6.6s %-22.22s %s", "Proto", "Rexmit", "OOORcv", "0-win", "Local Address", "Foreign Address"); else { printf((Aflag && !Wflag) ? "%-5.5s %-6.6s %-6.6s %-18.18s %-18.18s" : "%-5.5s %-6.6s %-6.6s %-22.22s %-22.22s", "Proto", "Recv-Q", "Send-Q", "Local Address", "Foreign Address"); if (!xflag && !Rflag) printf(" (state)"); } if (xflag) { printf(" %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s %-6.6s", "R-MBUF", "S-MBUF", "R-CLUS", "S-CLUS", "R-HIWA", "S-HIWA", "R-LOWA", "S-LOWA", "R-BCNT", "S-BCNT", "R-BMAX", "S-BMAX"); printf(" %7.7s %7.7s %7.7s %7.7s %7.7s %7.7s", "rexmt", "persist", "keep", "2msl", "delack", "rcvtime"); } else if (Rflag) { printf (" %8.8s %5.5s", "flowid", "ftype"); } putchar('\n'); first = 0; } if (Lflag && so->so_qlimit == 0) continue; if (Aflag) { if (istcp) printf("%*lx ", 2 * (int)sizeof(void *), (u_long)inp->inp_ppcb); else printf("%*lx ", 2 * (int)sizeof(void *), (u_long)so->so_pcb); } #ifdef INET6 if ((inp->inp_vflag & INP_IPV6) != 0) vchar = ((inp->inp_vflag & INP_IPV4) != 0) ? "46" : "6 "; else #endif vchar = ((inp->inp_vflag & INP_IPV4) != 0) ? "4 " : " "; if (istcp && (tp->t_flags & TF_TOE) != 0) printf("%-3.3s%-2.2s ", "toe", vchar); else printf("%-3.3s%-2.2s ", name, vchar); if (Lflag) { char buf1[15]; snprintf(buf1, 15, "%d/%d/%d", so->so_qlen, so->so_incqlen, so->so_qlimit); printf("%-14.14s ", buf1); } else if (Tflag) { if (istcp) printf("%6u %6u %6u ", tp->t_sndrexmitpack, tp->t_rcvoopack, tp->t_sndzerowin); } else { printf("%6u %6u ", so->so_rcv.sb_cc, so->so_snd.sb_cc); } if (numeric_port) { if (inp->inp_vflag & INP_IPV4) { inetprint(&inp->inp_laddr, (int)inp->inp_lport, name, 1); if (!Lflag) inetprint(&inp->inp_faddr, (int)inp->inp_fport, name, 1); } #ifdef INET6 else if (inp->inp_vflag & INP_IPV6) { inet6print(&inp->in6p_laddr, (int)inp->inp_lport, name, 1); if (!Lflag) inet6print(&inp->in6p_faddr, (int)inp->inp_fport, name, 1); } /* else nothing printed now */ #endif /* INET6 */ } else if (inp->inp_flags & INP_ANONPORT) { if (inp->inp_vflag & INP_IPV4) { inetprint(&inp->inp_laddr, (int)inp->inp_lport, name, 1); if (!Lflag) inetprint(&inp->inp_faddr, (int)inp->inp_fport, name, 0); } #ifdef INET6 else if (inp->inp_vflag & INP_IPV6) { inet6print(&inp->in6p_laddr, (int)inp->inp_lport, name, 1); if (!Lflag) inet6print(&inp->in6p_faddr, (int)inp->inp_fport, name, 0); } /* else nothing printed now */ #endif /* INET6 */ } else { if (inp->inp_vflag & INP_IPV4) { inetprint(&inp->inp_laddr, (int)inp->inp_lport, name, 0); if (!Lflag) inetprint(&inp->inp_faddr, (int)inp->inp_fport, name, inp->inp_lport != inp->inp_fport); } #ifdef INET6 else if (inp->inp_vflag & INP_IPV6) { inet6print(&inp->in6p_laddr, (int)inp->inp_lport, name, 0); if (!Lflag) inet6print(&inp->in6p_faddr, (int)inp->inp_fport, name, inp->inp_lport != inp->inp_fport); } /* else nothing printed now */ #endif /* INET6 */ } if (xflag) { printf("%6u %6u %6u %6u %6u %6u %6u %6u %6u %6u %6u %6u", so->so_rcv.sb_mcnt, so->so_snd.sb_mcnt, so->so_rcv.sb_ccnt, so->so_snd.sb_ccnt, so->so_rcv.sb_hiwat, so->so_snd.sb_hiwat, so->so_rcv.sb_lowat, so->so_snd.sb_lowat, so->so_rcv.sb_mbcnt, so->so_snd.sb_mbcnt, so->so_rcv.sb_mbmax, so->so_snd.sb_mbmax); if (timer != NULL) printf(" %4d.%02d %4d.%02d %4d.%02d %4d.%02d %4d.%02d %4d.%02d", timer->tt_rexmt / 1000, (timer->tt_rexmt % 1000) / 10, timer->tt_persist / 1000, (timer->tt_persist % 1000) / 10, timer->tt_keep / 1000, (timer->tt_keep % 1000) / 10, timer->tt_2msl / 1000, (timer->tt_2msl % 1000) / 10, timer->tt_delack / 1000, (timer->tt_delack % 1000) / 10, timer->t_rcvtime / 1000, (timer->t_rcvtime % 1000) / 10); } if (istcp && !Lflag && !xflag && !Tflag && !Rflag) { if (tp->t_state < 0 || tp->t_state >= TCP_NSTATES) printf("%d", tp->t_state); else { printf("%s", tcpstates[tp->t_state]); #if defined(TF_NEEDSYN) && defined(TF_NEEDFIN) /* Show T/TCP `hidden state' */ if (tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) putchar('*'); #endif /* defined(TF_NEEDSYN) && defined(TF_NEEDFIN) */ } } if (Rflag) { printf(" %08x %5d", inp->inp_flowid, inp->inp_flowtype); } putchar('\n'); } if (xig != oxig && xig->xig_gen != oxig->xig_gen) { if (oxig->xig_count > xig->xig_count) { printf("Some %s sockets may have been deleted.\n", name); } else if (oxig->xig_count < xig->xig_count) { printf("Some %s sockets may have been created.\n", name); } else { printf( "Some %s sockets may have been created or deleted.\n", name); } } free(buf); } /* * Dump TCP statistics structure. */ void tcp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct tcpstat tcpstat; #ifdef INET6 if (tcp_done != 0) return; else tcp_done = 1; #endif if (fetch_stats("net.inet.tcp.stats", off, &tcpstat, sizeof(tcpstat), kread_counters) != 0) return; printf ("%s:\n", name); #define p(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, (uintmax_t )tcpstat.f, plural(tcpstat.f)) #define p1a(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, (uintmax_t )tcpstat.f) #define p2(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \ printf(m, (uintmax_t )tcpstat.f1, plural(tcpstat.f1), \ (uintmax_t )tcpstat.f2, plural(tcpstat.f2)) #define p2a(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \ printf(m, (uintmax_t )tcpstat.f1, plural(tcpstat.f1), \ (uintmax_t )tcpstat.f2) #define p3(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, (uintmax_t )tcpstat.f, pluralies(tcpstat.f)) p(tcps_sndtotal, "\t%ju packet%s sent\n"); p2(tcps_sndpack,tcps_sndbyte, "\t\t%ju data packet%s (%ju byte%s)\n"); p2(tcps_sndrexmitpack, tcps_sndrexmitbyte, "\t\t%ju data packet%s (%ju byte%s) retransmitted\n"); p(tcps_sndrexmitbad, "\t\t%ju data packet%s unnecessarily retransmitted\n"); p(tcps_mturesent, "\t\t%ju resend%s initiated by MTU discovery\n"); p2a(tcps_sndacks, tcps_delack, "\t\t%ju ack-only packet%s (%ju delayed)\n"); p(tcps_sndurg, "\t\t%ju URG only packet%s\n"); p(tcps_sndprobe, "\t\t%ju window probe packet%s\n"); p(tcps_sndwinup, "\t\t%ju window update packet%s\n"); p(tcps_sndctrl, "\t\t%ju control packet%s\n"); p(tcps_rcvtotal, "\t%ju packet%s received\n"); p2(tcps_rcvackpack, tcps_rcvackbyte, "\t\t%ju ack%s (for %ju byte%s)\n"); p(tcps_rcvdupack, "\t\t%ju duplicate ack%s\n"); p(tcps_rcvacktoomuch, "\t\t%ju ack%s for unsent data\n"); p2(tcps_rcvpack, tcps_rcvbyte, "\t\t%ju packet%s (%ju byte%s) received in-sequence\n"); p2(tcps_rcvduppack, tcps_rcvdupbyte, "\t\t%ju completely duplicate packet%s (%ju byte%s)\n"); p(tcps_pawsdrop, "\t\t%ju old duplicate packet%s\n"); p2(tcps_rcvpartduppack, tcps_rcvpartdupbyte, "\t\t%ju packet%s with some dup. data (%ju byte%s duped)\n"); p2(tcps_rcvoopack, tcps_rcvoobyte, "\t\t%ju out-of-order packet%s (%ju byte%s)\n"); p2(tcps_rcvpackafterwin, tcps_rcvbyteafterwin, "\t\t%ju packet%s (%ju byte%s) of data after window\n"); p(tcps_rcvwinprobe, "\t\t%ju window probe%s\n"); p(tcps_rcvwinupd, "\t\t%ju window update packet%s\n"); p(tcps_rcvafterclose, "\t\t%ju packet%s received after close\n"); p(tcps_rcvbadsum, "\t\t%ju discarded for bad checksum%s\n"); p(tcps_rcvbadoff, "\t\t%ju discarded for bad header offset field%s\n"); p1a(tcps_rcvshort, "\t\t%ju discarded because packet too short\n"); p1a(tcps_rcvmemdrop, "\t\t%ju discarded due to memory problems\n"); p(tcps_connattempt, "\t%ju connection request%s\n"); p(tcps_accepts, "\t%ju connection accept%s\n"); p(tcps_badsyn, "\t%ju bad connection attempt%s\n"); p(tcps_listendrop, "\t%ju listen queue overflow%s\n"); p(tcps_badrst, "\t%ju ignored RSTs in the window%s\n"); p(tcps_connects, "\t%ju connection%s established (including accepts)\n"); p2(tcps_closed, tcps_drops, "\t%ju connection%s closed (including %ju drop%s)\n"); p(tcps_cachedrtt, "\t\t%ju connection%s updated cached RTT on close\n"); p(tcps_cachedrttvar, "\t\t%ju connection%s updated cached RTT variance on close\n"); p(tcps_cachedssthresh, "\t\t%ju connection%s updated cached ssthresh on close\n"); p(tcps_conndrops, "\t%ju embryonic connection%s dropped\n"); p2(tcps_rttupdated, tcps_segstimed, "\t%ju segment%s updated rtt (of %ju attempt%s)\n"); p(tcps_rexmttimeo, "\t%ju retransmit timeout%s\n"); p(tcps_timeoutdrop, "\t\t%ju connection%s dropped by rexmit timeout\n"); p(tcps_persisttimeo, "\t%ju persist timeout%s\n"); p(tcps_persistdrop, "\t\t%ju connection%s dropped by persist timeout\n"); p(tcps_finwait2_drops, "\t%ju Connection%s (fin_wait_2) dropped because of timeout\n"); p(tcps_keeptimeo, "\t%ju keepalive timeout%s\n"); p(tcps_keepprobe, "\t\t%ju keepalive probe%s sent\n"); p(tcps_keepdrops, "\t\t%ju connection%s dropped by keepalive\n"); p(tcps_predack, "\t%ju correct ACK header prediction%s\n"); p(tcps_preddat, "\t%ju correct data packet header prediction%s\n"); p3(tcps_sc_added, "\t%ju syncache entr%s added\n"); p1a(tcps_sc_retransmitted, "\t\t%ju retransmitted\n"); p1a(tcps_sc_dupsyn, "\t\t%ju dupsyn\n"); p1a(tcps_sc_dropped, "\t\t%ju dropped\n"); p1a(tcps_sc_completed, "\t\t%ju completed\n"); p1a(tcps_sc_bucketoverflow, "\t\t%ju bucket overflow\n"); p1a(tcps_sc_cacheoverflow, "\t\t%ju cache overflow\n"); p1a(tcps_sc_reset, "\t\t%ju reset\n"); p1a(tcps_sc_stale, "\t\t%ju stale\n"); p1a(tcps_sc_aborted, "\t\t%ju aborted\n"); p1a(tcps_sc_badack, "\t\t%ju badack\n"); p1a(tcps_sc_unreach, "\t\t%ju unreach\n"); p(tcps_sc_zonefail, "\t\t%ju zone failure%s\n"); p(tcps_sc_sendcookie, "\t%ju cookie%s sent\n"); p(tcps_sc_recvcookie, "\t%ju cookie%s received\n"); p3(tcps_hc_added, "\t%ju hostcache entr%s added\n"); p1a(tcps_hc_bucketoverflow, "\t\t%ju bucket overflow\n"); p(tcps_sack_recovery_episode, "\t%ju SACK recovery episode%s\n"); p(tcps_sack_rexmits, "\t%ju segment rexmit%s in SACK recovery episodes\n"); p(tcps_sack_rexmit_bytes, "\t%ju byte rexmit%s in SACK recovery episodes\n"); p(tcps_sack_rcv_blocks, "\t%ju SACK option%s (SACK blocks) received\n"); p(tcps_sack_send_blocks, "\t%ju SACK option%s (SACK blocks) sent\n"); p1a(tcps_sack_sboverflow, "\t%ju SACK scoreboard overflow\n"); p(tcps_ecn_ce, "\t%ju packet%s with ECN CE bit set\n"); p(tcps_ecn_ect0, "\t%ju packet%s with ECN ECT(0) bit set\n"); p(tcps_ecn_ect1, "\t%ju packet%s with ECN ECT(1) bit set\n"); p(tcps_ecn_shs, "\t%ju successful ECN handshake%s\n"); p(tcps_ecn_rcwnd, "\t%ju time%s ECN reduced the congestion window\n"); p(tcps_sig_rcvgoodsig, "\t%ju packet%s with valid tcp-md5 signature received\n"); p(tcps_sig_rcvbadsig, "\t%ju packet%s with invalid tcp-md5 signature received\n"); p(tcps_sig_err_buildsig, "\t%ju packet%s with tcp-md5 signature mismatch\n"); p(tcps_sig_err_sigopt, "\t%ju packet%s with unexpected tcp-md5 signature received\n"); p(tcps_sig_err_nosigopt, "\t%ju packet%s without expected tcp-md5 signature received\n"); #undef p #undef p1a #undef p2 #undef p2a #undef p3 } /* * Dump UDP statistics structure. */ void udp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct udpstat udpstat; uint64_t delivered; #ifdef INET6 if (udp_done != 0) return; else udp_done = 1; #endif if (fetch_stats("net.inet.udp.stats", off, &udpstat, sizeof(udpstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (udpstat.f || sflag <= 1) \ printf("\t%ju " m, (uintmax_t)udpstat.f, plural(udpstat.f)) #define p1a(f, m) if (udpstat.f || sflag <= 1) \ printf("\t%ju " m, (uintmax_t)udpstat.f) p(udps_ipackets, "datagram%s received\n"); p1a(udps_hdrops, "with incomplete header\n"); p1a(udps_badlen, "with bad data length field\n"); p1a(udps_badsum, "with bad checksum\n"); p1a(udps_nosum, "with no checksum\n"); p1a(udps_noport, "dropped due to no socket\n"); p(udps_noportbcast, "broadcast/multicast datagram%s undelivered\n"); p1a(udps_fullsock, "dropped due to full socket buffers\n"); p1a(udpps_pcbhashmiss, "not for hashed pcb\n"); delivered = udpstat.udps_ipackets - udpstat.udps_hdrops - udpstat.udps_badlen - udpstat.udps_badsum - udpstat.udps_noport - udpstat.udps_noportbcast - udpstat.udps_fullsock; if (delivered || sflag <= 1) printf("\t%ju delivered\n", (uint64_t)delivered); p(udps_opackets, "datagram%s output\n"); /* the next statistic is cumulative in udps_noportbcast */ p(udps_filtermcast, "time%s multicast source filter matched\n"); #undef p #undef p1a } /* * Dump CARP statistics structure. */ void carp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct carpstats carpstat; if (fetch_stats("net.inet.carp.stats", off, &carpstat, sizeof(carpstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (carpstat.f || sflag <= 1) \ printf(m, (uintmax_t)carpstat.f, plural(carpstat.f)) #define p2(f, m) if (carpstat.f || sflag <= 1) \ printf(m, (uintmax_t)carpstat.f) p(carps_ipackets, "\t%ju packet%s received (IPv4)\n"); p(carps_ipackets6, "\t%ju packet%s received (IPv6)\n"); p(carps_badttl, "\t\t%ju packet%s discarded for wrong TTL\n"); p(carps_hdrops, "\t\t%ju packet%s shorter than header\n"); p(carps_badsum, "\t\t%ju discarded for bad checksum%s\n"); p(carps_badver, "\t\t%ju discarded packet%s with a bad version\n"); p2(carps_badlen, "\t\t%ju discarded because packet too short\n"); p2(carps_badauth, "\t\t%ju discarded for bad authentication\n"); p2(carps_badvhid, "\t\t%ju discarded for bad vhid\n"); p2(carps_badaddrs, "\t\t%ju discarded because of a bad address list\n"); p(carps_opackets, "\t%ju packet%s sent (IPv4)\n"); p(carps_opackets6, "\t%ju packet%s sent (IPv6)\n"); p2(carps_onomem, "\t\t%ju send failed due to mbuf memory error\n"); #if notyet p(carps_ostates, "\t\t%s state update%s sent\n"); #endif #undef p #undef p2 } /* * Dump IP statistics structure. */ void ip_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct ipstat ipstat; if (fetch_stats("net.inet.ip.stats", off, &ipstat, sizeof(ipstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (ipstat.f || sflag <= 1) \ printf(m, (uintmax_t )ipstat.f, plural(ipstat.f)) #define p1a(f, m) if (ipstat.f || sflag <= 1) \ printf(m, (uintmax_t )ipstat.f) p(ips_total, "\t%ju total packet%s received\n"); p(ips_badsum, "\t%ju bad header checksum%s\n"); p1a(ips_toosmall, "\t%ju with size smaller than minimum\n"); p1a(ips_tooshort, "\t%ju with data size < data length\n"); p1a(ips_toolong, "\t%ju with ip length > max ip packet size\n"); p1a(ips_badhlen, "\t%ju with header length < data size\n"); p1a(ips_badlen, "\t%ju with data length < header length\n"); p1a(ips_badoptions, "\t%ju with bad options\n"); p1a(ips_badvers, "\t%ju with incorrect version number\n"); p(ips_fragments, "\t%ju fragment%s received\n"); p(ips_fragdropped, "\t%ju fragment%s dropped (dup or out of space)\n"); p(ips_fragtimeout, "\t%ju fragment%s dropped after timeout\n"); p(ips_reassembled, "\t%ju packet%s reassembled ok\n"); p(ips_delivered, "\t%ju packet%s for this host\n"); p(ips_noproto, "\t%ju packet%s for unknown/unsupported protocol\n"); p(ips_forward, "\t%ju packet%s forwarded"); p(ips_fastforward, " (%ju packet%s fast forwarded)"); if (ipstat.ips_forward || sflag <= 1) putchar('\n'); p(ips_cantforward, "\t%ju packet%s not forwardable\n"); p(ips_notmember, "\t%ju packet%s received for unknown multicast group\n"); p(ips_redirectsent, "\t%ju redirect%s sent\n"); p(ips_localout, "\t%ju packet%s sent from this host\n"); p(ips_rawout, "\t%ju packet%s sent with fabricated ip header\n"); p(ips_odropped, "\t%ju output packet%s dropped due to no bufs, etc.\n"); p(ips_noroute, "\t%ju output packet%s discarded due to no route\n"); p(ips_fragmented, "\t%ju output datagram%s fragmented\n"); p(ips_ofragments, "\t%ju fragment%s created\n"); p(ips_cantfrag, "\t%ju datagram%s that can't be fragmented\n"); p(ips_nogif, "\t%ju tunneling packet%s that can't find gif\n"); p(ips_badaddr, "\t%ju datagram%s with bad address in header\n"); #undef p #undef p1a } /* * Dump ARP statistics structure. */ void arp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct arpstat arpstat; if (fetch_stats("net.link.ether.arp.stats", off, &arpstat, sizeof(arpstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (arpstat.f || sflag <= 1) \ printf("\t%ju " m, (uintmax_t)arpstat.f, plural(arpstat.f)) #define p2(f, m) if (arpstat.f || sflag <= 1) \ printf("\t%ju " m, (uintmax_t)arpstat.f, pluralies(arpstat.f)) p(txrequests, "ARP request%s sent\n"); p2(txreplies, "ARP repl%s sent\n"); p(rxrequests, "ARP request%s received\n"); p2(rxreplies, "ARP repl%s received\n"); p(received, "ARP packet%s received\n"); p(dropped, "total packet%s dropped due to no ARP entry\n"); p(timeouts, "ARP entry%s timed out\n"); p(dupips, "Duplicate IP%s seen\n"); #undef p #undef p2 } static const char *icmpnames[ICMP_MAXTYPE + 1] = { "echo reply", /* RFC 792 */ "#1", "#2", "destination unreachable", /* RFC 792 */ "source quench", /* RFC 792 */ "routing redirect", /* RFC 792 */ "#6", "#7", "echo", /* RFC 792 */ "router advertisement", /* RFC 1256 */ "router solicitation", /* RFC 1256 */ "time exceeded", /* RFC 792 */ "parameter problem", /* RFC 792 */ "time stamp", /* RFC 792 */ "time stamp reply", /* RFC 792 */ "information request", /* RFC 792 */ "information request reply", /* RFC 792 */ "address mask request", /* RFC 950 */ "address mask reply", /* RFC 950 */ "#19", "#20", "#21", "#22", "#23", "#24", "#25", "#26", "#27", "#28", "#29", "icmp traceroute", /* RFC 1393 */ "datagram conversion error", /* RFC 1475 */ "mobile host redirect", "IPv6 where-are-you", "IPv6 i-am-here", "mobile registration req", "mobile registration reply", "domain name request", /* RFC 1788 */ "domain name reply", /* RFC 1788 */ "icmp SKIP", "icmp photuris", /* RFC 2521 */ }; /* * Dump ICMP statistics. */ void icmp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct icmpstat icmpstat; size_t len; int i, first; if (fetch_stats("net.inet.icmp.stats", off, &icmpstat, sizeof(icmpstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (icmpstat.f || sflag <= 1) \ printf(m, icmpstat.f, plural(icmpstat.f)) #define p1a(f, m) if (icmpstat.f || sflag <= 1) \ printf(m, icmpstat.f) #define p2(f, m) if (icmpstat.f || sflag <= 1) \ printf(m, icmpstat.f, plurales(icmpstat.f)) p(icps_error, "\t%lu call%s to icmp_error\n"); p(icps_oldicmp, "\t%lu error%s not generated in response to an icmp message\n"); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) if (icmpstat.icps_outhist[i] != 0) { if (first) { printf("\tOutput histogram:\n"); first = 0; } if (icmpnames[i] != NULL) printf("\t\t%s: %lu\n", icmpnames[i], icmpstat.icps_outhist[i]); else printf("\t\tunknown ICMP #%d: %lu\n", i, icmpstat.icps_outhist[i]); } p(icps_badcode, "\t%lu message%s with bad code fields\n"); p(icps_tooshort, "\t%lu message%s less than the minimum length\n"); p(icps_checksum, "\t%lu message%s with bad checksum\n"); p(icps_badlen, "\t%lu message%s with bad length\n"); p1a(icps_bmcastecho, "\t%lu multicast echo requests ignored\n"); p1a(icps_bmcasttstamp, "\t%lu multicast timestamp requests ignored\n"); for (first = 1, i = 0; i < ICMP_MAXTYPE + 1; i++) if (icmpstat.icps_inhist[i] != 0) { if (first) { printf("\tInput histogram:\n"); first = 0; } if (icmpnames[i] != NULL) printf("\t\t%s: %lu\n", icmpnames[i], icmpstat.icps_inhist[i]); else printf("\t\tunknown ICMP #%d: %lu\n", i, icmpstat.icps_inhist[i]); } p(icps_reflect, "\t%lu message response%s generated\n"); p2(icps_badaddr, "\t%lu invalid return address%s\n"); p(icps_noroute, "\t%lu no return route%s\n"); #undef p #undef p1a #undef p2 if (live) { len = sizeof i; if (sysctlbyname("net.inet.icmp.maskrepl", &i, &len, NULL, 0) < 0) return; printf("\tICMP address mask responses are %sabled\n", i ? "en" : "dis"); } } -#ifndef BURN_BRIDGES -/* - * Dump IGMP statistics structure (pre 8.x kernel). - */ -static void -igmp_stats_live_old(const char *name) -{ - struct oigmpstat oigmpstat, zerostat; - size_t len = sizeof(oigmpstat); - - if (zflag) - memset(&zerostat, 0, len); - if (sysctlbyname("net.inet.igmp.stats", &oigmpstat, &len, - zflag ? &zerostat : NULL, zflag ? len : 0) < 0) { - warn("sysctl: net.inet.igmp.stats"); - return; - } - - printf("%s:\n", name); - -#define p(f, m) if (oigmpstat.f || sflag <= 1) \ - printf(m, oigmpstat.f, plural(oigmpstat.f)) -#define py(f, m) if (oigmpstat.f || sflag <= 1) \ - printf(m, oigmpstat.f, oigmpstat.f != 1 ? "ies" : "y") - p(igps_rcv_total, "\t%u message%s received\n"); - p(igps_rcv_tooshort, "\t%u message%s received with too few bytes\n"); - p(igps_rcv_badsum, "\t%u message%s received with bad checksum\n"); - py(igps_rcv_queries, "\t%u membership quer%s received\n"); - py(igps_rcv_badqueries, - "\t%u membership quer%s received with invalid field(s)\n"); - p(igps_rcv_reports, "\t%u membership report%s received\n"); - p(igps_rcv_badreports, - "\t%u membership report%s received with invalid field(s)\n"); - p(igps_rcv_ourreports, -"\t%u membership report%s received for groups to which we belong\n"); - p(igps_snd_reports, "\t%u membership report%s sent\n"); -#undef p -#undef py -} -#endif /* !BURN_BRIDGES */ - /* * Dump IGMP statistics structure. */ void igmp_stats(u_long off, const char *name, int af1 __unused, int proto __unused) { struct igmpstat igmpstat; if (fetch_stats("net.inet.igmp.stats", 0, &igmpstat, sizeof(igmpstat), kread) != 0) return; if (igmpstat.igps_version != IGPS_VERSION_3) { warnx("%s: version mismatch (%d != %d)", __func__, igmpstat.igps_version, IGPS_VERSION_3); } if (igmpstat.igps_len != IGPS_VERSION3_LEN) { warnx("%s: size mismatch (%d != %d)", __func__, igmpstat.igps_len, IGPS_VERSION3_LEN); } printf("%s:\n", name); #define p64(f, m) if (igmpstat.f || sflag <= 1) \ printf(m, (uintmax_t) igmpstat.f, plural(igmpstat.f)) #define py64(f, m) if (igmpstat.f || sflag <= 1) \ printf(m, (uintmax_t) igmpstat.f, pluralies(igmpstat.f)) p64(igps_rcv_total, "\t%ju message%s received\n"); p64(igps_rcv_tooshort, "\t%ju message%s received with too few bytes\n"); p64(igps_rcv_badttl, "\t%ju message%s received with wrong TTL\n"); p64(igps_rcv_badsum, "\t%ju message%s received with bad checksum\n"); py64(igps_rcv_v1v2_queries, "\t%ju V1/V2 membership quer%s received\n"); py64(igps_rcv_v3_queries, "\t%ju V3 membership quer%s received\n"); py64(igps_rcv_badqueries, "\t%ju membership quer%s received with invalid field(s)\n"); py64(igps_rcv_gen_queries, "\t%ju general quer%s received\n"); py64(igps_rcv_group_queries, "\t%ju group quer%s received\n"); py64(igps_rcv_gsr_queries, "\t%ju group-source quer%s received\n"); py64(igps_drop_gsr_queries, "\t%ju group-source quer%s dropped\n"); p64(igps_rcv_reports, "\t%ju membership report%s received\n"); p64(igps_rcv_badreports, "\t%ju membership report%s received with invalid field(s)\n"); p64(igps_rcv_ourreports, "\t%ju membership report%s received for groups to which we belong\n"); p64(igps_rcv_nora, "\t%ju V3 report%s received without Router Alert\n"); p64(igps_snd_reports, "\t%ju membership report%s sent\n"); #undef p64 #undef py64 } /* * Dump PIM statistics structure. */ void pim_stats(u_long off __unused, const char *name, int af1 __unused, int proto __unused) { struct pimstat pimstat; if (fetch_stats("net.inet.pim.stats", off, &pimstat, sizeof(pimstat), kread_counters) != 0) return; printf("%s:\n", name); #define p(f, m) if (pimstat.f || sflag <= 1) \ printf(m, (uintmax_t)pimstat.f, plural(pimstat.f)) #define py(f, m) if (pimstat.f || sflag <= 1) \ printf(m, (uintmax_t)pimstat.f, pimstat.f != 1 ? "ies" : "y") p(pims_rcv_total_msgs, "\t%ju message%s received\n"); p(pims_rcv_total_bytes, "\t%ju byte%s received\n"); p(pims_rcv_tooshort, "\t%ju message%s received with too few bytes\n"); p(pims_rcv_badsum, "\t%ju message%s received with bad checksum\n"); p(pims_rcv_badversion, "\t%ju message%s received with bad version\n"); p(pims_rcv_registers_msgs, "\t%ju data register message%s received\n"); p(pims_rcv_registers_bytes, "\t%ju data register byte%s received\n"); p(pims_rcv_registers_wrongiif, "\t%ju data register message%s received on wrong iif\n"); p(pims_rcv_badregisters, "\t%ju bad register%s received\n"); p(pims_snd_registers_msgs, "\t%ju data register message%s sent\n"); p(pims_snd_registers_bytes, "\t%ju data register byte%s sent\n"); #undef p #undef py } /* * Pretty print an Internet address (net address + port). */ void inetprint(struct in_addr *in, int port, const char *proto, int num_port) { struct servent *sp = 0; char line[80], *cp; int width; if (Wflag) sprintf(line, "%s.", inetname(in)); else sprintf(line, "%.*s.", (Aflag && !num_port) ? 12 : 16, inetname(in)); cp = strchr(line, '\0'); if (!num_port && port) sp = getservbyport((int)port, proto); if (sp || port == 0) sprintf(cp, "%.15s ", sp ? sp->s_name : "*"); else sprintf(cp, "%d ", ntohs((u_short)port)); width = (Aflag && !Wflag) ? 18 : 22; if (Wflag) printf("%-*s ", width, line); else printf("%-*.*s ", width, width, line); } /* * Construct an Internet address representation. * If numeric_addr has been supplied, give * numeric value, otherwise try for symbolic name. */ char * inetname(struct in_addr *inp) { char *cp; static char line[MAXHOSTNAMELEN]; struct hostent *hp; struct netent *np; cp = 0; if (!numeric_addr && inp->s_addr != INADDR_ANY) { int net = inet_netof(*inp); int lna = inet_lnaof(*inp); if (lna == INADDR_ANY) { np = getnetbyaddr(net, AF_INET); if (np) cp = np->n_name; } if (cp == 0) { hp = gethostbyaddr((char *)inp, sizeof (*inp), AF_INET); if (hp) { cp = hp->h_name; trimdomain(cp, strlen(cp)); } } } if (inp->s_addr == INADDR_ANY) strcpy(line, "*"); else if (cp) { strlcpy(line, cp, sizeof(line)); } else { inp->s_addr = ntohl(inp->s_addr); #define C(x) ((u_int)((x) & 0xff)) sprintf(line, "%u.%u.%u.%u", C(inp->s_addr >> 24), C(inp->s_addr >> 16), C(inp->s_addr >> 8), C(inp->s_addr)); } return (line); } Index: user/ngie/stable-10-libnv =================================================================== --- user/ngie/stable-10-libnv (revision 293638) +++ user/ngie/stable-10-libnv (revision 293639) Property changes on: user/ngie/stable-10-libnv ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,2 ## Merged /head:r279017,290275,292057-292058,293340,293379 Merged /stable/10:r293618-293638